Initial Commit
This commit is contained in:
789 files changed
+149185
No files matched your search
@@ -0,0 +1,649 @@
|
||||
# Plan: algorithms
|
||||
|
||||
Written 2026-10-08, revised 2026-10-09 for `invokable`, which changes how
|
||||
predicates, orders and keys are taken, and brought up to date 2026-10-20 for what std
|
||||
and the compiler gained since: sorting, bisection, `heap`, `groups` and `runs` in std,
|
||||
the iterators' consumers, `min`, `max` and `clamp` in `std::math`, lambdas typed from
|
||||
`invokable` bounds, and lambdas that no longer allocate. This is a proposal. std is
|
||||
yours, so the decisions at the end are yours to make. Much of what it proposed is in std
|
||||
now, built apart from it; the rest isn't built.
|
||||
|
||||
**Comes after the ffi plan, now built:** `std::sys` is `system`, and `@foreign` and
|
||||
`@link` are `extern` sections.
|
||||
|
||||
**What it is:** the operations on runs of elements that programs keep writing by hand:
|
||||
- sorting;
|
||||
- searching, including by bisection;
|
||||
- testing, counting and finding;
|
||||
- grouping elements by a key;
|
||||
- reversing, filling and removing;
|
||||
- a heap of least-first elements;
|
||||
- `min`, `max`, `clamp` and `swap`.
|
||||
|
||||
std has most of these now (see [What's there now](#whats-there-now)). What's left:
|
||||
- orders and tests taken as anything `invokable`, sorting by a key, and a sort that
|
||||
allocates nothing;
|
||||
- `swap`, `reverse`, `fill` and `is_sorted`;
|
||||
- for vectors, taking the last element out, keeping only some, and dropping repeats.
|
||||
|
||||
**Its users:**
|
||||
- **the compiler,** which moved onto std's sort, heap, groups, runs and
|
||||
bisections on 2026-10-19, and still writes the rest by hand. See
|
||||
[What the compiler gains](#what-the-compiler-gains);
|
||||
- the random plan ([random.md](random.md)), whose `shuffle` swaps elements;
|
||||
- the build tool, ordering files and steps;
|
||||
- writers of documents that want keys in order, and every program that sorts.
|
||||
|
||||
**Probed:** in the scratchpad, on 2026-10-08 and 2026-10-09 (`algo/`, since gone), and
|
||||
again on 2026-10-20 (`plans/algorithms/`) against std as it is now. Each program was
|
||||
built at `-O2` by the compiler. The machine was busy on 2026-10-20, so those times are
|
||||
the best of three runs on one core.
|
||||
|
||||
- **A generic sort** (2026-10-08): introsort over a private `comparer<T>` trait, sorting
|
||||
1,000,000 random words:
|
||||
|
||||
| How the order is given | Time |
|
||||
|---|---|
|
||||
| `<`, through `ordered` | 0.17 s |
|
||||
| A function value | 0.23 s |
|
||||
| The compiler's own `sort_words`, a heap sort | 0.30–0.35 s |
|
||||
|
||||
Also:
|
||||
- Sorting 1,000,000 structs by a function value took 0.25 s. Packing the same two
|
||||
fields into words and calling `sort_words` took 0.30 s.
|
||||
- Sorting 100,000 strings by a function value worked.
|
||||
- **std's sort** (2026-10-20), a stable merge sort, over a million random words made the
|
||||
same way:
|
||||
|
||||
| Sort | Time |
|
||||
|---|---|
|
||||
| `sort`, by `<` | 0.19 s |
|
||||
| `sort_by`, a named function | 0.26 s |
|
||||
| `sort_by`, a lambda | 0.25 s |
|
||||
| 1,000,000 structs by a field, `sort_by` with a lambda | 0.19 s |
|
||||
| The introsort above, by `<`, written again beside it | 0.13 s |
|
||||
|
||||
The introsort allocates nothing and isn't stable. The merge sort takes a buffer as
|
||||
long as the run.
|
||||
- **Grouping by key** (2026-10-08): a counting sort of 1,000,000 items into 65,536 keys
|
||||
took 0.02 s. The register allocator's way then, which packed, sorted, counted and
|
||||
summed, took 0.33 s for the same order. std's `groups` counts this way now.
|
||||
- **Bisection through a key function that captures nothing** (2026-10-08) ran as fast as
|
||||
the loop written out: 3.24 s against 3.40 s for 10,000,000 searches.
|
||||
- **Through `invokable`** (2026-10-09). The same introsort, generic over its order
|
||||
`F: invokable<def(&T, &T): bool>` instead of the private trait, sorting 1,000,000
|
||||
random words:
|
||||
|
||||
| How the order is given | Time |
|
||||
|---|---|
|
||||
| `<`, through a functor, `by_order<T>` | 0.14 s |
|
||||
| A functor comparing a key of its own | 0.15 s |
|
||||
| A function value | 0.22 s |
|
||||
| A function value held in a struct, as `comparer<T>` held it | 0.23 s |
|
||||
|
||||
A function value costs the same through `invokable` as through a parameter of
|
||||
function type, or held as `comparer<T>` held it: 0.23 s in the sort.
|
||||
- **Lambdas in a hot loop** (2026-10-20): 10,000,000 searches of 8 elements, each for a
|
||||
value that changes:
|
||||
|
||||
| Search | Time |
|
||||
|---|---|
|
||||
| A loop over indexes, written out | 0.12 s |
|
||||
| `span::contains` | 0.19 s |
|
||||
| `any` of a span, generic over its test, given a functor holding the value | 0.19 s |
|
||||
| `for &each in v`, written out | 0.26 s |
|
||||
| `iter().any`, given such a functor | 0.26 s |
|
||||
| `any` of a span, given a lambda referring to the value | 0.44 s |
|
||||
| `iter().any`, given that lambda | 0.65 s |
|
||||
|
||||
- Memory grew in none.
|
||||
- On 2026-10-09 such a lambda took 3.23 s, where a functor took 0.09 s, in a probe
|
||||
searching for one value. Each lambda made then allocated twice.
|
||||
- A named function given for the test, looking for a constant, took 0.13 s. The
|
||||
compiler calls it directly and inlines it.
|
||||
|
||||
**Found:**
|
||||
- **A lambda allocates nothing now, but is called through its value.**
|
||||
- Lambdas refer to the locals they use where those are (README, "Functions"), so the
|
||||
two allocations are gone: 0.44 s where it was 3.23 s.
|
||||
- The compiler's `devirtualize` (compiler/optimizer/inline.sakura) calls a known
|
||||
function value directly, so a named function, or a lambda referring to nothing, is
|
||||
inlined once the algorithm is. "A function taking an environment is left called
|
||||
through the value," so a lambda referring to locals isn't: 2.3 times a functor in
|
||||
the search.
|
||||
- A lambda given for `F` is of its function type, so all lambdas of one signature
|
||||
share an instance of an algorithm. One the optimizer doesn't inline, as a sort,
|
||||
calls its order through the value however the order was made.
|
||||
|
||||
Decision 4 is about this.
|
||||
- **A functor costs about what `span::contains` costs.** An algorithm generic over its
|
||||
test is compiled for each functor's type, so `invoke` is a direct call, inlined at
|
||||
`-O2`, and what the test needs is a field. It's still the cheap path, and needs no
|
||||
change to the compiler. The loop over indexes is faster still, 0.12 s against 0.19 s,
|
||||
where on 2026-10-09 they ran even.
|
||||
- **A functor for a view's iterator takes `& &T`.** `v.span.iter()` gives `&T`, and
|
||||
the consumers' tests take a reference to what's given, so `iter().any` wants
|
||||
`invokable<def(& &block): bool>`. A functor taking `&block` doesn't meet it. A lambda
|
||||
doesn't care (decision 3).
|
||||
- **Bounds at methods work now.** The compiler takes
|
||||
`def span<T>::is_sorted(&this): bool where T: ordered`, and the method belongs only to
|
||||
ordered `T` (README, "Methods and properties"). std's `lower_bound`, `upper_bound`,
|
||||
`sort` and `heap` guard with `if const !(T is ordered)` and `compile_error`, which
|
||||
gives a message of their own. Probed.
|
||||
- **Lambdas take their types from `invokable` bounds,** and the compiler infers a type
|
||||
parameter from a lambda, as `F` of `take<F>(f: F)` given `def(x: i64): i64 => x`.
|
||||
That was phase 0 here, built with the iterators on 2026-10-19. Probed.
|
||||
- **Overloads give a lambda the function type.** Where `apply(x: i64, f: def(i64): i64)`
|
||||
and `apply<F>(x: i64, f: F) where F: invokable<def(i64): i64>` take the same
|
||||
arguments, the compiler gives a lambda the function type and calls the first. It
|
||||
doesn't give a lambda its types from the bound of a generic overload, even where the
|
||||
other overloads take fewer arguments. So overloads still don't serve both forms
|
||||
(decision 1). Probed.
|
||||
- **A key's type is inferred from what gives it,** as `K` of `least_by_key<F, K>` from a
|
||||
lambda giving a `u32`. Probed again.
|
||||
- **A test taken by value is a copy.** A functor counting what it's asked counts in the
|
||||
algorithm's copy, and lent as `&mut` it counts in the caller's. Both work. Probed
|
||||
again.
|
||||
- **`strview` isn't `ordered`.** Its `compare` takes the other view by value, not as
|
||||
`&self`, so `<` doesn't work on text views. Taking `&strview` fixes it. `string` is
|
||||
ordered, so `sort` sorts strings, as std's tests do.
|
||||
- **`for &each in v` over a vector runs about 1.4 times** `span::contains`, and twice the
|
||||
loop over indexes. It ran about 3 times `span::contains` on 2026-10-09, before
|
||||
`maybe<&T>` was one word. std's algorithms loop over the span's pointer.
|
||||
- **`sort_words` is gone.** std's `sort`, `heap` and `groups` replaced both copies, in
|
||||
`machine/heap.sakura` and `native/registers.sakura`, on 2026-10-19.
|
||||
- **std's `sort_by` and `partition_point` take a function type,** `def(&T, &T): bool`
|
||||
and `def(&T): bool`, where the iterators' adapters and consumers take
|
||||
`F: invokable`. A functor reaches them only through a lambda calling it (decision 1).
|
||||
- **std's `pop`s give nothing back.** `stack`, `queue` and `heap` `pop` the value `peek`
|
||||
reads, and give nothing back. `vector::truncate()` removes the last, which `last()`
|
||||
reads, and is named apart from `pop`, its comment says, since a vector is no stack.
|
||||
So this plan's `vector::pop(): maybe<T>` would be a `pop` unlike the others, and its
|
||||
`truncate(length)` takes a name std uses (decision 5).
|
||||
- **Fixed while probing** on 2026-10-09, in the compiler's sources, each with a test:
|
||||
- The compiler moved a functor called as `f(x)` to the heap on every call, where
|
||||
`f.invoke(x)` kept it in the frame: 1.45 s against 0.09 s for the functor search.
|
||||
Its `keeps` analysis also took `f(x)` to keep `f`.
|
||||
- Fixing that showed an older fault: the machine ran a function returning a struct of
|
||||
no fields with a destination its code didn't take, and gave wrong values or
|
||||
crashed. Native code was right.
|
||||
- The compiler didn't infer the `K` of `invokable<def(&T): K>` from a function given
|
||||
for it.
|
||||
|
||||
## What's there now
|
||||
|
||||
- **`span<T>`** (std/containers/span.sakura): `index_of`, `last_index_of`, `count_of`,
|
||||
`contains`, `equals`, `first`, `last`, `get` and `sub`. In a sorted run, `lower_bound`
|
||||
and `upper_bound` by `<`, and `partition_point` by a test, `def(&T): bool`.
|
||||
- **Sorting** (std/containers/sort.sakura): `sort`, by `<`, and `sort_by`, by a function
|
||||
`def(&T, &T): bool`, of `slice<T>` and `vector<T>`.
|
||||
- Both are stable. Runs of 16 are sorted by insertion, then merged in pairs, back and
|
||||
forth with a buffer as long as the run, from the program's heap. No allocator is
|
||||
taken.
|
||||
- Elements are moved byte for byte, so strings and other owning values sort without
|
||||
being copied or closed.
|
||||
- One core, `sort_elements<T, O>`, is generic over a private trait, `sort_order<T>`:
|
||||
`natural_order<T>` gives `<`, and `given_order<T>` holds the function.
|
||||
- **`vector<T>`:** `append`, `extend`, which copies a span's elements, `insert_at`,
|
||||
`remove_at`, `remove`, `truncate()`, which closes the last, `first()` and `last()`,
|
||||
which give a reference and stop the program where it's empty, `resize(size)` and
|
||||
`resize(size, fill)`, `clear`, `reserve`, `drain(range)` and `from(iterator)`. Nothing
|
||||
takes the last out, and there's no `retain` or `dedup`.
|
||||
- **`heap<T>`** (std/containers/heap.sakura): least first by `<`, with `push`, `peek`,
|
||||
`pop`, which gives nothing, `span` and `clear`. No order but `<`.
|
||||
- **`groups<T>`** (std/containers/groups.sakura): elements gathered by a key from 0, in
|
||||
two passes: `count` each key's, `seal`, which turns the counts into starts, then `put`
|
||||
each. `of(key)` gives a run as a span.
|
||||
- **`runs<T>`** (std/containers/runs.sakura): many short lists in one block, each added
|
||||
whole by `add(span)` or built by `push` and `end`, named by a `u32`, and read by
|
||||
`view(id)`.
|
||||
- **The iterators' consumers,** default methods of `iter<T>`
|
||||
(core/traits/iteration.sakura), over any iterator, as `v.iter()`: `count`, `sum`,
|
||||
`product`, `fold`, `reduce`, `any`, `all`, `find`, `position`, `min`, `max`, `min_by`,
|
||||
`max_by`, `min_by_key`, `max_by_key`, `last`, `nth`, `for_each`, `to_vector` and
|
||||
`into`. Their tests, orders and keys are anything `invokable` (README, "Control
|
||||
flow"), and `rev()` walks a view from its far end.
|
||||
- **`min`, `max` and `clamp`,** in `std::math` (std/math/exact.sakura), for every ordered
|
||||
type. Of reals, `min` and `max` give NaN where either is NaN, and put `-0` below `0`.
|
||||
- **`invokable<def(...): R>` and `signature`,** in `std/traits`. Functions, lambdas and
|
||||
addresses of C functions meet `invokable` through an `invoke` the compiler gives them.
|
||||
A value of any other type is called through its own `invoke`, so `f(x)` works on all of
|
||||
them. A lambda leaving out its types takes them from an `invokable` bound.
|
||||
`function<S>` (std/functions/function.sakura) holds any callable.
|
||||
- **No** `swap`, `reverse`, `fill` of a slice, `is_sorted`, sort by a key, sort that
|
||||
allocates nothing, or heap by an order given.
|
||||
|
||||
## What it needs
|
||||
|
||||
Of the ten needs this plan began with, std meets bisection, the tests over a run,
|
||||
grouping, a heap, `min`, `max` and `clamp`, and owning elements sorted and moved. It
|
||||
sorts stably. What's left:
|
||||
|
||||
1. **Sorting by a key,** and **sorting in place without allocating** where equal
|
||||
elements may move.
|
||||
2. **Orders and tests of every kind** for `sort_by` and `partition_point`, as the
|
||||
iterators take them: functions, lambdas, and functors holding what they need.
|
||||
3. **Changing a run:** swapping, reversing and filling, and, for vectors, taking the
|
||||
last out, keeping only some, and dropping repeats.
|
||||
4. **`is_sorted`,** to check a run's order.
|
||||
5. **As fast as code written out,** so the compiler loses nothing by using them.
|
||||
|
||||
## How it fits the rules
|
||||
|
||||
- **Elements are moved, never copied,** except where a type copies freely.
|
||||
- `swap` copies plain data through a held value, and swaps the bytes of anything that
|
||||
closes, so nothing is closed twice, as `heap`'s private `swap` does.
|
||||
- Sorting and reversing move elements only by `swap`, or byte for byte as std's sort
|
||||
does, so they work on strings and other owning values.
|
||||
- `fill` copies, as `resize(size, fill)` does, so it needs `copyable` or plain data.
|
||||
- **Nothing allocates** but the stable sorts, which take a buffer as `sort` does now,
|
||||
and `groups`, which is a container.
|
||||
- **Tests, orders and keys are anything `invokable` (decision 1):** a function, a
|
||||
lambda, or a functor, or `&mut` one.
|
||||
- Each is taken by value, as a function value is. A functor is copied in, or moved in
|
||||
where it owns something.
|
||||
- `&mut f` lends a functor instead, so the caller keeps it and sees what it changed.
|
||||
- An algorithm is compiled for each functor's type, so a functor's `invoke` is a
|
||||
direct call.
|
||||
- **Orders come three ways:**
|
||||
- through `ordered`, where `<` is inlined: `sort`;
|
||||
- through anything invokable as `def(&T, &T): bool`: `sort_by`;
|
||||
- through a key it gives: `sort_by_key`.
|
||||
|
||||
One sorting core serves all three, generic over its order, as `sort_elements` is now.
|
||||
`sort` gives it `by_order::<T>{}`, `sort_by` the order given, and `sort_by_key` a
|
||||
`by_key` holding the key's function. They take the place of the private
|
||||
`sort_order<T>`, `natural_order<T>` and `given_order<T>`.
|
||||
- **Bounds:** `where`, on free functions, on a method's own type parameters, as `F` and
|
||||
`K` of `sort_by_key<F, K>`, on a struct, as `by_order` and `by_key`, and on a type's own
|
||||
parameters at a method, as `def span<T>::is_sorted(&this): bool where T: ordered`. The
|
||||
compiler takes all four now. A guard of `if const` and `compile_error` still serves
|
||||
where a message of its own reads better, as std's sort has one.
|
||||
- **Nothing fails:** a bisection gives a position, and what may find nothing gives a
|
||||
`maybe`.
|
||||
|
||||
## The API (decisions 1, 2, 3 and 5)
|
||||
|
||||
What's there stays as it is: `sort`, `lower_bound`, `upper_bound`, `heap`, `groups`,
|
||||
`runs`, the iterators' consumers, and `std::math`'s `min`, `max` and `clamp`. This adds:
|
||||
|
||||
```sakura
|
||||
module std;
|
||||
|
||||
# Two values.
|
||||
pub def swap<T>(a: &mut T, b: &mut T): void; # moves both, copying nothing that closes
|
||||
|
||||
# Orders, which the sorts take as they take any other.
|
||||
pub struct by_order<T> : invokable<def(&T, &T): bool> where T: ordered {} # `<`
|
||||
pub struct by_key<T, F, K> : invokable<def(&T, &T): bool>
|
||||
where F: invokable<def(&T): K> where K: ordered { pub var key_of: F; } # `<` of the keys
|
||||
|
||||
# Reading a run: the tests, counts, least and greatest are the iterators' consumers,
|
||||
# as `v.iter().any(test)` (decision 3).
|
||||
pub def span<T>::is_sorted(&this): bool where T: ordered;
|
||||
|
||||
# In a sorted run: `partition_point` takes anything invokable, where it takes
|
||||
# `def(&T): bool` now (decision 1).
|
||||
pub def span<T>::partition_point<F>(&this, held: F): u64 # the first that fails
|
||||
where F: invokable<def(&T): bool>;
|
||||
|
||||
# Changing a run where it is: methods of slice<T>, and of vector<T> as `sort` is.
|
||||
pub def slice<T>::sort_by<F>(&mut this, before: F): void # stable, as now (decision 1)
|
||||
where F: invokable<def(&T, &T): bool>;
|
||||
pub def slice<T>::sort_by_key<F, K>(&mut this, key_of: F): void # stable
|
||||
where F: invokable<def(&T): K> where K: ordered;
|
||||
pub def slice<T>::sort_unstable(&mut this): void where T: ordered; # decision 2; also
|
||||
# `_by` and `_by_key`
|
||||
pub def slice<T>::reverse(&mut this): void;
|
||||
pub def slice<T>::fill(&mut this, value: T): void;
|
||||
pub def slice<T>::swap(&mut this, i: u64, j: u64): void;
|
||||
|
||||
# Vectors (decision 5).
|
||||
pub def vector<T>::take_last(&mut this): maybe<T>; # moved out; `truncate()` closes it
|
||||
pub def vector<T>::retain<F>(&mut this, keep: F): void # in order; closes the rest
|
||||
where F: invokable<def(&T): bool>;
|
||||
pub def vector<T>::dedup(&mut this): void where T: equatable; # equal neighbours
|
||||
```
|
||||
|
||||
`sort_by_key` takes its buffer as `sort` does, from the program's heap.
|
||||
|
||||
```sakura
|
||||
names.sort(); # strings are ordered
|
||||
entries.sort_by_key(def(e) => e.size); # equal sizes keep their order
|
||||
views.sort_by(def(a, b) => a.compare(b) < 0); # views aren't ordered
|
||||
|
||||
# A lambda refers to `wanted` where it is, and allocates nothing.
|
||||
val slot := this.free.span.iter().position(def(c) => c.size == wanted) else { return made(); };
|
||||
|
||||
# A functor holds what it tests against, and is called directly. A view's iterator
|
||||
# gives `&block`, so its test takes `& &block`.
|
||||
struct sized : invokable<def(& &block): bool> { var wanted: u64; }
|
||||
def sized::invoke(&this, c: & &block): bool { return c.size == this.wanted; }
|
||||
|
||||
val slot := this.free.span.iter().position(sized{ wanted = wanted }) else { return made(); };
|
||||
|
||||
# Lent as `&mut`, a functor keeps what it saw, once `sort_by` takes one (decision 1).
|
||||
struct counting_order : invokable<def(&u64, &u64): bool> { var comparisons: u64; }
|
||||
def counting_order::invoke(&mut this, a: &u64, b: &u64): bool {
|
||||
this.comparisons++;
|
||||
return a < b;
|
||||
}
|
||||
|
||||
var asked := counting_order{};
|
||||
words.sort_by(&mut asked);
|
||||
println($"{asked.comparisons} comparisons");
|
||||
|
||||
deepest = math::max(inner, deepest);
|
||||
while todo.take_last() is some(at) {
|
||||
# ...
|
||||
}
|
||||
```
|
||||
|
||||
The two `position`s, `names.sort()`, `views.sort_by` and `math::max` work today.
|
||||
Probed.
|
||||
|
||||
## How each part works
|
||||
|
||||
- **`sort_unstable`** is introsort (decision 2):
|
||||
- quicksort with the median of three;
|
||||
- insertion sort for runs of 16 or fewer;
|
||||
- heap sort once the depth passes 2·log₂ n, so it's never quadratic.
|
||||
|
||||
It's in place, allocates nothing, and isn't stable. Probed: 0.13 s against `sort`'s
|
||||
0.19 s for a million words.
|
||||
- **One core, three orders, for each sort:**
|
||||
- `sort`, `sort_by` and `sort_by_key` call one core, generic over its order
|
||||
`F: invokable<def(&T, &T): bool>` and compiled for each order's type. std's merge
|
||||
core is generic that way now, over its private trait.
|
||||
- `by_order<T>`'s `invoke` is `<`, a direct call inlined at `-O2`, so sorting numbers
|
||||
costs no more than written-out code. A functor's order is as cheap.
|
||||
- A function value or a lambda costs an indirect call per comparison, as through
|
||||
`given_order` now: 0.26 s against 0.19 s. Every function value of a signature shares
|
||||
one instance of the core, so not even a named function's order is inlined into it.
|
||||
- **`sort_by_key`** is the stable merge sort through `by_key`, which compares the keys
|
||||
its function gives. A functor's key cost 0.15 s against `<`'s 0.14 s on 2026-10-09.
|
||||
- **`partition_point`** is the bisection there now, taking `F` rather than a function
|
||||
type. The compiler's calls of it give lambdas, which still work.
|
||||
- **`is_sorted`** compares each element with the one before.
|
||||
- **`reverse`** swaps from both ends inward. **`fill`** copies its value into each
|
||||
element, closing what was there. A slice's **`swap`** swaps two of its elements as the
|
||||
free `swap` does.
|
||||
- **`take_last`** moves the last element out and shortens the vector, giving `none`
|
||||
where it's empty.
|
||||
- **`retain`** moves the kept elements down in one pass and closes the rest. Calling
|
||||
`remove_at` in a loop shifts the tail for every removal.
|
||||
- **`dedup`** keeps the first of each run of equal neighbours and closes the rest, in
|
||||
one pass.
|
||||
- **Tests, orders and keys:**
|
||||
- A functor is cheap: the functor search ran as fast as `span::contains`. A named
|
||||
function or a lambda referring to nothing is as cheap, where the algorithm is
|
||||
inlined.
|
||||
- A lambda referring to locals allocates nothing, but is called through its value:
|
||||
0.44 s against 0.19 s for the same search by a functor. That's fine outside hot
|
||||
loops.
|
||||
- Decision 4 is whether the compiler learns to call that lambda directly too.
|
||||
|
||||
## What the compiler gains
|
||||
|
||||
These counts come from the compiler as it stands on 2026-10-20: about 72,700 lines in
|
||||
`analyzer/`, `compiler/`, `machine/`, `native/` and `entry.sakura`, where there were
|
||||
about 49,000 on 2026-10-08.
|
||||
|
||||
**Moved onto std on 2026-10-19,** apart from this plan:
|
||||
|
||||
| Written by hand on 2026-10-08 | Sites then | Now |
|
||||
|---|---|---|
|
||||
| A heap sort of words with keys packed in, as `key << 32 \| item` | 5 calls, 2 copies of the sort | `sort` at 7 sites, `sort_by` at 3 and one more in `server/`, `heap`, and `groups` |
|
||||
| Pack, sort, count, sum and scatter into a `*_first` array | 2: live-ins and gap moves | `groups` |
|
||||
| Count, sum and fill, in two passes | 4 more | `groups` and `runs` |
|
||||
| Loops from one `_first` entry to the next | at least 9 | `groups::of` and `runs::view` |
|
||||
| Bisection | 5 | `lower_bound`, `upper_bound` and `partition_point`, at 10 sites |
|
||||
| A binary heap | 1 | `heap<u64>`, of a start and an interval packed as a pair's key |
|
||||
| A loop filling a vector after `resize` | 12 | `resize(size, fill)`, at 34 sites |
|
||||
| A loop appending another run's elements | 6 | `extend`, at 81 sites |
|
||||
|
||||
Seven `*_first` arrays are left, as `child_first`, `edge_first` and `row_first`. Some
|
||||
index several vectors at once, as `child_first` does `child_starts`, `child_ends` and
|
||||
`child_locs`, which neither `groups` nor `runs` holds.
|
||||
|
||||
**Still by hand:**
|
||||
|
||||
| Written by hand now | Sites | Becomes |
|
||||
|---|---|---|
|
||||
| `a < b ? a : b`, and the like | 38 | `math::min`, `max`, `clamp` |
|
||||
| `val at: u32 = todo.last;`, then `todo.truncate();` | 29 | `take_last` |
|
||||
| A loop filling a vector or array where it is | 6 | `fill` |
|
||||
| Reversing | 1, in `code::reverse_postorder` | `reverse` |
|
||||
| Searches by hand, as in the emitter's cells | several | `iter().any`, `position`, `index_of` |
|
||||
|
||||
**Before and after.** The grouping and the bisection this section showed on 2026-10-08
|
||||
are done: `native/registers.sakura` counts, seals and puts the live-ins with `groups`,
|
||||
and `analyzer/syntax.sakura` finds a declaration's first documentation line with
|
||||
`partition_point`. What's left:
|
||||
|
||||
```sakura
|
||||
# compiler/flows.sakura, and 28 more.
|
||||
while todo.length != 0 {
|
||||
val at: u32 = todo.last;
|
||||
todo.truncate();
|
||||
|
||||
# After.
|
||||
while todo.take_last() is some(at) {
|
||||
```
|
||||
|
||||
```sakura
|
||||
# compiler/emitter.sakura: whether a statement still closes a cell.
|
||||
var kept := false;
|
||||
for &each in this.kept {
|
||||
kept = kept || each.cell == cell + 1;
|
||||
}
|
||||
|
||||
# After. The lambda refers to `cell` where it is and allocates nothing, but is called
|
||||
# through its value unless decision 4(b) is built.
|
||||
val kept := this.kept.iter().any(def(each) => each.cell == cell + 1);
|
||||
|
||||
# Or, where it's hot, a functor, which costs what `span::contains` does.
|
||||
struct closes_cell : invokable<def(& &kept_value): bool> { var cell: u32; }
|
||||
def closes_cell::invoke(&this, each: & &kept_value): bool { return each.cell == this.cell; }
|
||||
|
||||
val kept := this.kept.span.iter().any(closes_cell{ cell = cell + 1 });
|
||||
```
|
||||
|
||||
```sakura
|
||||
# analyzer/checker/generics.sakura: the deepest nesting of a type's parts.
|
||||
deepest = inner > deepest ? inner : deepest;
|
||||
|
||||
# After, with `import std::math`, which the compiler's sources don't import today.
|
||||
deepest = math::max(inner, deepest);
|
||||
```
|
||||
|
||||
```sakura
|
||||
# compiler/intermediate/verifier.sakura: postorder turned round.
|
||||
val length := order.length;
|
||||
for i in 0..length / 2 {
|
||||
val other := length - 1 - i;
|
||||
val held: u32 = order[i];
|
||||
order[i] = order[other];
|
||||
order[other] = held;
|
||||
}
|
||||
|
||||
# After.
|
||||
order.slice.reverse();
|
||||
```
|
||||
|
||||
**Speed:**
|
||||
- **Sorting** became faster where `sort_words` was used: std's `sort` takes 0.19 s for
|
||||
a million words, where `sort_words` took 0.30–0.35 s on 2026-10-08.
|
||||
`sort_unstable` would take 0.13 s.
|
||||
- **The two pack-and-sort groupings** became linear with `groups`.
|
||||
- **Pops, `min` and `reverse`** cost what they cost now.
|
||||
- **Loops over a vector** that become `any`, `position` or `count` run a little faster
|
||||
given a functor, 0.19 s against 0.26 s for `for &each in v`. Given a lambda referring
|
||||
to locals they run slower, 0.44 s, unless decision 4(b) is built.
|
||||
|
||||
What's left hasn't been measured on a self-build. Phase 4 measures it, and keeps only
|
||||
the changes that don't slow it.
|
||||
|
||||
## Lambdas for `invokable` parameters (phase 0, built)
|
||||
|
||||
Built with the iterators on 2026-10-19, as this section planned (README, "Functions"):
|
||||
- a lambda leaving out its types takes them from a type parameter's
|
||||
`invokable<def(A...): R>` bound, with the type parameters inferred so far put in, and
|
||||
one in the result not yet known, as `K` of a key, inferred from the lambda's result;
|
||||
- the compiler infers a type parameter from a lambda;
|
||||
- a type parameter bounded only by `signature` still needs the lambda's types written.
|
||||
|
||||
Overloads take no part: the compiler doesn't give a lambda its types from the bound of
|
||||
an overloaded function (see Found).
|
||||
|
||||
## Lambdas that refer to locals (decision 4)
|
||||
|
||||
The memory work of 2026-10-19 built half of what this section planned. A lambda refers
|
||||
to the locals it uses where they are, through an environment that is a cell of the
|
||||
frame, so nothing moves to the heap and a lambda never allocates (README, "Functions").
|
||||
The search it took 3.23 s for on 2026-10-09 takes 0.44 s.
|
||||
|
||||
What's left is the call. The compiler's `devirtualize` turns a `call_value` whose
|
||||
function is a known constant into a direct `call`, but leaves one taking an
|
||||
environment called through the value. So a lambda referring to locals isn't inlined
|
||||
into the loop calling it, and costs 2.3 times a functor: 0.44 s against 0.19 s.
|
||||
Decision 4 is whether that call should be direct too:
|
||||
|
||||
- **(a) Leave it.** A test that refers to locals in a hot loop is written as a functor,
|
||||
and as a lambda elsewhere. Phase 4's measurements say where it's hot.
|
||||
- **(b) Call a known lambda directly, environment and all.** `devirtualize` learns
|
||||
closures: the call becomes a direct `call` given the environment. Once `any` is
|
||||
inlined, the lambda is called directly, may be inlined in turn, and `promote` can then
|
||||
make the locals it refers to plain values.
|
||||
- It helps only where the algorithm is inlined into the code making the lambda, as
|
||||
`any` and `position` are. A sort's core isn't, and calls each order through the
|
||||
value, whatever this decides.
|
||||
- What a program means doesn't change, only how a call is made.
|
||||
- It's smaller than the 150 lines planned on 2026-10-09, which included the frame
|
||||
half, now built. It hasn't been estimated again.
|
||||
- The 0.44 s case should come near the 0.19 s functor. That's the phase's measure.
|
||||
|
||||
Only a type for each lambda would inline a lambda's order into a sort. That's a change
|
||||
to the language, which the memory work left open, and isn't proposed here.
|
||||
|
||||
## Testing
|
||||
|
||||
- **`test/std/algorithms.sakura`, written with `std::testing`,** beside
|
||||
`test/std/containers.sakura`, which tests std's sort, heap, runs and groups now,
|
||||
covers:
|
||||
- **sorting,** by `sort_unstable`, `sort_by` and `sort_by_key`:
|
||||
- inputs of every length from 0 to 40, and of 1,000 and 100,000 elements;
|
||||
- random, sorted, reversed, all equal, and organ-pipe orders;
|
||||
- an input that defeats the median of three, to drive heap sort;
|
||||
- checked by `is_sorted`, and against a count of each element;
|
||||
- **stability** of `sort_by` and `sort_by_key`;
|
||||
- **owning elements:** strings sorted, reversed, retained and taken out, each closed
|
||||
exactly once, counted as the containers' tests count closes;
|
||||
- **tests, orders and keys** given as named functions, lambdas with and without their
|
||||
types, functors taking `&this` or `&mut this`, and functors lent as `&mut`, whose
|
||||
state the caller reads after;
|
||||
- **`partition_point`** given a functor, in empty runs, below and above every
|
||||
element, and among repeats;
|
||||
- **the rest:** `retain` closing what it drops, `dedup`, `fill`, `reverse` of odd and
|
||||
even lengths, `take_last` of an empty vector, and `swap`.
|
||||
- **Where they run:** in the machine, as executables at `-O0` and `-O2`, and under
|
||||
`run --checks`, which stops at a dangling reference or a block released twice, and
|
||||
lists what leaked.
|
||||
- **Direct calls of lambdas (phase 3, if decision 4(b)):** a test of the intermediate
|
||||
code showing a direct `call` of a lambda given to `any`, and the probe's loop timed.
|
||||
- **The compiler moved onto them (phase 4),** after each file:
|
||||
- stage 2 equals stage 3;
|
||||
- the corpus passes at every level;
|
||||
- the compiler's and std's tests pass;
|
||||
- the self-build's instructions are measured against before.
|
||||
|
||||
## Phases
|
||||
|
||||
About 350 lines of std and 300 of tests, judged by the size of std's sort and
|
||||
containers. Decision 4(b) adds to the optimizer only. Moving the compiler onto what's left removes
|
||||
few lines, about 50: it reads better rather than shrinks.
|
||||
|
||||
0. **Lambdas for `invokable` parameters:** built with the iterators, 2026-10-19.
|
||||
1. **`swap`, `by_order` and `by_key`;** `sort_by` and `partition_point` taking `F`
|
||||
(decision 1), `sort_by_key` and `is_sorted`; the slice's `reverse`, `fill` and
|
||||
`swap`; and `strview` becoming `ordered`.
|
||||
2. **The vector methods** (decision 5), and **`sort_unstable`** (decision 2).
|
||||
3. **Direct calls of lambdas,** if decision 4 is (b).
|
||||
4. **The compiler moved onto them,** file by file: the pops, `min` and `max`, the
|
||||
fills and the reverse, and searches, with functors where a test refers to locals in a
|
||||
hot loop. The sorts, the heap, the groupings and the bisections moved on 2026-10-19.
|
||||
5. **The README:** sorting and bisection, which it doesn't mention today, beside the
|
||||
containers in "Variables and types", and the new methods.
|
||||
|
||||
## Later, where wanted
|
||||
|
||||
- **Runs already in order,** sorted in linear time: pdqsort for `sort_unstable`, or a
|
||||
merge sort that finds the runs it's given, for `sort`. The compiler often sorts what's
|
||||
nearly in order, such as blocks in layout order.
|
||||
- **Order adaptors,** as `reversed<F>`, which gives a descending sort from any order.
|
||||
- **A heap by an order given.** The register allocator packs a start and an interval
|
||||
into a `u64` so `heap<u64>` orders them by `<`.
|
||||
- **`groups` from a key function in one call,** as `groups::by_key(items, keys, key_of)`,
|
||||
which counts, seals and puts.
|
||||
- **A sort's buffer from an allocator given,** so the compiler's sorts, whose vectors
|
||||
are in its scratch arena, take their buffers from it too.
|
||||
- **Merging and intersecting sorted runs.** The register allocator's `intersection` is
|
||||
one.
|
||||
- **A bit set,** for the 56 places the compiler makes a `vector<bool>`.
|
||||
- **Selection,** as `nth_element`, and parallel sorting, now that `std::thread` exists.
|
||||
|
||||
Built elsewhere since: **lazy adaptors,** as `map`, `filter`, `enumerate` and `zip`,
|
||||
with the iterators on 2026-10-19, generic over their functions through `invokable`.
|
||||
|
||||
## Decisions for you
|
||||
|
||||
What was built since settled four of the eight decisions of 2026-10-09:
|
||||
- **Where it lives:** module `std`, beside the containers, in
|
||||
`std/containers/sort.sakura`, `heap.sakura`, `groups.sakura` and `runs.sakura`.
|
||||
- **How they're spelled:** methods of `span`, `slice` and `vector`, as `v.sort()` and
|
||||
`v.span.lower_bound(&x)`. The compiler takes `where` at a method now, so the
|
||||
`if const` guards are a choice, not a need.
|
||||
- **Grouping:** `groups<T>`, filled in two passes by `count`, `seal` and `put`, with
|
||||
`runs<T>` for lists built one at a time. `seal` does what `prefix_sums` would have.
|
||||
- **`min` and `max`:** in `std::math`, for every ordered type, with IEEE 754's rule for
|
||||
reals.
|
||||
|
||||
The decisions on how orders are given and what a test is are one now, the first below.
|
||||
The rest are left:
|
||||
|
||||
1. **What an order or a test is, for `sort_by` and `partition_point`:**
|
||||
- **(a) Anything `invokable`, with `sort_by_key` beside them (recommended),** as the
|
||||
iterators' adapters and consumers take them. A functor is called directly, `&mut`
|
||||
lends one, and a lambda still leaves out its types, so no caller changes. The
|
||||
private `sort_order<T>` goes.
|
||||
- **(b) Function types, as now,** with `sort_by_key` taking `def(&T): K`. A functor
|
||||
is given as a lambda calling it, which is called through its value.
|
||||
- **(c) Both, as overloads.** Each is declared twice.
|
||||
2. **A sort that allocates nothing:**
|
||||
- **(a) `sort_unstable`, an introsort, beside the stable `sort` (recommended).** It
|
||||
takes 0.13 s against `sort`'s 0.19 s for a million words, and no buffer. All seven
|
||||
of the compiler's `sort`s are of `u64` words, where equal ones can't be told apart,
|
||||
so stability buys them nothing.
|
||||
- **(b) Only the stable `sort`,** as now, and its buffer.
|
||||
3. **Tests over a run:**
|
||||
- **(a) The iterators' consumers, as `v.iter().any(test)` (recommended).** There's
|
||||
one of each, and views take no more names. A functor for a view's iterator takes
|
||||
`& &T`.
|
||||
- **(b) Also methods of `span`:** `any`, `all`, `count`, `position`,
|
||||
`last_position`, `least` and `least_by_key`, as this plan had them, taking tests of
|
||||
`&T`. They read shorter and take a functor of `&T`, but repeat the consumers.
|
||||
4. **Lambdas that refer to locals:**
|
||||
- **(a) Leave them called through their value, and write a test that refers to
|
||||
locals in a hot loop as a functor (recommended).** A lambda no longer allocates,
|
||||
so it costs 2.3 times a functor, not 36 times. Direct calls can follow if phase 4
|
||||
shows lambdas costing where a functor would read badly.
|
||||
- **(b) Also call a known lambda directly, environment and all.** Lambdas then cost
|
||||
about what functors do, where the algorithm is inlined. It's in the optimizer only.
|
||||
5. **The vector methods:**
|
||||
- **(a) `take_last`, `retain` and `dedup` (recommended).** The compiler pops by hand
|
||||
29 times, and taking an owning element out needs a `move` of it before
|
||||
`truncate()` closes what's left. `pop` stays the name of removing without giving
|
||||
back, as the stack, queue and heap have it.
|
||||
- **(b) The same, with the first named `pop`,** giving a `maybe<T>`, and the `pop`s
|
||||
of `stack`, `queue` and `heap` changed to match.
|
||||
- **(c) None,** keeping `vector` as it is.
|
||||
@@ -0,0 +1,176 @@
|
||||
# The analyzer reworked
|
||||
|
||||
Asked on 2026-10-29: build every change of "If we were to rewrite the analyzer" (the answer
|
||||
of 2026-10-28), in stages, each leaving the compiler building itself and every suite passing.
|
||||
|
||||
The measure throughout is the compiler checking the sources of the commit 0575609 (the
|
||||
squashed one), best of five on CPU 2, as `measure.sh` takes it. The baseline is that
|
||||
commit's compiler built by itself: 0.312 s, 49.7 MB resident, 1,462M instructions, 549M
|
||||
cycles, 9,853,928 bytes. (Until stage 3 the measure was taken on the commit before it,
|
||||
which has an error the old checker let through, `&mut` of a `val` in an argument, and a
|
||||
checker that reports it skips evaluating, so its numbers are not comparable.)
|
||||
|
||||
The profile of the same run, by inclusive share of 1.50 billion instructions:
|
||||
|
||||
| Part | Share |
|
||||
|---|---|
|
||||
| Reading files: lexing, parsing, finding modules | 24.5% (finding modules on disk 5.6%) |
|
||||
| Checking declarations | 42.5% (the lifetime walk within it 8.9%) |
|
||||
| Checking instances of generics again | 12.3% |
|
||||
| Evaluating after checking | 7.7% |
|
||||
| Declaring, linking, signatures | 4.7% |
|
||||
|
||||
## Each stage is done when
|
||||
|
||||
- the compiler built by the last stage's builds itself twice alike (`build.sh`);
|
||||
- the corpus runs alike natively at -O1 and -O2 against the baseline, and `check` says the same of
|
||||
every corpus program, but where the stage means it to differ, said here (`validate.sh`);
|
||||
- the blossom suites of sakurac, std (but its known failure), linear and ecs pass;
|
||||
- it's measured, and what it left is in later.md.
|
||||
|
||||
## The stages
|
||||
|
||||
1. **Modules from an index.** The resolver lists each library's folders once and finds
|
||||
modules in memory, not by asking the disk. A file whose first declaration is a `when`
|
||||
section of another target is not parsed.
|
||||
2. **Lifetimes from the checking walk.** The checker records what the lifetime warnings
|
||||
need as it checks a body; the warnings come from that record, not a second walk.
|
||||
3. **Overloads chosen without checking each.** Each argument is checked once, into what
|
||||
choosing needs; each candidate is scored by a function that writes no result and makes
|
||||
no note; the one chosen is applied once. `mute`, `dropped` and `uninferred` go.
|
||||
4. **Node accessors from the shapes.** Each kind's slots are read by accessors that the
|
||||
shapes table describes, rather than by `extras[lefts[n] + slot]`.
|
||||
5. **IDs of their own types.** Declarations, types, nodes, names, tables and instances
|
||||
each have an ID type of their own, an enum of `u32`, which the checker refuses where
|
||||
another is wanted; every table keeps entry 0 for none, so nothing is stored as one more
|
||||
than an index; what keys on a file's node takes one `place`.
|
||||
6. **Checking on demand.** A declaration's signature, a body, a type's members and a
|
||||
constant's value are each worked out when first asked for, once. What's checked whole is
|
||||
the program's own files; a library's declarations are checked when reached.
|
||||
7. **Results by declaration.** Each top-level declaration has a result table of its own, so
|
||||
an edit drops the tables of what it changed and nothing else moves; checking again is
|
||||
asking again for what an edit made stale.
|
||||
8. **One evaluator, while checking.** The analyzer asks the program's evaluator, the
|
||||
machine, for a value when it needs one; the checker's own evaluator goes, and so does
|
||||
holding `compile_error` for later. An `if const` is decided when it's reached, so a
|
||||
branch not taken is not checked, as where its condition folds now.
|
||||
9. **One kind of compile-time value.** `constant` becomes a kind of `known`.
|
||||
10. **Instances check what depends on their arguments.** Checking a template marks each node
|
||||
whose results depend on its type parameters; an instance checks those, and reads the
|
||||
rest from the template's results.
|
||||
11. **Rows only for nodes with results.** A result table holds rows for the nodes that can
|
||||
have results, numbered by the parser.
|
||||
12. **Library bodies parsed when reached.** A library's function bodies are skipped at their
|
||||
braces and parsed when checking first asks for them.
|
||||
13. **Notes as data.** A note holds what it's about, as IDs, and its text is made when it's
|
||||
shown.
|
||||
14. **Bodies checked on threads.** Once the signatures a body needs are worked out, bodies
|
||||
are checked on several threads, each with its own place in checking, and what they
|
||||
work out is made the same whatever the threads' order, so a build is still the same
|
||||
every time.
|
||||
|
||||
## Status
|
||||
|
||||
| Stage | State | Instructions after |
|
||||
|---|---|---|
|
||||
| 1 | Built, validated | 1,445M (−1.4%) |
|
||||
| 2 | Built, validated | 1,332M (−7.8%) |
|
||||
| 3 | Built, validated | 1,327M (−0.4%) |
|
||||
| 4 | Built | 1,327M |
|
||||
| 5 | Built, validated | 1,332M; 506M cycles, 47.8 MB |
|
||||
| 6 | Built, validated | 1,277M; a corpus program 116M → 77M |
|
||||
| 7 | Built, validated | 1,278M |
|
||||
| 8 | Built, validated | 1,270M; 92 KB smaller |
|
||||
| 9 | Built, validated | 1,271M |
|
||||
| 10 | Built, measured, taken out | — |
|
||||
| 11 | Built, measured, taken out | — |
|
||||
| 12 | Reading built, bodies not | 1,261M; 482M cycles; a corpus program 77M → 67M |
|
||||
| 13 | Not built | — |
|
||||
| 14 | Not built | — |
|
||||
|
||||
What the stages built that differs from what they said:
|
||||
|
||||
- **3:** muting is gone from choosing overloads: an argument that may need its
|
||||
parameter's type is checked once, and waits only where its call's one overload wants a
|
||||
type argument nothing gave, and `path_waits` keeps what it found for checking the path
|
||||
later. `bounds_met` asks without reporting, and `dropped` and `uninferred`, which read
|
||||
the text of notes, are gone. One rule stays, `quiet`, for what is checked for its
|
||||
results alone: a type written for `this`, an attribute's type as reflection reads it,
|
||||
a template's branch where `if const` names what a parameter is, and an editor's query.
|
||||
It fixed a checker that let an error through: what was wrong within an argument that
|
||||
waited, as an undefined name in `take::<i32>(make(nope))`, was never reported, and the
|
||||
compiler then failed lowering it.
|
||||
- **5:** an enum can't be an ID type, since a value cast to an enum must be one of its
|
||||
members, and a struct of one `u32` is kept in memory, not a register, so IDs of their
|
||||
own types would slow the checker. Nodes of files and of tables are told apart instead:
|
||||
`file_node` and `table_node`, and `keyed<K>` maps that take no bare node. Instances,
|
||||
tables, bindings, and constants keep entry 0 for none; a struct's traits are marked
|
||||
worked out by a flag, so their run is held as it is.
|
||||
- **6:** every declaration's signature is still resolved first, since much of checking
|
||||
reads what a declaration is without asking (a field of `maybe` read unresolved gave
|
||||
a binding no value, and a range of an enum printed nothing); what is checked on
|
||||
demand is bodies and values. A declaration is reached where `depend` first records
|
||||
it, and a named type depends on its declaration; a struct reaches its fields, whose
|
||||
defaults a value of it takes. The compiler checks late what only it reaches, as the
|
||||
runtime's helpers, under the guard instance checking had, and lowers only checked
|
||||
globals; `system::dispatch` is reached with `system::handle`.
|
||||
|
||||
- **7:** as designed below, a table for an edit's nodes and the file's tables found by
|
||||
halving; per declaration tables were not needed for an edit to move nothing.
|
||||
- **8:** as designed below. Evaluating found two more of the old limits gone: a local
|
||||
constant reads another, or a struct's field, through its own evaluation, and an
|
||||
`if const` in an instance decides what follows it. A call written as a constant
|
||||
type argument is still refused, as before; a constant a call gives works there.
|
||||
- **9:** as said: a value is a `known` of its own kind, number or real, found again by
|
||||
`value_known` through an index of its own; the constants table is gone.
|
||||
- **10:** built and measured, then taken out. Of the compiler's templates, 21% of the
|
||||
top-level statements, which hold 53% of their nodes, depend on no type parameter. An
|
||||
instance reading those from its template's table left lowering an instance recursing
|
||||
without end. What's left is in later.md.
|
||||
- **11:** built and measured, then taken out. Of the rows a file's table holds, 72% are
|
||||
of nodes with results checking the compiler, and 15% checking a corpus program, whose
|
||||
libraries are mostly not reached. Numbering only those nodes saved 1.5% of the
|
||||
instructions and no memory: the peak rose. What's left is in later.md.
|
||||
- **12:** what was built reads less, not later: entry reads in rounds, growing what it
|
||||
holds each round, with the reporting thread started once reading ends; and the resolver
|
||||
lists a folder without asking again whether the folder holding it lists it, and passes
|
||||
a file that isn't Sakura by its name. Bodies parsed when reached were not built. Of a
|
||||
corpus program's library bodies, those never reached are 59% of the tokens (19,529 of
|
||||
them in generic bodies, 15,680 in others), and of the compiler's 7%. A generic's
|
||||
instance table covers its template's nodes in one run, so its body must be parsed with
|
||||
it; the checker holds the syntax's columns by address while it checks, so nodes added
|
||||
while checking move them; and the resolver finds the modules a body names from its
|
||||
paths. Parsing the other bodies when reached would save at most about 4M of a corpus
|
||||
program's 67M, and under 1% of checking the compiler.
|
||||
- **13:** not built. The text made for notes left out is 0.01% of checking the compiler,
|
||||
so making it only when shown saves nothing measurable. A note
|
||||
of IDs whose text is made when shown would need the checker's tables where it's shown,
|
||||
but `sakurac` shows notes from another thread while checking goes on, so the text
|
||||
would still be made where the note is given. 85 notes write lists or numbers that a
|
||||
few IDs don't hold. Nothing reads a note's IDs yet: it waits for the server offering
|
||||
fixes.
|
||||
- **14:** not built. Checking bodies is 48% of checking the compiler, but it writes what
|
||||
every body shares: of the 14,391 types, 3,246 instances, 903 knowns and 4,300 tables
|
||||
checking the compiler makes, its bodies make 6,157 types, 3,241 instances, 291 knowns
|
||||
and 3,987 tables, and reach 8,195 of the 9,249 declarations checked. Their IDs reach
|
||||
what the compiler builds, so threads need those tables made the same in any order
|
||||
first, as by IDs given in declaration order after the bodies are checked. What's left
|
||||
is in later.md.
|
||||
|
||||
## Designs of the stages still to build
|
||||
|
||||
- **7:** an edit adds a table for the nodes it added, past the file's last, rather than
|
||||
a table for the whole file with what was kept copied into it; a file keeps its tables
|
||||
in order, and a node no table around one being written holds is found among them by
|
||||
halving, outside an instance. A file parsed whole again gets one table anew.
|
||||
- **8:** the machine makes one evaluator before checking, whose lowerer and interpreter
|
||||
live through it, and gives the checker a function asking it for a value. Asking
|
||||
checks what checking reached first, keeps `at`, lowers the evaluation and what it
|
||||
calls, loads what is new into the interpreter, and runs it. A constant's value is
|
||||
asked for where it is read and not known; a local constant, an array's length, a
|
||||
range's end, an `if const`'s condition, and `compile_error`'s text where checking
|
||||
reaches them. A program with errors is not run. Without an evaluator, what only
|
||||
running gives is not known, and an `if const` it would decide has both branches
|
||||
checked quietly. After checking, the evaluator works out what the compiler needs
|
||||
that nothing asked for. A declaration checked within another's body sees none of
|
||||
that body's bindings.
|
||||
@@ -0,0 +1,580 @@
|
||||
# Plan: benchmarks
|
||||
|
||||
Written 2026-10-18, and brought up to date 2026-10-20 for memory without a collector,
|
||||
fixtures lent by reference, callables taken through `invokable` bounds, and a second probe
|
||||
on Linux. This is a proposal. std is yours, so the decisions at the end are yours to make.
|
||||
Nothing is built yet.
|
||||
|
||||
**Comes after the ffi plan, now built:** `std::sys` is `system`, and `@foreign` and
|
||||
`@link` are `extern` sections.
|
||||
|
||||
**What it is:** measuring how long code takes, the way `std::testing` checks what it
|
||||
does:
|
||||
- functions marked `@bench`, which a runner finds and measures one after another;
|
||||
- a report of each, as a typical time a round and how much it varied;
|
||||
- saving what was measured, and comparing a later run with it;
|
||||
- `keep`, which stops the optimizer from taking away the work being measured.
|
||||
|
||||
**Its users:**
|
||||
- std's containers: `dict` against `hashset`, the interner, sorting, and `vector`
|
||||
growing. The abstraction and optimization work chose between these by timing by hand;
|
||||
- the compiler's hot spots that `docs/performance.md` names: hash tables, the lexer's
|
||||
cost a token, and allocation;
|
||||
- the optimizer: whether a pass makes code faster, at each `-O` level. The 2026-10-18
|
||||
passes were measured only by timing whole builds;
|
||||
- the probes in `tools/`, which time calls, iterators and memory by hand, and check a
|
||||
ratio between two ways of each;
|
||||
- JSON, YAML and regex throughput;
|
||||
- any program, comparing two ways of doing something.
|
||||
|
||||
**Probed:** twice, in the scratchpad:
|
||||
- on 2026-10-18 (`benchprobe/`), on Windows, as executables at `-O2` and `-O0`,
|
||||
and in the VM;
|
||||
- on 2026-10-20 (`plans/benchmarks/`), on Linux, the same, pinned to one P-core of an
|
||||
i5-13420H. Other work kept the machine busy, so its numbers come from the runs where
|
||||
it was quiet.
|
||||
|
||||
The probes covered:
|
||||
- **The steady clock,** which `instant::now()` reads:
|
||||
- On Windows, through `QueryPerformanceCounter`, its smallest step is 100 ns. A read
|
||||
took 30 ns in `-O2` executables, and 58 ns in `-O0` ones.
|
||||
- On Linux, `CLOCK_MONOTONIC` steps by 1 ns, but std makes a system call for each
|
||||
read. A read took 211 ns in `-O2` executables, and 293 ns in `-O0` ones. A C program
|
||||
reading the same clock through the vDSO, as glibc does, took 25 ns.
|
||||
- **What the optimizer takes away from a loop timed by hand,** in nanoseconds a round,
|
||||
the best of five runs of 20 million rounds, on Linux on 2026-10-20. The work is three
|
||||
multiplies and shifts, as a hash finishes a word:
|
||||
|
||||
| The loop | `-O2` | `-O0` |
|
||||
|---|---|---|
|
||||
| Empty | 0.24 | 0.38 |
|
||||
| A constant in, the result stored to a global | **0.32** | 3.64 |
|
||||
| A global read in, the result stored to a global | **0.27** | 3.70 |
|
||||
| The counter in, the result discarded | **0.24** | 3.61 |
|
||||
| The counter in, the result stored to a global | 1.79 | 3.65 |
|
||||
| The counter in, the results summed and printed | 1.96 | 3.85 |
|
||||
| In and out through a `@foreign def` that gives its argument back, the result stored | 1.79 | 7.75 |
|
||||
| The same, the result discarded | **0.24** | 7.32 |
|
||||
| In and out through relaxed atomics | 1.92 | 10.65 |
|
||||
| The work in a function value read from a global, called each round | 3.20 | 4.88 |
|
||||
|
||||
- The bold rows measured an empty loop. The compiler moves work on a constant or a
|
||||
global out of the loop.
|
||||
- The compiler drops a result that nothing reads, even through a `@foreign def` with a
|
||||
body, so going through one hides nothing.
|
||||
- Relaxed atomics keep the work. Three a round, a store and a load in and a store out,
|
||||
cost 0.1 ns over storing to a global.
|
||||
- The 2026-10-18 run on Windows found the same of a constant, a global, and a result
|
||||
discarded.
|
||||
- **A runner, written in a program of its own.** It found `@bench` functions through
|
||||
`declarations()` and `attached`, as `std::testing` finds tests. It doubled the rounds
|
||||
until a run took 1 ms, then took 51 runs as samples, each giving a time a round. Each
|
||||
benchmark took 2–3 ms to calibrate and 60–90 ms to sample. A relaxed atomic stood in
|
||||
for `keep`.
|
||||
- **Medians on Windows,** on 2026-10-18, over three runs of each executable and one in
|
||||
the VM:
|
||||
|
||||
| Benchmark | `-O2` | VM |
|
||||
|---|---|---|
|
||||
| `mixes`, the work above | 0.672–0.673 ns | 22.8 ns |
|
||||
| `inserts_1000`, into a new `dict` | 4.84–4.85 µs | 159 µs |
|
||||
| `formats`, interpolating two numbers | 54.10–54.12 ns | 173 ns |
|
||||
|
||||
The median absolute deviation was under 0.5% of the median in the executables.
|
||||
- **Medians on Linux,** on 2026-10-20, over three runs of each executable, and eight to
|
||||
ten of `links_100`:
|
||||
|
||||
| Benchmark | `-O2` |
|
||||
|---|---|
|
||||
| `mixes` | 1.92–1.93 ns |
|
||||
| `inserts_1000` | 35.3–36.0 µs |
|
||||
| `formats` | 172–173 ns |
|
||||
| `links_100`, a list of 100 `box`es made and closed | 4.63–4.73 µs, and twice 5.76 µs |
|
||||
|
||||
The median absolute deviation was under 1.4% of the median.
|
||||
- **Allocation no longer splits the samples.** On 2026-10-18, `links_100` made a list
|
||||
of 100 references from the collector each round. Its median was six times its
|
||||
fastest sample (3.05 µs and 0.51 µs), since most samples held a collection. With no
|
||||
collector, its fastest sample is within 1% of its median.
|
||||
- **A build, or a run, can be off as a whole:**
|
||||
- Code layout alone moved a result by 13%. `inserts_1000` took 4.85 µs in one `-O2`
|
||||
build on Windows, and 5.47 µs in a build that only added other benchmarks.
|
||||
- On Linux, one executable gave `links_100` medians of 4.63–4.73 µs in eight runs
|
||||
and 5.76 µs in two. Each run's own deviation was under 0.6%.
|
||||
- **Calibrating can stop early.** In one Linux run, `inserts_1000` stopped doubling at
|
||||
2 rounds, 75 µs a run, where every other run of the executable stopped at 32. One
|
||||
slow run while doubling is enough to stop it.
|
||||
- **Benchmarks in constants:** generic instances, as `@bench const views_u8 :=
|
||||
views::<u8>;`, worked. A closure in a constant, as
|
||||
`@bench const inserts_10 := def(b: &mut bencher): void { inserts(b, 10); };`,
|
||||
worked too.
|
||||
- **Fixtures, on 2026-10-20:**
|
||||
- A fixture that closes, given by value to a benchmark the runner calls many times, is
|
||||
refused: "`words` is closed where its scope ends, so it has one owner and is not
|
||||
copied out of the place holding it." A test runs once, so `std::testing` can give
|
||||
its fixture by value.
|
||||
- Lent as `&F` or `&mut F`, a fixture was made once, lent to every run, and closed
|
||||
once.
|
||||
- `type_of(params_of(d)[1])` gives only the reference, and nothing gives the type it
|
||||
refers to. Two overloads of a generic function, taking `def(&mut bencher, &F): void`
|
||||
and `def(&mut bencher, &mut F): void`, found `F` from the benchmark itself. A
|
||||
parameter that isn't a fixture gave the runner's `compile_error`.
|
||||
- `if const type_of(params_of(d)[1]) is fixture<type_of(params_of(d)[1])>` holds of a
|
||||
fixture taken by value and not of one lent, so the runner can refuse the first with a
|
||||
`compile_error` of its own.
|
||||
- **`batched` taking lambdas, on 2026-10-20:** with `make` and `work` bounded by
|
||||
`invokable`, the compiler took `b.batched(def() => shuffled(10000), def(v: &mut
|
||||
vector<u64>) { v.sort(); })`, and inferred `T` from the first lambda.
|
||||
- **Windows' CPU clocks:**
|
||||
- `GetThreadTimes` and `GetProcessTimes` step by 15.625 ms, so they can't time a
|
||||
1 ms sample.
|
||||
- `QueryThreadCycleTime` counts cycles exactly: 428.7 million in 100 ms busy, about
|
||||
4.29 GHz. But a cycle's length changes as the processor speeds up and slows down.
|
||||
|
||||
## What's there now
|
||||
|
||||
- **`std::testing`** (`std/testing.sakura`):
|
||||
- It finds `@test` functions and constants while compiling, through
|
||||
`declarations()`, `attached` and `value_of`. It tells their shapes apart with `if
|
||||
const value_of(d) is def(&mut tester): void` and `params_of`, and reports any other
|
||||
with `compile_error`.
|
||||
- It runs each test in a copy of the program: forked on Linux, started again with
|
||||
`SAKURA_TEST_ONE` on Windows.
|
||||
- It reads `--only TEXT` and `--here`.
|
||||
- It gives a test a fixture by value, after the tester, made by the fixture's
|
||||
`setup(t: &mut tester)`. The test runs once, and the fixture closes where the test
|
||||
returns, where it's a type that closes.
|
||||
- **`std::time`:**
|
||||
- `instant::now()` reads the steady clock: `QueryPerformanceCounter` on Windows, and
|
||||
`clock_gettime(CLOCK_MONOTONIC)` by a system call on Linux, not through the vDSO.
|
||||
- `instant - instant` and `elapsed()` give a `duration`, which counts whole
|
||||
nanoseconds in an `i64`. One divided by another is an `f64`, so `took /
|
||||
nanoseconds(1)` is the nanoseconds as a real.
|
||||
- `describe` writes one to two places, as "250ms".
|
||||
- **No CPU clock.** `sys::clock` reads only `clock_kind::wall` and `clock_kind::steady`.
|
||||
Nor does std pin a thread to a core: it reads the affinity only to count processors.
|
||||
- **Nothing that stops the optimizer.** The compiler has no `keep` or anything like it.
|
||||
As the probe found, a loop timed by hand at `-O2` can measure nothing at all.
|
||||
- **No collector, and no allocation counts.** Memory is owned, as the README's "Pointers
|
||||
and memory" says, so there are no collections for a benchmark to account for. Each
|
||||
block is taken from and given back to free lists as the program goes, and once the
|
||||
program starts a thread, through a cache of that thread's own. A program still can't
|
||||
ask how many blocks or bytes it allocated. `run --checks` knows every block, but only
|
||||
lists those never released, as the program ends.
|
||||
- **Benchmarks so far are probes timed by hand,** or scripts outside the language:
|
||||
- `tools/function.sakura`, `tools/iterators.sakura` and `tools/memory.sakura` each time
|
||||
one loop each way with `instant::now()`, keep the work by printing what it gave, and
|
||||
check a ratio: a functor held in a `function` costs what a function value does;
|
||||
adapters given functors are within 10% of `for &x in v`; a `box` costs within a
|
||||
tenth of `raw_allocate`. Each is built at `-O2` and run pinned to a core with
|
||||
`taskset`;
|
||||
- CPU-time medians of whole builds, and profiles of `build -g` compilers through
|
||||
`tools/profile/`;
|
||||
- hand-timed loops in a plan's probe, as the random plan's.
|
||||
|
||||
## What it needs
|
||||
|
||||
1. **Benchmarks marked and found as tests are,** with nothing in the compiler knowing
|
||||
about them, except `keep`.
|
||||
2. **A way to keep the work being measured** from being moved or taken away, at every
|
||||
`-O` level, that costs nothing itself.
|
||||
3. **Rounds sized to the clock:** enough per sample that Windows' 100 ns clock step, and
|
||||
a clock read of 30–58 ns there and about 210 ns on Linux, don't matter.
|
||||
4. **Statistics that ignore outliers:** a median, and how much the samples spread. An
|
||||
interrupt, a page fault, or another program's work makes a sample slower, never
|
||||
faster.
|
||||
5. **Setup that isn't timed:** once for a benchmark, through fixtures, and once a round
|
||||
for work that uses up its input, such as sorting.
|
||||
6. **Rates:** bytes a second, where a benchmark says how many bytes a round handles.
|
||||
7. **Saving and comparing:** whether a change made code faster, slower, or neither,
|
||||
given the noise.
|
||||
8. **The same in the VM and as executables,** with the report saying which it is.
|
||||
|
||||
## How it fits the rules
|
||||
|
||||
- **A benchmark is a function with an attribute,** found by reflection while compiling,
|
||||
as a test is. One that isn't one of the shapes below is a `compile_error`, which says
|
||||
which shapes are allowed, as `tester::run` does.
|
||||
- **`bencher` is plain data,** passed as `&mut bencher`. It owns nothing.
|
||||
- **Inputs made for a batch belong to the runner,** in a vector it sized before. The
|
||||
work borrows each one as `&mut T`. They're closed after the clock stops, so closing
|
||||
isn't timed: the one-owner rule decides when, and the runner decides it's outside the
|
||||
measurement.
|
||||
- **Callables are taken as std's adapters take them,** through `invokable` bounds, so a
|
||||
lambda given to `batched` is compiled for its type. It refers to the benchmark's
|
||||
locals where they are, allocates nothing, and doesn't outlive the call.
|
||||
- **A fixture** is made before calibration and closed after the last sample. Neither is
|
||||
timed. In between it's lent to every run, as `&F` or `&mut F`: a fixture that closes
|
||||
has one owner, so it can't be given by value to a benchmark run more than once.
|
||||
- **The runner allocates nothing while timing.** Its vectors of samples are sized
|
||||
before the clock starts. With no collector, what a benchmark allocates costs it as it
|
||||
goes, and no pause lands in a later sample.
|
||||
- **One thread.** Benchmarks run one at a time on the thread that called the runner. A
|
||||
benchmark may start threads of its own.
|
||||
- **Not while compiling.** The runner reads the clock, a system call evaluation
|
||||
refuses, so a constant that runs it is noted as not constant.
|
||||
- **`keep` changes no value.** A program means the same with every `keep` taken out. It
|
||||
only limits what the optimizer may assume.
|
||||
|
||||
## Layers
|
||||
|
||||
### The compiler gains `keep` (decision 4)
|
||||
|
||||
```sakura
|
||||
#! Gives a value back as it is, while the optimizer takes it as unknown. The work
|
||||
#! making the value is never taken away or moved out of a loop, and nothing is
|
||||
#! worked out ahead from what it gives back. Memory a reference given to it
|
||||
#! reaches is taken as read and written. Where the program runs, it costs nothing
|
||||
#! beyond the value being made, and while compiling it is the value itself.
|
||||
#! @tparam T The type of the value.
|
||||
#! @param value The value to keep.
|
||||
#! @returns The value.
|
||||
@intrinsic
|
||||
pub def keep<T>(value: T): T;
|
||||
```
|
||||
|
||||
- A new operation, `keep`, in `compiler/intermediate/code.sakura`, with the traits
|
||||
`op_calls`. The passes go by an operation's traits, so none moves it, merges it, or
|
||||
takes it away: `dead.sakura`, `loops.sakura` and `sink.sakura` remove or move only
|
||||
loads and what `code::removable` allows, which no call is. Numbering doesn't take its
|
||||
result as its operand, so nothing is folded through it.
|
||||
- `escapes.sakura` and `keeps.sakura` already take what an intrinsic is given as kept,
|
||||
so `keep(&buffer)` keeps the buffer in memory with nothing added there.
|
||||
- `emitter/intrinsics.sakura` emits it.
|
||||
- Natively it's a move into a register, which the allocator usually removes. In
|
||||
bytecode it's a move.
|
||||
|
||||
### `std::testing` gains (decision 1)
|
||||
|
||||
```sakura
|
||||
#! Marks a function, or a constant holding one, as a benchmark that `bencher::run`
|
||||
#! measures, as `@test` marks a test.
|
||||
#!
|
||||
#! A benchmark is a `def(b: &mut bencher): void` that does its work `b.rounds`
|
||||
#! times. It may also take a fixture after the bencher, by reference, as
|
||||
#! `def(b: &mut bencher, text: &sample_text): void`, which is made once before it
|
||||
#! is measured, lent to every run, and closed after, untimed.
|
||||
@usage{ on = target::functions | target::constants }
|
||||
pub struct bench : attribute {
|
||||
pub val name: strview = ""; #! What the report calls it, which is its path when this is empty.
|
||||
pub val skip: bool = false; #! Whether it is left out, which the report counts.
|
||||
}
|
||||
|
||||
#! What a benchmark is run with.
|
||||
pub struct bencher {
|
||||
pub val rounds: u64; #! How many times to do the work in this run.
|
||||
pub var bytes: u64; #! How many bytes a round handles, which the report gives a rate of where set.
|
||||
}
|
||||
|
||||
#! Does the work once for each of `rounds` inputs that `make` gives, timing only
|
||||
#! the work. `make` runs before the clock starts, and what it gave is closed after
|
||||
#! the clock stops. Each is compiled for the callable given, as a lambda.
|
||||
pub def bencher::batched<T, M, W>(&mut this, make: M, work: W): void
|
||||
where M: invokable<def(): T> where W: invokable<def(&mut T): void>;
|
||||
|
||||
#! Measures every benchmark of the program, one after another (decision 2), and
|
||||
#! reports each as it finishes.
|
||||
#!
|
||||
#! The arguments may say:
|
||||
#! - `--only TEXT`: the benchmarks whose name holds the text;
|
||||
#! - `--time MS`: how long each sample runs at least, 1 by default;
|
||||
#! - `--samples N`: how many samples are taken, 51 by default;
|
||||
#! - `--save FILE`: write every sample to the file, as JSON;
|
||||
#! - `--compare FILE`: compare with the samples saved there (decision 3).
|
||||
#! @param args The arguments the program was given.
|
||||
#! @returns The status to stop with: zero unless a benchmark could not run.
|
||||
pub def bencher::run(args: span<strview>): i32;
|
||||
```
|
||||
|
||||
`std::sys` gains nothing: the steady clock is enough. Two reads a sample of 1 ms are
|
||||
0.04% of it, even at a system call each on Linux.
|
||||
|
||||
## Using it
|
||||
|
||||
```sakura
|
||||
import std;
|
||||
import std::io;
|
||||
import std::json;
|
||||
import std::sys;
|
||||
import std::testing;
|
||||
|
||||
# The work itself, in the loop: for the smallest work, with no call each round.
|
||||
@bench def hashes_words(b: &mut bencher): void {
|
||||
for i in 0..b.rounds {
|
||||
val word := keep(i);
|
||||
_ = keep(hash(&word));
|
||||
}
|
||||
}
|
||||
|
||||
# Text read once by a fixture, so reading it isn't timed, and closed after the last
|
||||
# sample, as the string it holds closes.
|
||||
struct sample_text : fixture<sample_text> {
|
||||
var data: string;
|
||||
}
|
||||
|
||||
def sample_text::setup(t: &mut tester): sample_text {
|
||||
val at := path::parse("bench/sample.json") else (_) { return sample_text {}; };
|
||||
var text := io::read_file(&at) else (_) {
|
||||
_ = t.expects(false);
|
||||
return sample_text {};
|
||||
};
|
||||
return sample_text { data = move(&mut text) };
|
||||
}
|
||||
|
||||
# The fixture lent to every run. A rate is reported.
|
||||
@bench def parses_json(b: &mut bencher, text: &sample_text): void {
|
||||
b.bytes = text.data.length;
|
||||
for _ in 0..b.rounds {
|
||||
val doc := json::parse(text.data.span) else (_) { return; };
|
||||
_ = keep(&doc);
|
||||
}
|
||||
}
|
||||
|
||||
# Work that uses up its input: each round sorts a vector shuffled before the clock
|
||||
# started.
|
||||
@bench def sorts_10000(b: &mut bencher): void {
|
||||
b.batched(def() => shuffled(10000), def(v: &mut vector<u64>) { v.sort(); });
|
||||
}
|
||||
|
||||
# One generic benchmark, measured at two types.
|
||||
@bench const fills_u8 := fills::<u8>;
|
||||
@bench const fills_u64 := fills::<u64>;
|
||||
|
||||
def main(args: span<strview>): void {
|
||||
exit(bencher::run(args));
|
||||
}
|
||||
```
|
||||
|
||||
Built and run:
|
||||
|
||||
```
|
||||
sakura build -O2 --std std -o bench.exe bench/*.sakura
|
||||
bench.exe --only json --save before.json
|
||||
... a change ...
|
||||
bench.exe --only json --compare before.json
|
||||
```
|
||||
|
||||
The report would read like this. The numbers are only for illustration:
|
||||
|
||||
```
|
||||
windows-x86_64, native: 51 samples of at least 1 ms each
|
||||
[ BENCH ] hashes_words 0.673 ns ±0.2%
|
||||
[ BENCH ] parses_json 1.21 ms ±0.4% 412 MB/s
|
||||
[ BENCH ] sorts_10000 402 µs ±0.9%
|
||||
[ BENCH ] fills_u8 2.10 µs ±0.3%
|
||||
```
|
||||
|
||||
And compared:
|
||||
|
||||
```
|
||||
parses_json 1.21 ms -> 1.09 ms -9.9% faster
|
||||
sorts_10000 402 µs -> 405 µs +0.7% same
|
||||
```
|
||||
|
||||
## How each part works
|
||||
|
||||
- **Calibrating:**
|
||||
- The benchmark runs with 1 round, then 2, 4 and so on, until one run takes at least
|
||||
the sample time, 1 ms by default. That's ten thousand of Windows' clock steps, so
|
||||
the step is under 0.01% of a sample.
|
||||
- Calibrating also warms the caches, and lets the code page in.
|
||||
- One slow run stops the doubling early, as the Linux probe found once. So the rounds
|
||||
found are run once more, and doubled on while that run is under the sample time.
|
||||
- The probe took 2–3 ms for each benchmark.
|
||||
- **Sampling:**
|
||||
- The rounds found are run 51 times. Each run is one sample: its time divided by its
|
||||
rounds.
|
||||
- An odd count makes the median one of the samples.
|
||||
- The probe took 60–90 ms for each benchmark, so a hundred benchmarks take about ten
|
||||
seconds.
|
||||
- **The report:**
|
||||
- **The median,** which an interrupt or a page fault hardly moves.
|
||||
- **The median absolute deviation,** as a percentage of the median.
|
||||
- **Not the fastest sample.** The 2026-10-18 report showed it where it was under half
|
||||
the median, since that meant most samples held a collection. With no collector,
|
||||
`links_100`'s fastest sample is within 1% of its median, so a wide spread shows in
|
||||
the deviation alone.
|
||||
- **A rate,** where `bytes` is set: bytes a round over the median, in MB/s of 10^6
|
||||
bytes.
|
||||
- **Times to three figures,** in ns, µs, ms or s. Interpolation writes a real in full,
|
||||
and `describe` counts whole nanoseconds, so the runner rounds them itself.
|
||||
- **The header** names the system and the backend, through the `os`, `arch` and
|
||||
`backend` intrinsics, so a VM's numbers aren't mistaken for an executable's.
|
||||
- **`batched`:**
|
||||
- Inputs are made in batches of up to 1,024. Each batch is timed on its own, and the
|
||||
times are summed, so a batch's inputs needn't all fit in memory at once.
|
||||
- Each round is one call of `work`, compiled for the lambda given, so at `-O2` it's
|
||||
inlined. By `tools/function.sakura` on 2026-10-20, such a call costs 0.50 ns in
|
||||
`-O2` executables, against 2.78 ns for a function value. Work that needs fresh input
|
||||
usually takes far longer than either.
|
||||
- **Saving (`--save`):**
|
||||
- A JSON object, written through `@serial` structs and `json::to_text`, and read back
|
||||
by `json::from_text`, which the probe did. It holds the header,
|
||||
then each benchmark's name, rounds, bytes, and every sample, in nanoseconds a round.
|
||||
- `io::write_file` gives a `result<void, io_error>`. A file that can't be written is
|
||||
reported, and the status is 1.
|
||||
- **Comparing (`--compare`, decision 3):**
|
||||
- For each benchmark in both runs: the old median, the new median, and the change.
|
||||
- **"faster" or "slower"** only where a Mann–Whitney U test on the two sets of
|
||||
samples gives p < 0.01, and the medians differ by at least 1%. Otherwise "same".
|
||||
- The test compares ranks, so it doesn't assume the samples are normal. They
|
||||
aren't: interrupts and page faults only ever slow a sample down.
|
||||
- With 51 samples a side, the normal approximation of U is close. It needs only
|
||||
sorting and a square root.
|
||||
- **A header that differs,** as a VM against an executable, is said before anything
|
||||
else.
|
||||
- **The 1% floor is a guess,** and may be too low: the probe saw code layout alone move
|
||||
a result by 13% between two builds of the same benchmark. The documentation should
|
||||
say that a change of a few percent between builds may be layout. Building twice,
|
||||
with an unrelated change, shows how big that is.
|
||||
- **Two runs of one build can differ too.** The Linux probe's `links_100` was 4.63–4.73
|
||||
µs in eight runs and 5.76 µs in two, while each run's samples agreed within 0.6%. The
|
||||
U test on one run a side would call that a change, so the documentation should say
|
||||
to compare a few runs a side before believing one.
|
||||
- **A benchmark's shapes,** checked while compiling:
|
||||
- `def(b: &mut bencher): void`;
|
||||
- `def(b: &mut bencher, f: &F): void` or `def(b: &mut bencher, f: &mut F): void`,
|
||||
where `F` is a `fixture<F>`, lent to every run. Its `setup` takes a tester, which
|
||||
the runner makes, and where a check fails, the benchmark fails with that check's
|
||||
message. A fixture taken by value, as a test takes one, is a `compile_error` saying
|
||||
to take it by reference;
|
||||
- a constant holding any of these, including a generic instance.
|
||||
- The runner finds `F` through two overloads of a generic function, one taking
|
||||
`def(&mut bencher, &F): void` and one `def(&mut bencher, &mut F): void`, since
|
||||
`type_of` gives the parameter's type only as the reference.
|
||||
- **`keep` in a benchmark:**
|
||||
- **Input:** `keep(i)` stops the work from being worked out once, ahead of the loop.
|
||||
- **Output:** `keep(result)` stops it from being dropped.
|
||||
- **A reference:** `keep(&buffer)` keeps the writes into a buffer that nothing reads
|
||||
after.
|
||||
|
||||
## Testing
|
||||
|
||||
- **The runner, in std's tests** (`test/std/bench.sakura`), written with
|
||||
`std::testing`:
|
||||
- **calibration and sampling against a clock the test drives:** the runner reads its
|
||||
clock through a function value inside, so a fake clock gives fixed times. That
|
||||
covers doubling, stopping at the sample time, and the count of samples;
|
||||
- **statistics on fixed samples:**
|
||||
- the median and the median absolute deviation;
|
||||
- Mann–Whitney U and its p, against SciPy's `mannwhitneyu`, run once in the
|
||||
scratchpad. SciPy isn't installed here, so that run installs it;
|
||||
- **numbers in the report:** three figures, and units changing at 1,000;
|
||||
- **`--save` read back by `--compare`,** a header that differs, a benchmark in only
|
||||
one of the two, and a file that can't be written;
|
||||
- **fixtures:** made once, lent to every run, and closed once, as `&F` and as `&mut F`;
|
||||
- **`batched`:** each input made once and closed once, outside the time;
|
||||
- **`--only` and `skip`;**
|
||||
- **shapes that aren't allowed,** as `compile_error`s, in the analyzer's tests.
|
||||
- **`keep`, in the compiler's tests:**
|
||||
- At `-O2`, a loop of `keep(mixed(keep(i)))` still holds its multiplies, by the IR
|
||||
tests and `--verify`.
|
||||
- `keep(42)` isn't folded.
|
||||
- `keep(&buffer)` keeps stores that nothing reads after.
|
||||
- A corpus program printing values through `keep` gives the same output at every
|
||||
level, and in the VM.
|
||||
- **Where they run:** in the VM and as executables at `-O0` and `-O2`, and under
|
||||
`run --checks`, which stops where an input or fixture is used after it's closed, and
|
||||
lists the blocks of any never closed. (`SAKURA_COLLECT_ALWAYS=1` went with the
|
||||
collector.)
|
||||
|
||||
## Phases
|
||||
|
||||
About 60 lines in the compiler for `keep`, 700 of `std::testing`, and 400 of tests.
|
||||
|
||||
1. **`keep`, in the compiler,** with its tests.
|
||||
2. **The runner:** `@bench`, `bencher`, calibrating, sampling, the report, `--only`,
|
||||
`--time` and `--samples`. Lent fixtures and constants included.
|
||||
3. **`batched` and rates.**
|
||||
4. **`--save` and `--compare`.**
|
||||
5. **Benchmarks of std,** in a `bench/` directory beside the tests:
|
||||
- containers, hashing, sorting and formatting;
|
||||
- JSON and YAML throughput;
|
||||
- and the compiler's lexer, interner and hash tables, which `docs/performance.md`
|
||||
names;
|
||||
- and the probes in `tools/`, `function.sakura`, `iterators.sakura` and
|
||||
`memory.sakura`, as benchmarks in place of their loops timed by hand.
|
||||
6. **A "Benchmarks" section in the README.**
|
||||
|
||||
## Found along the way
|
||||
|
||||
- **std can't write a real to a number of places.** Interpolation writes
|
||||
`1.4970779418945312`, and `describe` counts whole nanoseconds. The runner rounds
|
||||
numbers itself, but a formatter in std would serve it, and others. Still so on
|
||||
2026-10-20: `lpad` and `rpad` pad text, but nothing rounds a real.
|
||||
- **On Linux, std reads the steady clock by a system call,** about 210 ns a read in
|
||||
executables, where glibc's `clock_gettime` reads it through the vDSO in 25 ns. A
|
||||
sample of 1 ms doesn't notice, but code timing short spans by hand does.
|
||||
|
||||
## Later, where wanted
|
||||
|
||||
- **Allocation counts:** blocks and bytes allocated a round. With no collector, there
|
||||
are no collections to count or force. This needs a counter in each of the two
|
||||
runtimes: the native runtime, in `runtime/memory.sakura`, and the VM. Since threads
|
||||
allocate from caches of their own, each thread counts its own.
|
||||
- **Timing whole programs:** running a command a number of times and giving the median
|
||||
of its CPU time, as the optimizer work measured builds. `std::process`'s status would
|
||||
gain the child's CPU time: `GetProcessTimes` on Windows, and `wait4`'s `rusage` on
|
||||
Linux, where `sys::wait` already calls `wait4`, asking for none. On Windows, it comes
|
||||
in 15.625 ms steps.
|
||||
- **Ratios within a run,** as the probes in `tools/` check theirs: adapters within 10% of
|
||||
a loop, a `box` within a tenth of `raw_allocate`. A benchmark would name the one it's
|
||||
measured against, and the report would give the ratio.
|
||||
- **The steady clock through the vDSO on Linux,** 25 ns a read rather than 210 ns. The
|
||||
runtime would find it through the auxiliary vector's `AT_SYSINFO_EHDR`, as C libraries
|
||||
do.
|
||||
- **Cycles a round,** where the system counts them: `QueryThreadCycleTime`, or Linux's
|
||||
performance counters.
|
||||
- **Steadier numbers:** pinning the thread to one core (`SetThreadAffinityMask`,
|
||||
`sched_setaffinity`), and a higher priority.
|
||||
- **A failing status for slowing down,** as `--compare FILE --slower 5`, for a check
|
||||
before merging.
|
||||
- **The `-O` level in the header,** and whether `run --checks` is checking every access,
|
||||
neither of which an intrinsic gives yet. `lanes_held()` tells only `-O2` executables
|
||||
from the rest.
|
||||
|
||||
## Decisions for you
|
||||
|
||||
1. **Where it lives:**
|
||||
- **(a) In `std::testing` (recommended).** It shares the walk over attributes,
|
||||
`--only`, fixtures, and the style of the report. A program importing
|
||||
`std::testing` gets both.
|
||||
- **(b) In a module of its own, `std::bench`.** It's separate from tests, but
|
||||
repeats the walk and the arguments, or the two share code through a third module.
|
||||
2. **How benchmarks run:**
|
||||
- **(a) One after another in one program (recommended),** as Go and Criterion run
|
||||
them.
|
||||
- There's no copying, and no protocol for handing samples back.
|
||||
- A benchmark that faults stops the run, with its trace.
|
||||
- What one benchmark leaves behind can change the next. There's no collector's heap
|
||||
now, but the blocks it released wait on the free lists, the chunks it opened stay
|
||||
open, and once any benchmark starts a thread, every allocation after goes
|
||||
through a thread's cache. `--only` measures one alone.
|
||||
- **(b) Each in a copy of its own, as tests run.**
|
||||
- Each starts from the memory the program had before the runner, so the order
|
||||
doesn't matter, and a fault fails alone.
|
||||
- But a copy must hand its samples back: through a pipe on Linux, and through a
|
||||
handle named in the environment on Windows. That isn't probed.
|
||||
3. **Comparing:**
|
||||
- **(a) A Mann–Whitney U test on every sample, with a 1% floor (recommended).** This
|
||||
needs every sample saved, about 1 KB of JSON for each benchmark.
|
||||
- **(b) Medians only,** where the change is called real when it's over three median
|
||||
absolute deviations. This is simpler and saves less, but it's worse at telling
|
||||
noise from a change.
|
||||
- Either way, each side is one run, and the Linux probe saw two runs of one build
|
||||
differ by a fifth. `--save` could add a run to its file rather than replace it, so
|
||||
that `--compare` weighs several.
|
||||
4. **`keep`'s name and home:**
|
||||
- **(a) `keep`, in `std::testing` (recommended).** The compiler's corpus has programs
|
||||
with functions of their own named `keep`, and `std::args` has a private one, so it
|
||||
isn't put in module `std`, where every program would see it. Programs that
|
||||
benchmark import `std::testing` anyway.
|
||||
- **(b) `black_box`, as Rust names it, in module `std`.** No program here uses that
|
||||
name, and the optimizer's own tests could use it without `std::testing`.
|
||||
5. **Samples by default:**
|
||||
- **(a) 51 samples of at least 1 ms (recommended).** That's 60–90 ms a benchmark. On
|
||||
Windows, the probe's medians repeated within 0.3%. On Linux, within 2.3%, but for
|
||||
the runs of `links_100` that were off by a fifth as a whole, which more samples in
|
||||
one run wouldn't fix.
|
||||
- **(b) A time for each benchmark, as Criterion's 5 seconds,** with as many samples
|
||||
as fit. That's steadier, but a hundred benchmarks take minutes.
|
||||
@@ -0,0 +1,578 @@
|
||||
# Plan: programs with no operating system
|
||||
|
||||
Written 2026-10-20. This is a proposal. The language is yours, so the decisions at the end
|
||||
are yours to make. Nothing is built yet.
|
||||
|
||||
**Comes after the ffi plan, now built:** `std::sys` is `system`, and `@foreign` and
|
||||
`@link` are `extern` sections.
|
||||
|
||||
**The std plan is built:** `core/` and `system/` are libraries found beside the
|
||||
compiler, and `core` needs nothing of a system but memory and `fault`.
|
||||
|
||||
**The runtime is a library of its own** since 2026-10-21: `runtime/` (`rt/` for part of
|
||||
2026-10-26), found beside the compiler as `core/` and `system/` are, whose module is
|
||||
`runtime`. It needs `core` and
|
||||
`system`, and nothing of std, so std plays no part in a build that doesn't import it.
|
||||
|
||||
**The short answer:**
|
||||
- **The std plan's `core` makes the source freestanding.** None of its files has a
|
||||
`when os` section. Its only ties to a platform are intrinsics: the heap's, `fault`'s,
|
||||
atomics' and lanes'.
|
||||
- **An executable is more than that source.** Three things tie every native build to
|
||||
Linux or Windows:
|
||||
1. **The runtime** the compiler builds into every executable: the module `runtime`,
|
||||
whose 16 helpers it calls by name.
|
||||
2. **Code the compiler writes itself:** `_start`, the fault handlers, the trap
|
||||
stub, thread starts. All of it makes system calls or calls `kernel32`.
|
||||
3. **What generated code assumes:**
|
||||
- a thread record at `gs`, read by function prologues;
|
||||
- an image at `0x400000` addressed absolutely;
|
||||
- SSE2 and x87 turned on;
|
||||
- an ELF or console PE.
|
||||
- **Allocation is the smallest of these.** The heap's algorithm is already plain Sakura:
|
||||
size classes, chunks, free lists, thread caches. Only taking memory from the system
|
||||
(`mmap`, `mprotect`, `mremap`, `VirtualAlloc`) and the lock (`futex`, `WaitOnAddress`)
|
||||
belong to a platform. Split there, the algorithm goes into `core`, and a platform
|
||||
gives it pages. On bare metal, that's a region of the image, or what the boot memory
|
||||
map says is free.
|
||||
- **Alongside the platforms there now, the platform becomes a layer the target chooses.**
|
||||
- `linux-x86_64` and `windows-x86_64` keep the runtime of `runtime/`.
|
||||
- A new `none-x86_64` takes the program's own: a module `platform` of up to four
|
||||
functions, of which only `stop` is required.
|
||||
- The compiler writes a start for it that needs no system.
|
||||
- **Operating systems need more than a target:**
|
||||
- privileged instructions;
|
||||
- memory the optimizer leaves alone (`volatile`);
|
||||
- interrupt handlers;
|
||||
- alignment and packing;
|
||||
- a kernel in the top 2 GiB.
|
||||
|
||||
None of these exists yet.
|
||||
|
||||
**Its users:**
|
||||
- **Kernels and bootloaders,** in ring 0, booted by a loader such as Limine.
|
||||
- **Programs for an operating system of one's own,** in ring 3, whose platform module
|
||||
makes that system's calls.
|
||||
- **UEFI tools,** later, whose platform is the firmware's boot services.
|
||||
- **Programs on Linux and Windows,** which are unchanged. The heap's split moves code
|
||||
but not behavior.
|
||||
|
||||
**Probed** on 2026-10-20, in the scratchpad's `plans2/f/`, with `x2` (the compiler's fixed
|
||||
point), and by three searches of the compiler's sources. A program summing a vector, built
|
||||
at `-O2`:
|
||||
|
||||
| | sakurac |
|
||||
|---|---|
|
||||
| Executable | 164 KB |
|
||||
| Kind | ELF `ET_EXEC`, base `0x400000`, segments `.rodata`, `.data`, `.text`, `.lines` |
|
||||
| Instructions reading through `gs` | 55 |
|
||||
| `syscall` instructions | 42: `_start`, the heap, its lock, threads, `fail`, `exit`, the trap stub |
|
||||
| Instructions naming an `xmm` register | 133: formatting, `memcpy`, clearing, comparing |
|
||||
| RIP-relative operands | 0 |
|
||||
| Stores below `rsp` (the red zone) | 0 |
|
||||
|
||||
- **`core`'s source has no `when` section.** The copy of `core` the std plan probed (11,294
|
||||
lines) has none, and its intrinsics are only the heap's, `exit` and `abort`, atomics,
|
||||
lanes, bits, and compile time.
|
||||
- **Linux lets a program here set its own `gs` base.** `AT_HWCAP2` holds FSGSBASE, and a
|
||||
C program's `wrgsbase` and `rdgsbase` worked in user mode on this machine. So a
|
||||
freestanding image can be tested as a Linux process ([Testing](#testing)).
|
||||
- **There's no QEMU here.** Booting a kernel needs `qemu-system-x86_64`, and UEFI
|
||||
needs OVMF as well.
|
||||
|
||||
## What's there now
|
||||
|
||||
### What an executable takes from its platform
|
||||
|
||||
| Piece | What it does now | What it needs of the system |
|
||||
|---|---|---|
|
||||
| `_start` (`native.sakura:1080-1141` in `sakura-native`) | Points `gs` at the first thread's record, reads the thread's ID, maps a stack, installs a `SIGSEGV` handler, probes the CPU, runs `processor` over the environment, then `<globals>` and `main`, then exits with 0 | `arch_prctl`, `gettid`, `mmap`, `rt_sigaction`, `exit_group`; argc, argv and envp on the first stack. On Windows, `kernel32` throughout (`windows.sakura:306-365`) |
|
||||
| Stacks | The compiler keeps frames on `rsp`, 32 MiB mapped | `mmap`, or the system's thread stack |
|
||||
| The thread record | 32 words at `gs`. It holds the stack limit (word 1), the trap frame, the record itself, C-call words, signals, heap caches and format builders | Something must set the `gs` base: `arch_prctl`, or a TLS slot on Windows |
|
||||
| The 16 helpers, by name in `runtime` (`native.sakura:31-58`) | `fail`, `arguments`, `allocate`, `allocate_untraced`, `release`, `resize`, `equal`, `format_begin`, `format_text`, `format_value`, `format_owned`, `exit`, `abort`, `processor`, `start_thread`, `thread_main`, and `system_start` on Windows | Formatting, `equal` and the heap's logic need nothing. The rest map memory, write, exit, lock or start threads |
|
||||
| The heap (`runtime/memory.sakura`, 809 lines) | 19 size classes carved from 1 MiB chunks, in up to 64 GiB of reserved address space. Larger blocks are mapped alone. Caches per thread once threaded | `mmap` with `PROT_NONE`, `mprotect`, `munmap`, `mremap`; `VirtualAlloc` on Windows. A `futex` or `WaitOnAddress` lock once threaded |
|
||||
| Faults | Checks call the trap stub, which calls `fail`. A second trap while reporting exits at once, by `exit_group` written inline. A null read faults in page 0, and the `SIGSEGV` or vectored handler turns it into a report | `fail` allocates from the heap, walks the `rbp` chain over the `.lines` tables, writes to descriptor 2, and exits with 1 |
|
||||
| Safe points | Only where `std::sys::handle` is used | Signals |
|
||||
|
||||
**Generated code assumes:**
|
||||
- **The stack limit through `gs`.** The compiler checks `rsp - frame` against `gs:[8]`
|
||||
in every prologue but a small leaf's (`calls.sakura:1039-1047`).
|
||||
- **SSE2 and x87, always.**
|
||||
- Floats are scalar SSE2.
|
||||
- Copies and clears up to 128 bytes, and the prologue's zeroing, go through `xmm`
|
||||
registers.
|
||||
- Float `%` is x87's `fprem`.
|
||||
- AVX is chosen at run time, from the probe.
|
||||
- **Frame pointers, always,** for traces. **No red zone.**
|
||||
- **Absolute addresses:**
|
||||
- `[disp32]` with no base, sign-extended;
|
||||
- also `mov r32, imm32`, which is zero-extended, and switch tables of `u32`.
|
||||
|
||||
So an image runs only where it was linked, in the low 2 GiB.
|
||||
|
||||
**The image** (`binary::elf` and `binary::pe`, in `binary`):
|
||||
- `ET_EXEC` at `0x400000`, or a console PE with its relocations stripped that imports
|
||||
`kernel32`.
|
||||
- No `.bss`: `.data` is written whole, zeros and all, so a large zeroed global grows
|
||||
the file.
|
||||
- No object files, no flat binaries, no linker.
|
||||
- An ELF calling C names `/lib64/ld-linux-x86-64.so.2`.
|
||||
- `build_options.stack` exists, but nothing sets it.
|
||||
|
||||
**Targets are a closed list:** the `platform` enum (`entry.sakura:107-110`),
|
||||
`checker::target_value` (`checker/declare.sakura:146-171` in `sakura-analyzer`), and
|
||||
`build_options.windows: bool`, tested in about 18 places.
|
||||
|
||||
`os` may be `linux`, `macos`, `windows` or `freebsd`, and none of these means "no
|
||||
system".
|
||||
|
||||
### What the language has for systems work
|
||||
|
||||
**There:**
|
||||
- **Raw pointers,** with arithmetic, and `as` between integers and pointers, so a device
|
||||
register's address can be a pointer.
|
||||
- **`cfn<F>`** made from an address.
|
||||
- **Atomics,** with C11's orders. A fence keeps loads and stores from moving across it,
|
||||
in the optimizer, even where no instruction is emitted.
|
||||
- **Struct layout as C's:** fields in order, each aligned to itself, never reordered.
|
||||
It's stated only in the compiler's sources. `@foreign` unions overlay their fields.
|
||||
|
||||
**Not there:**
|
||||
- **Inline assembly,** or any intrinsic for `in`/`out`, `cli`/`sti`/`hlt`, control
|
||||
registers, MSRs, `lgdt`/`lidt`/`ltr`, `invlpg`, `iretq`, `swapgs`, `rdtsc` or `pause`.
|
||||
- The encoder emits only `syscall`, `cpuid`, `xgetbv`, `mfence`, `lock`, `rep`,
|
||||
`ud2`, `vzeroupper` and `fprem` beyond ordinary code.
|
||||
- The only one a program can reach is Linux's `std::sys::syscall`.
|
||||
- **Volatile memory.**
|
||||
- The optimizer reuses a value read through a pointer when nothing between may
|
||||
write it.
|
||||
- Its loop passes move such a read out of the loop.
|
||||
- So a loop polling a device register would read it once.
|
||||
- **`@align`, `@packed`,** field offsets, sections, placing anything at an address.
|
||||
- **An entry of one's own.** `main` is `def main(): void` or
|
||||
`def main(args: span<strview>): void`.
|
||||
- **Interrupt handlers,** naked functions, a function C or assembly can call outside a C
|
||||
call, `noreturn` beyond `exit` and `abort`, exported symbols.
|
||||
|
||||
**Allocators:**
|
||||
- Every container's `new` takes a `maybe<&mut allocator>`, and `nothing {}` means the
|
||||
default heap.
|
||||
- These always use the default heap: `box`, `rc` and `arc`; a `function` holding more
|
||||
than 24 bytes; `$"..."`; `to_vector`, `vector::from`, `dict::from` and `to_string`.
|
||||
- `arena::over(buffer)` serves from memory it's given, then falls back to the heap.
|
||||
|
||||
### std with no operating system
|
||||
|
||||
| Needs only `core` and a heap | Needs a system |
|
||||
|---|---|
|
||||
| `std::math`, `std::json`, `std::yaml`, `std::serial`, `regex`, `uri`, `version` | `std::io`, `std::sys`, `std::args`, `std::time`, `std::thread`, `std::process`, `std::testing` |
|
||||
|
||||
## What it needs
|
||||
|
||||
1. **A target with no operating system,** beside the two, and a `when` value for it.
|
||||
2. **The platform as a layer the target chooses:** std's for Linux and Windows, the
|
||||
program's for none.
|
||||
3. **The heap's algorithm apart from where its memory comes from.**
|
||||
4. **A start that needs no system:** the thread record, stacks, SSE, `<globals>`,
|
||||
`main`.
|
||||
5. **Faults reported with no system:** a place the platform says the report goes, and a
|
||||
way for a kernel's own exception handlers to report as a fault does.
|
||||
6. **An image a loader can place:** its base, the top 2 GiB for kernels, and a `.bss`.
|
||||
7. **What operating-system code does:**
|
||||
- privileged instructions;
|
||||
- volatile memory;
|
||||
- interrupt handlers;
|
||||
- alignment and packing.
|
||||
8. **Testing without hardware,** and on QEMU where it's installed.
|
||||
|
||||
## How it fits the rules
|
||||
|
||||
- **"Programs run on a virtual machine, or as standalone x86-64 executables for Linux
|
||||
and Windows that behave identically."**
|
||||
- A freestanding executable behaves the same wherever it shares a meaning with them:
|
||||
the same faults, reports and traces.
|
||||
- Where the report goes, where memory comes from, and how the program stops are the
|
||||
platform's.
|
||||
- **Targets:** `os` gains `none`. `--target none-x86_64` is `os == none`,
|
||||
`arch == x86_64` and `backend == native`. Nothing existing changes name.
|
||||
- **The VM stays hosted.** `run` refuses `none`. A freestanding program's logic runs in
|
||||
the VM under the host's target, with its `when os == none` sections set aside.
|
||||
- **std's system modules aren't read** on `none` unless a program refers to them, under
|
||||
reading by reference. Where one is, the compiler says it's for other
|
||||
targets ([std on none](#std-on-none)).
|
||||
|
||||
## The design
|
||||
|
||||
### The target (decision 1)
|
||||
|
||||
- **`none-x86_64`:** no operating system. The program's platform module decides whether
|
||||
it runs in ring 0, as a kernel, or in ring 3, on a system of its own.
|
||||
- `check --target none-x86_64` and `build --target none-x86_64`. The language server
|
||||
takes it as `check` does.
|
||||
- **The native backend's one switch,** `build_options.windows: bool`, becomes a choice
|
||||
of three systems.
|
||||
- **UEFI** comes later ([Later](#later-where-wanted)): a PE for the firmware, with the
|
||||
Windows calling convention the compiler already has.
|
||||
|
||||
### The platform layer (decision 2)
|
||||
|
||||
The 16 helpers split three ways:
|
||||
|
||||
| Helpers | Where they go | Why |
|
||||
|---|---|---|
|
||||
| `format_begin`, `format_text`, `format_value`, `format_owned`, `equal`, and `float`'s and `values`' code | `core` | They're the language's: `$"..."` and comparing values |
|
||||
| `allocate`, `allocate_untraced`, `release`, `resize` | `core`'s heap, over the platform's pages | The algorithm is the language's, the memory the platform's |
|
||||
| `fail` | `core` builds the report and walks the trace; the platform writes it and stops | The `.lines` tables are the image's own |
|
||||
| `arguments`, `processor`, `exit`, `abort`, `start_thread`, `thread_main`, `system_start` | `runtime`'s Linux and Windows sections only | They're the system's. On `none`: no arguments, the probe's features as they are, `exit` stops, and `abort` traps |
|
||||
|
||||
**On `none`, the platform is a module `platform`,** given by the program or by a
|
||||
library, which the compiler looks up by name, as it looks up `runtime` now:
|
||||
|
||||
```sakura
|
||||
module platform;
|
||||
|
||||
pub def start(): void; # optional: runs first, before <globals>
|
||||
pub def pages(count: u64): *mut u8; # optional: count 4 KiB pages for the heap, or null
|
||||
pub def report(text: strview): void; # optional: where a fault's report goes; dropped if absent
|
||||
pub def stop(status: i32): void; # required: never returns
|
||||
```
|
||||
|
||||
- **On Linux and Windows,** `system` gives the same four, from the ffi plan. So the
|
||||
runtime's system parts shrink to those, the lock's wait and wake, and threads.
|
||||
- **A kernel may write its `platform` as `extern module platform when os == none;`,** so
|
||||
the structs its loader hands over, as Limine's requests and answers, are laid out as
|
||||
C's.
|
||||
|
||||
### The heap (decision 3)
|
||||
|
||||
- **`memory.sakura`'s algorithm moves into `core`.** Its system parts become calls to the
|
||||
platform: reserving and opening chunks, mapping a large block, giving memory back.
|
||||
`mremap`'s growth stays Linux's, as an extra the platform may give.
|
||||
- **On Linux and Windows, nothing changes:** their `pages` are the reservation and
|
||||
`mprotect` or `VirtualAlloc` of today.
|
||||
- **On `none`, memory comes from where the program says:**
|
||||
- `platform::pages`, from what a kernel knows is free;
|
||||
- or `--heap SIZE`, a region of the image's `.bss` the heap takes first;
|
||||
- or both, the region first.
|
||||
- **With neither, there is no default heap.** A build that reaches it fails, naming the
|
||||
way: "`main` reaches the heap through `vector::append` and `acquire`, and
|
||||
`none-x86_64` gives no memory: declare `platform::pages`, build with `--heap SIZE`, or
|
||||
give the vector an allocator."
|
||||
- The compiler already knows what's reached, since it compiles only that.
|
||||
- **Allocators given by hand work with no heap at all,** for every container but those
|
||||
above that always use it. Allocators for `box`, `rc` and `arc` come later.
|
||||
- **One processor at first.** The heap's lock does nothing until a thread starts, and
|
||||
`none` has no threads. Several processors come later.
|
||||
|
||||
### The start (decision 4)
|
||||
|
||||
On `none`, the compiler writes `_start` as it does now, without the system:
|
||||
1. **Ring 0** (`cs & 3 == 0`):
|
||||
- turn on x87 and SSE, since every prologue and copy may use them: CR0's EM off and
|
||||
MP on, CR4's OSFXSR and OSXMMEXCPT on, `fninit`;
|
||||
- set the `gs` base with `wrmsr` to `IA32_GS_BASE`.
|
||||
|
||||
**Ring 3:** set it with `wrgsbase`, which the system must allow, as Linux does.
|
||||
2. **The stacks:**
|
||||
- switch `rsp` to a stack in `.bss`, `--stack SIZE`;
|
||||
- set the limit in the record, and `rbp` to 0.
|
||||
3. **Probe the CPU** into the record. No `SAKURA_CPU`, since there's no environment.
|
||||
4. **Run** `platform::start()` if it's declared, then `<globals>`, then `main()`, then
|
||||
`platform::stop(0)`.
|
||||
|
||||
No system calls, no signal handlers, no arguments. `main` stays `def main(): void`. What a
|
||||
loader hands over, as Limine's answers or a memory map, the platform module reads in its
|
||||
own way.
|
||||
|
||||
### Faults
|
||||
|
||||
- **Reporting:**
|
||||
- The trap stub's second trap calls `platform::stop(1)` rather than `exit_group`.
|
||||
- `fail` builds "sakura: runtime error: ..." and the trace from `.lines` into a buffer
|
||||
in `.bss`, not the heap, since the heap may be what failed.
|
||||
- It hands the buffer to `platform::report`, then calls `platform::stop(1)`.
|
||||
- **The processor's own faults** are the kernel's, through its interrupt table.
|
||||
- A null read faults only if the kernel leaves page 0 unmapped.
|
||||
- A kernel's `@interrupt` handler for a page fault, a division or a general protection
|
||||
fault calls `core::fault_at(kind, rip, rbp)`. That reports it as the language
|
||||
reports a fault, with the trace.
|
||||
- **The stack:** the prologue's compare works as it does on Linux.
|
||||
|
||||
### The image (decision 5)
|
||||
|
||||
- **ELF `ET_EXEC`, as now,** with:
|
||||
- `--base ADDR`;
|
||||
- a `.bss`, so zeroed globals, `--heap` and `--stack` cost nothing in the file;
|
||||
- `_start` as the entry.
|
||||
- **The top 2 GiB,** where kernels usually live and where Limine's protocol wants them.
|
||||
- `[disp32]` already sign-extends and reaches it.
|
||||
- The compiler's `mov r32, imm32` of an address becomes `mov r64, simm32`, and its
|
||||
switch tables of `u32` become `i32`.
|
||||
- So do the handlers' `mov ecx, imm32` of the text's end.
|
||||
- **Not now:** code that can be placed anywhere (RIP-relative), relocatable PEs, flat
|
||||
binaries. Multiboot2 enters in 32-bit mode, which the native backend can't write.
|
||||
|
||||
### Reaching the hardware (decision 6)
|
||||
|
||||
**`core::x86_64`,** a child of `core`, imported where it's used:
|
||||
|
||||
| Intrinsics | Instruction |
|
||||
|---|---|
|
||||
| `port_in8`, `port_in16`, `port_in32`, `port_out8`, `port_out16`, `port_out32` | `in`, `out` |
|
||||
| `read_cr0`, `read_cr2`, `read_cr3`, `read_cr4`, `write_cr0`, `write_cr3`, `write_cr4` | `mov` to and from control registers |
|
||||
| `read_msr`, `write_msr` | `rdmsr`, `wrmsr` |
|
||||
| `load_gdt`, `load_idt`, `load_task` | `lgdt`, `lidt`, `ltr` |
|
||||
| `interrupts_off`, `interrupts_on`, `halt`, `pause` | `cli`, `sti`, `hlt`, `pause` |
|
||||
| `invalidate_page` | `invlpg` |
|
||||
| `cpuid`, `read_tsc` | `cpuid`, `rdtsc` |
|
||||
| `read_gs_base`, `write_gs_base` | `rdgsbase`, `wrgsbase` |
|
||||
| `system_call` | `syscall`, for a platform in ring 3 |
|
||||
|
||||
**`volatile_load<T>(p: *T): T` and `volatile_store<T>(p: *mut T, value: T)`,** in
|
||||
`core` for every target.
|
||||
- The optimizer treats each as it treats an atomic: touching all memory, so it's
|
||||
neither removed, merged nor moved.
|
||||
- An atomic already works this way.
|
||||
|
||||
The table holds 28 intrinsics. The encoder gains about 20 instructions, with `fninit`, `fxsave`,
|
||||
`fxrstor` and `iretq` for the start and interrupts. On the VM, a privileged intrinsic stops
|
||||
the program, as it can't be run there. `check` is unaffected.
|
||||
|
||||
### Interrupt handlers (decision 7)
|
||||
|
||||
```sakura
|
||||
struct interrupt_frame { pub val rip: u64; pub val cs: u64; pub val flags: u64; pub val rsp: u64; pub val ss: u64; }
|
||||
|
||||
@interrupt def page_fault(frame: &interrupt_frame, code: u64): void { ... }
|
||||
@interrupt def timer(frame: &interrupt_frame): void { ... }
|
||||
```
|
||||
|
||||
- **The compiler writes the entry:**
|
||||
- save every general register and the SSE state (`fxsave`);
|
||||
- set up what generated code needs, then call the body;
|
||||
- restore everything, and `iretq`.
|
||||
|
||||
A handler taking `code` is one the processor pushes an error code for.
|
||||
- **Its address,** for the interrupt table, comes from naming it: an `@interrupt`
|
||||
function's value is a `u64`.
|
||||
- **The compiler keeps frames on `rsp`,** so a handler's frames go below the interrupted
|
||||
code's.
|
||||
|
||||
### Layout (decision 8)
|
||||
|
||||
- **`@align(N)`** on a struct or a global, as a page table's 4096.
|
||||
- **`@packed`** on a struct: no padding. Its fields may be unaligned, which x86-64 reads
|
||||
and writes.
|
||||
- **The README says how structs are laid out,** as the compiler already does it.
|
||||
|
||||
### std on `none`
|
||||
|
||||
- **What it can use:** `core`, and std's modules that need only a heap.
|
||||
- **A module whose sections are all for other targets** is reported as such: "`std::io`
|
||||
is written for `os == linux` and `os == windows`, and this target is `none`."
|
||||
- Today that case gives "No file declares this module", or a missing `sys::` name
|
||||
deep inside.
|
||||
- This helps every target, not only `none`.
|
||||
|
||||
## Using it
|
||||
|
||||
```sakura
|
||||
# platform.sakura: what this kernel gives the language
|
||||
module platform;
|
||||
import core::x86_64;
|
||||
|
||||
pub def report(text: strview): void {
|
||||
for c in text { x86_64::port_out8(0x3F8, c); } # the first serial port
|
||||
}
|
||||
|
||||
pub def stop(status: i32): void {
|
||||
x86_64::interrupts_off();
|
||||
while true { x86_64::halt(); }
|
||||
}
|
||||
```
|
||||
|
||||
```sakura
|
||||
# kernel.sakura
|
||||
def main(): void {
|
||||
var frames := vector::<u64>::new(); # from --heap
|
||||
frames.append(0x100000);
|
||||
platform::report($"{frames.length} frame\n");
|
||||
}
|
||||
```
|
||||
|
||||
```sh
|
||||
sakura check --target none-x86_64 kernel.sakura platform.sakura
|
||||
sakura build --target none-x86_64 --base 0xffffffff80000000 --heap 16M --stack 64K \
|
||||
-g -o kernel.elf kernel.sakura platform.sakura
|
||||
qemu-system-x86_64 -cdrom os.iso -serial stdio -s # gdb loads kernel.elf.petal for source lines
|
||||
```
|
||||
|
||||
## How each part works
|
||||
|
||||
**The compiler:**
|
||||
- **Targets:**
|
||||
- `entry.sakura`'s `platform` gains `none-x86_64`;
|
||||
- `target_checker` (`program.sakura` in `sakura-server`) sets `os = "none"`;
|
||||
- `checker::target_value` (`checker/declare.sakura` in `sakura-analyzer`) gains `none`;
|
||||
- `build_options.windows` becomes a system of three, at its 18 places.
|
||||
- **The start** (`native.sakura` in `sakura-native`): a third entry beside Linux's and
|
||||
Windows'. Ring 0 or 3 by `cs`, the stacks from `.bss`, then the `platform` functions
|
||||
found as `runtime`'s are (`building::prepare`).
|
||||
- **Faults:**
|
||||
- the trap stub's second trap calls `stop`;
|
||||
- on `none` there's no `SIGSEGV` or vectored handler;
|
||||
- `core::fault_at` enters the trap stub as the Linux handler does now.
|
||||
- **The image** (`binary::elf`, in `binary`): a `.bss` segment of `PT_LOAD` with a
|
||||
file size short of its memory size, `--base`, and, for the top 2 GiB, the sign-extended
|
||||
forms in `binary::amd64`, `calls.sakura` in `sakura-native` and the handlers.
|
||||
- **Intrinsics:**
|
||||
- `emitter/intrinsics.sakura` in `sakura-compiler` lowers each to an IR operation;
|
||||
- `binary::amd64` encodes it;
|
||||
- the optimizer's table (`intermediate/code.sakura` in `sakura-compiler`) marks the
|
||||
volatile and privileged ones as touching all memory.
|
||||
- **`@interrupt`, `@align` and `@packed`:**
|
||||
- the checker reads them (`checker/attributes.sakura` in `sakura-analyzer`);
|
||||
- `layouts.sakura` in `sakura-compiler` lays out `@align` and `@packed`;
|
||||
- `calls.sakura` in `sakura-native` writes the interrupt entry.
|
||||
|
||||
**`runtime` and `core`:**
|
||||
- `runtime/`'s formatting, values, floats and the heap's algorithm move into `core`;
|
||||
- the four platform functions go into its Linux and Windows sections;
|
||||
- `core::x86_64` and the volatile intrinsics are added.
|
||||
|
||||
## Testing
|
||||
|
||||
- **As a Linux process,** without QEMU.
|
||||
- An image for `none-x86_64` runs on this machine. Linux loads its `ET_EXEC` and
|
||||
starts it in ring 3, where the start takes `wrgsbase`.
|
||||
- A test platform module stops and reports through `x86_64::system_call`, as Linux's
|
||||
`exit_group` and `write`.
|
||||
- That tests the start, the heap over `pages` and over `--heap`, faults and their
|
||||
traces, `<globals>`, the stack's limit, volatile memory, and the corpus's programs
|
||||
that need only `core`.
|
||||
- **Each build that reaches the heap with none given** fails, naming the way.
|
||||
- **On QEMU,** where it's installed: a small kernel in `test/kernel/`, booted by Limine.
|
||||
- It writes to the serial port, which `-serial stdio` gives the test.
|
||||
- It ends through QEMU's `isa-debug-exit` device, `port_out32(0xF4, code)`, which
|
||||
gives QEMU's exit status.
|
||||
- It takes a breakpoint and a page fault through `@interrupt` handlers, and reports
|
||||
the page fault as a fault, with its trace.
|
||||
- It reads a timer through volatile memory, and builds at its top-2-GiB base.
|
||||
- **Layout:** `@packed` and `@align` structs' sizes and offsets, checked by reflection.
|
||||
- **Linux and Windows unchanged:**
|
||||
- the corpus in the VM and natively at each level;
|
||||
- the std suite, and the compiler's unit tests;
|
||||
- the compiler building itself to its fixed point.
|
||||
|
||||
## Phases
|
||||
|
||||
1. **The runtime split,** after the std plan's `core`:
|
||||
- formatting, values and floats into `core`;
|
||||
- the heap's algorithm into `core` over `pages`;
|
||||
- `fail` split into building and writing.
|
||||
|
||||
Linux and Windows behave as before. About 900 lines of `runtime` moved, and 150 in the
|
||||
compiler.
|
||||
2. **`none-x86_64`:** the target and `when os == none`, the start, `platform`, faults,
|
||||
`.bss`, `--base` (low 2 GiB), `--heap` and `--stack`, and the note for a module of
|
||||
other targets. Tested as a Linux process. About 600 lines in the compiler.
|
||||
3. **The hardware:** `core::x86_64` and the volatile intrinsics. About 400 lines in the
|
||||
compiler.
|
||||
4. **Layout:** `@align` and `@packed`, and the README's layout. About 250 lines.
|
||||
5. **Interrupts:** `@interrupt`. About 300 lines.
|
||||
6. **The top 2 GiB.** About 300 lines.
|
||||
7. **A kernel booting on QEMU,** in `test/kernel/`. This needs QEMU, and Limine's files,
|
||||
on the machine running it.
|
||||
8. **The README:** "Executables and tools", "Pointers and memory", and a section on
|
||||
programs with no operating system.
|
||||
|
||||
## Found along the way
|
||||
|
||||
- **A loop polling memory reads it once,** in the optimizer, since nothing in the loop
|
||||
writes it. Harmless now, wrong for a device register.
|
||||
- **`.data` is written whole,** so a zeroed global costs its size in the file.
|
||||
- **`build_options.stack` exists,** and nothing sets it.
|
||||
- **`arena::over(buffer)` falls back to the heap** when its buffer is full, which on a
|
||||
target with no heap must fail instead.
|
||||
|
||||
## Later, where wanted
|
||||
|
||||
- **UEFI:** `uefi-x86_64`, a PE for the firmware (subsystem 10) with its entry under the
|
||||
Windows calling convention.
|
||||
- Its platform: pages from `AllocatePages`, reports to `ConOut`, `stop` through
|
||||
`Exit`.
|
||||
- A PE with its relocations stripped loads only where its base is free, so it may
|
||||
need a `.reloc`.
|
||||
- **Several processors:** a record per processor at `gs`, the heap's lock as a spin, and
|
||||
starting the others.
|
||||
- **Programs for one's own system,** in ring 3, with `swapgs` and system calls of its
|
||||
own.
|
||||
- **Code that can be placed anywhere,** RIP-relative, for PIE and relocatable PEs.
|
||||
- **Allocators for `box`, `rc` and `arc`,** and for `$"..."`, so a program with no heap
|
||||
can use them.
|
||||
- **`aarch64`,** where the platform layer would carry over unchanged.
|
||||
- **Object files and exported symbols,** to link with assembly or C.
|
||||
- **Thread-local variables,** which [later.md](later.md) lists already.
|
||||
|
||||
## Decisions for you
|
||||
|
||||
1. **Which targets first:**
|
||||
- **(a) `none-x86_64` alone,** with UEFI later.
|
||||
- **(b) `none-x86_64` and `uefi-x86_64` together.**
|
||||
|
||||
Recommended: **(a)**. It holds everything a kernel needs, and UEFI then reuses its
|
||||
platform layer.
|
||||
2. **Where a freestanding program's platform lives:**
|
||||
- **(a) A module `platform`, given by the program or a library,** whose functions the
|
||||
compiler finds by name, as it finds `runtime`'s. A platform can be shared as
|
||||
a package.
|
||||
- **(b) Attributes on the program's functions,** as `@platform(stop)`.
|
||||
- **(c) A whole runtime of the program's own** in place of `runtime`, writing all
|
||||
16 helpers.
|
||||
|
||||
Recommended: **(a)**. Four functions, one required, and the language's helpers stay
|
||||
the language's.
|
||||
3. **The heap on `none`:**
|
||||
- **(a) Only where it's given,** by `platform::pages` or `--heap SIZE`. A build that
|
||||
reaches it otherwise fails, naming the way.
|
||||
- **(b) Always a region of a fixed size,** unless `--heap` says otherwise.
|
||||
- **(c) None at all.** Every container takes an allocator, and `box`, `rc`, `arc` and
|
||||
`$"..."` are refused.
|
||||
|
||||
Recommended: **(a)**. A kernel chooses where its memory comes from, and a mistake is
|
||||
caught at build time, not at boot.
|
||||
4. **The start:**
|
||||
- **(a) Written by the compiler,** as now, with no system calls.
|
||||
- **(b) Written by the program,** with naked functions and the intrinsics.
|
||||
|
||||
Recommended: **(a)**. The thread record, the stacks and SSE must be set before any
|
||||
Sakura code runs, and only the compiler knows their layouts.
|
||||
5. **Where an image may be placed:**
|
||||
- **(a) The low 2 GiB,** at `--base`.
|
||||
- **(b) Also the top 2 GiB,** for kernels.
|
||||
- **(c) Anywhere,** with RIP-relative code.
|
||||
|
||||
Recommended: **(b)**. Kernels live there, and it changes only how addresses are
|
||||
written as numbers. (c) changes every address the native backend writes.
|
||||
6. **Reaching the hardware:**
|
||||
- **(a) Intrinsics in `core::x86_64`,** and `volatile_load` and `volatile_store`.
|
||||
- **(b) Inline assembly.**
|
||||
|
||||
Recommended: **(a)**. 28 intrinsics cover a kernel. The optimizer knows what
|
||||
each does. And the compiler has no assembler to read text with.
|
||||
7. **Interrupt handlers:**
|
||||
- **(a) `@interrupt` functions,** whose entry and exit the compiler writes.
|
||||
- **(b) Naked functions** the program writes, with the intrinsics.
|
||||
|
||||
Recommended: **(a)**, for the same reason as decision 4.
|
||||
8. **Layout:**
|
||||
- **(a) `@align(N)` and `@packed`.**
|
||||
- **(b) `@align(N)` only,** with packed data written as bytes.
|
||||
|
||||
Recommended: **(a)**. Descriptor tables' pointers and many on-disk formats are
|
||||
packed.
|
||||
9. **The first boot to test on:**
|
||||
- **(a) Limine,** whose protocol starts a 64-bit ELF in long mode, in the top 2 GiB.
|
||||
- **(b) UEFI,** which needs decision 1's (b).
|
||||
|
||||
Recommended: **(a)**, with decision 5's (b).
|
||||
+729
@@ -0,0 +1,729 @@
|
||||
|
||||
|
||||
|
||||
# Later
|
||||
|
||||
What the built plans left for later, and the problems they found and didn't fix. Each item
|
||||
was checked against the compiler and std on 2026-10-28, and is still open unless it says
|
||||
what's left of it. What was built since went, as did the records of what was built, which
|
||||
the CHANGELOGs keep.
|
||||
|
||||
The plans not yet built keep their own "Later" lists: [algorithms.md](algorithms.md),
|
||||
[benchmarks.md](benchmarks.md), [freestanding.md](freestanding.md), [linear.md](linear.md),
|
||||
[logging.md](logging.md), [random.md](random.md) and [tui.md](tui.md).
|
||||
|
||||
[roadmap.md](roadmap.md) says what's left before the language's freeze, and which items
|
||||
here must come before it.
|
||||
|
||||
## The language
|
||||
|
||||
### Lambdas that own what they use
|
||||
|
||||
A lambda only refers to the locals it uses. Whatever must outlive its frame is a functor
|
||||
written by hand, or a `function` holding one. Capture lists, or a `func` that owns what it
|
||||
captures, would let a lambda be returned or given to a thread. You set both aside when
|
||||
the memory plan was built ("for now"). A `function` holding such a lambda would own what
|
||||
it captured with nothing in `function` changed. It's the roadmap's last step, with
|
||||
directions that avoid a list in brackets ([roadmap.md](roadmap.md#lambdas-that-own-what-they-use)).
|
||||
|
||||
### References and values: what the rule left
|
||||
|
||||
What the rule "where a value goes says what happens to it", built on 2026-10-22, left:
|
||||
|
||||
- **Only named functions are adapted.** A lambda whose parameter types are written,
|
||||
as `def(s: &string)` given where `def(&mut string)` is asked, and a function value
|
||||
held in a variable, must still match. A lambda with its types left out takes them
|
||||
from where it goes.
|
||||
- **A copy of `T` in generic code is refused only per instance.** `val x := v[i]` in a
|
||||
generic over `T` copies, and an instance whose `T` closes reports it, as C++ would.
|
||||
A bound saying "closes nothing" would let the template report it once.
|
||||
- **`&&T` still exists inside instances.** Where a type parameter is a reference,
|
||||
`&x` of a `T` refers to the variable holding it, as the template means. Only
|
||||
generic code sees such a type; a function given where one is asked is adapted.
|
||||
- **A reference variable is pointed elsewhere by a reference written as one**, `r =
|
||||
&y`, as C++'s pointers are and its references aren't. Refusing it would match
|
||||
C++'s references, but chains walked by reassigning a reference need it.
|
||||
- **An overloaded member named with its type's arguments**, as `box::<i64>::get`,
|
||||
is the first overload, not the one the type expected chooses. Named without them,
|
||||
`box::get` chooses.
|
||||
- **`for x` copies each element**, which for a large struct costs a copy that
|
||||
`for &x` avoids. How often the optimizer removes it hasn't been measured; for a
|
||||
256-byte struct at `-O2`, it did.
|
||||
|
||||
### Joining text with `+`
|
||||
|
||||
`string + strview`, with `+=` as an `add_assign` that appends in place, which a compound
|
||||
assignment calls since 2026-10-20. The compiler refuses `+` today: "`string` has no `add`
|
||||
taking a `&strview`, which `+` calls."
|
||||
|
||||
### More operator traits
|
||||
|
||||
- Traits for mixed operands, as `scales<S>` for a vector times a number, once programs
|
||||
show which ones they need.
|
||||
- A partial order for floats, so generic code can say what NaN does.
|
||||
- There is no `bitwise` trait, by decision: a program's own trait gives `&`, `|` and the
|
||||
shifts to generic code.
|
||||
|
||||
### `strview` has no order
|
||||
|
||||
`strview::compare` takes the other view by value, so `strview` isn't `ordered`, and
|
||||
`v < w` of two views is refused: "`strview` has no order". So the note refusing `s < v` of
|
||||
a `string` and a view, which asks for `s.span`, leads to a second refusal.
|
||||
|
||||
### A trait's defaults reach only the types naming it
|
||||
|
||||
A method a trait writes a body for is its default, which a type may leave out. The compiler
|
||||
counts a type as meeting the trait by its methods, whether or not it names the trait, but
|
||||
only one naming it gets the defaults. So a struct with only `put` passes `where S: sink`
|
||||
for a `sink` asking for `put` and giving `done`, and `S is sink` is true of it, and the
|
||||
instance then fails where the generic calls `done`: "`plain` has no field, property, or
|
||||
method `done`. (In `finish<plain>`)". Either the defaults should reach every type meeting
|
||||
the trait, or a type leaving a default out should meet the trait only by naming it. The
|
||||
first would let `writable` give a `flush` that does nothing, so `flushable` could go with
|
||||
`if const S is flushable` in `std::io::writer`. A constant a trait gives a value is a
|
||||
default the same way, since 2026-11-19, taken only by a type naming the trait.
|
||||
|
||||
### Named constants without a type
|
||||
|
||||
`const pi := 3.14` is an `f64`, and `const k := 7` an `i64`, so `val x: f32 = pi` is
|
||||
refused, where the literal would fit. `std::math`'s constants are `f64` for that reason,
|
||||
and f32 code writes `math::pi as f32`.
|
||||
|
||||
### What a constant may hold
|
||||
|
||||
```sakura
|
||||
const b: box<i64> = box::new(3);
|
||||
const s: string = string::from("abc", nothing {});
|
||||
```
|
||||
|
||||
The compiler takes both, and a `vector<i64>` made by a function, on the machine, under
|
||||
`--checks` and in executables. The README says a constant holds what is only read, "so a
|
||||
`span<T>` works and a `string` doesn't". Which is the language isn't decided, and refusing
|
||||
them later would break programs, so it comes before the freeze ([roadmap.md](roadmap.md)).
|
||||
|
||||
### `decl_of` of a built-in type
|
||||
|
||||
`decl_of::<i64>()` gives a declaration named `i64`, whose kind is `target::all`, 65,535, so
|
||||
`decl_of::<T>().kind == target::structs` is false of it but
|
||||
`(kind & target::structs) == target::structs` is true. The README says `decl_of` takes "a
|
||||
type a declaration makes, so not a reference or a number". Refusing it, as "`i64` is built
|
||||
into the language, so there is no declaration of it to describe.", would break programs
|
||||
later, so it comes before the freeze too.
|
||||
|
||||
### `type_of(f)::name()`
|
||||
|
||||
It doesn't parse: "Expected `)` to close the arguments. Found `::`." `std::args` works
|
||||
around it with generic helpers, as `switched::<type_of(f)>()`, `is_command` and
|
||||
`shape_of`.
|
||||
|
||||
### Documentation as a reflection intrinsic
|
||||
|
||||
An intrinsic giving a declaration's `#!` comment would let `std::args` print a field's
|
||||
documentation as its help, rather than `help = "..."` repeating it. Only the language
|
||||
server reads those comments now.
|
||||
|
||||
### Thread-local variables
|
||||
|
||||
`@thread_local var`, reached through the thread's record at `gs:[offset]`.
|
||||
|
||||
### 128-bit integers
|
||||
|
||||
Their multiplication would serve `fma` and hashing.
|
||||
|
||||
### Tracking moved locals
|
||||
|
||||
A local moved on every path needn't be closed at all, and reading one after a move could
|
||||
be an error. The checker doesn't track moves: a moved-from value is left zeroed and
|
||||
closed as usual.
|
||||
|
||||
### `equatable` and `hashable` for `void`
|
||||
|
||||
They'd take methods the compiler gives, and nothing needs them yet. So `dict<void, V>`
|
||||
fails at `hash<void>` and `equals<void>`.
|
||||
|
||||
### Refused for now
|
||||
|
||||
What the rules settled on 2026-10-20 refuse, where accepting it later is an addition:
|
||||
- **A function ending in `while true` with no `break`:** "The function can end without
|
||||
returning a value."
|
||||
- **A lambda's types inferred through overloads,** as `go(def(a) => a + 1, 2)` where two
|
||||
`go`s take a function: "The call fits more than one overload of `go` as well". Merging
|
||||
`spawn` and `spawn_with` waits on it ([Threads](#threads)).
|
||||
- **A variable declared through a generic type,** as `var holder::count: i64 = 0;` for a
|
||||
`holder<T>`.
|
||||
- **A property of a type rather than a value.** Every property is a value's. If one's
|
||||
wanted, it's better marked in the declaration, as `get()` with an empty list, than
|
||||
inferred from whether a body uses `this`, which a trait's `{ get; }` has no body to
|
||||
tell by.
|
||||
|
||||
### What `match const` left
|
||||
|
||||
Built on 2026-11-16, with `core`'s traits naming a type's parts (`pointer`, `reference`,
|
||||
`array`, `generic`), `T is vector`, and packs of types walked and indexed; then aliases
|
||||
of it standing for what they choose, branches and arms ruling out what they don't fit,
|
||||
a body checked once for each case, and trait constants as constants; then the shapes of
|
||||
`T: array` and `T is vector`, `C ? A : B` types, what follows a leaving branch checked
|
||||
per case, and a trait ruling out what implies it; then shapes of generics taking packs,
|
||||
bounded as the generic bounds them, `*x` of a `T: pointer`, and branches naming a type
|
||||
checked within the generic; then tests of types, calls, and `==` choosing types, each part
|
||||
of a condition resolved with what the parts before it proved, constants only an instance
|
||||
decides worked out for each, and generic types' own variables and constants; then values
|
||||
given as types not chosen yet, or used, checked in each way those can be chosen; then
|
||||
ternaries choosing by constants naming type parameters, `match const` of values, and
|
||||
`T: reference` as a reference. Left:
|
||||
- **Patterns that name parts,** as `pair<type A, string>` or `type L[const N]`. The style
|
||||
is settled: a name a pattern declares is written `type A`, or `const N` for a constant,
|
||||
only where a known type could stand too, so parameter lists keep `<L[N]>` and
|
||||
`<def(Ts...): R>` bare. Today such a shape is a trait arm and a test within it, as
|
||||
`pair => if const T::args...[1] is string { ... }`, which leaves the arms after it
|
||||
untried. `match const` refuses `type` there now, so it's an addition.
|
||||
- **`C ? A : B` takes a name, `!` of one, a call, a name tested with `is` or compared
|
||||
with `==` or `!=`, or `( expression )`, and what `&&` and `||` join to those,** so
|
||||
`N > 4 ? A : B` needs its parentheses, since `<` and `>` are a type's arguments; `!`
|
||||
takes only a name, so `!small(N) ? A : B` needs them too; after `as` or `is`, `?` is
|
||||
the expression's; and among type arguments, `M ? K1 : K2` of two constants' names is
|
||||
read as types, where `(M ? K1 : K2)` is a constant, and `!M ? A : B` is read as a
|
||||
value.
|
||||
- **`if const A && B` checks `B` before `A` proves anything,** so `if const T is pointer
|
||||
&& T::target is integer` reports `T` having no `target`, twice, where a type's
|
||||
condition resolves `T::target` with what `T is pointer` proved. Within an instance,
|
||||
`T::target` as a value's path, as the left of `is`, is refused where `T` is given a
|
||||
pointer, though the type `T::target` is found through `pointer`.
|
||||
- **A fault working out a constant for an instance doesn't say which,** so `split<0>` of
|
||||
`type split<const N: u64> = halves(N) ? u8 : u64;` reports "Evaluating `<value>`
|
||||
stopped: Division by zero." at `halves(N)`, with nothing of `N` being 0.
|
||||
- **A note a value of a type not chosen yet gives where it converts says its type
|
||||
whole,** as "Expected `u32`, but the value is `N == 4 ? u32 : uint`." of `return w +
|
||||
1;` within `def f<const N: u64>(w: word<N>): u32`, where a note said in one way of what
|
||||
uses it says which way. A way that only says what fails says nothing of it either, as
|
||||
`T` not converting to `&T` where `T` is neither a reference nor a pointer, said
|
||||
without "(Where ...)".
|
||||
- **`match const` of values takes values written in place as patterns,** as `4`, `-1`,
|
||||
`'a'`, or `true`; a named constant or an enum's member is read as a type there, so
|
||||
`match const N { MAX => ... }` reports no type `MAX`. Such a pattern would be read as
|
||||
the constant it names where the subject is a constant.
|
||||
- **A `match const` value whose arms share no type is an error** within a generic's own
|
||||
body, where a ternary choosing so is of a type chosen as its condition chooses, as `M
|
||||
? u8 : strview`.
|
||||
- **What follows a guard testing a value of a type not chosen yet** names what the test
|
||||
names as the first way the type can be chosen does, so after `if !(h is some(x)) {
|
||||
return 0; }` of a `W ? maybe<u64> : maybe<u8>`, `x` is a `u64` in what follows,
|
||||
where each instance has its own.
|
||||
- **A `match const` value's type in an instance** is the one its arms share in the
|
||||
generic's own body only where that body is checked first, as it is for a program's
|
||||
generics; otherwise it is the chosen arm's.
|
||||
|
||||
### What sealed traits left
|
||||
|
||||
Built on 2026-11-19: `@sealed` traits, whose constants and types are their own, read
|
||||
through the trait given its arguments, and trait constants' values as defaults. Left:
|
||||
- **A sealed constant in a condition says what its value tests only of a type parameter
|
||||
given for one of the trait's own,** as `owns::<T>::value` does. Given a type holding
|
||||
one, as `owns::<&T>::value`, it says nothing within the generic's own body, so a branch
|
||||
it guards is checked knowing nothing, and each instance decides it. Its value says
|
||||
something only through `is` tests, `&&`, `||`, `!`, and other sealed constants, as
|
||||
`if const` does.
|
||||
|
||||
### What pack fields left
|
||||
|
||||
Built on 2026-11-19: a struct's field holding a pack, `items: Ts...`, `core`'s
|
||||
`tuple`, and a pack's type at an index worked out from constant parameters,
|
||||
`Ts...[I]`. Left:
|
||||
- **A pack given whole to a parameter,** as `take(args)` of `take<T>(x: T)`, gives `T`
|
||||
the pack, which each instance then refuses with "A pack is passed on among type
|
||||
arguments written `Ts...`". The call should be refused where it is written, as a pack
|
||||
bound to a local now is.
|
||||
- **A field's pack is written a value at a time,** or given whole by a literal: `t.items
|
||||
= args` is refused as a mismatch rather than writing each value.
|
||||
- **`tuple` names no traits,** since a struct names its traits for every instance and
|
||||
none can be named only where each of its types implements them. So a tuple is copied
|
||||
byte for byte where nothing in it closes, and no `copy_of`, `move_of`, `equals`,
|
||||
`hash`, or `compare` reaches through one.
|
||||
- **No destructuring,** as `val (a, b) := t`, and `t[0]` is not `t.items[0]`.
|
||||
- **A known pack at an index only a template knows,** as `pick::<J>(1, true, 2u)`
|
||||
within `def outer<const J: u64>()`, is a type parameter bounded by nothing there, so
|
||||
returning it as a `bool` is refused even where each instance made gives a `bool`. A
|
||||
`match const` over the index's values would check it as each way instead.
|
||||
- **`for const` over a field's pack reached through `&this`** reports a write to its
|
||||
variable once for each of the pack's types in each instance.
|
||||
|
||||
### Contracts
|
||||
|
||||
What the contracts plan left for later:
|
||||
- **Contracts on a trait's methods,** checked for every type implementing it.
|
||||
- **`old` of what closes,** copied and closed after the check.
|
||||
- **A type's invariant,** checked after each of its `pub` methods.
|
||||
- **The checker proving contracts:** warning where one always fails, and leaving out one
|
||||
it proved, from what it already knows of bounds.
|
||||
- **Levels,** as `--contracts expects`, keeping pre-conditions only.
|
||||
|
||||
### Calling C
|
||||
|
||||
What the ffi plan left for later:
|
||||
- **C's variables,** as `errno` or `environ`: a `var` in an extern section is a Sakura
|
||||
global of its own.
|
||||
- **Variadic C functions,** as `printf`. A parameter written `i64...` passes a span.
|
||||
- **A C name that isn't a Sakura name,** as a keyword: a name given to the symbol apart
|
||||
from the declaration's.
|
||||
- **The machine calling C on Linux,** with System V's convention, so a program calling C
|
||||
runs without being built. It stops where it reaches one, or a C function's address: "Program
|
||||
uses a construct that cannot be compiled."
|
||||
- **`system::macos` and `system::freebsd`.** macOS needs `libSystem` and a Mach-O writer.
|
||||
|
||||
## The compiler
|
||||
|
||||
### Addresses made numbers while evaluating
|
||||
|
||||
- **`remove_at`, `extend` and `string::append` in a constant.** std's containers work in
|
||||
a constant, but `memcpy` (`core/mem.sakura`) turns two addresses into numbers to compare
|
||||
them where it moves 8 bytes or more, so evaluating stops there: "Function does not run
|
||||
while compiling. at memcpy". Comparing the pointers themselves (`p < q`, `q - p`) runs
|
||||
in a constant, so `memcpy` could do without the numbers.
|
||||
- **The note doesn't say why.** Evaluating says only "Evaluating `k` stopped: Function
|
||||
does not run while compiling.", with a trace, where it could say that an address is
|
||||
only known where the program runs, so pointers and integers don't convert while
|
||||
compiling.
|
||||
|
||||
### Small unions as values
|
||||
|
||||
A union of two or three words, as `maybe<u64>`, would be held as words and returned in
|
||||
`rax`, `rdx` and `rcx`, so a range's `next` gives its `maybe` in registers. It's returned
|
||||
in memory now. The iterators plan's numbers held without it.
|
||||
|
||||
### Lambdas given to adapters
|
||||
|
||||
`v.iter().filter(lambda).map(lambda).sum()` costs 3 to 4 times what functors do: 565 to
|
||||
599 ms against 144 to 190 ms over ten million elements at `-O2` (`tools/iterators.sakura`).
|
||||
The adapter is built by 16-byte copies, and its lambdas are called through `call_value`,
|
||||
so they aren't inlined, even one whose function is known as a constant. Reading words
|
||||
through wide copies, or a type of each lambda, would fix it.
|
||||
|
||||
### `box` within 10% of `raw_allocate`
|
||||
|
||||
The memory plan asked for it. `tools/memory.sakura` gives `box` 1.31 to 1.38 times
|
||||
`raw_allocate`. What's left:
|
||||
- walking a list through a `maybe<&T>` picks the next node with a `select` that the
|
||||
loop's exit also reads;
|
||||
- every `move` of a value that closes writes the zeroes its source is left with.
|
||||
|
||||
### Atomics
|
||||
|
||||
- **`lock add`, `lock or` and the like where the result isn't used,** as
|
||||
`_ = hits.fetch_add(1)`, which is `lock xadd`. `fetch_and`, `fetch_or` and `fetch_xor`
|
||||
would lose their `lock cmpxchg` loops.
|
||||
- **Two-word atomics through `cmpxchg16b`,** for a pointer with a count beside it. The
|
||||
oldest x86-64 processors lack it.
|
||||
|
||||
### What the vector work left
|
||||
|
||||
- **`%` of lanes is a loop over them,** as no instruction divides integers.
|
||||
- **The least and greatest of real lanes, and the product of integer ones,** are loops.
|
||||
`smallest` and `largest` work real lanes from lane 0, as which NaN or zero they give
|
||||
depends on the order, which the instructions' pairs of lanes don't keep.
|
||||
- **`scatter` writes a lane at a time.** Only AVX-512 has an instruction for it.
|
||||
- **64 bytes, AVX-512's,** were checked only by disassembling what's built, as this
|
||||
machine has no AVX-512. On one that has it, native's test
|
||||
`vectors_of_64_bytes_give_the_same_bits_at_every_level` works each operation with the
|
||||
instructions, and `tests/programs/simd_lanes_agree_everywhere_2`, built and run, does
|
||||
too; the corpus itself runs on the machine. Such a vector is held in its
|
||||
slot, never a register, and read a quarter at a time; a mask of one is a vector, and
|
||||
`k1` holds it only within an operation. 64 bytes of 8-bit lanes aren't allowed, as their
|
||||
mask's bits wouldn't fit a `u32`. The least and greatest of real lanes go a half or a
|
||||
quarter at a time, and the sums across the lanes, `shuffle`, and changing the lanes'
|
||||
type or size a lane at a time.
|
||||
- **A struct of a size not a multiple of 16,** as three `f32` fields, is built a field at a
|
||||
time: merging stores fills 16 bytes from a multiple of 16 only.
|
||||
- **32-byte vectors go through memory a half at a time** in a function working several,
|
||||
as `geometry`'s frustum test of eight planes as one `f32x8` did: each `select`'s and
|
||||
splat's result was stored whole and read back as two halves, and each splat was two
|
||||
shuffles where `vbroadcastss` is one. It ran no faster than a plane at a time, and in
|
||||
one build twice as slow, where two `f32x4`s run twice as fast, so `geometry` uses those.
|
||||
- **A vector's lanes read as numbers,** as `vec3::dot` adds its products' lanes, made
|
||||
`geometry`'s rays two to three times as slow as the same dot worked a number at a time,
|
||||
though `linear`'s bench of `dot` alone finds the two even. `geometry` works its dots a
|
||||
number at a time.
|
||||
|
||||
### What the analyzer's tables left
|
||||
|
||||
What making the analyzer's tables smaller and its passes quicker left, as checking the
|
||||
compiler's own sources measured it:
|
||||
- **Vectors made for each call checked.** `arg_kinds`, `try_candidate`, the five vectors
|
||||
`begin_inference` makes, and `check_args_bounds`'s copy of the parameters are made for
|
||||
each call, about 1% of checking. They nest, as checking an argument checks its calls,
|
||||
so a scratch column would need marks, as `type_table::substitute`'s has.
|
||||
- **Rows for nodes that have no results.** A result table has a row for each node, but
|
||||
many are never written: statements, type names, and declarations. Of a file's rows, 72%
|
||||
are of nodes with results checking the compiler, and 15% checking a corpus program,
|
||||
whose libraries are mostly not reached. Numbering only those nodes, as the analyzer's
|
||||
rework built and took out, saved 1.5% of the instructions, and the peak resident memory
|
||||
rose. It would pay where the rows of what isn't reached are never made, as with bodies
|
||||
parsed when reached.
|
||||
- **Evaluating what checking left.** Evaluating now runs while checking, where checking
|
||||
asks (1% of checking the compiler), but what the compiler needs that nothing asked for,
|
||||
the values of the constants it lowers, is still worked out after checking, in
|
||||
`compile_time::finish`: 6.8% of checking the compiler, almost all of it lowering what
|
||||
those constants call. It wasn't looked into.
|
||||
- **Words written a field at a time.** `zeroed_cells` counts a word as written only where
|
||||
one store covers it whole, so a cell built field by field, of fields narrower than a
|
||||
word, is zeroed though every byte of it is written. Following 4-byte halves would catch
|
||||
most structs.
|
||||
|
||||
### What the analyzer's rework left
|
||||
|
||||
What building the changes of "If we were to rewrite the analyzer" left, as checking the
|
||||
compiler's own sources measured it (1,261M instructions after the rework, from 1,462M):
|
||||
- **Instances checked again whole.** An instance checks every node of its template again,
|
||||
about 15% of checking the compiler. Of its templates, 21% of the top-level statements,
|
||||
which hold 53% of their nodes, depend on no type parameter, so an instance could read
|
||||
those from its template's table. Built, it left lowering an instance recursing without end,
|
||||
and it was taken out.
|
||||
- **Bodies parsed when reached.** Of a corpus program's library bodies, those never reached
|
||||
are 59% of the tokens, 19,529 in generic bodies and 15,680 in others; of the
|
||||
compiler's, 7%. A generic's instance table covers its template's nodes in one run, so
|
||||
its body is parsed with it; the checker holds the syntax's columns by address while it
|
||||
checks, which nodes added while checking would move; and the resolver finds the
|
||||
modules a body names from its paths, so a body skipped would have its paths read from
|
||||
its tokens. The other bodies would save at most about 4M of a corpus program's 67M.
|
||||
- **Bodies checked on threads.** Checking bodies is 48% of checking the compiler, but
|
||||
bodies write what they all share: they make 6,157 of the 14,391 types, 3,241 of the
|
||||
3,246 instances, 291 of the 903 knowns, and 3,987 of the 4,300 tables, and reach 8,195
|
||||
of the 9,249 declarations checked. Those IDs reach what the compiler builds, so a build
|
||||
that's the same every time needs them given in an order threads don't change, as in
|
||||
declaration order once the bodies are checked, with each body's own new types, knowns
|
||||
and instances held apart until then. The evaluator runs on one thread too.
|
||||
- **Notes as data.** A note could be a code, a node, and a few IDs, its text made when
|
||||
it's shown, once something reads its IDs, as the server offering fixes would. Today
|
||||
the text made for notes left out is 0.01% of checking the compiler, `sakurac` shows
|
||||
notes from another thread while checking goes on, which can't read the checker's
|
||||
tables, and 85 notes write lists or numbers that a few IDs don't hold.
|
||||
- **`quiet`.** What's checked for its results alone is checked with its notes left out: a
|
||||
type written for `this`, an attribute's type as reflection reads it, a template's branch
|
||||
where `if const` names what a parameter is, and an editor's query. Each could ask for
|
||||
what it needs without checking, so no note is made to be left out.
|
||||
- **IDs of their own types.** An enum can't be an ID's type, since a value cast to one
|
||||
must be one of its members, and a struct of one `u32` is kept in memory, not a
|
||||
register, so declarations, types, names and instances are still bare `u32`s; only a
|
||||
file's nodes and a table's are told apart, by `file_node` and `table_node`. Either
|
||||
needs the compiler to change first.
|
||||
- **One more than an index.** The analyzer holds none, but `id_index` keeps an ID as one
|
||||
more within its words, and the compiler holds many: `flows`' links, `reader_next`,
|
||||
`program`'s `niche` and `adapted`, and a report's place.
|
||||
- **Two records of an `if const`.** The checker records whether an `if const`'s condition
|
||||
holds as the condition's value, and evaluating records it again in `decisions`, which
|
||||
the compiler reads.
|
||||
|
||||
### What `@inline` left
|
||||
|
||||
- `@inline` on `checker::unalias`, a test of a type's flags and a call where it fails,
|
||||
made the compiler 312 KB larger across its 342 calls, about 900 bytes each, and ran no
|
||||
fewer cycles, so it isn't marked. What a copy takes at each call is worth seeing.
|
||||
|
||||
- std's own helpers called in its loops over text aren't marked, std being a repository
|
||||
of its own: `json`'s `plain_stops` and `is_json_space`, and `yaml`'s `comment_ends`.
|
||||
- At `-O0` a copy still writes each argument into its cell and reads it back, and each
|
||||
span a copy returns waits on the stores that built it, so a chain of copies waits on
|
||||
memory as a chain of calls does. Marked, `span::sub` and `span::over`, `find_byte`,
|
||||
`find_last_byte` and `count_byte`, and `bytes8::upper` and `lower` were slower at `-O0`
|
||||
(`find_byte` at `-O2` too), so they aren't. `swar::load_last` and `u8::digit_value`
|
||||
gained only at `-O2`, by 4%, so they aren't either.
|
||||
|
||||
### aarch64
|
||||
|
||||
There's no aarch64 back end. Atomics would be `ldar`, `stlr` and `ldaxr`/`stlxr` loops or
|
||||
LSE there, which is why an atomic's order is a value as the program runs, and `simd`
|
||||
would be NEON.
|
||||
|
||||
### The command's name
|
||||
|
||||
`sakurac check --help` says `usage: sakura check`, and a wrong option says "Try
|
||||
`sakura build --help`", the name the compiler had.
|
||||
|
||||
### Checked executables
|
||||
|
||||
`build --checks` makes the checks of a checked program, as indexes, and none of
|
||||
`run --checks`' of memory. A runtime with a shadow map, as AddressSanitizer has, would
|
||||
check an executable's references and pointers, and the bytes nothing wrote.
|
||||
|
||||
### Guard pages for the stack
|
||||
|
||||
A page nothing may touch below each stack would report an overflow from the fault, and
|
||||
the prologue's compare with the stack's end could go. The compiler already leaves that
|
||||
compare out of small leaf functions.
|
||||
|
||||
### Fresh pages taken as zero
|
||||
|
||||
The compiler's result tables read zero as "nothing yet", so they grow by zeroed
|
||||
elements, a file at a time, and every byte is cleared. A vector grown into pages fresh
|
||||
from the system could take them as zero without clearing them, if `raw_resize` said
|
||||
which bytes it gave fresh. Only a vector's first allocation does that today.
|
||||
|
||||
### Reading libraries
|
||||
|
||||
What the std plan left for later:
|
||||
- **The checked `core` kept between runs.** It's the same for every program, so the time
|
||||
checking it takes could be read from a file the compiler wrote, rather than checked
|
||||
again.
|
||||
- **`core` written into the compiler whole.** It needs the compiler to take a file in
|
||||
while compiling, as an `embed` intrinsic, which it can't now.
|
||||
- **An index of a library's modules,** written by blossom where it fetches a package, if
|
||||
a library's folders ever grow too many to list. The resolver lists each folder once,
|
||||
but a module's files may be in any folder within its own, so finding the files of a
|
||||
library's first module, as `std` where `--lib std=` names the whole repository, lists
|
||||
every folder of it: the 403 folders of std's YAML test suite cost a corpus program 8M
|
||||
instructions of 67M. blossom names each module's library, as `std::io`, which lists
|
||||
none of them.
|
||||
|
||||
### Large blocks kept at one size
|
||||
|
||||
The runtime keeps up to 64 large blocks given back, 32 MB in all, but hands one out again
|
||||
only for as many bytes as it was, so the token and node vectors the lexer and parser trim
|
||||
to fit leave their old blocks resident, and so do the vectors that grew past them. Checking
|
||||
the compiler peaks at 48 MB resident where the analyzer's tables hold 28 MB.
|
||||
|
||||
### What the race checker leaves
|
||||
|
||||
- **Two reads a word.** Of each word it keeps the last write and the last reads of two
|
||||
threads, so a write racing a third thread's read, while two others read too, can go
|
||||
unseen.
|
||||
- **Atomics against plain reads and writes.** An atomic operation orders threads but isn't
|
||||
kept as an access, so a plain write racing an atomic load of the same word isn't seen.
|
||||
- **What only the frame reaches.** A cell no reference to which is taken is never watched,
|
||||
which is right, as no other thread can reach it; one reached through a pointer made by
|
||||
arithmetic on another cell's address is missed.
|
||||
- **Executables.** It's the machine's; `build --checks` checks no races, as it checks no
|
||||
memory (see [Checked executables](#checked-executables)).
|
||||
|
||||
### What overflow checks leave
|
||||
|
||||
- **Shifts and narrowing.** `<<` past the bits of a type, and `as` narrowing an integer,
|
||||
wrap as they always do.
|
||||
- **Negating an unsigned number** wraps, so `x & -x` works; Rust refuses `-x` of one.
|
||||
- **Tests that wrap on purpose.** blossom gives a test run on the machine `--checks`, so a
|
||||
test's own arithmetic is checked: `linear`'s and `geometry`'s fold their bits with
|
||||
`mix` for that. std's `thread` tests seed a generator by wrapping, which stops only
|
||||
where they're run with `--checks` by hand, as blossom runs them natively, unchecked.
|
||||
|
||||
### The machine interrupting waits
|
||||
|
||||
`system` has no signal to spare on the machine. While threads run, a futex wait without a
|
||||
time lasts 0.1 s and std's waits wait again, a read blocked forever isn't interrupted, and
|
||||
the first thread waits up to 3 s for the others as `main` ends. With a thread blocked
|
||||
reading, `run` takes about 3.7 s, where the executable ends at once.
|
||||
|
||||
## std
|
||||
|
||||
### `function`
|
||||
|
||||
`core`'s `function`:
|
||||
- **Converting where a `function` is expected,** so `val f: function<S> = functor;`
|
||||
needs no `function::new`. The compiler would have to know the type by name, and the
|
||||
conversion allocates where the callable doesn't fit.
|
||||
- **`function::bound(&mut x, T::m)`,** binding a method to a value.
|
||||
- **More held in place,** through a constant parameter for the buffer's size, for code
|
||||
that must never allocate. Callables of 24 bytes or fewer are held in place now.
|
||||
- **An allocator for the box,** once `box` takes one as the containers do.
|
||||
- **Constants.** A constant keeps the buffer's words but not the function a function
|
||||
value among them names, so `function::new` reaches its buffer through its address as a
|
||||
number, which refuses every constant `function`. A functor that holds no function
|
||||
value could be allowed.
|
||||
- **C functions,** which `function` holds, but no test covers: the machine can't take a C
|
||||
function's address.
|
||||
|
||||
### Threads
|
||||
|
||||
- **A pool of threads taking tasks, and a parallel `for`.** The compiler's own crew
|
||||
(`compiler/workers.sakura`) could seed one.
|
||||
- **Read-write locks, semaphores and barriers.** `std::thread` has a mutex, a condition,
|
||||
a channel and `once`.
|
||||
- **Waiting on several channels at once.**
|
||||
- **Calling C from any thread, on Linux.** Threads started by `clone` keep the first
|
||||
thread's `fs`, so libc's state for each thread, as malloc's caches and `errno`, is
|
||||
shared. Five threads calling `malloc` and `free` 200,000 times each abort in glibc
|
||||
every time, and nothing warns. Windows starts threads through `CreateThread` and is
|
||||
fine.
|
||||
- **Reentrant console locks.** A thread holding `io::output_locked()` that calls
|
||||
`println` waits forever, even with no other thread.
|
||||
- **A thread given a value and giving one.** `spawn_with` gives a `handle<void>`, so such
|
||||
a thread needs a closure, and a loop variable must be moved in by hand. Merging
|
||||
`spawn` and `spawn_with` into overloads waits on the checker inferring a closure's type
|
||||
through overloads, which it doesn't: "No overload of `go` takes these arguments."
|
||||
|
||||
### Atomics and signals
|
||||
|
||||
- **The signals' waiting word as an `atomic<u64>`.** Handlers would set it, `dispatch`
|
||||
would empty it with `exchange`, and the `take_signals` intrinsic would go.
|
||||
- **Holding signals off for a stretch of code,** as a guard over `rt_sigprocmask`.
|
||||
- **Timers:** `alarm`, and timers that repeat. `signal::alarm` exists, but nothing sets
|
||||
one.
|
||||
- **What a signal says of itself,** as who sent it or which child stopped. A handler is
|
||||
given only the `signal`.
|
||||
- **Real-time signals,** and rarer ones as SIGTTIN, SIGTTOU and SIGPROF.
|
||||
- **Signals as a stream,** through `signalfd` or a pipe, so `poll` wakes for them.
|
||||
`system::watch` and `system::watched` note a signal, but aren't a handle.
|
||||
- **Chaining handlers:** `handle` giving back the handler it replaced.
|
||||
|
||||
### Processes
|
||||
|
||||
- **Waiting for whichever of several children stops first,** and capturing several at
|
||||
once, for a build tool's jobs. Only `system::wait(-1, ...)` waits for any child.
|
||||
- **`child::send(signal)`,** to ask a child to stop, and timeouts on `wait`. `child` has
|
||||
only `kill`. `system::poll` takes a timeout, but `std::process` doesn't use it.
|
||||
- **The error merged into the output in order,** as `2>&1`, and `io::file::duplicate`.
|
||||
- **Overlapped reads on Windows,** in place of looking at each pipe with
|
||||
`PeekNamedPipe` and sleeping up to 10 ms between looks.
|
||||
- **Starting faster with `clone(CLONE_VM | CLONE_VFORK)`,** for a large program starting
|
||||
many children.
|
||||
- **Process groups and sessions,** and a child that outlives the program.
|
||||
|
||||
### Streams
|
||||
|
||||
- **Interpolation written straight into a stream,** without a `string` made for each
|
||||
`$"..."`. A language change.
|
||||
- **Adapters:** a tee, a writer that counts, a reader limited to a length, and
|
||||
compression.
|
||||
- **Reads that don't wait, timeouts, and polling several readers.** `system::poll` does
|
||||
it for handles, but nothing in `std::io` does.
|
||||
|
||||
### Text
|
||||
|
||||
- **Vectors in more text functions.** `find_byte`, and so `index_of`, `contains`, `split`
|
||||
and `read_line`, use vectors where they're held, as do `memset`, `memcpy`, `memcmp`
|
||||
and the JSON reader. `strview::find`, `find_any`, `is_ascii`, `upper` and `lower`,
|
||||
spans' `last_index_of` and `count_of`, and `std::serial`'s `is_utf8` read words only.
|
||||
- **UTF-8 checked a word at a time past ASCII,** as simdutf does. `is_utf8` skips ASCII
|
||||
by words, then checks each sequence a byte at a time.
|
||||
- **Hexadecimal and base64,** encoded and decoded by words. std has neither.
|
||||
- **Comparing text without regard to ASCII case,** through `lower` of each word.
|
||||
- **`core::swar` lanes of 16 and 32 bits,** for UTF-16 and wider tables. It has bytes
|
||||
only.
|
||||
- **Left a byte at a time, on measurement:** trimming (0.76 to 0.93 times as fast by
|
||||
words), and YAML's plain scalars (0.82 to 0.97).
|
||||
|
||||
### Reading the clock
|
||||
|
||||
On Linux, `std::time` reads the steady clock with a system call, about 211 ns in an
|
||||
executable, where glibc reads it through the vDSO in 25 ns. Programs that time small work,
|
||||
and the benchmarks plan, pay it on every read.
|
||||
|
||||
### Parsing numbers
|
||||
|
||||
`integer::parse::<T>` checks only the 64-bit limits, so a narrower `T` wraps:
|
||||
`integer::parse::<u8>("300")` is 44, and `parse::<i8>("-200")` is 56. Positive values
|
||||
stop at `i64`'s largest, so `std::args` reads a `u64` with a reader of its own
|
||||
(`whole_of`, `signed_within` and `unsigned_within`).
|
||||
|
||||
### JSON, YAML and `std::serial`
|
||||
|
||||
- **Fixed arrays,** `T[n]`, aren't written or read by the walk, which refuses a type
|
||||
holding one. A type holding one gives a form of its own.
|
||||
- **The walk over trait references.** It's `encode<T>(value, out: &mut encoder)`, one
|
||||
indirect call for each value, because a trait couldn't be a type argument then. That
|
||||
works now (`feed<E>(out: E) where E: sink` given a `&mut sink`), so the walk could be
|
||||
generic over its encoder.
|
||||
- **Faster float printing,** as Ryu. About 45% of writing JSON, 0.46 s for a 4.3 MB
|
||||
document, was the runtime's `put_float`, exact but working in big integers of 128
|
||||
limbs. Every program printing floats pays it.
|
||||
- **JSON Pointer,** as `doc.find("/params/position/line")`.
|
||||
- **Trees that can be changed,** for JSON and YAML. Both are read-only arrays of 16-byte
|
||||
nodes.
|
||||
- **A field read as a `json::value`.** `json::value` is written but not read, so the
|
||||
language server reads `method` first, then decodes `params`.
|
||||
- **YAML:** comments kept when read and written again; a writer of comments, flow style
|
||||
and anchors for repeated values; tags in typed values, as `!circle {radius: 1}`; and
|
||||
keys that are collections, which `serial::encoder` can't write.
|
||||
|
||||
### Iterators
|
||||
|
||||
- **Splitting a sized iterator across threads.**
|
||||
- **`chunks(n)` and `windows(n)` of a view,** giving views.
|
||||
- **Iterators that write,** as `fill` and `copy_into`, which the algorithms plan has as
|
||||
methods of slices.
|
||||
|
||||
### Math
|
||||
|
||||
- **`erf`, `gamma`, `lgamma`, and the Bessel functions.**
|
||||
- **Correctly rounded versions,** from CORE-MATH, for programs that need results never
|
||||
off by a rounding. MIT-licensed, but several times larger and slower than musl's.
|
||||
|
||||
### Time
|
||||
|
||||
- **`TZ`, and `TZDIR` beyond Windows,** read from the environment. On Linux, zones come
|
||||
from `/usr/share/zoneinfo` and `/etc/localtime` only. `process::variable` exists, so
|
||||
nothing blocks it.
|
||||
- **Formats written with a pattern,** as `strftime`'s.
|
||||
- **Windows zones by name, and the history of its local zone,** from the registry or
|
||||
ICU. `zone::local()` there is the current rule only.
|
||||
- **Leap seconds.** A day is 86,400 seconds, and a second of 60 is `out_of_range`.
|
||||
|
||||
### Arguments
|
||||
|
||||
- **`std::testing` reading its arguments through `std::args`.** `tester::run` compares
|
||||
`--only` and `--here` by hand, since `std::args` would refuse the other arguments tests
|
||||
are run with.
|
||||
- **Environment variables as fallbacks,** as `@option{ env = "SAKURA_TARGET" }` for
|
||||
`--target`. `process::variable` exists, so nothing blocks it.
|
||||
- **Suggestions for a misspelled option:** "`--levle` is not an option; did you mean
|
||||
`--level`?"
|
||||
- **Shell completion scripts** written from the declarations.
|
||||
- **Response files,** `@arguments.txt`, for lists longer than a system allows.
|
||||
- **Help wrapped to the terminal's width.** It aligns its columns but never wraps.
|
||||
- **The rest of the declarations checked while compiling.** The marks' shapes and types
|
||||
are `compile_error`s, but duplicate names, duplicate short letters, which letters may
|
||||
be short names, and `count` of an integer are checked as each run starts. Since
|
||||
2026-10-28 a `compile_error` a running condition chooses is reported, so they could be
|
||||
too.
|
||||
|
||||
### `core`
|
||||
|
||||
- **A `core` for places with no heap,** with the containers in a child of their own.
|
||||
- **Lang items by attribute,** as `@lang("string")`, rather than by name in the module
|
||||
`core`, so `core` could be split into modules of its own.
|
||||
|
||||
## blossom
|
||||
|
||||
- **The blossom plan's "Later, where wanted":** more `install` tags than `!include`, tags
|
||||
for the build and test pipelines, versions resolved from ranges with a lock file,
|
||||
`blossom new`, compiling in blossom's own process, and an index of packages by
|
||||
`gpid/name`. Several blossomfiles built as one project came on 2026-11-14, as `members`;
|
||||
several projects of their own names and versions, built together, are still later.
|
||||
- **Not run here:** an rpm package, as there's no `rpmbuild`, though the spec it's built
|
||||
from is written and the missing tool said; a Debian package with `dpkg`, which isn't here
|
||||
either, though `ar` and `tar` read it back whole; and blossom on Windows, which was only
|
||||
built and checked. Its tests of its commands run `git`, `sh` and `tar`, so they're
|
||||
Linux's.
|
||||
- **Building the compiler is checked by hand, not by a test.** A test would take
|
||||
minutes.
|
||||
- **zip files are stored, not compressed,** until std has deflate.
|
||||
|
||||
## Debugging information
|
||||
|
||||
- **No Windows debugger has read a PDB file.** Visual Studio or WinDbg, stopping in a
|
||||
program built with `-g`, would show whether they take what LLVM's tools do.
|
||||
- **What CodeView can't say of a variable:** a value known as a constant over a range,
|
||||
which the DWARF gives, isn't named there; a part of a variable of several words held
|
||||
in the frame isn't either; and a variable whose frame slot holds the address of its
|
||||
object of the heap is shown as a pointer to it.
|
||||
- **Every function's type is `void ()`** in the PDB file, as the DWARF gives none, and a
|
||||
debugger can't call them anyway.
|
||||
- **Names aren't qualified.** Two functions of one name in different modules, as two
|
||||
`write_all`s, are told apart by their IDs, but a debugger finding one by name finds
|
||||
both, as with the DWARF and the symbol tables.
|
||||
- **Globals aren't described,** in the PDB file or the DWARF.
|
||||
- **`binary::amd64`'s `absolute` meets `std::io`'s,** so a file importing both, as
|
||||
`native/native.sakura` does, writes `amd64::absolute`.
|
||||
|
||||
## Tests not written
|
||||
|
||||
- **Writing to the program's own output once nothing reads it.** A test can't make its
|
||||
own output a closed pipe. The machine stops with status 141, as it should.
|
||||
- **A read from a real pipe interrupted by a signal.** `io::pipe::open()` exists, but
|
||||
the test reads a stream made to look interrupted.
|
||||
- **`function` holding a C function.** See [`function`](#function).
|
||||
- **Windows, since `extern` and `system`.** Its sources and std's tests were checked for
|
||||
`windows-x86_64`, and the compiler's import table matched the seed's. None of it was
|
||||
run, and neither was the machine's test of `ucrtbase.dll`
|
||||
(`tests/machine/machine.sakura`): there's no Windows or Wine here. Since `core` the
|
||||
same holds, with `CreateDirectoryW` imported too, for the language server's copy of the
|
||||
built-in text.
|
||||
- **`--deps` from the compiler's own tests.** Only blossom's tests run `sakurac` with it,
|
||||
through blossom.
|
||||
+423
@@ -0,0 +1,423 @@
|
||||
# Plan: logging
|
||||
|
||||
Written 2026-10-07, and brought up to date 2026-10-20 for threads, owners and
|
||||
`function`, `std::time`, and what probing showed. This is a proposal.
|
||||
std is yours, so the decisions at the end are yours to make. Nothing of it is built
|
||||
yet but the clock, which `std::time` brought on 2026-10-12.
|
||||
|
||||
**Comes after the ffi plan, now built:** `std::sys` is `system`, and `@foreign` and
|
||||
`@link` are `extern` sections.
|
||||
|
||||
**What it is:** a program saying what it's doing, at levels a user can turn up or
|
||||
down. Each record carries when and where it was written. Records go to the standard
|
||||
error, or anywhere the program chooses.
|
||||
|
||||
**Its users:**
|
||||
- the build tool and the self-hosted compiler, saying what they run and how long it
|
||||
takes;
|
||||
- the language server, `sakura lsp`, whose records go to the client as
|
||||
`window/logMessage`, since its standard output belongs to the protocol;
|
||||
- programs whose records other programs read, as JSON lines.
|
||||
|
||||
**Probed:**
|
||||
- **On 2026-10-07,** in the scratchpad (`logprobe/`): the clocks, which `std::sys` now
|
||||
has; whether a handle is a terminal, through the `TCGETS` `ioctl`; and a floor,
|
||||
`call_site()` as a default, and a sink held in a module's variable.
|
||||
- **On 2026-10-20,** in the scratchpad (`plans/logging/`): in the VM, as executables
|
||||
at `-O0` and `-O2`, with `run --checks`, and checked for Windows, with 0 notes and 0
|
||||
warnings. A sketch of `std::log` in a copy of std covered:
|
||||
- `sys::is_terminal`, added to a copy of `std::sys`: false through a pipe, and true
|
||||
under a pseudo-terminal;
|
||||
- the floor, `log::to` with owned and borrowed sinks and nested guards, and the text
|
||||
and JSON sinks;
|
||||
- 400 records from four threads, all counted;
|
||||
- `math::log` beside `log::info`, and the "Using it" program below.
|
||||
|
||||
## What's there now
|
||||
|
||||
- **`io::error_output()`,** the shared writer of the standard error, which writes at
|
||||
once. `io::error_output_locked()` holds it for one thread across several writes, as
|
||||
`print` and `println` hold the standard output for each call.
|
||||
- **`call_site()`,** which, as a default, is filled in with where the call is
|
||||
written: its file, line, column, and the function's signature, while compiling.
|
||||
- **Interpolation,** which formats any value: enums by their member's name, and
|
||||
structs field by field.
|
||||
- **The clocks and the calendar:** `sys::clock(clock_kind::wall)` and `steady`, and in
|
||||
`std::time`, `timestamp::now()`, `timestamp::at(zone)`, which gives the `date_time`
|
||||
a zone's clocks show, and `rfc3339()`. That writes as many places of a second as
|
||||
the moment has: `.372006452`, `.45`, or none for a whole second.
|
||||
- **No way to tell whether a stream is a terminal:** `std::sys` has only a private
|
||||
`is_console` on Windows.
|
||||
- **Threads:** `std::thread`'s `mutex`, and `atomic<T>`, so several threads may log at
|
||||
once. A signal handler runs in the thread the program began with, at a safe point,
|
||||
and std's own code has none.
|
||||
- **`io::writer_of(stream)`,** which owns a stream given by value, as `move(f)`, and
|
||||
borrows one given as `&mut f`.
|
||||
- **Owning a value whatever its type:** `function<S>` owns any callable of a signature
|
||||
through a table of what its type does, and `sys::handle` keeps each handler in one
|
||||
until another is set. A sink of any type can be owned the same way.
|
||||
- **`json::writer`,** which writes into a string it keeps, `clear()`s to write the
|
||||
next value in the same memory, and writes text that isn't UTF-8 once `set_lossy`.
|
||||
- **`process::variable(name)`,** which reads the environment.
|
||||
- **Programs print with `println`,** or write to `io::error_output()` directly. The
|
||||
language server sends `window/logMessage` through its own `server::log`.
|
||||
|
||||
## What it needs
|
||||
|
||||
1. **Levels:** trace, debug, info, warning and error, and a floor below which nothing
|
||||
is written.
|
||||
2. **Where and when:** each record's file, line and function, and the time.
|
||||
3. **Cheap when off:** a record below the floor costs a load and a comparison.
|
||||
4. **Sinks:**
|
||||
- the standard error, by default;
|
||||
- any `writable`, as a file;
|
||||
- a program's own sink, as a language server's.
|
||||
5. **Formats:** text for people, coloured on a terminal, and JSON lines for programs.
|
||||
6. **Order kept with the rest of the output:** a record to the standard error is
|
||||
written at once, as other writes to it are, and as one write, so lines don't
|
||||
interleave.
|
||||
7. **Threads:** records made by several threads at once are each written whole.
|
||||
|
||||
## How it fits the rules
|
||||
|
||||
- **One logger, shared, as `io::output()` is (decision 2).**
|
||||
- Its floor is an `atomic<u8>` of `std::log`, read with `order::relaxed`, which in
|
||||
an executable is a plain load.
|
||||
- Its sink is behind a `thread::mutex`, so records from several threads are written
|
||||
whole, one at a time, and each thread's in the order it made them.
|
||||
- A record made while its own thread holds that lock, by a sink that logs, or by a
|
||||
signal handler run at a safe point in a program's own sink, is dropped rather
|
||||
than waited for. A thread holding `io::error_output_locked()` logs only after
|
||||
letting go of it, as it may not `print` while holding `io::output_locked()`.
|
||||
- **A sink is taken as `io::writer_of` takes a stream (decision 4).** `log::to(sink)`
|
||||
owns a sink given by value, and borrows one given as `&mut mine`. It gives back a
|
||||
guard that puts the previous sink back where it closes, closing one it owns. The
|
||||
guard is `@nodiscard`, so `log::to(&mut mine);` on its own, which would put the old
|
||||
sink back at once, is an error (probed).
|
||||
- **A record is plain data,** made of views. It's valid only while a sink writes it,
|
||||
so a sink keeping one copies what it needs.
|
||||
- **Logging never fails the program.**
|
||||
- A write that fails is dropped. No `result` comes back from `log::info`, and a
|
||||
sink's `write` gives `void`, where a stream's gives `result<void, io_error>`.
|
||||
- Writing to a closed standard error still stops the program quietly, by
|
||||
`SIGPIPE`, as any write to the console does (status 141 in the VM and in
|
||||
executables, probed).
|
||||
- **Calls are written qualified, as `log::info(...)`.** Without the module,
|
||||
`info` is ambiguous with `std::io::info` under `import std::io;` (probed again), and
|
||||
`error` reads as `result`'s field. The logarithm doesn't clash: under
|
||||
`import std::math;` and `import std::log;`, `log(x)` is `math::log` and `log::info`
|
||||
the module (probed).
|
||||
|
||||
## Layers
|
||||
|
||||
### `std::sys` gains
|
||||
|
||||
| Operation | Does |
|
||||
|---|---|
|
||||
| `is_terminal(handle: fd): bool` | Whether the handle is a terminal. Probed |
|
||||
| `allow_colour(handle: fd): bool` | Whether the handle shows colour codes, letting it where it can |
|
||||
|
||||
- **On Linux:** `is_terminal` is an `ioctl` with `TCGETS` (16 on x86-64), through
|
||||
`syscall`, as `clock` calls `clock_gettime`. `allow_colour` is `is_terminal`.
|
||||
- **On Windows:** `std::sys` already has a private `is_console`, which asks
|
||||
`GetConsoleMode`, and `is_terminal` gives it the handle `handle_of` finds. A
|
||||
console shows colour codes only once its virtual terminal processing is on, so
|
||||
`allow_colour` turns it on with `SetConsoleMode`, and is false where that's refused.
|
||||
- **The clock is built:** `sys::clock(which: clock_kind): i64`, of `clock_gettime` on
|
||||
Linux, and of `GetSystemTimePreciseAsFileTime` and `QueryPerformanceCounter` on
|
||||
Windows. `clock_kind` is in module `std`, in `std/time/clock.sakura`.
|
||||
- **Records keep a `time::timestamp`.** `std::log` writes its text from the
|
||||
`date_time` that `timestamp::at(zone::utc())` gives, to the millisecond, so every
|
||||
line's time is one width, where `rfc3339()` would write as many places as the
|
||||
moment has. The calendar is `std::time`'s.
|
||||
|
||||
### `std::log` (decision 1)
|
||||
|
||||
```sakura
|
||||
module std::log;
|
||||
|
||||
#! How much a record matters, from least to most.
|
||||
pub enum level: u8 {
|
||||
trace, #! Each step, for following the program closely.
|
||||
debug, #! What a developer wants while looking into a problem.
|
||||
info, #! What the program is doing, at a pace a user follows.
|
||||
warning, #! Something unexpected that the program went on past.
|
||||
error, #! Something that failed.
|
||||
off, #! As a floor, nothing is written.
|
||||
}
|
||||
|
||||
#! What the program said, as a sink is given it.
|
||||
pub struct record {
|
||||
pub val level: level; #! How much it matters.
|
||||
pub val time: time::timestamp; #! When, by the wall clock.
|
||||
pub val at: site; #! Where it was written: file, line, column, and function.
|
||||
pub val message: strview; #! What was said, valid only while the sink writes it.
|
||||
}
|
||||
|
||||
#! Where records go.
|
||||
pub trait sink {
|
||||
#! Writes a record.
|
||||
def write(&mut this, entry: &record): void;
|
||||
|
||||
#! Writes what it holds back, which a sink holding nothing back leaves as it is.
|
||||
def flush(&mut this): void {}
|
||||
}
|
||||
|
||||
pub def trace(message: strview, at: site = call_site()): void;
|
||||
pub def debug(message: strview, at: site = call_site()): void;
|
||||
pub def info(message: strview, at: site = call_site()): void;
|
||||
pub def warning(message: strview, at: site = call_site()): void;
|
||||
pub def error(message: strview, at: site = call_site()): void;
|
||||
pub def write(wanted: level, message: strview, at: site = call_site()): void;
|
||||
|
||||
pub def enabled(wanted: level): bool; # whether a record at the level is written
|
||||
pub def set_floor(lowest: level): void; # `info` until it's set
|
||||
pub def floor(): level;
|
||||
|
||||
#! Sends records to a sink until the guard closes. One given by value is the
|
||||
#! logger's, and one given as `&mut mine` is borrowed, as `io::writer_of` takes a
|
||||
#! stream.
|
||||
pub def to<K>(target: K): guard where K: sink;
|
||||
pub def flush(): void;
|
||||
|
||||
#! Puts the sink before it back where it closes, closing one the logger owns.
|
||||
@nodiscard
|
||||
pub struct guard : owning { ... }
|
||||
|
||||
#! How text records are written.
|
||||
pub struct style {
|
||||
pub var time: bool = true; #! Whether the time is written.
|
||||
pub var site: bool = true; #! Whether the file and line are written.
|
||||
pub var colour: bool = false; #! Whether levels are coloured, for a terminal.
|
||||
}
|
||||
|
||||
#! Writes records as lines of text, to a stream it owns or borrows, as
|
||||
#! `io::writer_of` does.
|
||||
pub struct text_sink<S> : sink, owning where S: writable { ... }
|
||||
pub def text_to<S>(stream: S, how: style = style {}): text_sink<S> where S: writable;
|
||||
|
||||
#! Writes each record as a line holding one JSON object.
|
||||
pub struct json_sink<S> : sink, owning where S: writable { ... }
|
||||
pub def json_to<S>(stream: S): json_sink<S> where S: writable;
|
||||
```
|
||||
|
||||
- **`flush` has an empty body, not `@optional`.** The compiler doesn't call an
|
||||
`@optional` method through a trait reference, which is how the logger reaches its
|
||||
sink, while a default is taken even by a sink that doesn't name the trait (both
|
||||
probed).
|
||||
|
||||
## Using it
|
||||
|
||||
```sakura
|
||||
import std;
|
||||
import std::args;
|
||||
import std::io;
|
||||
import std::log;
|
||||
|
||||
@command{ help = "Builds things." }
|
||||
struct options {
|
||||
@option{ short = 'v', count = true, help = "Says more: -v for debug, -vv for trace." }
|
||||
var verbose: u8;
|
||||
@argument{ value = "FILE", help = "The files to build." }
|
||||
var files: vector<strview>;
|
||||
}
|
||||
|
||||
def main(args: span<strview>): void {
|
||||
val given := args::parse_or_exit::<options>(args);
|
||||
log::set_floor(given.verbose >= 2 ? log::level::trace
|
||||
: given.verbose == 1 ? log::level::debug
|
||||
: log::level::info);
|
||||
|
||||
log::info($"building {given.files.length} files");
|
||||
if log::enabled(log::level::debug) {
|
||||
log::debug(list_of(&given.files)); # built only where it's written
|
||||
}
|
||||
|
||||
# Records go to a file instead of the console until `using` closes.
|
||||
val named := path::parse("build.log") else { return; };
|
||||
var file := io::file::create(&named) else { return; };
|
||||
val using := log::to(log::text_to(move(file)));
|
||||
log::warning("this goes to build.log");
|
||||
} # `using` closes, closing the sink and the file
|
||||
```
|
||||
|
||||
A language server sends records to its client, as `server::log` sends
|
||||
`window/logMessage`:
|
||||
|
||||
```sakura
|
||||
struct client_log : log::sink {
|
||||
var to: &mut server;
|
||||
}
|
||||
|
||||
def client_log::write(&mut this, entry: &log::record): void {
|
||||
val kind: u32 = match entry.level { error => 1, warning => 2, info => 3, else => 4 };
|
||||
this.to.log(kind, entry.message);
|
||||
}
|
||||
|
||||
# In a method of `server`, for as long as it serves:
|
||||
val using := log::to(client_log { to = this });
|
||||
```
|
||||
|
||||
## How each part works
|
||||
|
||||
- **Below the floor:**
|
||||
- `log::info` and the rest each compare the level with the floor before calling
|
||||
what makes the record. They're small, so `-O2` inlines them where they're
|
||||
called, and a record below the floor costs a load and a compare, besides its
|
||||
arguments (probed; a test inside the one function they all call
|
||||
wasn't copied out of it).
|
||||
- Its message is still built by the caller, as any argument is. So a message costly
|
||||
to build is written under `if log::enabled(...)` (decision 3).
|
||||
- **Making a record:** the time is read by `time::timestamp::now()` only for a record
|
||||
that's written, and the site comes from the default.
|
||||
- **The default sink** writes text to the standard error, through
|
||||
`io::error_output_locked()` for each record, so it mixes with nothing another
|
||||
thread writes there holding it.
|
||||
- It colours levels where `sys::allow_colour(sys::fd::stderr)` holds, asked once.
|
||||
- It holds nothing of its own, so there's nothing to close.
|
||||
- **Text:** one line per record, made in a `string`, then written as one write.
|
||||
|
||||
```
|
||||
2026-10-07T12:42:03.451Z INFO main.sakura:16 building 12 files
|
||||
2026-10-07T12:42:03.517Z WARN plan.sakura:88 `old.sakura` is listed twice
|
||||
```
|
||||
|
||||
- The time is RFC 3339 in UTC, to the millisecond, always three places. A time
|
||||
before 1970 is floored, as `std::time` floors it: 995 milliseconds before 1970 is
|
||||
`1969-12-31T23:59:59.005Z` (probed).
|
||||
- Levels are padded to five, as `TRACE`, `DEBUG`, ` INFO`, ` WARN` and `ERROR`.
|
||||
- The path is as the compiler was given it.
|
||||
- With `colour`, `TRACE` and `DEBUG` are dim, `WARN` is yellow and `ERROR` red.
|
||||
- A message holding line breaks is written as it is, so its later lines begin
|
||||
with nothing before them.
|
||||
- **JSON:** one object per line, written through a `json::writer` the sink keeps,
|
||||
cleared for each record, so the message is escaped. The writer is lossy, so a
|
||||
message that isn't UTF-8 is written with U+FFFD where it breaks, rather than as
|
||||
`null`. The level is its member's name, as interpolation writes it:
|
||||
|
||||
```
|
||||
{"time":"2026-10-07T12:42:03.451Z","level":"info","file":"main.sakura","line":16,"function":"def main(args: span<strview>): void","message":"building 12 files"}
|
||||
```
|
||||
|
||||
- **`log::to`** moves the sink it's given to the heap, as `function` holds a callable
|
||||
too large for itself, keeps a `&mut sink` to it, and gives a guard holding the one
|
||||
before. Given `&mut mine`, what it moves is only the reference.
|
||||
- Guards closed in the reverse of the order they were made, as RAII closes them,
|
||||
put back each sink in turn, holding the lock, so a record being written on
|
||||
another thread is finished first.
|
||||
- A guard then closes the sink it set where the logger owns it, which flushes what
|
||||
the sink holds back.
|
||||
- **`log::flush`** flushes the sink, where it flushes. A program stopping through
|
||||
`sys::exit` flushes nothing and closes nothing, guards included, as now (probed), so
|
||||
a sink that holds records back is flushed first. The logger's
|
||||
own variables are never closed, as no module's are when the program ends.
|
||||
|
||||
## Testing
|
||||
|
||||
- **`test/std/log.sakura`, written with `std::testing`,** covers:
|
||||
- **the floor:** each level against each floor, `off`, and `enabled`;
|
||||
- **sites:** the file and line a record gives are where `log::info` was written;
|
||||
- **sinks:**
|
||||
- a program's own sink collecting records, owned and borrowed;
|
||||
- `log::to` guards, nested, putting each sink back as they close, and closing
|
||||
those the logger owns;
|
||||
- `log::flush` reaching a sink that flushes, and one that doesn't;
|
||||
- **text:** records with a fixed time written by `text_to(&mut text)` into a
|
||||
`string`, compared exactly, with and without the time, the site and colour;
|
||||
- **times:** always three places, as `.000` and `.450`, and a time before 1970.
|
||||
Dates themselves are `std::time`'s, tested in `test/std/time.sakura`;
|
||||
- **JSON:** each line read back with `json::parse`, including a message with quotes
|
||||
and line breaks, and one that isn't UTF-8;
|
||||
- **threads:** several threads logging at once into one sink, every record whole
|
||||
and counted;
|
||||
- **a sink that logs,** whose record is dropped rather than waited for.
|
||||
|
||||
Each test runs in a copy of the program, so a floor or sink one sets is gone for
|
||||
the next.
|
||||
- **In the corpus, `test/programs`:** records to `io::output()` between `println`s,
|
||||
written in the order they were made, and records to the standard error beside them,
|
||||
with the time left out.
|
||||
- **Where they run:** in the VM, as executables at `-O0` and `-O2`, and with
|
||||
`run --checks`. The compiler must check them with 0 notes and 0 warnings.
|
||||
|
||||
## Phases
|
||||
|
||||
About 30 lines of `std::sys`, 450 of `std::log`, and 300 of tests, and no change to the
|
||||
compiler. The sketch probed was 200 lines of code without its documentation. Each phase
|
||||
ends with its tests passing.
|
||||
|
||||
1. **`sys::is_terminal` and `sys::allow_colour`,** for Linux and Windows on x86-64.
|
||||
`sys::clock` is built.
|
||||
2. **`std::log`:** levels, records, the floor, `sink`, `log::to` and its guard, the
|
||||
lock, and the text sink, with the default sink over the standard error.
|
||||
3. **The JSON sink.**
|
||||
4. **A "Logging" part of the README's standard library section,** and `std::log` in
|
||||
its table of modules.
|
||||
|
||||
## Later, where wanted
|
||||
|
||||
- **Fields:** pairs of names and values that the JSON sink writes as members, as in
|
||||
`log::info("served", log::field("path", p), log::field("ms", ms))`.
|
||||
- **Named loggers,** one for each part of a program, each with its own floor.
|
||||
- **The floor from the environment,** as `SAKURA_LOG=debug`, and `NO_COLOR`.
|
||||
`process::variable` exists now, so this waits only on choosing the names.
|
||||
- **Several sinks at once,** as a sink that writes to two others.
|
||||
- **A sink on a thread of its own,** handed records through a `thread::channel`, so a
|
||||
slow sink doesn't hold up the threads logging. It would copy each record's message,
|
||||
since a record's views last only while it's written.
|
||||
- **A sink to `syslog`,** or to the systemd journal.
|
||||
|
||||
Durations and dates as types, with the time zone from the system, were on this list.
|
||||
`std::time` has them now.
|
||||
|
||||
## Decisions for you
|
||||
|
||||
1. **Where it lives:**
|
||||
- **(a) `std::log`, in `std/log/` (recommended).** Calls read as `log::info(...)`.
|
||||
- **(b) `std::logging`.** It was to leave the name `log` free for a logarithm, but
|
||||
`std::math` has `log` now, and it lives beside a module `log` (probed). So it's
|
||||
only a longer name.
|
||||
2. **The logger:**
|
||||
- **(a) One, shared, as `io::output()` is (recommended).** Any function can log
|
||||
without being given anything. Threads logging at once wait on its lock for each
|
||||
record written.
|
||||
- **(b) Logger values given to what logs.** That's explicit and easy to test, and a
|
||||
value one thread holds needs no lock, but every function that logs needs a
|
||||
parameter.
|
||||
3. **Messages below the floor:**
|
||||
- **(a) Built anyway, with `log::enabled` for messages costly to build
|
||||
(recommended).** Interpolating a few values costs little next to what a program
|
||||
does between records.
|
||||
- **(b) Also overloads taking a function that builds the message,** as
|
||||
`log::debug(def() => describe(&plan))`. It's shorter at the call, and the
|
||||
closure costs only its two words now, since closures refer to what they use
|
||||
rather than own it. But the compiler calls a lambda written in place ambiguous
|
||||
between `debug(strview)` and `debug(def(): string)`, typed or not (probed
|
||||
2026-10-20). A function value named first works.
|
||||
- **(c) Records below a floor the build sets are removed while compiling.** That
|
||||
needs a new `when` key, as `log >= debug`, and a compiler option to set it.
|
||||
4. **How a sink is held:**
|
||||
- **(a) As `io::writer_of` holds a stream, until its guard closes (recommended).**
|
||||
`log::to` owns a sink given by value, and borrows one given as `&mut mine`. The
|
||||
guard keeps a borrowed sink from outliving it, and closes an owned one, flushing
|
||||
what it holds back. Both were probed.
|
||||
- **(b) Owned until another is set, with no guard,** as `sys::handle` keeps a
|
||||
handler in a `function` until another handles the signal. It's one call for the
|
||||
whole run, but nothing puts the old sink back, and nothing closes the logger as
|
||||
the program ends, so a sink holding records back loses them unless the program
|
||||
flushes first.
|
||||
- **(c) Borrowed only, until its guard closes,** as `log::to(&mut mine)`. This was
|
||||
the recommendation of 2026-10-07, before std owned values of any type, as
|
||||
`function` does. It makes a program declare its sink before the guard, or the
|
||||
sink closes first.
|
||||
5. **The time a record gives:**
|
||||
- **(a) The wall clock, in UTC, written as RFC 3339 to the millisecond
|
||||
(recommended).**
|
||||
- **(b) The wall clock in the local zone, with its offset,** from
|
||||
`timestamp::at(zone::local())`. That's what a person nearby reads, but records
|
||||
from machines in other zones, or from either side of a change of the clocks,
|
||||
don't sort as text.
|
||||
- **(c) Time since the program started,** from the steady clock, as an
|
||||
`instant`'s `elapsed()`. That's easier to read in a short run, but means nothing
|
||||
next to another program's records.
|
||||
- **(d) None unless a style asks for it.**
|
||||
@@ -0,0 +1,368 @@
|
||||
# Performance
|
||||
|
||||
Where the compiler started, where it is now, and where it needs work: how fast it checks
|
||||
and builds, how much memory it takes, how large it and what it makes are, and how fast
|
||||
the code it makes runs.
|
||||
|
||||
"Start" is the compiler as committed on 2026-10-08, at `e5b7636`, its first commit.
|
||||
"Now" is its working tree on 2026-10-20. Every comparison of start and now was measured
|
||||
on 2026-10-20, on one machine in the same hour. The probes of other programs are dated
|
||||
where they're given.
|
||||
|
||||
## How it was measured
|
||||
|
||||
- **The machine:** an i5-13420H, on battery, which caps its performance cores at
|
||||
2.1 GHz. Wall times are about half what the same runs take plugged in, so they compare
|
||||
with each other and not with older notes. Instructions and cycles are the processor's
|
||||
own counts of the program's work outside the kernel, and don't depend on the clock.
|
||||
- **Each run** was pinned to CPU 2, a performance core, the runs of a group taken in
|
||||
turns: the best of 5 for builds, 9 for checks, 21 for a one-line program, 3 for the
|
||||
VM. Peak memory is the largest resident size of any run.
|
||||
- **The compiler runs on one thread here (`-j 1`),** as the start compiler does.
|
||||
[Threads](#threads) gives what its default of up to eight does.
|
||||
- **The compiler:** its own fixed point at `-O2`.
|
||||
- **The work:** sakurac checking and building its own sources of its day, as it builds
|
||||
itself (`entry.sakura analyzer compiler machine native`, and `server` now), against
|
||||
its std. Those grew, so each result is also given per 1,000 lines of what was read:
|
||||
|
||||
| | Start | Now | |
|
||||
|---|---|---|---|
|
||||
| sakurac's sources | 49,307 lines, 112 files | 76,816 lines, 160 files | +56% |
|
||||
| std | 21,892 lines | 40,241 lines | +84% |
|
||||
| All read, per build or check | 71,199 lines | 117,057 lines | +64% |
|
||||
|
||||
## At a glance
|
||||
|
||||
| | Start | Now |
|
||||
|---|---|---|
|
||||
| Building sakurac | 1.78 s | 3.38 s |
|
||||
| · instructions per 1,000 lines | 121M | 131M (+8%) |
|
||||
| · peak memory | 132 MB | 229 MB |
|
||||
| Checking sakurac | 0.256 s | 0.353 s |
|
||||
| · instructions per 1,000 lines | 19.0M | 16.0M (−16%) |
|
||||
| · peak memory | 42 MB | 74 MB |
|
||||
| Checking a one-line program | 0.061 s | 0.093 s |
|
||||
| · instructions per 1,000 lines of std | 13.7M | 11.2M (−18%) |
|
||||
| · peak memory | 15 MB | 27 MB |
|
||||
| The compiler's executable | 11.6 MB | 8.7 MB |
|
||||
| A program printing a line | 274 KB | 155 KB |
|
||||
|
||||
**The compiler held its cost per line** while what it reads grew by two thirds: checking
|
||||
costs less a line than it did, and building 8% more, which the 2026-10-18 optimizer
|
||||
passes cost and pay back in the code they make.
|
||||
|
||||
## Speed
|
||||
|
||||
Building and checking, the compiler on the sources of its day, at 2.1 GHz:
|
||||
|
||||
| | Start | Now |
|
||||
|---|---|---|
|
||||
| Building: wall time, best | 1.778 s | 3.375 s |
|
||||
| · median | 1.787 s | 3.388 s |
|
||||
| · instructions | 8.63G | 15.39G |
|
||||
| · cycles | 3.49G | 6.44G |
|
||||
| Checking: wall time, best | 0.256 s | 0.353 s |
|
||||
| · instructions | 1.36G | 1.88G |
|
||||
| · cycles | 0.49G | 0.65G |
|
||||
| A one-line program: wall time, best | 0.061 s | 0.093 s |
|
||||
| · instructions | 300M | 451M |
|
||||
|
||||
Every program is checked with the whole of std, so the one-line program is what std
|
||||
costs each check: about 2.3 ms for each 1,000 lines now, at this clock. Generic code
|
||||
costs two to three times what plain code does, as `std/simd.sakura` measured on
|
||||
2026-10-14.
|
||||
|
||||
### The code it makes
|
||||
|
||||
Other programs, from the plans' probes, at `-O2`. These were measured as each plan was
|
||||
built or brought up to date, on a busy machine:
|
||||
|
||||
| What | Time | Measured |
|
||||
|---|---|---|
|
||||
| `f32` `a * b + c`, scalar | 87.9 ms | 10-20 |
|
||||
| The same, `f32x8` | 5.9 ms | 10-20 |
|
||||
| Finding a byte, `u8x16` | 1.78 ms | 10-20 |
|
||||
| `index_of`, a byte at the end of 1 MiB | 62 µs | 10-20 |
|
||||
| `is_ascii` of 1 MiB | 62 µs | 10-20 |
|
||||
| Vectors of three `f32`s, by operators | 166 ms | 10-20 |
|
||||
| Random draws, 64 bits | 2.5 ns | 10-20 |
|
||||
| A call through a function value | 2.72 ns | 10-20 |
|
||||
| A generic `F`, inlined | 0.48 ns | 10-20 |
|
||||
| A call through a `function` | 2.86 ns | 10-20 |
|
||||
| A list of 1,000,000 `box`es, ten times | 539 ms | 10-19 |
|
||||
| The same through `raw_allocate` | 414 ms | 10-19 |
|
||||
| The same in a `pool` | 209 ms | 10-19 |
|
||||
| Three relaxed atomics | 0.1 ns | 10-20 |
|
||||
|
||||
Where the speed comes from:
|
||||
- **Vectors in registers.** The compiler's `-O2` holds `simd` values in registers and
|
||||
picks AVX2 or SSE2 as the program runs.
|
||||
- **Values out of memory.** A statement's temporary cell holds each value it's given in
|
||||
a cell of its own, so one call given its address no longer keeps the rest in memory,
|
||||
and a cell written as a vector and read by its lanes, or the other way, holds one
|
||||
width. Before, small structs as temporaries went through the stack, and four writes
|
||||
read back as one vector waited for the cache: a contact solved with `vec2`s took
|
||||
three times the same written a number at a time, and now takes 1.06 times it.
|
||||
- **`f32`s as `f32`s.** Comparing, negating, and choosing keep an `f32` single, a choice
|
||||
by a comparison is `maxss`, `minss`, or a mask rather than a branch, and no conversion
|
||||
waits on what its register held before, which chained a loop's iterations together.
|
||||
|
||||
Against native code, physics's benchmarks, after 2026-10-31's work, take three to four
|
||||
times as long as Box2D's scalar build and five to six times Jolt's, each built by GCC
|
||||
16.2 at `-O2`. What's left, as profiled:
|
||||
- **Registers.** Values get 11 of the 16 SSE registers, the rest being scratch for
|
||||
vectors' operations, so a loop of `f32x8`s or many `f32`s spills where GCC's doesn't.
|
||||
- **`std::math::min` and `max` of reals** follow IEEE 754's minimum and maximum: a NaN
|
||||
test of each, and one of signed zeros, around `minss`, three branches where the
|
||||
physics wants one instruction.
|
||||
- **Inlining.** The limit stays 16, but since the later 10-31 work a call is inlined by
|
||||
what its copy costs where it is, so `cross` and `mat3`'s helpers, taking vectors in
|
||||
memory, are inlined where their reads promote. A loop already holding seven vectors
|
||||
is left its calls, as the registers above would spill what inlining promotes:
|
||||
inlining `cross` into the contact solver of Jolt's scenes made it 50% slower so.
|
||||
- **A cell's values that cross blocks,** and a named local's, stay in one cell, as an
|
||||
`apart` struct and a `vec2` temporary do in physics2d's `furthest_apart`.
|
||||
- **Parameters held in memory** are copied by the function given them, though the caller
|
||||
made a copy too.
|
||||
- **What the optimizer takes out:** checks of a view's data, indexes checked again,
|
||||
bounds in counted loops, work on constants moved out of loops, small branches as
|
||||
`cmov`, the stack's limit in small leaf functions, and the order of an atomic known
|
||||
while compiling.
|
||||
|
||||
### The VM
|
||||
|
||||
The compiler running itself on its VM, which then checks a one-line program. The time
|
||||
includes checking and lowering the compiler for the VM:
|
||||
|
||||
| | Start | Now |
|
||||
|---|---|---|
|
||||
| The VM | 2.69 s, 17.8G instructions, 122 MB | 5.00 s, 29.2G, 244 MB |
|
||||
|
||||
A call through a function value takes 81.8 ns in the VM, and an inlined generic call
|
||||
24.5 ns.
|
||||
|
||||
### Compiled code in the machine
|
||||
|
||||
Since 2026-10-28 the machine compiles each function to x86-64 as it is first called, where
|
||||
it runs as a Windows executable (`machine/jit.sakura`), and since 2026-10-29 as a Linux one. Measured on a Ryzen 9 9950X3D,
|
||||
plugged in, each benchmark a function of its own called through a value, so none is
|
||||
inlined into another; `run --fast` against `build -O2`, the checksums alike:
|
||||
|
||||
| Work | Built | Interpreted | Compiled by the machine | Compiled ÷ built |
|
||||
|---|---|---|---|---|
|
||||
| Multiplies and shifts mixing a word, 20M times | 9.4 ms | 93.6 ms | 9.1 ms | 0.97 |
|
||||
| `fib(30)`, calls | 2.5 ms | 50.1 ms | 3.8 ms | 1.5 |
|
||||
| 10,000 particles of `f32`, 300 steps | 5.5 ms | 148 ms | 19.8 ms | 3.6 |
|
||||
| Methods of a struct of three `f32`s | 10.8 ms | 121 ms | 24.1 ms | 2.2 |
|
||||
| A sieve of 20M bytes | 30.5 ms | 246 ms | 37.9 ms | 1.2 |
|
||||
| A `dict` of 200,000, then 1M lookups | 26.0 ms | 102 ms | 26.3 ms | 1.0 |
|
||||
| Sorting 1M words | 68.9 ms | 444 ms | 78.7 ms | 1.1 |
|
||||
| Interpolating 200,000 texts | 13.5 ms | 33.4 ms | 36.4 ms | 2.7 |
|
||||
|
||||
hearth's scripts, 2,000 entities each running a behavior (`hearth.scripting.bench`, run as
|
||||
its executable): an `update` turning its transform took 311 ns an entity interpreted and
|
||||
121 ns compiled, against 27 ns as a system of the program's own.
|
||||
|
||||
Where it falls short of built code:
|
||||
- **Words, not values.** The machine's code holds values in words of the frame shared by
|
||||
values whose lives don't overlap, an `f32` and an `f64` alike, and compiled code keeps a
|
||||
word a single only where every value in it is one. Splitting each word into the values
|
||||
it holds, by liveness, would let `f32` arithmetic stay single throughout.
|
||||
- **What the bytecode reloads.** A vector's data pointer is read from its cell each time
|
||||
round a loop, which built code moves out of the loop.
|
||||
- **Formatting** calls the machine's own code for each part of a text.
|
||||
- **A function inlining many loops** shares its registers among the words its loops use
|
||||
most: all eight benchmarks inlined into one `main` ran mix in 18.6 ms, not 9.1.
|
||||
|
||||
### Threads
|
||||
|
||||
The compiler runs on threads, one for each processor up to eight. Unpinned, on this
|
||||
machine's twelve:
|
||||
|
||||
| | `-j 1` | Default | |
|
||||
|---|---|---|---|
|
||||
| Building sakurac | 3.34 s, 226 MB | 1.97 s, 257 MB | 1.70× |
|
||||
| Checking it | 0.353 s | 0.301 s | 1.17× |
|
||||
|
||||
Reading files, optimizing, and placing values run on threads. Checking, lowering, and
|
||||
choosing code are one thread's.
|
||||
|
||||
## Memory
|
||||
|
||||
Peak resident memory:
|
||||
|
||||
| | Start | Now |
|
||||
|---|---|---|
|
||||
| Building sakurac | 132 MB | 229 MB |
|
||||
| · per 1,000 lines | 1.85 MB | 1.96 MB |
|
||||
| Checking sakurac | 42 MB | 74 MB |
|
||||
| · per 1,000 lines | 0.59 MB | 0.63 MB |
|
||||
| Checking a one-line program | 15 MB | 27 MB |
|
||||
|
||||
The compiler's memory grew as what it reads did, 6% to 7% more a line.
|
||||
|
||||
The compiler has no collector since 2026-10-19. Programs hold what they allocate in
|
||||
owners, arenas and pools, and each thread keeps a cache of free blocks.
|
||||
|
||||
## Size
|
||||
|
||||
### The compiler
|
||||
|
||||
| | Start | Now |
|
||||
|---|---|---|
|
||||
| Executable | 11,570,800 bytes | 8,730,512 |
|
||||
| · code | 2.52 MB | 3.01 MB |
|
||||
| · constant data | 0.60 MB | 1.02 MB |
|
||||
| · line tables | 8.28 MB | 4.63 MB |
|
||||
|
||||
The compiler's executable carries its line tables, which fault traces read, as 53% of
|
||||
it.
|
||||
|
||||
### What it makes
|
||||
|
||||
A program printing a line, at `-O2`:
|
||||
|
||||
| | Start | Now |
|
||||
|---|---|---|
|
||||
| Executable | 273,512 bytes | 154,856 |
|
||||
| · code | 36,046 | 35,618 |
|
||||
| · constant data | 24,128 | 30,616 |
|
||||
| · line tables | 203,032 | 74,296 |
|
||||
|
||||
The compiler's 2026-10-18 optimizer drops every function nothing reaches, with its code,
|
||||
lines and symbols.
|
||||
|
||||
## Where a build goes now
|
||||
|
||||
The compiler building its own sources of now, profiled with callgrind: on one thread,
|
||||
built with `-g`, 15.8G instructions in all. Shares are of instructions, inclusive of what
|
||||
each phase calls:
|
||||
|
||||
| Phase | Share |
|
||||
|---|---|
|
||||
| Reading the files: lexing and parsing | 3.0% |
|
||||
| Checking | 7.9% |
|
||||
| Evaluating constants | 0.9% |
|
||||
| Lowering, less what follows | 14.8% |
|
||||
| Working out what calls keep | 1.4%, within the rows around it |
|
||||
| Optimizing, inlining included | 56.5% |
|
||||
| Choosing code and placing values | 14.8% |
|
||||
| Writing the executable, closing what's left | about 1% |
|
||||
|
||||
**Optimizing is over half of a build,** and no pass stands out: the optimizer's files
|
||||
take 23% of the instructions by themselves, and the code they walk and edit
|
||||
(`compiler/intermediate/`) another 14%. Spread through every phase:
|
||||
- **indexing vectors** (`vector::at`) is 13% of all instructions, and appending 4%. The
|
||||
checks on them are about 3% of a build, as the checks plan measured;
|
||||
- **`dict`** is 2.8%, `memset` and `memcpy` 3.5%, and the heap 1.8%;
|
||||
- **the checker's own lifetime warnings** are 1.8%.
|
||||
|
||||
## Where work is needed
|
||||
|
||||
In order of what each would gain.
|
||||
|
||||
1. **Optimizing.** It's 56% of a build, and the 2026-10-18 passes cost 13% of a build
|
||||
for code 10.5% faster. No pass stands out; what the passes walk and index does, as
|
||||
`vector::at` at 13% of all instructions. Code held in fewer, denser arrays, or walked
|
||||
without an index checked at each step, would serve every pass.
|
||||
2. **The compiler's threads.** Eight give 1.7 times one. Checking, lowering and choosing
|
||||
code run on one thread, which caps what more processors give.
|
||||
3. **std's cost to every check.** Before the std plan, a one-line program cost a check
|
||||
of 40,241 lines of std: 93 ms and 27 MB at this clock. The std plan, built on
|
||||
2026-10-20, made `core`, a library of the language's own that every program reads,
|
||||
and reads std's modules only where a program refers to them. An empty `main` now
|
||||
checks in 21.4 ms and 7.3 MB, and a program printing a line in 42.2 ms and 11.0 MB,
|
||||
since `std::io` still reads std's root. The plan had probed 30.1 ms for it. What's
|
||||
read still costs about 2.3 ms each 1,000 lines, and two to three times that for
|
||||
generic code.
|
||||
4. **Line tables,** 53% of the compiler's executable and 48% of a small program's.
|
||||
5. **The VM on calls,** 81.8 ns through a function value and 24.5 ns for an inlined
|
||||
generic call.
|
||||
6. **Smaller costs that programs meet** ([later.md](later.md)):
|
||||
- reading the clock on Linux is a system call, 211 ns, where the vDSO takes 25;
|
||||
- lambdas given to adapters cost 3 to 4 times functors;
|
||||
- `box` is 1.31 to 1.38 times `raw_allocate`.
|
||||
|
||||
## How it got here
|
||||
|
||||
Each step as it was measured then, on the machine and clock of its day.
|
||||
|
||||
| Date | What | Measured |
|
||||
|---|---|---|
|
||||
| 10-05 | The analyzer, before self-hosting | Checking 23,574 lines: 0.09 s, 19 MB, 495M instructions |
|
||||
| 10-08 | The scratch arena | The compiler compiling itself: 5.34G to 4.84G instructions, 100 MB to 89 MB |
|
||||
| 10-08 | First self-build | 15.4G instructions, about 3 s; then 8.37G, 1.65 s, 129 MB, an 11.3 MB executable |
|
||||
| 10-08 | The back end's remaining work | Code 2,644,785 to 2,517,459 bytes; building 9.42G to 8.96G |
|
||||
| 10-14 | Simplifying and speeding up | Building 11.10G to 8.31G, 2.20 s to 1.66 s; checking 0.31 s to 0.21 s; executable 14.4 MB to 6.8 MB |
|
||||
| 10-14 | Vectors in registers | Building 8.61G to 7.99G; checking 1.36G to 1.27G; `f32x8` loop 21.6 ms to 8.7 ms |
|
||||
| 10-16 | Compiling on threads | On 32 processors under load: building 838 ms to 564 ms on eight threads |
|
||||
| 10-16 | One-word references, text by words | Building 8.37G to 7.85G, 171 MB to 166 MB; checking 1.355G to 1.302G |
|
||||
| 10-18 | The optimizer's new passes | Code 10.5% faster; building the old sources 13% slower; executable 9.51 MB to 8.17 MB |
|
||||
| 10-19 | Iterators | The fixed point 7.80 MB to 8.67 MB, from inlining `next` |
|
||||
| 10-19 | Memory without a collector | A list of a million nodes, ten times: 3,046 ms collected in the plan's probe, 539 ms in `box`es released one by one as built; four threads allocating, 8.5 s to 0.29 s with caches |
|
||||
| 10-20 | `std::function` and `void` | The fixed point 8,730,512 bytes |
|
||||
| 10-20 | `core`, and std read as it's imported | Checking an empty `main` 93.1 ms to 21.4 ms, 27.7 MB to 7.3 MB; a program printing a line 93.3 ms to 42.2 ms; the compiler checking itself 352.5 ms to 338.6 ms, 72.4 MB to 54.0 MB |
|
||||
| 10-20 | Contracts as statements | A contract that holds costs 0.11 ns more than a plain `if`, with the blocks that only stop the program laid out last; it was 5.7 ns as a call into std |
|
||||
| 10-20 | Checks in checked programs only | One frozen copy built with `--checks` and without: building 3,523 ms to 3,372 ms (16.2G to 14.0G instructions), checking 350.8 ms to 323.5 ms, executable 9,209,216 to 8,732,296 bytes |
|
||||
| 10-20 | The rules settled (roadmap step 5) | The compiler checking itself on one thread, step 4's checker against step 5's: 324.7 ms and 323.9 ms, no difference; the fixed point 8,770,256 bytes |
|
||||
| 10-20 | Accessors with `this` and `value` implied (step 6) | Checking itself: 324.5 ms with step 5's checker on its form of the sources, 324.4 ms with step 6's; the fixed point 8,773,288 bytes |
|
||||
| 10-28 | `f32` in single precision, instructions chosen by the processor, stores merged into vectors, spilling the value read furthest ahead, a loop's head that jumps through a table at a multiple of 64 | In cycles at this machine's low-power clock: `linear`'s `cross` 30 to 12, `quat * quat` 35 to 18, `normalized` 34 to 6; a loop of `vec3<i32>` 17 ms to 11 ms; the machine's loop 1,264M to 1,017M cycles, and no longer 1,180M when the code before it moves |
|
||||
| 10-31, later | Bit tracking, code lifting, constants a branch learned, constants grouped and added last, loops regrouping what they keep, and inlining by what each call's copy costs, after LLVM's passes | physics's benchmarks, the installed compiler against this one, best of three in turns, in ms a step: Box2D's large pyramid 7.27 to 7.19, its many pyramids 30.36 to 29.89; Jolt's pyramid 33.39 to 30.17, its convex hulls on a mesh 13.13 to 12.54, the same to the bit. Building itself on one thread 1.68 s to 1.76 s, on eight 0.84 s to 0.86 s; the fixed point 10,943,790 bytes |
|
||||
| 10-31 | Conversions that wait on nothing; `f32` comparisons, negation, and choosing in single precision; reals chosen by a comparison without a branch; `x != x` tested by the parity flag; versions made from the code as lowered; a temporary cell's values split apart; vectors read by lanes and lanes by vectors; `scatter` written out; promotion once more after numbering | physics's benchmarks, each against the 10-30 compiler side by side on a busy machine, in ms a step: Box2D's large pyramid 13.4 to 7.6, its many pyramids 60.1 to 40.3; Jolt's pyramid 52.0 to 40.6, its convex hulls on a mesh 21.5 to 16.0. A contact solved with `vec2` temporaries 11.7 ns to 4.35, with GCC's `-O2` at 2.98. Building itself 0.76 s to 0.85 s; the fixed point 10,530,038 bytes |
|
||||
|
||||
What made the compiler faster, in the order of what each saved:
|
||||
- a build optimized every function twice (12% of building);
|
||||
- dependencies recorded only for the language server, and results held per slot rather
|
||||
than in dictionaries (13% of checking);
|
||||
- what calls keep worked out, so receivers and locals stay off the heap: boxes made
|
||||
while building itself fell from 4.7M to 30K;
|
||||
- the scratch arena for each pass's temporaries;
|
||||
- one-word references;
|
||||
- the per-thread caches of blocks, and the blocks kept for reuse over 2 KiB;
|
||||
- vectors in registers, and `memset`, `memcpy` and frames zeroed 16 bytes at a time;
|
||||
- the lexer interning through an open table of hashes, finding punctuators by tables,
|
||||
and skipping comment lines eight bytes at a time;
|
||||
- line tables of 16-byte rows (10.2 MB to 3.0 MB then);
|
||||
- leaving the checks of indexes and the rest to checked programs, and null and division
|
||||
by zero to the processor's faults (4% of building, 8% of checking).
|
||||
|
||||
Tried and dropped, so they needn't be tried again:
|
||||
- an open-addressing `dict`, at loads of 3/4 and 1/2: 0.5–1.7% slower to check;
|
||||
- inline limits of 20 and 24: checking 8–11% faster, building 1–4% slower, code 9–19%
|
||||
larger;
|
||||
- one arena for every function's code: more instructions and 122 MB;
|
||||
- a radix sort for the register allocator, which ran more than the heap sort;
|
||||
- forwarding a call's result into the cell it's copied to, which saved nothing;
|
||||
- waiting a while for the heap's lock before sleeping;
|
||||
- a table of names for each file, which lexed every name again on each thread;
|
||||
- compacting in the middle of the passes as well as at the end;
|
||||
- inlining every function called once into callers of up to 6,000 instructions: 6%
|
||||
more time;
|
||||
- inlining by each call's cost with no regard for the vectors a loop holds: Jolt's
|
||||
convex hulls 14% slower, its contact solver spilling a value at a time;
|
||||
- raising the limit within loops for functions of several blocks too, as
|
||||
`clamp`'s IEEE tests are: Box2D's scenes 4–7% slower;
|
||||
- working out the bits known of every word at once, round after round until a
|
||||
loop's settle: 2% of a build, where asking of each word a few steps back, as LLVM
|
||||
does, costs a third of that;
|
||||
- copying the test of `vector::close` into its callers: 400 KB more code;
|
||||
- alias classes by type, which a reinterpreting cast would make wrong;
|
||||
- words for trimming text, YAML's plain scalars, and the lexer's words and spacing,
|
||||
each slower than bytes, as most runs are short;
|
||||
- aligning every loop's head to 16 bytes, as functions are: the machine's loop took about
|
||||
10% more cycles, and no native loop gained. What its loop needed was the head that jumps
|
||||
through the table of operations within one 64-byte line, which a 16-byte boundary
|
||||
doesn't promise: such heads begin at a multiple of 64 since 2026-10-28.
|
||||
|
||||
## Reproducing this
|
||||
|
||||
The start's numbers stand as measured on 2026-10-20: today's compiler doesn't read
|
||||
`e5b7636`'s sources, so nothing builds the start again.
|
||||
|
||||
`tools/profile/count.c` runs a command pinned to a processor and prints its wall time,
|
||||
peak memory, instructions and cycles, and `tools/profile/measure.py` times the
|
||||
compiler's work, start and now, in turns through it. Its paths are at its top. `perf`
|
||||
isn't installed here, and the counters need `perf_event_paranoid` at 2 or less.
|
||||
|
||||
For where the time goes, build the compiler with `-g`, profile it with callgrind, and
|
||||
read the profile with `tools/profile/costs.py`, as its header says.
|
||||
+451
@@ -0,0 +1,451 @@
|
||||
# Plan: random numbers
|
||||
|
||||
Written 2026-10-08, and brought up to date 2026-10-20 for what std has gained since:
|
||||
ranges as values, `real` and `std::math`, threads and atomics, Windows, and checked runs
|
||||
in place of the collector. This is a proposal. std is yours, so the decisions at the end
|
||||
are yours to make. Nothing is built yet.
|
||||
|
||||
**Comes after the ffi plan, now built:** `std::sys` is `system`, and `@foreign` and
|
||||
`@link` are `extern` sections.
|
||||
|
||||
**What it is:** generators of random numbers, numbers drawn from them in a range,
|
||||
shuffling and picking, and the system's randomness for keys and seeds.
|
||||
|
||||
**Its users:**
|
||||
- games and simulations: dice, procedural worlds, and replays, which need the same
|
||||
numbers from the same seed;
|
||||
- tests whose inputs are made from a seed, so a failure can be repeated. std's own tests
|
||||
of memory, vectors, words and threads each write a generator by hand today;
|
||||
- programs with secrets: keys, tokens, and names nobody can guess;
|
||||
- the algorithms plan ([algorithms.md](algorithms.md)), whose sorts are tested on random
|
||||
orders, and which counts this plan's `shuffle` among the users of its `swap`;
|
||||
- the grammars plan ([grammars.md](grammars.md)), whose tests make sentences and bytes
|
||||
at random.
|
||||
|
||||
**Probed:** on 2026-10-08, and again on 2026-10-20 against today's std, in the
|
||||
scratchpad (`plans/random/`). Each part ran:
|
||||
- in the machine and as executables at `-O0` and `-O2`;
|
||||
- with `run --checks`;
|
||||
- while compiling.
|
||||
|
||||
The results agreed everywhere, except where noted. It covered:
|
||||
- **The generator:** xoshiro256++ seeded through SplitMix64. Its first numbers for seed
|
||||
42, and those after a jump, matched a Python reference, including in a constant. A
|
||||
generator was a constant too.
|
||||
- **Numbers in a range** by Lemire's method, generic over every integer type through
|
||||
`u64`. `i8` from −100 to 100 and the whole of `u64` matched the reference. 600,000
|
||||
draws from 0 to 5 each came within 0.3% of 100,000.
|
||||
- **Ranges as values:** draws from `1..=6`, `-5..5` and a `range<u8>`.
|
||||
- **Reals from 0 up to 1,** with `f32` ones made from their own 24 bits, the largest
|
||||
being 0.99999994. The compiler inferred the type from the declaration, and asked for
|
||||
`fraction::<...>` where nothing gave it.
|
||||
- **Shuffling** a vector of strings by swapping bytes, under `run --checks`.
|
||||
- **The system's randomness:** 16 bytes from `getrandom`. The compiler also built a
|
||||
Windows executable calling `ProcessPrng`, which wasn't run.
|
||||
- **Forking:** a page marked `MADV_WIPEONFORK`, where a forked child read 0 and its
|
||||
parent read 12345.
|
||||
- **Threads:** four threads, each handed a copy of one generator jumped between them,
|
||||
summed the same in the machine and in executables.
|
||||
- **Speed in an `-O2` executable,** measured 2026-10-20 on a P-core, with bounds checked
|
||||
as [How it fits the rules](#how-it-fits-the-rules) says. On 2026-10-08 they were 5.3,
|
||||
11 and 5.4 ns.
|
||||
|
||||
| A draw | Time |
|
||||
|---|---|
|
||||
| 64 bits | 2.5 ns |
|
||||
| A number below a bound | 6.8 ns |
|
||||
| A real | 4.0 ns |
|
||||
|
||||
In the machine, each draw took 76 to 250 ns.
|
||||
|
||||
**Still so: a parameter taken by value draws from a copy.** Parameters belong to the
|
||||
function, which may change them (README, "Functions"). So `def roll(g: generator)` can
|
||||
call `g.next()`, and the caller's generator gives the same numbers again. Decision 5
|
||||
settles it for generators.
|
||||
|
||||
**Found: `contract::expects` costs about 22 ns where it holds,** in `-O2` executables.
|
||||
A draw below a bound took 28.5 ns checked by it, against 6.8 ns checked by a plain test
|
||||
and `sys::abort()`. Its default arguments, a `string` among them, are made at every
|
||||
call.
|
||||
|
||||
## What's there now
|
||||
|
||||
- **`hash` and `mix`** (`core/traits/comparison.sakura`), which scramble words but take no
|
||||
seed.
|
||||
- **No generator.** std's tests write their own: an xorshift in `test/std/mem.sakura`,
|
||||
`simd.sakura` and `swar.sakura` and in the corpus's `simd_lanes_agree_everywhere_1`,
|
||||
and a multiplying one in `test/std/threads.sakura`.
|
||||
- **No system randomness, no shuffling, and no generic swap.** `sort` and `heap` move
|
||||
elements' bytes themselves, and the algorithms plan proposes `swap`.
|
||||
- **`std::sys`** has `syscall` and `fork` on Linux, but neither `getrandom` nor a way to
|
||||
map memory; the runtime, `runtime`, maps its own. On Windows it calls the system's DLLs through
|
||||
`@link`, and `fork` gives `unsupported`.
|
||||
- **`real` and `integer`** (`std/traits`), which draws are bounded by. `std::math` has
|
||||
`rotate_left` and the other integer operations, but no wide product.
|
||||
- **Ranges are values:** `a..b` and `a..=b` make a `range<T>` of integers
|
||||
(`std/iterators/range.sakura`).
|
||||
- **Threads and atomics:** `std::thread`, with `spawn_with`, `mutex<T>` and `once`, and
|
||||
`atomic<T>` (`std/atomic.sakura`). Nothing gives a thread storage of its own.
|
||||
- **Clocks:** `std::time`'s `instant::now()` and `timestamp::now()` read nanoseconds. Two
|
||||
runs can read the same, and a clock is no secret, so seeds come from the system.
|
||||
- **Constants** run any function, unless it reads a global variable, calls C, or turns
|
||||
an address into a number (README, "Constants"). The compiler runs a constant and stops
|
||||
where it can't go on.
|
||||
|
||||
## What it needs
|
||||
|
||||
1. **A fast generator** that gives the same numbers from the same seed, wherever it
|
||||
runs, and in every version (decision 3).
|
||||
2. **Integers in a range,** with no bias, of any integer type, given as a range (decision
|
||||
4).
|
||||
3. **Reals** from 0 up to 1 and in a range, as `f32` and `f64`.
|
||||
4. **Chances, shuffling and picking.**
|
||||
5. **The system's randomness,** for secrets and seeds, on Linux and Windows.
|
||||
6. **A generator ready to use with no setup,** seeded differently on each run, which
|
||||
threads draw from at once (decision 6), and which a forked child doesn't share with
|
||||
its parent (decision 7).
|
||||
7. **Seeded generators in constants,** worked out while compiling.
|
||||
8. **Portable above `std::sys`.**
|
||||
|
||||
## How it fits the rules
|
||||
|
||||
- **A generator is plain data (decision 5).** It's four words, so it copies freely,
|
||||
compares through `equatable`, and can be a constant. Drawing takes `&mut this`, so
|
||||
functions that draw take `&mut generator`.
|
||||
- **The same numbers in the machine, in executables, and while compiling,** by
|
||||
construction:
|
||||
- the generator, and everything drawn from it, is integer arithmetic;
|
||||
- reals are made from integers by conversions that are exact, so no rounding can
|
||||
differ.
|
||||
|
||||
It was probed in the machine and in executables, under `run --checks`, and in
|
||||
constants.
|
||||
- **Nothing fails:**
|
||||
- A bound of 0, or an empty range, stops the program, as indexing past an end does.
|
||||
It's a plain test and `sys::abort()`, which reports where the program was, not
|
||||
`contract::expects`. Through `contract`, such a draw takes about four times as long
|
||||
(found above).
|
||||
- The system's randomness doesn't fail on Linux 3.17 or later, nor on Windows, where
|
||||
`ProcessPrng` never fails. Where it can't be had at all, the program stops, as Go
|
||||
1.24's `crypto/rand` does: no program should go on with keys it believes are
|
||||
random.
|
||||
- **Nothing allocates.** Shuffling swaps elements where they are.
|
||||
- **Threads:** a generator belongs to whoever holds it, as any value does. Each thread is
|
||||
handed its own, as `spawn_with` gives a value, and `jump` keeps their numbers apart.
|
||||
The shared generator is drawn from by every thread at once (decision 6).
|
||||
- **It isn't for secrets.** xoshiro256++'s state can be worked out from four of its
|
||||
numbers, so keys and tokens come from `system_bytes`, as its documentation will say.
|
||||
- **A build stays the same every time.** A seeded generator runs while compiling. The
|
||||
system's randomness makes a system call, or calls C on Windows, and the shared
|
||||
generator reads a global, so the compiler refuses a constant drawing from either.
|
||||
Probed.
|
||||
|
||||
## Layers
|
||||
|
||||
### `std::sys` gains
|
||||
|
||||
| Operation | Does |
|
||||
|---|---|
|
||||
| `getrandom(into: *mut u8, length: u64): i64` | Bytes from the system's generator, or the negated error number. Probed |
|
||||
| `map_wiped(length: u64): *mut u8` | Zeroed memory of its own, which a forked child sees as zeros again, or null where the system can't. Probed. Decision 7 |
|
||||
|
||||
- **On Linux:**
|
||||
- `getrandom` (318 on x86-64);
|
||||
- `mmap` (9), then `madvise` (28) with `MADV_WIPEONFORK` (18), from Linux 4.14.
|
||||
- **On Windows:** `getrandom` is `ProcessPrng`, from `bcryptprimitives.dll`, as Go and
|
||||
Rust use, linked as `std::sys` links `kernel32.dll`. The compiler built an executable
|
||||
calling it. There are no forks to guard against, so `map_wiped` is plain
|
||||
zeroed memory.
|
||||
- Both join the operations `std/system/system.sakura` lists for each system.
|
||||
|
||||
### `std::random` (decision 1)
|
||||
|
||||
```sakura
|
||||
module std::random;
|
||||
|
||||
#! A generator of random numbers, xoshiro256++ (decision 2), in four words. One made
|
||||
#! from a seed gives the same numbers every time (decision 3).
|
||||
pub struct generator : equatable { var _s: u64[4]; }
|
||||
|
||||
pub def generator::seeded(seed: u64): generator; # SplitMix64 spreads the seed
|
||||
pub def generator::from_system(): generator; # 32 bytes from the system
|
||||
pub def generator::next(&mut this): u64; # 64 bits
|
||||
pub def generator::equals(&this, other: &generator): bool;
|
||||
|
||||
#! From 0 up to a bound, not including it.
|
||||
pub def generator::below<T>(&mut this, bound: T): T where T: integer;
|
||||
#! From a range: `a..b` leaves its end out, and `a..=b` takes it in (decision 4).
|
||||
pub def generator::within<T>(&mut this, among: range<T>): T where T: integer;
|
||||
#! From 0 up to 1, not including 1.
|
||||
pub def generator::fraction<T>(&mut this): T where T: real;
|
||||
#! From low up to high, not including high.
|
||||
pub def generator::between<T>(&mut this, low: T, high: T): T where T: real;
|
||||
pub def generator::chance(&mut this, probability: f64): bool;
|
||||
pub def generator::fill(&mut this, into: slice<u8>): void;
|
||||
pub def generator::shuffle<T>(&mut this, items: slice<T>): void;
|
||||
pub def generator::pick<T>(&mut this, items: span<T>): maybe<&T>; # none where empty
|
||||
pub def generator::jump(&mut this): void; # 2^128 numbers ahead
|
||||
|
||||
# The shared generator, seeded from the system when first drawn from, which every
|
||||
# thread may draw from at once (decision 6).
|
||||
pub def below<T>(bound: T): T where T: integer;
|
||||
pub def within<T>(among: range<T>): T where T: integer;
|
||||
pub def fraction<T>(): T where T: real;
|
||||
pub def between<T>(low: T, high: T): T where T: real;
|
||||
pub def chance(probability: f64): bool;
|
||||
pub def shuffle<T>(items: slice<T>): void;
|
||||
pub def pick<T>(items: span<T>): maybe<&T>;
|
||||
|
||||
# The system's randomness, for keys, tokens and seeds.
|
||||
pub def system_bytes(into: slice<u8>): void;
|
||||
pub def system_word(): u64;
|
||||
```
|
||||
|
||||
```sakura
|
||||
import std;
|
||||
import std::random;
|
||||
import std::thread;
|
||||
|
||||
val roll := random::within(1..=6); # the shared generator
|
||||
random::shuffle(deck.slice);
|
||||
|
||||
# The same level from the same seed, every time.
|
||||
var world := random::generator::seeded(level.seed);
|
||||
for _ in 0..level.trees {
|
||||
val x := world.below(level.width);
|
||||
val y := world.below(level.height);
|
||||
val height: f32 = world.between(2.0, 9.0);
|
||||
plant(x, y, height);
|
||||
}
|
||||
|
||||
# A generator for each thread, from one seed, whose numbers never overlap.
|
||||
var source := random::generator::seeded(run.seed);
|
||||
var workers := vector::<thread::handle<void>>::new();
|
||||
for _ in 0..thread::cpu_count() {
|
||||
var started := thread::spawn_with(simulate, source) else (e) { return; };
|
||||
workers.append(move(started));
|
||||
source.jump();
|
||||
}
|
||||
|
||||
var key: u8[32];
|
||||
random::system_bytes(key[:]); # a secret
|
||||
```
|
||||
|
||||
## How each part works
|
||||
|
||||
- **The generator (decision 2):** xoshiro256++, by Blackman and Vigna.
|
||||
- Its four words change by adding, shifting, rotating and xor, with no
|
||||
multiplication, so it's quick in the machine too. It writes its rotations as two
|
||||
shifts, since `math::rotate_left` takes any width, and so a remainder and a branch.
|
||||
- Its period is 2^256 − 1, and it passes BigCrush and PractRand.
|
||||
- Its reference code is public domain. It's Julia's default generator, and Rust's
|
||||
`SmallRng` on 64-bit processors.
|
||||
- **Seeding:**
|
||||
- `seeded` fills the four words from SplitMix64 run from the seed, as the authors
|
||||
advise. Nearby seeds then give unrelated numbers.
|
||||
- The state is never all zeros, xoshiro's one forbidden state, since at most one of
|
||||
SplitMix64's four words can be zero.
|
||||
- `from_system` takes 32 bytes from the system, and takes them again if all were
|
||||
zero.
|
||||
- **Integers in a range:** Lemire's method (2019).
|
||||
- A 64-bit number is multiplied by the count of numbers in the range, and the high
|
||||
word of the 128-bit product is the result.
|
||||
- A number is drawn again only when the low word falls below 2^64 mod the count.
|
||||
That happens with a chance below the count divided by 2^64, and the division that
|
||||
works it out happens only then.
|
||||
- **Every integer type goes through `u64`.** `end as u64 - start as u64` wraps to the
|
||||
right count for signed types too, so nothing asks whether a type is signed. A range
|
||||
covering all of `u64` or `i64` takes a number as it is. Probed.
|
||||
- **A range** counts `end − start` numbers, and one more where it takes its end in, as
|
||||
`a..=b` does. Probed with both.
|
||||
- **The 128-bit product** is made of four 32-bit products today. A 64-bit `mul` gives
|
||||
both halves in one instruction, but `std::math` gave no wide product among its
|
||||
integer operations, and there are no 128-bit integers ([later.md](later.md),
|
||||
"128-bit integers"). An intrinsic for its high word would cut most of the 4 ns a
|
||||
draw in a range adds to `next`, and give the same bits.
|
||||
- **Reals:**
|
||||
- An `f64` is the top 53 bits times 2^−53, and an `f32` is the top 24 bits times
|
||||
2^−24. The values are evenly spaced and never reach 1.
|
||||
- Each width has its own because `fraction::<f64>() as f32` can round up to 1.0.
|
||||
`if const T is f32` chooses between them.
|
||||
- **The type comes from where the result goes,** as `val x: f32 = g.fraction();`.
|
||||
With nothing to say, the compiler asks for `fraction::<...>()`. Probed.
|
||||
- **The bound is `real`,** which std has had since 2026-10-14.
|
||||
- **`between`** gives low + (high − low) × a fraction. In the rare case where rounding
|
||||
reaches high, it draws again. It takes two ends, since a `range<T>` holds integers.
|
||||
- **`chance(p)`** is a fraction below `p`: never at 0, always at 1, and exactly the top
|
||||
bit at 0.5.
|
||||
- **`shuffle`** is Fisher–Yates from the end, swapping elements' bytes. An element is
|
||||
moved, never copied, so strings and other owning values shuffle safely. Probed under
|
||||
`run --checks`. It uses the algorithms plan's `swap` if that's built first, and
|
||||
otherwise swaps bytes itself, as `heap` does.
|
||||
- **`pick`** takes the element at `below(length)`, or none where there are none. A
|
||||
`maybe<&T>` is one word.
|
||||
- **`fill`** writes each number's 8 bytes from the lowest, so a seed gives the same bytes
|
||||
on every processor.
|
||||
- **`jump`** is the authors' jump, 2^128 numbers ahead. A generator jumped once for each
|
||||
thread, and handed to it by `spawn_with`, gives every thread numbers from one seed that
|
||||
never overlap. Probed.
|
||||
- **The shared generator (decision 6):**
|
||||
- Its state is kept in memory from `sys::map_wiped`, mapped and seeded from the
|
||||
system the first time it's drawn from. A program that never draws from it pays
|
||||
nothing. Threads that race to map it agree through `compare_exchange`, and the one
|
||||
that loses gives its page back.
|
||||
- **Threads draw from it at once.** Under 6(a) it's SplitMix64 over one `atomic<u64>`
|
||||
counter: each draw is one `fetch_add` and a mix. No thread waits, and since the mix
|
||||
gives each count its own number, no two draws are the same. Alone, a draw took
|
||||
14 ns in executables. With four threads drawing at once, 40 million draws took
|
||||
27 ns each by the clock, where xoshiro256++ behind a lock took 370 to 400 ns.
|
||||
- **The draws are written once,** generic over where their words come from, so
|
||||
`random::within` and `world.within` count a range alike.
|
||||
- **A forked child** finds it zeroed and seeds its own (decision 7), whatever forked:
|
||||
`sys::fork`, `process::command`'s child before it runs the new program, or C code a
|
||||
program calls.
|
||||
- **The system's randomness:**
|
||||
- `getrandom` with no flags waits only at boot, until the kernel's pool is first
|
||||
ready.
|
||||
- A read of up to 256 bytes is never cut short, longer ones are read in a loop, and an
|
||||
interrupted call is made again.
|
||||
- Before Linux 3.17, the call is missing, so `/dev/urandom` is read instead. Where
|
||||
neither works, the program stops.
|
||||
- On Windows, `ProcessPrng` fills any length in one call.
|
||||
|
||||
## Testing
|
||||
|
||||
- **`test/std/random.sakura`, written with `std::testing`,** covers:
|
||||
- **known answers:** xoshiro256++, its jump, and SplitMix64, checked against the
|
||||
authors' C code, which is run once in the scratchpad;
|
||||
- **ranges at each width's edges:** all of `i8` and of `u64`, `a..b` and `a..=b`, and
|
||||
the bounds 1 and 2^63 + 1, which is the worst for drawing again. A bound of 0, or an
|
||||
empty range, stops a forked copy, on Linux;
|
||||
- **evenness:**
|
||||
- chi-squared over a small bound and a large one;
|
||||
- the mean of reals;
|
||||
- never 1, for `f32` and `f64`.
|
||||
|
||||
Every check uses a fixed seed, so none can fail by chance;
|
||||
- **shuffling:** every order of 4 elements appearing about equally, strings, and
|
||||
runs of none and one;
|
||||
- **`pick`** of nothing giving none;
|
||||
- **the system:** two reads differing, and, on Linux, a forked child's shared numbers
|
||||
differing from its parent's;
|
||||
- **threads:** four drawing from the shared generator at once, with no number given
|
||||
twice under 6(a);
|
||||
- **while compiling:**
|
||||
- a constant from a seeded generator, drawing in a range and shuffling, equalling
|
||||
what running gives;
|
||||
- a constant from the system or the shared generator being refused, in the
|
||||
compiler's tests.
|
||||
- **Where they run:** in the machine, as executables at `-O0` and `-O2`, and with
|
||||
`run --checks`. They're also built for `windows-x86_64`.
|
||||
|
||||
## Phases
|
||||
|
||||
About 50 lines of `std::sys`, for Linux and Windows, 600 of `std::random`, and 400 of
|
||||
tests, with no change to the compiler.
|
||||
|
||||
1. **`sys::getrandom`, and the generator:**
|
||||
- `seeded`, `from_system` and `next`;
|
||||
- `below`, `within`, `fraction`, `chance` and `fill`;
|
||||
- also `system_bytes` and `system_word`.
|
||||
2. **`between`, `shuffle`, `pick` and `jump`.**
|
||||
3. **`sys::map_wiped`,** with the shared generator and its functions.
|
||||
4. **The README:** a `std::random` row in its table of modules, and a paragraph with an
|
||||
example under "The standard library", as `std::time` and `std::math` have.
|
||||
5. **std's tests moved onto it:** `mem`, `simd`, `swar` and `threads` drop the
|
||||
generators they write by hand. The corpus's `simd_lanes_agree_everywhere_1` keeps
|
||||
its own, since its expected output is made of its numbers.
|
||||
6. **Distributions,** if decision 8 is (a):
|
||||
- normal, by the ziggurat method, with its tables made while compiling. A table of
|
||||
`math::exp` and `math::log` works in a constant;
|
||||
- exponential, Poisson and binomial;
|
||||
- picks by weight, by the alias method.
|
||||
|
||||
## Later, where wanted
|
||||
|
||||
- **Samples:** k different elements out of n.
|
||||
- **An iterator of draws,** as `world.draws(1..=6).take(10).to_vector()`, for the
|
||||
adapters and consumers every iterator has.
|
||||
- **A wide product,** as an intrinsic among `std::math`'s integer operations, or
|
||||
128-bit integers, for Lemire's method and for hashing.
|
||||
- **A generator per thread behind the free functions,** in place of the atomic counter,
|
||||
once threads have storage of their own ([later.md](later.md), "Thread-local
|
||||
variables"). A draw would then cost what `next` does, with nothing shared.
|
||||
- **Text:** tokens, and version 4 UUIDs.
|
||||
- **Seeding `dict`'s hashes on each run,** against inputs crafted to collide. Its
|
||||
entries keep their places as it grows, so the order it gives them in wouldn't change.
|
||||
- **A strong generator in the program,** such as ChaCha, for a program that draws secrets
|
||||
too often for a system call each. `std::simd`'s `u32x4` and `u32x8` would work four or
|
||||
eight of its blocks at once in executables.
|
||||
- **macOS,** once `std::sys` has it.
|
||||
|
||||
## Decisions for you
|
||||
|
||||
1. **Where it lives:**
|
||||
- **(a) `std::random`, in `std/random/` (recommended),** as `std::time`,
|
||||
`std::math` and `std::thread` are modules of their own.
|
||||
- **(b) In module `std`.** Names such as `generator`, `below` and `shuffle` would
|
||||
then be taken in every program that imports `std`.
|
||||
2. **The generator:**
|
||||
- **(a) xoshiro256++ (recommended).**
|
||||
- It's 32 bytes and 2.5 ns here, with no multiplication, so it's also quick in the
|
||||
machine.
|
||||
- `jump` gives each thread its own numbers.
|
||||
- It isn't for secrets, which is why the system's randomness is separate.
|
||||
- **(b) PCG64 DXSM,** a variant of NumPy's default, PCG64. Each step multiplies
|
||||
128-bit numbers. Without 128-bit integers, that takes several of the four-multiply
|
||||
products, so it's slower here and much slower in the machine.
|
||||
- **(c) ChaCha8,** Go 1.22's default. Its numbers can't be predicted, so a program
|
||||
that wrongly makes tokens from it is still safe. But it keeps 64 bytes of state and
|
||||
a buffer, and it's many times slower per number in the machine, which works vector
|
||||
lanes one at a time. `std::simd` would speed it only in executables.
|
||||
3. **Numbers from a seed:**
|
||||
- **(a) The same in every version of std (recommended).** This covers the generator
|
||||
and every method drawing from it, for replays, saved worlds, and tests with seeds.
|
||||
The methods' algorithms then belong to the contract: Lemire's, 53 bits, and
|
||||
Fisher–Yates from the end. A faster way later needs a new name.
|
||||
- **(b) Only `next` stays the same.** Ranges, reals and shuffling may change between
|
||||
versions, as Rust's `rand` allows for `StdRng`.
|
||||
4. **How a range is given:**
|
||||
- **(a) As a `range<T>` (recommended),** as `within(1..=6)` and `within(0..n)`. `..`
|
||||
and `..=` say whether the end is in, as they do in `for`, so one name serves both.
|
||||
`below(n)` stays, for indexes.
|
||||
- **(b) Two ends, both included,** as `within(1, 6)`, as this plan first had it. But
|
||||
a range leaving its end out is `within(0, n - 1)`.
|
||||
5. **Copying a generator:**
|
||||
- **(a) Plain data, copying freely (recommended).**
|
||||
- A copy is a saved state to replay from.
|
||||
- It can be a constant, and it can be held in structs and arrays without making
|
||||
them close.
|
||||
- But `roll(g)` draws from a copy, as noted above, so the documentation says to
|
||||
take `&mut generator`.
|
||||
- **(b) `owning`, with a `close` that does nothing, and `copyable`,** as `atomic<T>`
|
||||
is `owning` so that it isn't copied by accident.
|
||||
- `roll(g)` is refused, and copies are named, as `copy(&g)`, which asks for
|
||||
`copy_of`.
|
||||
- A constant still works through `copy(&kept)`. All three were probed again.
|
||||
- But everything holding a generator then closes.
|
||||
6. **The shared generator:**
|
||||
- **(a) Yes, behind the free functions, as SplitMix64 over one atomic counter
|
||||
(recommended).** `random::within(1..=6)` needs no setup, which is what most
|
||||
programs want. It's seeded only when first drawn from. Threads draw from it at once
|
||||
without waiting: 14 ns a draw alone, and 27 ns by the clock with four drawing at
|
||||
once. Its numbers aren't xoshiro's, but nobody can seed it, so nothing can depend
|
||||
on them.
|
||||
- **(b) Yes, as xoshiro256++ behind a lock.** It's one generator throughout, and
|
||||
14 ns a draw alone, but 370 to 400 ns by the clock with four threads drawing at
|
||||
once.
|
||||
- **(c) Only generators a program makes.** There's no state in std, but every program
|
||||
makes and passes its own.
|
||||
7. **Forked children,** under 6(a) or 6(b):
|
||||
- **(a) Its state in memory a forked child sees as zeros (recommended).** This
|
||||
catches every fork, including C's, for one 4 KiB page, from Linux 4.14. `std::sys`
|
||||
gains `map_wiped`. Windows can't fork, so there it's plain memory.
|
||||
- **(b) A count of forks that `sys::fork` keeps, checked at each draw.** There's no
|
||||
page, but forks made by C code are missed.
|
||||
- **(c) Nothing.** A child repeats its parent's numbers, as the documentation would
|
||||
say.
|
||||
8. **Distributions:**
|
||||
- **(a) The uniform ones first, and normal, exponential and the rest in phase 6
|
||||
(recommended).** `std::math`'s `exp` and `log`, which they waited on, are built.
|
||||
- **(b) The uniform ones only.** Programs write their own.
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
# Roadmap: a language that holds
|
||||
|
||||
Written 2026-10-20, when you chose the recommended answer to every decision it asked, and
|
||||
cut on 2026-10-29 to what's left. Steps 1 to 6 are built: `extern` and the `system`
|
||||
library, `core`, contracts, the checks, the rules settled, and properties as C# writes
|
||||
them, and the rule for references and values beside them. The CHANGELOGs keep what each
|
||||
did, and [later.md](later.md) what each left.
|
||||
|
||||
**What's left:** the way to a language that stops changing under the programs written in
|
||||
it.
|
||||
- **Step 7, lambdas that own what they use,** the last change to the syntax.
|
||||
- **What else must be decided before the freeze,** as it would refuse programs if done
|
||||
after.
|
||||
- **Step 8, the freeze.**
|
||||
|
||||
**Plans that only add come after the freeze** (decision 5): [freestanding.md](freestanding.md),
|
||||
the library plans ([algorithms.md](algorithms.md), [benchmarks.md](benchmarks.md),
|
||||
[linear.md](linear.md), [logging.md](logging.md), [random.md](random.md) and
|
||||
[tui.md](tui.md)), and the compiler's own speed. Each one built first puts the freeze
|
||||
further off, and none of them needs it to wait.
|
||||
|
||||
## What "stable" means
|
||||
|
||||
From the freeze on, a program the compiler accepts:
|
||||
- is accepted by every later compiler;
|
||||
- means what it meant.
|
||||
|
||||
So a change after the freeze can only add:
|
||||
- modules, functions and types in std, `core` and `system`;
|
||||
- attributes and intrinsics;
|
||||
- warnings;
|
||||
- words that mean something only where they stand, as `ensures` does at the start of a
|
||||
statement;
|
||||
- accepting what was refused.
|
||||
|
||||
Adding a name can't break a program, since a program's own declaration hides a name of
|
||||
`core`'s and a built-in type: a program's `struct u32` hides the built-in one. A method a
|
||||
program declares on a type of `core`'s wins over one `core` adds later with the same name,
|
||||
so adding a method is an addition too.
|
||||
|
||||
Anything that would refuse a program, or change what one does, comes before the freeze
|
||||
or not at all. **Where it's unclear, refuse:** accepting something later is an addition,
|
||||
but refusing it later is a break.
|
||||
|
||||
**The freeze doesn't cover** (decision 4):
|
||||
- std's modules and their names, which change as a library's do, std being a repository
|
||||
of its own, versioned apart from the compiler;
|
||||
- the compiler's options, IR and messages;
|
||||
- how an ordinary struct is laid out. An extern section's layout is promised, and so
|
||||
will be freestanding.md's `@packed` and `@align`;
|
||||
- the calling convention between Sakura functions;
|
||||
- speed.
|
||||
|
||||
## Before the freeze
|
||||
|
||||
| What | Why it can't wait | Where |
|
||||
|---|---|---|
|
||||
| How a lambda owns what it uses, and whether every lambda has a type of its own | Giving every lambda a type refuses two lambdas given to one variable that isn't declared with a function type | [Step 7](#lambdas-that-own-what-they-use), below |
|
||||
| Whether a constant may hold what's written through, as a `string` | The compiler takes it, and the README refuses it | later.md, [What a constant may hold](later.md#what-a-constant-may-hold) |
|
||||
| Whether `decl_of` of a built-in type is refused | The compiler gives a declaration, and the README refuses it | later.md, [`decl_of` of a built-in type](later.md#decl_of-of-a-built-in-type) |
|
||||
| Whether a type that leaves a trait's default out meets the trait only by naming it | It would refuse what passes today. The other way, defaults reaching every type meeting the trait, only adds | later.md, [A trait's defaults reach only the types naming it](later.md#a-traits-defaults-reach-only-the-types-naming-it) |
|
||||
| Whether reading a moved local is an error | It would refuse what builds today. As a warning, it can come any time | later.md, [Tracking moved locals](later.md#tracking-moved-locals) |
|
||||
|
||||
The rest of later.md adds, or is the compiler's, std's or the tools' own, which the freeze
|
||||
doesn't cover, so it can come after.
|
||||
|
||||
## Lambdas that own what they use
|
||||
|
||||
Step 7, decisions 2 and 3, both decided (a). Its own plan measures and builds it, once you
|
||||
say to start.
|
||||
|
||||
**What can't be written today:**
|
||||
- a lambda that keeps state, returned;
|
||||
- a thread given a lambda that owns what it uses. A loop's variable goes through
|
||||
`spawn_with`;
|
||||
- a lambda kept in a `function` past the frame that made it.
|
||||
|
||||
Today the first and third take a functor, which is three declarations, and the second
|
||||
takes `spawn_with`:
|
||||
|
||||
```sakura
|
||||
struct counter : invokable<def(): i64> { var count: i64; }
|
||||
def counter::invoke(&mut this): i64 { this.count++; return this.count; }
|
||||
def make_counter(): function<def(): i64> { return function::new(counter{}); }
|
||||
|
||||
thread::spawn_with(def(i: i64) { work(i); }, i)
|
||||
```
|
||||
|
||||
**The direction** (decision 2): the lambda's own values in its parameter list, declared as
|
||||
locals are. A parameter written `val` or `var` belongs to the lambda:
|
||||
- it's made where the lambda is written, from the scope around it;
|
||||
- it's kept from call to call;
|
||||
- a call doesn't give it.
|
||||
|
||||
```sakura
|
||||
def counter(): function<def(): i64> {
|
||||
return def(var count := 0): i64 { count++; return count; };
|
||||
}
|
||||
|
||||
for i in 0..4 {
|
||||
val made := thread::spawn(def(val i := i) { work(i); }) else (e) { return; };
|
||||
handles.append(made);
|
||||
}
|
||||
|
||||
var lines := read_lines(path);
|
||||
thread::spawn(def(var lines := move(&mut lines)) { write_all(&lines); });
|
||||
|
||||
val scaled := def(x: i64, val k := factor * 2) => x * k; # k is worked out once
|
||||
```
|
||||
|
||||
```ebnf
|
||||
lambda_param = ident [ ":" type ] [ "=" expression ]
|
||||
| ( "val" | "var" ) ident ":" [ type ] "=" expression ; (* the lambda's own *)
|
||||
```
|
||||
|
||||
- **The signature leaves them out:** the lambdas above are `def(): i64`, `def(): void`
|
||||
and `def(i64): i64`. They come after the parameters a call gives.
|
||||
- **There's no new word and no brackets.** `val`, `var` and `:=` already mean "a value
|
||||
made here", and a `val` can't change while a `var` can, as for locals.
|
||||
- **A lambda with none of them is today's.** It still refers to anything else it uses.
|
||||
- **The parser is ready for it:** a parameter starts with a name today, so `val` and
|
||||
`var` there are free.
|
||||
|
||||
**What it needs:**
|
||||
- **A lambda that owns a value has a type of its own,** a struct of what it holds that
|
||||
implements `invokable<S>`. In effect it's a functor the compiler writes. It can't be a
|
||||
function value, since a function value owns nothing.
|
||||
- **It's moved, not copied,** once it holds something that closes, and it closes what it
|
||||
holds.
|
||||
- **Where a `function<S>` is expected, it becomes one.** That's later.md's "Converting
|
||||
where a `function` is expected", now that `core` holds `function`.
|
||||
- **`spawn` takes anything `invokable`.** `spawn_with` and `carrying` go.
|
||||
- **A lambda that refers to locals keeps today's rules,** and today's warnings, which
|
||||
since 2026-10-29 follow it through a call whose parameter is `@kept`, as
|
||||
`function::new`'s and `spawn`'s are.
|
||||
|
||||
**Every lambda has a type of its own** (decision 3), converting to a function type
|
||||
wherever one is expected. Generic code then takes each lambda as its own type, so a
|
||||
lambda costs what a functor does:
|
||||
- the adapters, which cost 3 to 4 times functors today (later.md, "Lambdas given to
|
||||
adapters");
|
||||
- a sort's order, which no optimization reaches otherwise (algorithms.md, decision 4).
|
||||
|
||||
What it refuses is two lambdas given to one variable that isn't declared with a function
|
||||
type:
|
||||
|
||||
```sakura
|
||||
var pick := def(x: i64) => x + 1;
|
||||
pick = def(x: i64) => x * 2; # refused: two lambdas, two types
|
||||
var chosen: def(i64): i64 = def(x) => x + 1;
|
||||
chosen = def(x) => x * 2; # both convert
|
||||
```
|
||||
|
||||
The cost is an instance of generic code for each lambda given to it, which the plan
|
||||
measures.
|
||||
|
||||
**Probed on 2026-10-20:**
|
||||
- There are about 340 lambdas in std, the compiler, its tests and its tools. Each refers
|
||||
to the locals it uses, and none can own a value.
|
||||
- std has eight functors: `function`, six adapters, and `carrying<A>`, which stands in
|
||||
for a lambda that owns what it's given, for `spawn_with`. The compiler's own sources
|
||||
start threads with `spawn_with` three times, and 13 test files write a functor by hand.
|
||||
- Every lambda the tree gives to an existing variable goes to one declared with a
|
||||
function type: fields of a `def` type, `var fib: transform`, a `maybe<def(i64): i64>`,
|
||||
and a `val maybe: def(): int` chosen by `?:`. No array holds lambdas. So decision 3
|
||||
refuses nothing in the tree.
|
||||
|
||||
**Not chosen:**
|
||||
- std's `bind(f, values...)`, a functor holding the values and passing them by `&mut`
|
||||
ahead of the call's arguments, with no syntax. It could still be built beside the
|
||||
direction chosen, if a library wants it.
|
||||
- `own val` and `own var` in the body, which read like the body but run at a different
|
||||
time than the lines under them.
|
||||
- Functors, as now.
|
||||
- Turned down on 2026-10-19: a list in brackets, as C++ has, of initializers
|
||||
(`[count = 0]`) or of words (`[move log, level]`), and `move def`, as Rust has.
|
||||
|
||||
## The freeze
|
||||
|
||||
Step 8, decision 4: additions only, from then on. Editions can come later without
|
||||
breaking it, since a file that names none would be of the first.
|
||||
|
||||
- **The README's grammar and rules are the language.** A line says from which version.
|
||||
- **A corpus of the grammar:** a program for each rule of the README's grammar that none
|
||||
of `tests/programs` uses yet, each with its `.out`. A change that breaks one fails a
|
||||
test.
|
||||
- **The bootstrap rule from then on:**
|
||||
- the compiler's own sources use only the language and std of the release before;
|
||||
- a release is built in two steps: the release before, with its own std, builds a
|
||||
first stage from the new sources, and that stage, with the new std, builds the
|
||||
release.
|
||||
+363
@@ -0,0 +1,363 @@
|
||||
# Style
|
||||
|
||||
Written 2026-11-18. This guide covers how Sakura code is laid out and named. The rules come
|
||||
from the code as it is written today: sakurac, std, blossom and binary, outside their tests.
|
||||
That is 353 files and 142,000 lines.
|
||||
|
||||
Where that code agrees with itself, the rule says what it does. Where it doesn't, the rule
|
||||
says which way the code leans and recommends one way. Those rules are gathered in
|
||||
[Decisions](#decisions) at the end, and the choices there are yours to make. Nothing checks
|
||||
these rules yet, since Sakura has no formatter.
|
||||
|
||||
A file keeps one style throughout. Change a file's layout in a change of its own, not inside
|
||||
a change to what the code does.
|
||||
|
||||
|
||||
## Files
|
||||
|
||||
- **Names:** a file's name is in snake_case and says what the file holds, as
|
||||
`deque.sakura` or `byte_writer.sakura`. A module's folder is named after the module: the
|
||||
folder `std/io/` holds `std::io`.
|
||||
- **Text:** files are UTF-8, end each line with `\n`, and end with a newline. They have no
|
||||
tabs and no spaces at the ends of lines. Every file surveyed follows this.
|
||||
- **Opening:** a file opens with a `#!` header that gives its name, author, copyright and
|
||||
license. A paragraph after the header says what the file holds. Then come:
|
||||
- one blank line;
|
||||
- the imports, with the `module` line right after them;
|
||||
- two blank lines;
|
||||
- the declarations.
|
||||
|
||||
Every file surveyed has the header, and most open in exactly this order. The rest differ
|
||||
only in their blank lines.
|
||||
|
||||
```sakura
|
||||
#! @file deque.sakura
|
||||
#! @author Name (address)
|
||||
#! @copyright Holder.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Defines `deque`, a container pushed and popped at either end.
|
||||
|
||||
import std::io;
|
||||
module std::containers;
|
||||
|
||||
|
||||
#! A double-ended queue, which keeps its elements in order.
|
||||
pub struct deque<T> : owning, iterable<T> {
|
||||
```
|
||||
|
||||
- **Sections:** a long file groups its declarations under headings. A heading is a `#` line
|
||||
alone with two blank lines before it and one after, as `analyzer/parser/helpers.sakura`
|
||||
does with `# Nodes`, `# Declarations` and `# Notes`.
|
||||
|
||||
```sakura
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
# Nodes
|
||||
|
||||
#! Appends a node.
|
||||
```
|
||||
|
||||
|
||||
## Layout
|
||||
|
||||
- **Indentation** is two spaces for each level. No file uses tabs.
|
||||
- **Braces:**
|
||||
- `{` ends the line that opens the block, and `}` stands alone at that line's indent.
|
||||
- `} else {` and `} else if c {` share one line.
|
||||
- An empty body is `{}`, as in `pub trait integer {}`.
|
||||
|
||||
8,800 blocks open this way. The 27 that don't follow a header broken across lines (see
|
||||
[Breaking long lines](#breaking-long-lines)).
|
||||
- **Blank lines:**
|
||||
- One blank line goes between top-level declarations. A doc comment sits right on what it
|
||||
documents, with no blank line between them.
|
||||
- Two blank lines go after the `module` line and before a section heading.
|
||||
- Inside a body, one blank line may separate steps. Bodies never have two blank lines in
|
||||
a row.
|
||||
- **Line length:** comments wrap at 80 columns, and 99% of comment lines fit. Code stays
|
||||
within 100 columns, which 97% of code lines do. See decision 1.
|
||||
- **One statement to a line.** For an early exit, use a guard (see
|
||||
[Statements](#statements)) rather than a one-line `if c { return; }`.
|
||||
|
||||
|
||||
## Spaces
|
||||
|
||||
| Write | Not |
|
||||
| --- | --- |
|
||||
| `x: u64`, `def f(a: u8): u8`, `where T: sized` | `x : u64`, `x:u64` |
|
||||
| `struct console : readable, writable {`, `enum flow : u8 {` | `struct console: readable` (see decision 2) |
|
||||
| `val x := 1;`, `a + b`, `a == b`, `x += 1`, `a ? b : c` | `a+b`, `x:=1` |
|
||||
| `x as u64`, `x is some(v)`, `x is not none` | |
|
||||
| `0..n`, `0..=n`, `xs[a:b]`, `xs[1:]` | `0 .. n`, `xs[a : b]` |
|
||||
| `!x`, `-x`, `~x`, `*p`, `&x`, `&mut x`, `x++` | `! x`, `& x` |
|
||||
| `f(a, b)`, `[1, 2, 3]`, `xs[i]` | `f( a, b )`, `[ 1, 2, 3 ]` |
|
||||
| `vector::<T>::new()`, `map<K, V>` | `vector :: < T >` |
|
||||
| `point { x = 1, y = 2 }`, `nothing {}` | `point{x=1}`, `point{ x = 1 }` |
|
||||
| `def(x: i64): i64 => x + 1` | |
|
||||
| `# Why.`, `#! What.` | `#Why.` |
|
||||
|
||||
- In a struct literal, put a space between the type and `{`, inside the braces, and around
|
||||
each `=`. The code does this 1,177 times to 106.
|
||||
- A `:` naming a type takes a space after it and none before. The `:` that lists a type's
|
||||
traits, or an enum's base type, takes a space on both sides. That tells
|
||||
`struct console : readable` apart from a field's `name: type`.
|
||||
|
||||
|
||||
## Lining up
|
||||
|
||||
A run is a group of like lines with no blank line between them.
|
||||
|
||||
- **Line up what reads as a table:**
|
||||
- field types and the `#!` notes after them;
|
||||
- enum members' values and notes;
|
||||
- the parameters of a signature written one to a line;
|
||||
- doc comment tags.
|
||||
|
||||
500 runs of fields are lined up, and 295 are not.
|
||||
|
||||
```sakura
|
||||
pub enum flow : u8 {
|
||||
goes_on, #! The block goes on past it.
|
||||
leaves, #! The block never goes on past it.
|
||||
skips, #! It leaves, as decided while checking.
|
||||
}
|
||||
|
||||
struct entry {
|
||||
var key: string; #! What it's found by.
|
||||
var value: u64; #! What it holds.
|
||||
var hashed: u64; #! The key's hash, kept so growing needn't hash again.
|
||||
}
|
||||
```
|
||||
|
||||
- **Don't line up statements.** Leave `:=` in a run of locals, and `=>` in a match's arms,
|
||||
where they fall. 1,517 runs of locals are not lined up and 530 are; for match arms it is
|
||||
211 to 129. Padding statements means one edit changes its neighbours' lines too. See
|
||||
decision 3.
|
||||
|
||||
|
||||
## Breaking long lines
|
||||
|
||||
- **Operator first.** A continued line starts with its operator (`&&`, `||`, `+`, `?`, `:`)
|
||||
rather than ending the line before with it. The code does this 480 times to 8.
|
||||
- **Ternaries:** a ternary that doesn't fit puts `?` and `:` each at the start of its own
|
||||
line, one level in.
|
||||
|
||||
```sakura
|
||||
return (dst as u64) - (src as u64) >= len
|
||||
? copyfwd(dst, src, len)
|
||||
: copybwd(dst, src, len);
|
||||
```
|
||||
|
||||
- **Chains of `&&`, `||` and arithmetic:** each continued line goes two levels in (four
|
||||
spaces) past the line it continues. That never matches the indent of the block it opens.
|
||||
See decision 4.
|
||||
|
||||
```sakura
|
||||
return false if body.insts[call].argc as u64 != callee.blocks[0].params.length
|
||||
|| body.insts[call].count as u64 != callee.results.length;
|
||||
```
|
||||
|
||||
- **Calls and parameter lists:**
|
||||
- Break after `(`. Put the items one level in, one to a line, or several to a line where
|
||||
they fit.
|
||||
- `)` starts its own line, back at the opening line's indent, followed by the rest of the
|
||||
header.
|
||||
- Parameters written one to a line line up their types.
|
||||
- Whether the last item takes a comma is decision 5.
|
||||
|
||||
```sakura
|
||||
pub def atomic<T>::compare_exchange(
|
||||
&mut this,
|
||||
expected: T,
|
||||
desired: T,
|
||||
success: order = order::seq_cst,
|
||||
failure: order = order::seq_cst
|
||||
): result<T, T> {
|
||||
|
||||
pub def WaitOnAddress(
|
||||
at: *mut u32, compare: &u32, size: u64, milliseconds: u32
|
||||
): i32;
|
||||
|
||||
memcpy(
|
||||
dst as *mut u8,
|
||||
src as *mut u8,
|
||||
bytes_of::<T>(this._len - index)
|
||||
);
|
||||
```
|
||||
|
||||
- **Headers broken before `where` or a trait list:**
|
||||
- A `where` that doesn't fit takes a line of its own, one level in.
|
||||
- A trait list that doesn't fit puts one trait to a line: the first led by `:`, the rest
|
||||
by `,`.
|
||||
- In both cases `{` takes a line of its own, so the header ends clearly where the body
|
||||
begins.
|
||||
|
||||
```sakura
|
||||
pub def maybe<T>::is_some_and<F>(&this, test: F): bool
|
||||
where F: invokable<def(&T): bool>
|
||||
{
|
||||
|
||||
pub struct deque<T>
|
||||
: owning
|
||||
, hashable
|
||||
, iterable<T>
|
||||
, copyable
|
||||
{
|
||||
```
|
||||
|
||||
|
||||
## Names
|
||||
|
||||
- **snake_case for every name a program declares:** modules, files, types, traits, aliases,
|
||||
enums and their members, functions, methods, properties, fields, locals, and constants.
|
||||
All 28,700 declarations surveyed follow this, except foreign names (below). Constants
|
||||
aren't capitalized: write
|
||||
`const page: u64 = 4096;`, not `PAGE`.
|
||||
- **Type parameters** are capitals, mostly a single letter:
|
||||
- `T` for the type;
|
||||
- `U` for a second type;
|
||||
- `E` for an error;
|
||||
- `K` and `V` for keys and values;
|
||||
- `F` for a function;
|
||||
- `I` for an iterator;
|
||||
- `S` for a signature;
|
||||
- `N` and `M` for constants, as in `const N: u64`;
|
||||
- `Ts...` for a pack.
|
||||
- **Foreign names** declared in an `extern` section keep their own spelling, as
|
||||
`GetLastError`.
|
||||
- **Private fields:** see decision 6. In core and std, a private field usually starts with
|
||||
`_`. In the compiler, fields have plain names.
|
||||
|
||||
|
||||
## Declarations
|
||||
|
||||
- **Variables:**
|
||||
- Use `val` unless something writes the value later.
|
||||
- Use `:=` where the value shows the type. Write the type where it doesn't, as for a
|
||||
number of a chosen width: `val mask: u8 = 0x0F;`. The code uses `:=` 13,000 times and
|
||||
writes the type 2,800 times.
|
||||
- **Literals:**
|
||||
- Use `0u` for an unsigned literal and `0.0` for a float.
|
||||
- Hexadecimal digits are capitals, as in `0xFFFF` (see decision 7).
|
||||
- **Methods** take `&this` where they only read, and `&mut this` where they write.
|
||||
- **Properties:** a property whose one accessor is a short `=>` may sit on one line:
|
||||
`pub val maybe<T>::is_some: bool { get => this is some; }`.
|
||||
- **Imports** are sorted by path (see decision 8). The compiler doesn't care about their
|
||||
order.
|
||||
|
||||
|
||||
## Statements
|
||||
|
||||
- **Leave early with a guard:** write `return x if c;`, `break if c;` or `continue if c;`
|
||||
rather than an `if` block that holds only the jump. Guards outnumber such blocks 3,400 to
|
||||
1,700.
|
||||
- **Loops:** write `while true { ... }` for a loop left from inside.
|
||||
- **Counting:** write `x++;` and `x--;` as statements. They are always postfix.
|
||||
- **Unused values:** write `_ = f();` to let go of a value nothing reads.
|
||||
- **`match`:**
|
||||
- `else` comes last.
|
||||
- A statement's arms each end with `;` or a block.
|
||||
- A value's arms are separated by `,`.
|
||||
|
||||
|
||||
## Comments
|
||||
|
||||
- **`#!` documents a declaration, and `#` explains code.**
|
||||
- **What to document:** document every declaration another file can call, so every `pub`
|
||||
one. sakurac documents nearly everything else too.
|
||||
- **A doc comment's shape:**
|
||||
- First, a sentence or two saying what the declaration is or does.
|
||||
- More paragraphs, if any, follow after a bare `#!` line.
|
||||
- Then the tags:
|
||||
- `@param` for each parameter, `this` included;
|
||||
- `@returns` unless the function returns `void`;
|
||||
- `@tparam` for each type parameter;
|
||||
- `@remarks` for what a caller should know beyond those.
|
||||
- Each tag is padded to the width of `@returns`, and the names after `@param` are padded
|
||||
to the longest.
|
||||
- A tag that runs to more lines continues under its text.
|
||||
|
||||
```sakura
|
||||
#! Checks a block's statements from one on.
|
||||
#! @param this The checker.
|
||||
#! @param run The block's run of statements.
|
||||
#! @param from The first to check.
|
||||
#! @param count How many the block has.
|
||||
#! @returns How they end: `leaves` where one leaves, and `skips` where one
|
||||
#! leaves as decided while checking, so the rest are not checked.
|
||||
```
|
||||
|
||||
- **Fields and enum members** take their `#!` note at the end of their line, lined up.
|
||||
- **A `#` comment** says why, in sentences, on its own line above the code it explains.
|
||||
Short notes at the ends of lines are for tables.
|
||||
- **Work left for later** goes in the project's notes, as sakurac's `docs/later.md` does,
|
||||
not in `TODO` comments. The code surveyed holds one.
|
||||
|
||||
|
||||
## Decisions
|
||||
|
||||
Each decision gives what the code does today and a recommendation.
|
||||
|
||||
1. **How long a line of code may be.**
|
||||
- Today: 7% of code lines pass 80 columns, and 3% pass 100. Comments keep to 80.
|
||||
- Recommended: **100 for code and 80 for comments.** That keeps nearly all of today's
|
||||
code. 80 would mean rewrapping 7,600 lines.
|
||||
2. **The `:` before a type's traits.**
|
||||
- Today: `struct console : readable` 185 times, and `struct console: readable` 41 times
|
||||
(mostly in std).
|
||||
- Recommended: **spaced**, as most of the code is. It tells the trait list apart from a
|
||||
field's type.
|
||||
3. **Lining up statements.**
|
||||
- Today: fields are mostly lined up, while locals' `:=` (530 runs of 2,000) and match
|
||||
arms' `=>` (129 of 340) mostly aren't.
|
||||
- Recommended: **line up tables, not statements**, as [Lining up](#lining-up) says.
|
||||
- The README's opening example lines up its arms. It would change to match.
|
||||
4. **How far a continued `&&` or `||` line goes in.**
|
||||
- Today: 139 continued lines line up under the start of the expression they continue.
|
||||
47 go two levels in, 40 go one level in, and 53 sit elsewhere.
|
||||
- Lining up depends on how long the start of the line is: renaming `scalar` in
|
||||
`val scalar := a || ...` moves every continued line.
|
||||
- Recommended: **two levels**, which never moves and never matches the block's indent.
|
||||
5. **A comma after the last item of a list that spans lines.**
|
||||
- Today: enums always have one (112 of 113). Value-match arms have one 26 times in 166,
|
||||
and struct literals 4 times in 133. The README's examples always have one.
|
||||
- Recommended: **always.** An item added at the end then changes one line, not two.
|
||||
6. **Private fields.**
|
||||
- Today: core and std start 379 private fields with `_`, often short (`_dat`, `_len`).
|
||||
The compiler, blossom and binary use plain names, 1,800 times.
|
||||
- Choices:
|
||||
- `_` on every private field;
|
||||
- `_` only on a field that a public member of the same meaning stands in front of, as
|
||||
`_len` behind the property `length`;
|
||||
- never.
|
||||
- Recommended: **only behind a public member.** The language already marks what's
|
||||
private by leaving out `pub`, so `_` is needed only where a field and a property
|
||||
would otherwise want the same name.
|
||||
7. **Hexadecimal digits.**
|
||||
- Today: capitals 1,156 times, lowercase 146 (mostly in the compiler's number tables).
|
||||
- Recommended: **capitals.**
|
||||
8. **Import order.**
|
||||
- Today: 24 files sort their imports and 47 don't.
|
||||
- Recommended: **sorted by path**, so a formatter can keep them that way.
|
||||
9. **Doc tags outside the toolchain.**
|
||||
- Today: `linear` and `geometry` write their docs in sentences, without tags.
|
||||
- Recommended: **tags in the toolchain and std, and in other libraries one style chosen
|
||||
per library.** The language server shows doc comments as they're written and reads no
|
||||
tags, so nothing depends on them yet.
|
||||
10. **Which files need the header.**
|
||||
- Today: every library file has it.
|
||||
- Recommended: **files of libraries and tools.** A program's own files, tests and
|
||||
examples may leave it out.
|
||||
|
||||
|
||||
## What could come next
|
||||
|
||||
- **A formatter.** Most of these rules can be applied by a program. `sakurac fmt`, or a
|
||||
formatting request answered by `sakurac lsp`, could apply them. The exceptions are where
|
||||
to break a long line and how to divide a file into sections.
|
||||
- **Editor defaults.** The VS Code extension could set two-space indents, rulers at 80 and
|
||||
100, trimmed spaces at line ends, and a final newline for `.sakura` files.
|
||||
- **The README.** Once decisions 3 and 5 are made, the README's examples should follow them.
|
||||
+836
@@ -0,0 +1,836 @@
|
||||
# Plan: terminal interfaces
|
||||
|
||||
Written 2026-10-13, and brought up to date 2026-10-20 for what std has gained since:
|
||||
`poll`'s timeout, Windows, threads, `strview::chars`, `std::swar`, signal handlers held
|
||||
as `function`s, and `result<void, E>`. This is a proposal. std is yours, so the
|
||||
decisions at the end are yours to make. Nothing is built yet.
|
||||
|
||||
**Comes after the ffi plan, now built:** `std::sys` is `system`, and `@foreign` and
|
||||
`@link` are `extern` sections.
|
||||
|
||||
**What it is:** a library for writing to a terminal:
|
||||
- **color and style:** text in sixteen, 256 or 16 million colors, bold, italic,
|
||||
underlined and the rest, written only where the output shows them;
|
||||
- **the cursor:** moving it, saving and restoring it, hiding it, and changing its
|
||||
shape, and clearing the screen;
|
||||
- **box drawing:** boxes and lines in light, heavy, double or rounded strokes, which
|
||||
join where they meet;
|
||||
- **full-screen programs:** raw mode, the alternate screen, keys, the mouse, pasting
|
||||
and resizing, and a canvas the program draws a frame on, of which only what changed
|
||||
is written.
|
||||
|
||||
**Its users:**
|
||||
- the logging plan ([logging.md](logging.md)), whose levels are colored on a terminal.
|
||||
Its `sys::is_terminal` is this plan's;
|
||||
- `std::args` (the README's "Arguments"), whose help is written in columns padded by
|
||||
bytes. It could be wrapped to the terminal's width and padded by `width_of`. A
|
||||
program's own `--no-color` would give its painters abilities of its choosing;
|
||||
- `std::testing`, which could color what passed and failed and keep one line of
|
||||
progress;
|
||||
- the compiler's notes, which could color their places and underlines;
|
||||
- the build tool's progress;
|
||||
- full-screen programs, such as a profile viewer, a debugger's front end, or a
|
||||
program that picks from a list.
|
||||
|
||||
**Probed:** in the scratchpad on 2026-10-13 (`tuiprobe/`), and again on 2026-10-20
|
||||
against today's std (`plans/tui/`). A small driver ran the probe under a
|
||||
pseudo-terminal of 24×80, resized it, and typed into it. The probe was built by the
|
||||
compiler and run as an executable and in the VM, and the two gave the same results
|
||||
both times:
|
||||
- `TCGETS`, made through `sys::syscall`, worked on the terminal and gave -25
|
||||
(`ENOTTY`) on a pipe;
|
||||
- `TIOCGWINSZ` gave 24×80, and 40×120 once the driver resized it;
|
||||
- raw mode was set through `TCSETS`, as `cfmakeraw` sets it. The mode put back
|
||||
afterward matched the saved one byte for byte;
|
||||
- `sys::poll` with a timeout, std's own now, was ended by the resize with -4. The
|
||||
handler given to `sys::handle(signal::resized, ...)`, a closure counting into a
|
||||
local, had run by then;
|
||||
- an up arrow arrived as one read of `ESC [ A`. A lone Escape was told apart from the
|
||||
start of a sequence by 30 ms of quiet;
|
||||
- `sys::raise(signal::suspend)` stopped the program, which went on from there once it
|
||||
was continued (2026-10-20);
|
||||
- bold red, 256-color and 24-bit color, hiding and moving the cursor, and a rounded
|
||||
box with `┬`, `┼` and `┴` were all written from literals, with `\x1b` and UTF-8 text,
|
||||
and reached the terminal as written (2026-10-13). No terminal showed them, so how
|
||||
they look wasn't probed;
|
||||
- the sketches under "Using it", over stubs of the API, checked and ran
|
||||
(2026-10-20), once union fields were `pub` and `attribute` was renamed `effect`
|
||||
(see "Found along the way").
|
||||
|
||||
Nothing was probed on Windows.
|
||||
|
||||
**Measured** on 2026-10-20: every program is checked with all of std, whatever it
|
||||
imports, and std is 40,200 lines now. The processor was held at 2.1 GHz, on battery,
|
||||
so the times are slower than 2026-10-13's, whose clock wasn't noted, and the two don't
|
||||
compare. Each is the best of 15 runs or more, interleaved, on one core.
|
||||
- A one-line program takes about 93 ms to check.
|
||||
- `std/yaml`'s 4,498 lines cost 12 ms of that, and `std/time`'s and `std/thread`'s
|
||||
1,965 lines 5 ms. That's about 2.6 ms per 1,000 lines.
|
||||
- So the 2,500 or so lines this plan adds to std would add about 6.5 ms to checking
|
||||
every program, at that clock: 7% of a one-line program's check.
|
||||
|
||||
## What's there now
|
||||
|
||||
- **Writers:** `io::output()` writes at line breaks, `io::error_output()` writes at
|
||||
once, and `io::writer_of` buffers anything `writable`. A write gives
|
||||
`result<void, io_error>`. `print` and `println` hold the standard output for each
|
||||
call, so two threads' lines never mix, and `io::output_locked()` holds it across
|
||||
several.
|
||||
- **Text:** literals take `\x1b` and UTF-8, and `strview` and `string` are bytes.
|
||||
- `strview::chars()` decodes UTF-8 lazily into code points, giving `U+FFFD` for each
|
||||
byte that begins none. `serial::is_utf8` checks text, and `serial::utf8_length`
|
||||
measures a sequence.
|
||||
- `index_of`, `find_any` and `is_ascii` go eight bytes at a time, and `std::swar`
|
||||
gives the words themselves, for passing over runs of plain ASCII.
|
||||
- Nothing knows how wide a character is.
|
||||
- **`std::sys`,** on Linux and, since 2026-10-19, on Windows:
|
||||
- it reads and writes handles;
|
||||
- `poll(handles, ready, wait)` waits on several handles for at most `wait`
|
||||
milliseconds, or forever where it's -1, and gives 0 where the wait ran out. On
|
||||
Windows it peeks pipes, so a console always reads as ready;
|
||||
- it handles signals, `resized` (`SIGWINCH`) among them. `handle` takes any
|
||||
callable, which it keeps as a `function<def(signal): void>`, the type
|
||||
`sys::handler`. A handler runs at a safe point, in the thread the program began
|
||||
with, and ends the wait it interrupts. `watch` and `watched` note a signal with no
|
||||
handler, and the waits it interrupts go on. `raise` sends a signal to the program
|
||||
itself;
|
||||
- it reads the environment, through `sys::environment()` and `process::variable`.
|
||||
- **Nothing knows the terminal on Linux:** whether a handle is one, its size, or its
|
||||
mode. There's no `ioctl`, though `sys::syscall` reaches it, as the probe did.
|
||||
- **On Windows,** `std::sys` asks `GetConsoleMode` whether a handle is a console, but
|
||||
only for itself. It reads and writes a console as UTF-16, through `ReadConsoleW` and
|
||||
`WriteConsoleW`, so UTF-8 shows whatever the code page. Nothing sets a console's
|
||||
mode, so a sequence written reaches it as text unless its virtual terminal
|
||||
processing is on already. The console's Ctrl-C, Ctrl-Break and closing are noted as
|
||||
`interrupt`, `quit` and `hangup`, no `resized` ever comes, and `raise(suspend)` gives
|
||||
`unsupported`.
|
||||
- **Nothing runs as the program stops,** besides `close` where a scope ends. `exit`
|
||||
and a fault from any thread, `abort` and a failed contract end in `exit_group`, or
|
||||
`ExitProcess` on Windows, through the runtime in `runtime/start.sakura` or
|
||||
through the VM.
|
||||
- **`flags32<T>`** is a set of flags named by an enum, which fits a style's effects.
|
||||
- **std::time's `duration`** fits a wait for input.
|
||||
- **`function<S>`** holds any callable of a signature, and owns it. It's moved, never
|
||||
copied.
|
||||
|
||||
## What it needs
|
||||
|
||||
1. **Colors and styles:**
|
||||
- the sixteen named colors, the 256 indexed ones, and 24-bit colors;
|
||||
- bold, dim, italic, underline, blink, reverse, hidden and strikethrough;
|
||||
- colors brought down to what the terminal shows, and nothing written where the
|
||||
output isn't a terminal or the user asked for no color.
|
||||
2. **The cursor:** moved to a place or by an amount, saved and restored, hidden and
|
||||
shown, and given a shape.
|
||||
3. **The screen:**
|
||||
- clearing it, a line, or the rest of either;
|
||||
- the alternate screen;
|
||||
- a scrolling region;
|
||||
- the window's title.
|
||||
4. **Box drawing:**
|
||||
- light, heavy, double and rounded strokes;
|
||||
- lines that meet joined into `├`, `┬` and `┼`;
|
||||
- boxes in a full-screen frame, and in ordinary output, as a table printed at the
|
||||
end of a build.
|
||||
5. **The terminal itself:**
|
||||
- whether a handle is one, and its size;
|
||||
- raw mode, and putting back the mode it was in;
|
||||
- resizing, and suspending with Ctrl-Z and resuming.
|
||||
6. **Input:**
|
||||
- keys, with Shift, Alt and Ctrl;
|
||||
- text, the mouse, pasting and focus;
|
||||
- reading with a timeout.
|
||||
7. **A canvas** the program draws a whole frame on, of which only the cells that
|
||||
changed are written.
|
||||
8. **The width of text** in columns, so that `中` takes two and an accent joining a
|
||||
letter none.
|
||||
9. **Tests without a terminal,** with one where it matters.
|
||||
10. **Portable above `std::sys`,** which has Windows now. Its console takes the same
|
||||
sequences once its virtual terminal processing is on. Every operation `std::sys`
|
||||
gains must exist there too, since std is checked whole for an executable for
|
||||
Windows (decision 11).
|
||||
|
||||
## How it fits the rules
|
||||
|
||||
- **A terminal is `owning`.** Closing it, on any way out of its scope, puts back what
|
||||
it changed:
|
||||
- the mode, and the screen;
|
||||
- the cursor;
|
||||
- mouse and paste reporting;
|
||||
- what the program did with `resized`.
|
||||
|
||||
Decision 5 is what happens when the program stops some other way.
|
||||
- **A painter borrows or owns its stream,** as `io::writer_of`'s writer does, so
|
||||
`painter_of(&mut text)` writes to a `string` and closes nothing.
|
||||
- **Colors, styles, keys, events and cells are plain data.** They copy freely and are
|
||||
`equatable`. A `maybe` has no `==`, so `style::equals` compares its colors itself. A
|
||||
pasted text views the terminal's buffer, and is good until the next event is read,
|
||||
as a `dir_entry`'s name is good until the next entry.
|
||||
- **Errors are values.** Anything that can fail gives `result<T, io_error>`, or
|
||||
`result<void, io_error>` where only whether it failed comes back. `io_error` gains
|
||||
`not_a_terminal`, for `ENOTTY`, which `error_of` gives as `other` today.
|
||||
- **Everything is written through `writable`,** so tests read what a painter wrote
|
||||
from a `string`.
|
||||
- **Signals stay the program's:**
|
||||
- in raw mode, Ctrl-C and Ctrl-Z are keys, so the program decides what they do;
|
||||
- while a terminal is open, it handles `resized`, and the program reads
|
||||
`event::resized`. On close, what the program did with `resized` comes back: its
|
||||
handler, or ignoring it, watching for it, or the default. A handler is a
|
||||
`function`, moved and never copied, so `std::sys` gains a way to take it and give
|
||||
it back.
|
||||
- **Interpolation formats a value by its fields,** so `$"{style}"` can't write a
|
||||
sequence. `paint` gives a `string` to interpolate instead.
|
||||
- **What's shared is made on first use,** as `io::output()` is: `term::output()` and
|
||||
`term::error_output()`, the standard streams' painters.
|
||||
- Each paints `term::standard`, a stream writing through `io::output()` or
|
||||
`io::error_output()` at each write, so painted text keeps its order with
|
||||
`println`'s. It can't hold a `&mut writer<console>`, since a module's variable
|
||||
needs a zero value and a reference has none (probed).
|
||||
- As `io::output()` doesn't, it takes no lock. A thread painting several pieces
|
||||
holds `io::output_locked()` around them.
|
||||
|
||||
## Layers
|
||||
|
||||
### `std::sys` gains
|
||||
|
||||
| Operation | Does |
|
||||
|---|---|
|
||||
| `is_terminal(handle: fd): bool` | Whether the handle is a terminal, through `TCGETS`, and on Windows `GetConsoleMode`, which `std::sys` asks already for itself. The logging plan's. Probed on Linux |
|
||||
| `terminal_size(handle: fd, columns: &mut u16, rows: &mut u16): i32` | Its size, through `TIOCGWINSZ`, and on Windows `GetConsoleScreenBufferInfo`'s window. Probed on Linux |
|
||||
| `terminal_mode` | The mode a terminal is in, as the system keeps it: 36 bytes on Linux, and the input's and output's modes on Windows, which nothing above reads |
|
||||
| `get_mode(handle: fd, into: &mut terminal_mode): i32` | Reads it, through `TCGETS`, or `GetConsoleMode`. Probed on Linux |
|
||||
| `set_mode(handle: fd, mode: &terminal_mode): i32` | Sets it, through `TCSETS`, or `SetConsoleMode`. Probed on Linux |
|
||||
| `terminal_mode::make_raw(&mut this): void` | Raw: no echo, no lines, no signals from keys, and every byte as it comes, with virtual terminal processing and input on Windows. Probed on Linux, as `cfmakeraw` sets it |
|
||||
| `take_handling(which: signal): handling`, `give_handling(which: signal, back: handling): i32` | What the program does with a signal, taken so that a library can handle it for a while and give it back: the default, ignoring it, watching for it, or its handler, moved out |
|
||||
| `restore_at_stop(...)`, `forget_at_stop()` | Decision 5's record, which the runtime and the VM keep |
|
||||
|
||||
- **`poll`'s timeout is there already,** in milliseconds, so `next` turns its
|
||||
`duration` into them. The plan had it gain one in nanoseconds.
|
||||
- **On Linux:** `ioctl` is 16 on x86-64. Its requests are `TCGETS` 0x5401, `TCSETS`
|
||||
0x5402 and `TIOCGWINSZ` 0x5413. They differ on a few processors, so they go in
|
||||
`linux_x86_64.sakura`, beside the other calls' numbers.
|
||||
- **`io_error::not_a_terminal`** is what `error_of` gives for -25.
|
||||
- **On Windows (decision 11):** `SetConsoleMode`, with
|
||||
`ENABLE_VIRTUAL_TERMINAL_PROCESSING` on the output, and for raw mode
|
||||
`ENABLE_VIRTUAL_TERMINAL_INPUT` on the input, without line input, echo or processed
|
||||
input. Windows sends no `resized`, so the terminal reads the size again each time
|
||||
`next` returns, or reads `ReadConsoleInput`'s window events. `poll` peeks pipes, so
|
||||
waiting for a console's input needs a wait on the console's own handle. None of it
|
||||
is probed.
|
||||
|
||||
### `std` gains nothing now
|
||||
|
||||
- **`decode_utf8` isn't needed:** `strview::chars()` decodes, and the canvas writes
|
||||
each character's UTF-8 into its cell itself.
|
||||
- The input decoder keeps a sequence cut short at the end of a read for the next one.
|
||||
It tells one from a wrong sequence by its first byte, which neither `chars` nor
|
||||
`serial::utf8_length` does.
|
||||
|
||||
### `std::term` (decision 1)
|
||||
|
||||
```
|
||||
std/term/
|
||||
style.sakura color, ansi, effect, style
|
||||
abilities.sakura color_depth, abilities, abilities_of
|
||||
painter.sakura painter, standard, output, error_output, paint, and the cursor and screen
|
||||
boxes.sakura line_style, and the glyph each meeting of lines takes
|
||||
widths.sakura width_of, over a table tools/widths.sakura writes
|
||||
canvas.sakura size, rect, cell, canvas
|
||||
input.sakura event, key, key_code, modifier, mouse, and the decoder
|
||||
terminal.sakura terminal, settings, show, next, suspend
|
||||
```
|
||||
|
||||
**Styles:**
|
||||
|
||||
```sakura
|
||||
#! One of the sixteen colors every color terminal has, which its theme decides.
|
||||
pub enum ansi: u8 {
|
||||
black, red, green, yellow, blue, magenta, cyan, white,
|
||||
bright_black, bright_red, bright_green, bright_yellow,
|
||||
bright_blue, bright_magenta, bright_cyan, bright_white,
|
||||
}
|
||||
|
||||
#! A color of text, or of what's behind it.
|
||||
pub union color : equatable {
|
||||
pub var ansi: ansi; #! One of the sixteen.
|
||||
pub var indexed: u8; #! One of 256: the sixteen, a 6×6×6 cube, and 24 grays.
|
||||
pub var rgb: u8[3]; #! Any, as red, green and blue.
|
||||
}
|
||||
|
||||
pub val color::red := color{ ansi = ansi::red }; # and the other fifteen
|
||||
pub def color::hex(value: u32): color; # color::hex(0xFF8800)
|
||||
|
||||
#! What text looks like besides its colors.
|
||||
pub enum effect: u32 {
|
||||
bold = 1, dim = 2, italic = 4, underline = 8,
|
||||
blink = 16, reverse = 32, hidden = 64, strike = 128,
|
||||
}
|
||||
|
||||
#! How text is drawn. A color that's `nothing` is the terminal's own.
|
||||
pub struct style : equatable {
|
||||
pub var fg: maybe<color>;
|
||||
pub var bg: maybe<color>;
|
||||
pub var effects: flags32<effect>;
|
||||
}
|
||||
```
|
||||
|
||||
**What a stream shows (decision 3):**
|
||||
|
||||
```sakura
|
||||
#! How many colors a stream shows.
|
||||
pub enum color_depth: u8 { none, basic, indexed, full }
|
||||
|
||||
#! What a stream shows of what a painter writes.
|
||||
pub struct abilities : equatable {
|
||||
pub var colors: color_depth; #! How many colors, if any.
|
||||
pub var controls: bool; #! Whether cursor moves, clearing and modes are written.
|
||||
}
|
||||
|
||||
#! What a handle shows, from whether it's a terminal and from the environment.
|
||||
pub def abilities_of(handle: sys::fd, environment: span<strview> = sys::environment()): abilities;
|
||||
```
|
||||
|
||||
**Painting, in ordinary output (decision 4):**
|
||||
|
||||
```sakura
|
||||
#! Writes text in styles to any stream, and moves the cursor, writing only what the
|
||||
#! stream shows. Colors are brought down to its depth, and where it shows none, only
|
||||
#! the text is written. A style's sequence is written only where the style changes.
|
||||
pub struct painter<W> : owning, writable, flushable where W: writable { ... }
|
||||
|
||||
#! The standard output or error, written through the writer `std::io` shares for it.
|
||||
pub struct standard : writable { ... }
|
||||
|
||||
pub def painter_of<W>(sink: W, shows: abilities): painter<W>;
|
||||
pub def output(): &mut painter<standard>; # the standard output's
|
||||
pub def error_output(): &mut painter<standard>; # the standard error's
|
||||
pub val painter<W>::shows: abilities;
|
||||
|
||||
pub def painter<W>::write(&mut this, text: strview): result<void, io_error>; # in the style set
|
||||
pub def painter<W>::write(&mut this, text: strview, with: style): result<void, io_error>; # in a style, then back
|
||||
pub def painter<W>::set(&mut this, with: style): void;
|
||||
pub def painter<W>::reset(&mut this): void;
|
||||
|
||||
#! Text in a style, as a string to interpolate, for a stream showing what `shows` says.
|
||||
pub def paint(text: strview, with: style, shows: abilities = output().shows): string;
|
||||
```
|
||||
|
||||
The cursor and the screen, each written only where `controls` holds:
|
||||
|
||||
| Method | Writes |
|
||||
|---|---|
|
||||
| `move_to(column: i32, row: i32)` | `CSI row;col H`, from 0 here and from 1 there (decision 10) |
|
||||
| `move_by(columns: i32, rows: i32)` | `CSI n A`, `B`, `C` and `D` |
|
||||
| `to_column(column: i32)` | `CSI n G` |
|
||||
| `save_cursor()`, `restore_cursor()` | `ESC 7` and `ESC 8`, which more terminals take than `CSI s` |
|
||||
| `show_cursor(shown: bool)` | `CSI ?25h` or `l` |
|
||||
| `cursor_shape(shape: cursor_shape)` | `CSI n SP q`: block, underline or bar, blinking or steady |
|
||||
| `clear(what: clearing)` | The screen, its rest, the line or its rest: `CSI 2J`, `CSI J`, `CSI 2K` or `CSI K` |
|
||||
| `scroll_region(top: i32, bottom: i32)`, `scroll(rows: i32)` | `CSI t;b r`, and `CSI n S` or `T` |
|
||||
| `title(text: strview)` | `OSC 2;text BEL` |
|
||||
|
||||
**The terminal:**
|
||||
|
||||
```sakura
|
||||
#! What a terminal is set to while it's open.
|
||||
pub struct settings {
|
||||
pub var alternate := true; #! Draw on the alternate screen, leaving the shell's as it was.
|
||||
pub var mouse := mouse_mode::none; #! none, buttons, drags, or every move.
|
||||
pub var paste := true; #! Report pasted text as one event, not as keys.
|
||||
pub var focus := false; #! Report the window gaining and losing focus.
|
||||
pub var escape := milliseconds(50); #! How long a lone Escape waits for a sequence.
|
||||
}
|
||||
|
||||
#! The terminal the program runs in, in raw mode. Closing it puts back everything it
|
||||
#! changed.
|
||||
pub struct terminal : owning { ... }
|
||||
|
||||
pub def terminal::open(with: settings = settings{}): result<terminal, io_error>; # not_a_terminal through a pipe
|
||||
pub val terminal::size: size;
|
||||
pub val terminal::out: &mut painter<...>; # for drawing without a canvas
|
||||
pub def terminal::show(&mut this, frame: &canvas): result<void, io_error>;
|
||||
pub def terminal::next(&mut this, wait: maybe<duration> = nothing{}): result<maybe<event>, io_error>;
|
||||
pub def terminal::suspend(&mut this): void; # for Ctrl-Z: put back, stop, and on resuming, take again
|
||||
```
|
||||
|
||||
**Input (decision 6):**
|
||||
|
||||
```sakura
|
||||
pub union event {
|
||||
pub var key: key; #! A key, with the modifiers held.
|
||||
pub var mouse: mouse; #! A button pressed or let go, the wheel, or a move.
|
||||
pub var paste: strview; #! Text pasted, good until the next event is read.
|
||||
pub var resized: size; #! The terminal's new size.
|
||||
pub var focused: bool; #! Whether the window gained focus or lost it.
|
||||
}
|
||||
|
||||
pub enum modifier: u32 { shift = 1, alt = 2, control = 4 }
|
||||
|
||||
pub struct key : equatable {
|
||||
pub var code: key_code; #! Which key.
|
||||
pub var character: u32; #! The character, where `code` is `character`.
|
||||
pub var modifiers: flags32<modifier>;
|
||||
}
|
||||
|
||||
pub enum key_code: u8 {
|
||||
character, enter, tab, backspace, escape,
|
||||
up, down, left, right, home, end, page_up, page_down, insert, delete,
|
||||
f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12,
|
||||
}
|
||||
|
||||
pub struct mouse : equatable {
|
||||
pub var action: mouse_action; #! press, release, drag, move, wheel_up or wheel_down.
|
||||
pub var button: mouse_button; #! left, middle, right, or none.
|
||||
pub var column: i32;
|
||||
pub var row: i32;
|
||||
pub var modifiers: flags32<modifier>;
|
||||
}
|
||||
```
|
||||
|
||||
**The canvas (decisions 7 to 9):**
|
||||
|
||||
```sakura
|
||||
pub struct size : equatable { pub var columns: i32; pub var rows: i32; }
|
||||
pub struct position : equatable { pub var column: i32; pub var row: i32; }
|
||||
pub struct rect : equatable { pub var left: i32; pub var top: i32; pub var width: i32; pub var height: i32; }
|
||||
|
||||
#! Light, heavy or double strokes, or light ones with rounded corners.
|
||||
pub enum line_style: u8 { light, heavy, double, rounded }
|
||||
|
||||
#! A grid of cells to draw a frame on.
|
||||
pub struct canvas : owning { ... }
|
||||
|
||||
pub def canvas::new(of: size): canvas;
|
||||
pub val canvas::size: size;
|
||||
pub def canvas::resize(&mut this, to: size): void;
|
||||
pub def canvas::clear(&mut this, with: style = style{}): void;
|
||||
pub def canvas::put(&mut this, column: i32, row: i32, text: strview, with: style = style{}): i32; # columns used
|
||||
pub def canvas::fill(&mut this, area: rect, character: u32, with: style = style{}): void;
|
||||
pub def canvas::draw_box(&mut this, area: rect, lines: line_style = line_style::light, with: style = style{}): void;
|
||||
pub def canvas::draw_across(&mut this, row: i32, from: i32, to: i32, lines: line_style = line_style::light, with: style = style{}): void;
|
||||
pub def canvas::draw_down(&mut this, column: i32, from: i32, to: i32, lines: line_style = line_style::light, with: style = style{}): void;
|
||||
pub var canvas::cursor: maybe<position>; # where the cursor shows after the frame, or hidden
|
||||
pub def canvas::write_to<W>(&this, into: &mut painter<W>): result<void, io_error>; # as lines, in ordinary output
|
||||
|
||||
pub def width_of(character: u32): u8; # 0, 1 or 2
|
||||
pub def width_of(text: strview): u64;
|
||||
```
|
||||
|
||||
## Using it
|
||||
|
||||
**Color in ordinary output,** which is plain text through a pipe:
|
||||
|
||||
```sakura
|
||||
import std;
|
||||
import std::io;
|
||||
import std::term;
|
||||
|
||||
def main(args: span<strview>): void {
|
||||
val out := term::output();
|
||||
val warn := style{ fg = color::yellow, effects = effect::bold };
|
||||
_ = out.write("note: ");
|
||||
_ = out.write("`x` is never read", warn);
|
||||
_ = out.write("\n");
|
||||
|
||||
println($"{term::paint("ok", style{ fg = color::green })} 12 tests");
|
||||
}
|
||||
```
|
||||
|
||||
**A line of progress,** written over itself:
|
||||
|
||||
```sakura
|
||||
val out := term::output();
|
||||
for i in 0u..total {
|
||||
out.to_column(0);
|
||||
out.clear(clearing::line);
|
||||
_ = out.write($"building {i + 1} of {total}");
|
||||
_ = out.flush();
|
||||
build(i);
|
||||
}
|
||||
_ = out.write("\n");
|
||||
```
|
||||
|
||||
**A box in ordinary output:**
|
||||
|
||||
```sakura
|
||||
var table := canvas::new(size{ columns = 32, rows = 4 });
|
||||
table.draw_box(rect{ left = 0, top = 0, width = 32, height = 4 });
|
||||
table.draw_down(16, 0, 3);
|
||||
table.put(2, 1, "files");
|
||||
table.put(18, 1, "1,204");
|
||||
table.put(2, 2, "notes");
|
||||
table.put(18, 2, "0", style{ fg = color::green });
|
||||
_ = table.write_to(term::output());
|
||||
```
|
||||
|
||||
```
|
||||
┌───────────────┬──────────────┐
|
||||
│ files │ 1,204 │
|
||||
│ notes │ 0 │
|
||||
└───────────────┴──────────────┘
|
||||
```
|
||||
|
||||
**A full-screen program:**
|
||||
|
||||
```sakura
|
||||
import std;
|
||||
import std::io;
|
||||
import std::term;
|
||||
import std::time;
|
||||
|
||||
def main(args: span<strview>): void {
|
||||
val names: strview[3] = ["build", "test", "clean"];
|
||||
var tty := terminal::open() else (e) { println("not a terminal"); return; };
|
||||
var frame := canvas::new(tty.size);
|
||||
var chosen := 0u;
|
||||
|
||||
while true {
|
||||
frame.clear();
|
||||
frame.draw_box(rect{ left = 0, top = 0, width = frame.size.columns, height = frame.size.rows }, line_style::rounded);
|
||||
frame.put(2, 0, " Pick one ", style{ effects = effect::bold });
|
||||
for i, name in names {
|
||||
frame.put(2, 1 + i as i32, name, i == chosen ? style{ effects = effect::reverse } : style{});
|
||||
}
|
||||
_ = tty.show(&frame);
|
||||
|
||||
val came := tty.next(milliseconds(250)) else (e) { return; };
|
||||
val ev := came else { continue; }; # nothing came within the wait
|
||||
if ev is resized(to) {
|
||||
frame.resize(to);
|
||||
} else if ev is key(k) {
|
||||
val typed := k.code == key_code::character;
|
||||
if k.code == key_code::up && chosen > 0 { chosen--; }
|
||||
if k.code == key_code::down && chosen + 1 < names.length { chosen++; }
|
||||
if k.code == key_code::enter || (typed && k.character == 'q') { return; }
|
||||
if typed && k.character == 'z' && k.modifiers.get(modifier::control) { tty.suspend(); }
|
||||
}
|
||||
}
|
||||
} # tty closes: the shell's screen, its mode and its cursor come back
|
||||
```
|
||||
|
||||
## How each part works
|
||||
|
||||
- **What it knows of terminals (decision 2):** the sequences of ECMA-48, and xterm's
|
||||
private modes, which the terminals in use today share. These include xterm, VTE's
|
||||
(GNOME Terminal), Konsole, kitty, Alacritty, WezTerm, foot, iTerm2, Windows
|
||||
Terminal, tmux and screen. Synchronized output (`CSI ?2026h`) is written around
|
||||
every frame, and terminals that don't know it ignore it.
|
||||
- **Detecting what a stream shows (decision 3):**
|
||||
- **Controls** are written where the handle is a terminal and `TERM` isn't `dumb`.
|
||||
- **Colors,** the first of these that holds:
|
||||
1. `NO_COLOR` set and not empty gives `none`. no-color.org allows keeping bold
|
||||
and the rest, but `none` drops them too, so it always means plain text;
|
||||
2. a handle that isn't a terminal, or `TERM=dumb`, gives `none`, unless
|
||||
`FORCE_COLOR` is set and not empty;
|
||||
3. `COLORTERM` of `truecolor` or `24bit` gives `full`;
|
||||
4. a `TERM` ending in `256color` gives `indexed`;
|
||||
5. on Windows, a console whose virtual terminal processing is on gives `full`;
|
||||
6. anything else gives `basic`.
|
||||
- It reads only the environment it's given, so tests pass their own.
|
||||
- **Bringing colors down:**
|
||||
- 24-bit becomes the nearest of the 6×6×6 cube and the 24 grays, as xterm's
|
||||
palette sets them;
|
||||
- either of those becomes the nearest of the sixteen, by xterm's default colors;
|
||||
- nothing is written at `none`.
|
||||
- **Writing a style:**
|
||||
- Where the style only gains something, only that is written.
|
||||
- Where anything turns off, `CSI 0m` is written, then the whole style. Bold and dim
|
||||
share their "off", so the shorter way isn't always right.
|
||||
- A painter remembers the style it last wrote, so a run of text in one style
|
||||
writes it once.
|
||||
- **Raw mode** is `cfmakeraw`'s, but for output:
|
||||
- a `\n` still begins a line, so the program's own `println` still works;
|
||||
- the canvas moves the cursor itself and never writes one.
|
||||
- **Reading input:**
|
||||
- The terminal polls its input with the wait given, reads what has come into a
|
||||
buffer, and decodes one event at a time.
|
||||
- **Keys** come as xterm writes them:
|
||||
- `CSI A` to `D` and `SS3 A` to `D` for the arrows;
|
||||
- `CSI H` and `CSI F` for Home and End, and `CSI n ~` for them too, and for
|
||||
Insert, Delete, PageUp, PageDown and F5 to F12;
|
||||
- `SS3 P` to `S` for F1 to F4;
|
||||
- `CSI 1;m X` with the modifiers, as `m - 1` holds Shift 1, Alt 2 and Ctrl 4;
|
||||
- `CSI Z` for Shift-Tab;
|
||||
- ESC before a key for Alt;
|
||||
- bytes 1 to 26 for Ctrl with a letter, but 9 is Tab and 13 is Enter;
|
||||
- 127 and 8 for Backspace, as terminals differ, so Ctrl-H reads as Backspace;
|
||||
- UTF-8 for any other character.
|
||||
- **A lone Escape** is told from the start of a sequence by waiting `escape` for
|
||||
more: 50 ms by default, as Neovim waits. The probe used 30.
|
||||
- **The mouse:** `mouse_mode`'s buttons, drags and moves turn on xterm's modes 1000,
|
||||
1002 and 1003, always with 1006. That's SGR's encoding (`CSI < b;x;y M` or `m`),
|
||||
whose places have no limit, unlike the original encoding's 223 columns.
|
||||
- **Pasting** comes between `CSI 200~` and `CSI 201~`, as one event.
|
||||
- **Focus** comes as `CSI I` and `CSI O`.
|
||||
- A sequence it doesn't know is passed over whole, and bytes that aren't UTF-8
|
||||
become `U+FFFD`.
|
||||
- **Resizing:**
|
||||
- While open, the terminal handles `resized` with a function that notes it in a
|
||||
variable of `std::term`. A closure won't do: the terminal moves once it's opened,
|
||||
and a closure would refer to where it was.
|
||||
- A wait the signal interrupts ends with -4, and `next` then reads the size again
|
||||
and gives `event::resized`. Watching for the signal instead wouldn't end the wait.
|
||||
- Handlers run only in the thread the program began with, so `next` called in
|
||||
another thread sees a resize only once its wait ends.
|
||||
- The program resizes its canvas, and the next `show` writes every cell.
|
||||
- On Windows, where no signal comes, `next` reads the size each time it returns
|
||||
(decision 11).
|
||||
- **Suspending:**
|
||||
- `suspend` puts the terminal back, as closing it would, then raises `suspend`, so
|
||||
the program stops as Ctrl-Z would stop it. Probed.
|
||||
- When the shell resumes it, the terminal is taken again, and `next` gives
|
||||
`event::resized` with the size, which may have changed meanwhile. That makes the
|
||||
next frame whole.
|
||||
- Windows has no such stopping, and `raise(suspend)` gives `unsupported` there, so
|
||||
`suspend` does nothing.
|
||||
- **Showing a frame:**
|
||||
- The terminal keeps the last frame it wrote, and compares the new one with it cell
|
||||
by cell.
|
||||
- For each run of changed cells, it moves the cursor only where the cursor isn't
|
||||
already, writes the style only where it changes, then writes the text.
|
||||
- All of it goes into one `string`, kept between frames, which is written in one
|
||||
write inside synchronized output, so a frame never shows half drawn.
|
||||
- The first frame, and the first after a resize, are written whole.
|
||||
- **Cells:**
|
||||
- A cell holds the UTF-8 of one character and of the marks joining it, up to 16
|
||||
bytes, with its style and its lines.
|
||||
- A character two columns wide takes the next cell too, which is marked as its
|
||||
second half. Drawing over either half clears the other.
|
||||
- A cluster longer than 16 bytes, as some emoji sequences are, keeps its first
|
||||
character.
|
||||
- A tab moves to the next column that's a multiple of eight. Other control
|
||||
characters are drawn as `�`.
|
||||
- **Width (decision 7):**
|
||||
- `width_of` follows Unicode 16. A character is two columns where its East Asian
|
||||
width is `W` or `F`. It's none where it's a mark (`Mn`, `Me`), a format
|
||||
character (`Cf`) other than the soft hyphen, a Hangul vowel or final
|
||||
(U+1160 to U+11FF), or U+200B. Any other character is one column.
|
||||
- The table is 369 ranges of none and 123 of two, about 4 KB.
|
||||
- `tools/widths.sakura` writes it into `std/term/widths.sakura`, from Unicode's
|
||||
`EastAsianWidth.txt` and `DerivedGeneralCategory.txt`, when Unicode changes.
|
||||
- `width_of(text)` passes over printable ASCII, a column a byte, eight bytes at a
|
||||
time with `std::swar`, and looks up only the rest.
|
||||
- **Lines that meet (decision 9):**
|
||||
- A cell holds, for each of its four sides, whether a line leaves by it, and how
|
||||
heavy: light, heavy or double. That's two bits a side, and a ninth bit for a
|
||||
rounded corner.
|
||||
- Drawing a line adds to what the cell holds, and the glyph is looked up from all
|
||||
four sides. So a line drawn down through a box's top edge gives `┬`, and two
|
||||
boxes sharing an edge give `├`, `┤` and `┼` where they meet.
|
||||
- A line's end leaves its last cell by one side only, so a line drawn down from a
|
||||
box's top edge meets it as `┬`, not `┼`. A cell with a line leaving by one side
|
||||
only is still drawn as a whole `─` or `│`, so a line standing alone looks whole.
|
||||
- Every one of the 80 meetings of light and heavy strokes has a glyph in
|
||||
U+2500–U+257F.
|
||||
- Double strokes have glyphs only where the two sides along a line agree. Elsewhere,
|
||||
and where double meets heavy, the double sides are drawn light.
|
||||
- A rounded corner becomes square once a third line joins it.
|
||||
- Text put on a cell clears its lines.
|
||||
- **Ordinary output:** `canvas::write_to` writes each row's cells with their styles,
|
||||
then a line break, with no cursor moves. So it works through a pipe, where it
|
||||
writes only the text.
|
||||
- **When the program stops some other way (decision 5):**
|
||||
- Opening the terminal gives the runtime one record: the handle, the mode to put
|
||||
back, the text that undoes the screen, and the process that made it.
|
||||
- `exit` and a fault from any thread, `abort` and a failed contract put them back
|
||||
before anything else, with two system calls. A fault's report then shows on the
|
||||
shell's screen, not on the alternate one about to vanish.
|
||||
- Closing the terminal forgets the record. A copy made by `fork` leaves it alone,
|
||||
since the process isn't the one that made it.
|
||||
- The terminal also handles `terminate` and `hangup` while open, where the program
|
||||
doesn't, putting things back and then stopping as the signal would have.
|
||||
|
||||
## Testing
|
||||
|
||||
- **`test/std/term.sakura`, written with `std::testing`,** covers:
|
||||
- **detection,** from environments the tests give: a pipe, `TERM=dumb`, `NO_COLOR`,
|
||||
`FORCE_COLOR`, `COLORTERM` and `256color`;
|
||||
- **painting:** every sequence, written to a `string` and compared exactly, at each
|
||||
depth. Also styles that only gain, styles that lose something, and nothing at all
|
||||
where the stream shows nothing;
|
||||
- **bringing colors down,** against a table, with the cube's and the grays' edges;
|
||||
- **decoding input,** from bytes the tests give, not from a terminal:
|
||||
- every key, with and without modifiers;
|
||||
- UTF-8 split across reads;
|
||||
- mouse reports, and pasting;
|
||||
- sequences it doesn't know, and bytes that aren't UTF-8;
|
||||
- **width,** of ASCII, `é` both composed and decomposed, `中`, `😀`, U+200B and
|
||||
U+0301;
|
||||
- **boxes:** each meeting of strokes, boxes sharing edges, a line through a box,
|
||||
double meeting light and heavy, and rounded corners joined;
|
||||
- **the canvas:** text clipped at its edges, wide characters at the last column, and
|
||||
drawing over half of one;
|
||||
- **showing frames:** a small terminal emulator in the test reads what `show` wrote,
|
||||
handling cursor moves, styles and text. The tests check its screen against the
|
||||
canvas, after a first frame, a changed one, a resize, and wide characters;
|
||||
- **a real terminal,** on Linux: the tests open a pseudo-terminal through
|
||||
`/dev/ptmx`, as the probe's driver did through Python, and run the terminal on it:
|
||||
- raw mode taken and put back;
|
||||
- the size, and a resize, from a `resized` the test raises;
|
||||
- keys written to it and read back as events;
|
||||
- a forked copy that opens the terminal and then faults, after which the mode is
|
||||
the one it found (decision 5).
|
||||
- **A program of the corpus** writes a box and a colored table to its output, a pipe,
|
||||
where it's plain text.
|
||||
- **Where they run:** in the VM, under `run --checks`, and as executables at `-O0` and
|
||||
`-O2`. The analyzer must check them with 0 notes, and std must still check
|
||||
for `--target windows-x86_64`. The time to check a one-line program is measured
|
||||
before and after.
|
||||
|
||||
## Phases
|
||||
|
||||
About 130 lines of `std::sys` for Linux and 80 for Windows (decision 11), 2,300 of
|
||||
`std::term` (150 of them written by the tool), 150 for the tool, and 1,000 of tests.
|
||||
Decision 5's record adds two intrinsics to the compiler, and a few lines to the
|
||||
runtime's ways of stopping.
|
||||
|
||||
1. **`std::sys`:** `is_terminal`, `terminal_size`, the modes, `take_handling` and
|
||||
`give_handling`, and `io_error::not_a_terminal`, on Linux and Windows. The logging
|
||||
plan can then color its levels.
|
||||
2. **Styles and painting:** `style`, `abilities_of`, `painter`, `paint`, and the cursor
|
||||
and screen.
|
||||
3. **Width:** the tool and the table.
|
||||
4. **The canvas and boxes,** with `write_to`.
|
||||
5. **The terminal:** raw mode, input, resizing, suspending, and `show`.
|
||||
6. **Putting it back on every way out (decision 5),** in the compiler and the runtime.
|
||||
7. **A "Terminals" section in the README.**
|
||||
|
||||
## Found along the way
|
||||
|
||||
- **`sys::poll` couldn't time out:** settled. It has taken a wait in milliseconds
|
||||
since 2026-10-19.
|
||||
- **`io_error` has nothing for `ENOTTY`,** which becomes `other`.
|
||||
- **Nothing runs when a program stops** but `close`. A module's variable is never
|
||||
closed, so a terminal kept in one would be left raw even when `main` returns.
|
||||
- **A signal's handler can't be read back,** so a library that handles a signal for a
|
||||
while can't give the program's own back. A handler is a `function` now, moved and
|
||||
never copied, so it can't be read and left in place either. This plan adds
|
||||
`sys::take_handling` and `sys::give_handling`, where it had `sys::handler_of`.
|
||||
- **Interpolation can't call a type's method** to format it. A trait for that, as
|
||||
`describable`, would let `$"{warn}"` write a style's sequence. It would be a change
|
||||
to the language, so this plan works around it with `paint`.
|
||||
- **`attribute` is taken** (2026-10-20). It's std's trait for the structs written after
|
||||
`@`, so a program importing `std::term` had to write `term::attribute::bold`. The enum
|
||||
is `effect` now, and a style's field `effects`.
|
||||
- **A module's variable can't hold a reference,** since it needs a zero value. So the
|
||||
shared painters paint `term::standard`, not `&mut writer<console>`.
|
||||
- **Union fields need `pub`** for a program to test them, as `ev is key(k)`. The
|
||||
sketches had left it out.
|
||||
- **Windows' `poll` sees a console as always ready,** since it peeks pipes, and a
|
||||
console isn't one.
|
||||
- **A signal watched for doesn't end a wait,** so the terminal handles `resized`
|
||||
rather than watching for it.
|
||||
|
||||
## Later, where wanted
|
||||
|
||||
- **Inline frames:** a canvas shown below the shell's prompt, not on the alternate
|
||||
screen, as a picker or a progress display does. It needs the cursor's position,
|
||||
read through `CSI 6n`, whose answer looks like F3 with modifiers, and is told apart
|
||||
only by waiting for it.
|
||||
- **Widgets:**
|
||||
- lists, tables and text fields;
|
||||
- scrolling views;
|
||||
- layout that splits a rect by constraints;
|
||||
- a line editor with history, as readline is.
|
||||
- **The kitty keyboard protocol,** for keys xterm's encoding can't tell apart, as
|
||||
Ctrl-I from Tab, and for keys let go.
|
||||
- **Hyperlinks** through `OSC 8`.
|
||||
- **The terminal's colors,** read through `OSC 10` and `11`, to tell a light theme from
|
||||
a dark one.
|
||||
- **Grapheme clusters,** by Unicode's segmentation rules, once terminals agree on how
|
||||
wide they are.
|
||||
- **ASCII boxes,** for terminals without UTF-8. Also the Linux console's font, which
|
||||
lacks heavy and rounded strokes.
|
||||
- **Images,** through sixel or kitty's graphics.
|
||||
- **terminfo,** for a `TERM` the built-in sequences don't suit.
|
||||
- **The terminal's input on Windows,** where decision 11 leaves it for later.
|
||||
- **Events from a thread:** a thread reading the terminal and sending its events
|
||||
through a `thread::channel`, so a program waits on its own work and on input at
|
||||
once. Resizes would still be noted in the thread the program began with.
|
||||
|
||||
## Decisions for you
|
||||
|
||||
1. **Where it lives:**
|
||||
- **(a) `std::term`, in `std/term/` (recommended).** One import gives a program all
|
||||
of it. Every program is checked with all of std anyway, so splitting it saves
|
||||
nothing.
|
||||
- **(b) `std::term` for styles, painting and the terminal, and `std::tui` for the
|
||||
canvas and boxes.** The names say more, at the cost of two imports for a
|
||||
full-screen program.
|
||||
- **(c) Styles, painting and the terminal in std, and the canvas, boxes and widths
|
||||
left to a library outside it.** Every program's check would pay for about 850
|
||||
fewer lines: about 2 ms less, at the clock measured above.
|
||||
2. **What it knows of terminals:**
|
||||
- **(a) xterm's sequences, built in (recommended).** It's what the terminals in use
|
||||
share, and what crossterm and termenv do.
|
||||
- **(b) The terminfo database,** as curses reads it. Its entries lag what terminals
|
||||
do, as with 24-bit color, and its files are a compiled format to read.
|
||||
- **(c) (a), with terminfo for a `TERM` it doesn't know.**
|
||||
3. **How color is decided:**
|
||||
- **(a) From the handle and the environment, as "How each part works" orders it,
|
||||
with colors brought down to what's found (recommended).**
|
||||
- **(b) The program says,** and std never looks. Every program then repeats the
|
||||
same checks, or writes color into files.
|
||||
- **(c) Ask the terminal,** through its replies to queries. It's exact, but slow
|
||||
over a network, and impossible through a pipe.
|
||||
4. **How styled text is written:**
|
||||
- **(a) Through a painter over any stream, with `paint` for interpolating
|
||||
(recommended).** A painter knows what its stream shows, and writes a style only
|
||||
where it changes.
|
||||
- **(b) Only as text to interpolate,** as `$"{term::red}x{term::reset}"`. It's the
|
||||
easiest to write, but colors reach files and pipes unless each program checks,
|
||||
and nothing brings them down.
|
||||
- **(c) Only through a `terminal`.** Ordinary output, such as the logging plan's,
|
||||
couldn't be colored.
|
||||
5. **When the program stops without closing the terminal:**
|
||||
- **(a) The runtime and the VM put it back, from a record std keeps
|
||||
(recommended).** This covers `exit`, faults, `abort`, failed contracts, and a
|
||||
terminal kept in a module's variable. It adds two intrinsics to the compiler.
|
||||
- **(b) Only `close`.** A fault leaves the shell in raw mode, on the alternate
|
||||
screen, with the mouse reported, until the user types `reset`.
|
||||
- **(c) (b), with `terminate` and `hangup` handled while the terminal is open.**
|
||||
That covers being killed politely, but not faults.
|
||||
6. **Input:**
|
||||
- **(a) Keys, text, the mouse, pasting, focus and resizing, read with a timeout
|
||||
(recommended).**
|
||||
- **(b) Keys and resizing only,** with the mouse and pasting later.
|
||||
- **(c) None:** output only. Full-screen programs would read bytes themselves.
|
||||
7. **How wide text is:**
|
||||
- **(a) A table of each character's width, from Unicode 16 (recommended).** It's
|
||||
what `wcwidth` does and what terminals do, for about 4 KB.
|
||||
- **(b) Every character is one column.** No table is needed, but Chinese,
|
||||
Japanese, Korean and emoji break the layout.
|
||||
- **(c) Grapheme clusters,** with Unicode's segmentation rules too. It's more
|
||||
exact where terminals agree, which they don't yet for emoji sequences, and it
|
||||
needs a second, larger table.
|
||||
8. **What draws the screen:**
|
||||
- **(a) A canvas the program draws whole each frame, of which std writes only the
|
||||
changes (recommended).** It's as ratatui and tcell work. The program keeps its
|
||||
own state, and draws from it.
|
||||
- **(b) Widgets std keeps,** which the program changes, and which redraw what they
|
||||
cover, as curses' windows do. It's more API, and state in two places.
|
||||
- **(c) No canvas:** programs draw with the painter's cursor moves. There's less to
|
||||
build, but every program works out what changed itself, and boxes can't join.
|
||||
9. **Boxes that meet:**
|
||||
- **(a) Joined, from the lines each cell holds (recommended).**
|
||||
- **(b) Each box writes its own glyphs, and the last drawn wins.** It's simpler,
|
||||
but boxes sharing an edge show broken corners.
|
||||
10. **Places on the screen:**
|
||||
- **(a) From 0, column first, as `rect` is (recommended).** It's as drawing in
|
||||
most libraries is, and the sequences' rows and columns from 1 stay inside std.
|
||||
- **(b) From 1, row first, as the sequences number them.** It matches what a
|
||||
terminal's documentation says, but not `rect`, `size` or the mouse's columns.
|
||||
11. **Windows,** which std has supported since 2026-10-19. Whatever is chosen, each
|
||||
operation `std::sys` gains exists there too, since std is checked whole for an
|
||||
executable for Windows, and one missing there is an error in every such check
|
||||
(probed):
|
||||
- **(a) Output now, input later (recommended).** `is_terminal`, the size, and
|
||||
virtual terminal processing, so painters and `canvas::write_to` color a console
|
||||
as they do a terminal, and the logging plan's levels with them. `terminal::open`
|
||||
gives `io_error::unsupported` there until raw input, a wait on the console, and
|
||||
resizing are built. About 80 lines.
|
||||
- **(b) All of it now,** with raw input through `ENABLE_VIRTUAL_TERMINAL_INPUT`, a
|
||||
wait on the console's handle, and resizes found by reading the size at each
|
||||
`next`. It's more code, and none of it can be probed here.
|
||||
- **(c) Linux only.** Each new operation gives `unsupported` on Windows, and
|
||||
`is_terminal` false, so nothing is colored there.
|
||||
Reference in new issue
Block a user