Initial Commit
This commit is contained in:
706 files changed
+135430
No files matched your search
@@ -0,0 +1,663 @@
|
||||
# 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 compilers 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.
|
||||
|
||||
**Built in the rebuild alone** ([roadmap.md](roadmap.md), decision 1). Where this plan
|
||||
says both compilers, C's half is left out. What was measured in C stays as measured.
|
||||
|
||||
**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 rebuild,** 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 rebuild's own compiler and by the C compiler, and both gave the
|
||||
same results. Times are the rebuild's where only one is given. 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 rebuild'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 | Rebuild | C |
|
||||
|---|---|---|
|
||||
| `sort`, by `<` | 0.19 s | 0.26 s |
|
||||
| `sort_by`, a named function | 0.26 s | 0.31 s |
|
||||
| `sort_by`, a lambda | 0.25 s | 0.31 s |
|
||||
| 1,000,000 structs by a field, `sort_by` with a lambda | 0.19 s | 0.31 s |
|
||||
| The introsort above, by `<`, written again beside it | 0.13 s | 0.17 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 | Rebuild | C |
|
||||
|---|---|---|
|
||||
| `<`, through a functor, `by_order<T>` | 0.14 s | 0.18 s |
|
||||
| A functor comparing a key of its own | 0.15 s | 0.17 s |
|
||||
| A function value | 0.22 s | 0.24 s |
|
||||
| A function value held in a struct, as `comparer<T>` held it | 0.23 s | 0.24 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 | Rebuild | C |
|
||||
|---|---|---|
|
||||
| A loop over indexes, written out | 0.12 s | 0.24 s |
|
||||
| `span::contains` | 0.19 s | 0.24 s |
|
||||
| `any` of a span, generic over its test, given a functor holding the value | 0.19 s | 0.27 s |
|
||||
| `for &each in v`, written out | 0.26 s | 0.42 s |
|
||||
| `iter().any`, given such a functor | 0.26 s | 0.37 s |
|
||||
| `any` of a span, given a lambda referring to the value | 0.44 s | 0.51 s |
|
||||
| `iter().any`, given that lambda | 0.65 s | 1.45 s |
|
||||
|
||||
- Memory grew in none.
|
||||
- On 2026-10-09 such a lambda took 3.23 s (C 4.09 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 in the
|
||||
rebuild, which calls it directly and inlines it, and 0.49 s in C, which calls it
|
||||
through the value.
|
||||
|
||||
**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 rebuild'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 compilers. The loop over indexes is faster still in the rebuild, 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.view().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, in both
|
||||
compilers. A lambda doesn't care (decision 3).
|
||||
- **Bounds at methods work in both compilers now.** Both take
|
||||
`def span<T>::is_sorted(&this): bool where T: ordered`, and the method belongs only to
|
||||
ordered `T` (README, "Methods and properties"). The C compiler refused it on
|
||||
2026-10-09, so this plan guarded such methods with `if const !(T is ordered)` and
|
||||
`compile_error`. std's `lower_bound`, `upper_bound`, `sort` and `heap` still guard that
|
||||
way, which gives a message of their own. Probed.
|
||||
- **Lambdas take their types from `invokable` bounds,** in both compilers, and the
|
||||
rebuild infers a type parameter from a lambda, as `F` of `take<F>(f: F)` given
|
||||
`def(x: i64): i64 => x`, as C did. That was phase 0 here, built with the iterators on
|
||||
2026-10-19. Probed.
|
||||
- **Overloads still split the compilers.** 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 rebuild gives a lambda the function type and calls the first, and C refuses the
|
||||
lambda, since no function type is expected. Neither gives 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,** in both compilers, 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 in both
|
||||
compilers. Probed again.
|
||||
- **`strview` isn't `ordered`.** Its `compare` takes the other view by value, not as
|
||||
`&self`, so `<` doesn't work on text views, in either compiler. 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, in the rebuild. 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 both compilers' sources, each with a test:
|
||||
- The rebuild 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 rebuild's 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.
|
||||
- C refused `f(x)` in a generic of another module where `f` was a `&mut` functor
|
||||
whose `invoke` wasn't `pub`, and accepted `f.invoke(x)`.
|
||||
- The rebuild didn't infer the `K` of `invokable<def(&T): K>` from a function given
|
||||
for it, which C did.
|
||||
|
||||
## 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, `view` 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 `iterator<T>`
|
||||
(std/traits/iterator.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, in both
|
||||
compilers. `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`. Both
|
||||
compilers take 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.view().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.view().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, in
|
||||
both compilers. 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`. In the
|
||||
rebuild, 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 rebuild learns to call that lambda directly too.
|
||||
|
||||
## What the compiler gains
|
||||
|
||||
These counts come from the rebuild 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.view().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, in both compilers, 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 rebuild infers a type parameter from a lambda, as C does;
|
||||
- a type parameter bounded only by `signature` still needs the lambda's types written.
|
||||
|
||||
Overloads take no part: neither compiler gives 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 rebuild'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, so the C compiler,
|
||||
which only builds stage 1, needn't follow.
|
||||
- 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 rebuild's 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. The C compiler and its machine must give the same.
|
||||
- **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 rebuild'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 rebuild's 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.view().lower_bound(&x)`. Both compilers take `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, and C refuses a lambda where a
|
||||
function type and an `invokable` overload take the same arguments, as probed.
|
||||
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 rebuild's
|
||||
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,626 @@
|
||||
# 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.
|
||||
|
||||
**Built in the rebuild alone** ([roadmap.md](roadmap.md), decision 1). Where this plan
|
||||
says both compilers, C's half is left out. What was measured in C stays as measured.
|
||||
|
||||
**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 rebuild'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, with both compilers as executables at
|
||||
`-O2`, the rebuild's at `-O0` too, and in both VMs;
|
||||
- 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 the rebuild's `-O2` executables, 58 ns in its `-O0` ones, and 94 ns
|
||||
in the C compiler's `-O2` ones.
|
||||
- On Linux, `CLOCK_MONOTONIC` steps by 1 ns, but std makes a system call for each
|
||||
read. A read took 211 ns in the rebuild's `-O2` executables, 293 ns in its `-O0`
|
||||
ones, and 220 ns in the C compiler's `-O2` ones. A C program reading the same clock
|
||||
through the vDSO, as glibc does, took 25 ns.
|
||||
- **What the optimizers take 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 | C compiler `-O2` | Rebuild `-O2` | Rebuild `-O0` |
|
||||
|---|---|---|---|
|
||||
| Empty | 0.48 | 0.24 | 0.38 |
|
||||
| A constant in, the result stored to a global | 2.28 | **0.32** | 3.64 |
|
||||
| A global read in, the result stored to a global | 2.24 | **0.27** | 3.70 |
|
||||
| The counter in, the result discarded | **0.48** | **0.24** | 3.61 |
|
||||
| The counter in, the result stored to a global | 2.20 | 1.79 | 3.65 |
|
||||
| The counter in, the results summed and printed | 2.26 | 1.96 | 3.85 |
|
||||
| In and out through a `@foreign def` that gives its argument back, the result stored | 2.18 | 1.79 | 7.75 |
|
||||
| The same, the result discarded | **0.48** | **0.24** | 7.32 |
|
||||
| In and out through relaxed atomics | 9.60 | 1.92 | 10.65 |
|
||||
| The work in a function value read from a global, called each round | 4.67 | 3.20 | 4.88 |
|
||||
|
||||
- The bold rows measured an empty loop. The rebuild moves work on a constant or a
|
||||
global out of the loop, and the C compiler doesn't.
|
||||
- Both compilers drop a result that nothing reads, even through a `@foreign def` with
|
||||
a body, so going through one hides nothing.
|
||||
- Relaxed atomics keep the work in both compilers. Three a round, a store and a load in
|
||||
and a store out, cost the rebuild 0.1 ns over storing to a global, and the C compiler
|
||||
7.4 ns.
|
||||
- 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
|
||||
each VM:
|
||||
|
||||
| Benchmark | C compiler `-O2` | Rebuild `-O2` | C compiler's VM | Rebuild's VM |
|
||||
|---|---|---|---|---|
|
||||
| `mixes`, the work above | 1.49–1.50 ns | 0.672–0.673 ns | 19.0 ns | 22.8 ns |
|
||||
| `inserts_1000`, into a new `dict` | 13.2–13.3 µs | 4.84–4.85 µs | 141 µs | 159 µs |
|
||||
| `formats`, interpolating two numbers | 83.1–84.5 ns | 54.10–54.12 ns | 130 ns | 173 ns |
|
||||
|
||||
The median absolute deviation was under 0.5% of the median in the executables,
|
||||
except the C compiler's `mixes`, at up to 1.4%.
|
||||
- **Medians on Linux,** on 2026-10-20, over three runs of each executable, and eight to
|
||||
ten of `links_100`:
|
||||
|
||||
| Benchmark | C compiler `-O2` | Rebuild `-O2` |
|
||||
|---|---|---|
|
||||
| `mixes` | 8.17–8.23 ns | 1.92–1.93 ns |
|
||||
| `inserts_1000` | 55.9–57.2 µs | 35.3–36.0 µs |
|
||||
| `formats` | 227–228 ns | 172–173 ns |
|
||||
| `links_100`, a list of 100 `box`es made and closed | 6.01–6.12 µs, and once 7.82 µs | 4.63–4.73 µs, and twice 5.76 µs |
|
||||
|
||||
- The median absolute deviation was under 1.4% of the median in the rebuild, and
|
||||
under 2.4% in the C compiler.
|
||||
- The C compiler's `mixes` is mostly the stand-in for `keep`: four relaxed atomics a
|
||||
round.
|
||||
- **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 in the rebuild (3.05 µs and 0.51 µs), and eight times in the C
|
||||
compiler (8.71 µs and 1.07 µs), since most samples held a collection. With no
|
||||
collector, its fastest sample is within 1% of its median in the rebuild, and within
|
||||
6% in the C compiler.
|
||||
- **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
|
||||
rebuild `-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 rebuild's 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 in both compilers. A closure in a constant, as
|
||||
`@bench const inserts_10 := def(b: &mut bencher): void { inserts(b, 10); };`,
|
||||
worked in the rebuild, but the C compiler refused it, and still did on 2026-10-20.
|
||||
See "Found along the way".
|
||||
- **Fixtures, on 2026-10-20,** in both compilers:
|
||||
- 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`, both compilers 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`, the same in both trees):
|
||||
- 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.** Neither compiler has `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–94 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 compilers gain `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;
|
||||
```
|
||||
|
||||
- **The rebuild:**
|
||||
- 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.
|
||||
- **The C compiler:**
|
||||
- `INTRINSIC_KEEP` in `sources/table.h` and the intrinsic table in `checker.c`.
|
||||
- `compiler.c` emits an instruction that `optimizer.c` doesn't mark `pure`, and that
|
||||
reads and writes memory, as a call does.
|
||||
- `machine.c` and `native.c` treat it as 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.view()) 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 6% 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
|
||||
the rebuild's `-O2` executables and 1.78 ns in the C compiler's, against 2.78 ns
|
||||
and 4.80 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 in both compilers. 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 each tree's std tests** (`tests/std/bench.sakura` in the C
|
||||
compiler's tree, `test/std/bench.sakura` in the rebuild's), 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 each compiler's tests:**
|
||||
- At `-O2`, a loop of `keep(mixed(keep(i)))` still holds its multiplies:
|
||||
- in the rebuild, by its IR tests and `--verify`;
|
||||
- in the C compiler, in `tests/native.c`.
|
||||
- `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:** both compilers, 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 each compiler for `keep`, 700 of `std::testing`, and 400 of tests.
|
||||
|
||||
1. **`keep`, in both compilers,** with its tests.
|
||||
2. **The runner:** `@bench`, `bencher`, calibrating, sampling, the report, `--only`,
|
||||
`--time` and `--samples`. Lent fixtures and constants included. Mirrored in both
|
||||
stds.
|
||||
3. **`batched` and rates.**
|
||||
4. **`--save` and `--compare`.**
|
||||
5. **Benchmarks of std,** in a `bench/` directory beside each tree's tests:
|
||||
- containers, hashing, sorting and formatting;
|
||||
- JSON and YAML throughput;
|
||||
- and in the rebuild, its 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
|
||||
|
||||
- **The C compiler refuses a closure in a constant whose body calls what can't run
|
||||
while compiling.** The rebuild accepts it, and runs it:
|
||||
|
||||
```sakura
|
||||
def shown(n: u64): void { println($"shown {n}"); }
|
||||
const plain := def(): void { shown(1); };
|
||||
# C compiler: "Value is not known while compiling. `shown` cannot run while
|
||||
# compiling: it calls `println`, which reads `output_held` ..."
|
||||
```
|
||||
|
||||
Making a closure doesn't run its body, so this looks like a fix to the C compiler.
|
||||
It still held on 2026-10-20, and also where the closure only fills a `dict`, which C
|
||||
refuses since `dispose` "is a method of a trait that is not a `const def`". Until it's
|
||||
fixed, std's own benchmarks write one function a size, since both compilers run them.
|
||||
- **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.
|
||||
- **Reading the steady clock costs three times as much in the C compiler's
|
||||
executables on Windows** (94 ns) as in the rebuild's (30 ns). Both call
|
||||
`QueryPerformanceCounter`. Not probed again, as Windows wasn't at hand. On Linux the
|
||||
two cost the same, 220 ns and 211 ns.
|
||||
- **Relaxed atomics cost the C compiler time,** and cost the rebuild nothing. On
|
||||
Windows, one round of them cost it 1.3 ns. On Linux, three a round cost it 7.4 ns,
|
||||
and the rebuild 0.1 ns. On x86-64, a relaxed load or store is a plain `mov`.
|
||||
- **On Linux, std reads the steady clock by a system call,** about 210 ns a read in both
|
||||
compilers' 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 four
|
||||
runtimes: both compilers' native runtimes, in the rebuild's `runtime/memory.sakura`
|
||||
and C's `std/runtime/memory.sakura`, and both VMs. 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 the rebuild's `-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 rebuild'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% in the rebuild, and within 1.7%
|
||||
in the C compiler. On Linux, within 2.3% in both, 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,607 @@
|
||||
# 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.
|
||||
|
||||
**Built in the rebuild alone** ([roadmap.md](roadmap.md), decision 1). Where this plan
|
||||
says both compilers, C's half is left out. What was measured in C stays as measured.
|
||||
|
||||
**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 compilers build into every executable: the module `runtime`,
|
||||
whose 16 helpers they call by name.
|
||||
2. **Code the compilers write themselves:** `_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 compilers write 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, in either compiler.
|
||||
|
||||
**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 rebuild's fixed
|
||||
point) and `cexp/sakura` (C's working tree), and by three searches of both compilers'
|
||||
sources. A program summing a vector, built at `-O2`:
|
||||
|
||||
| | Rebuild | C |
|
||||
|---|---|---|
|
||||
| Executable | 164 KB | 761 KB |
|
||||
| Kind | ELF `ET_EXEC`, base `0x400000`, segments `.rodata`, `.data`, `.text`, `.lines` | the same |
|
||||
| Instructions reading through `gs` | 55 | 174 |
|
||||
| `syscall` instructions | 42: `_start`, the heap, its lock, threads, `fail`, `exit`, the trap stub | 61 |
|
||||
| Instructions naming an `xmm` register | 133: formatting, `memcpy`, clearing, comparing | 101 |
|
||||
| RIP-relative operands | 0 | 0 |
|
||||
| Stores below `rsp` (the red zone) | 0 | 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` (rebuild `native.sakura:1080-1141` in `sakura-native`, C `native.c:5208-5277`) | 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 rebuild keeps frames on `rsp`, 32 MiB mapped. C keeps frames on a stack of its own through `rbx` (8 MiB), and return addresses on `rsp` (33 MiB) | `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` (rebuild `native.sakura:31-58`, C `native.c:210-250`) | `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 rebuild checks `rsp - frame` against `gs:[8]` in every prologue but a small
|
||||
leaf's (`calls.sakura:1039-1047`).
|
||||
- C checks `rbx + frame` against `gs:[8]` in every one (`native.c:3868-3880`).
|
||||
- **SSE2 and x87, always.**
|
||||
- Floats are scalar SSE2.
|
||||
- Copies and clears up to 128 bytes, and the rebuild's prologue 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;
|
||||
- in the rebuild, 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** (rebuild `binary::elf` and `binary::pe`, in `binary`; C `elf.c`, `pe.c`):
|
||||
- `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 in both compilers, but nothing sets it.
|
||||
|
||||
**Targets are a closed list in each compiler:**
|
||||
- the rebuild's `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;
|
||||
- C's `target_parse` and `context_build` (`context.c:114-133`, `501-504`), the names in
|
||||
`table.c:16-25`, and `native.c`'s Windows-or-else (`5994`).
|
||||
|
||||
`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 both optimizers, 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 compilers' sources. `@foreign` unions overlay their fields.
|
||||
|
||||
**Not there, in either compiler:**
|
||||
- **Inline assembly,** or any intrinsic for `in`/`out`, `cli`/`sti`/`hlt`, control
|
||||
registers, MSRs, `lgdt`/`lidt`/`ltr`, `invlpg`, `iretq`, `swapgs`, `rdtsc` or `pause`.
|
||||
- The encoders emit 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.**
|
||||
- Both optimizers reuse a value read through a pointer when nothing between may
|
||||
write it.
|
||||
- The rebuild's 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, in both compilers, 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 compilers say it's for other
|
||||
targets ([std on none](#std-on-none)).
|
||||
- **Both compilers agree,** with the same tests run by each.
|
||||
|
||||
## 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` in the rebuild, and
|
||||
C's Windows-or-else, become a choice of three systems.
|
||||
- **UEFI** comes later ([Later](#later-where-wanted)): a PE for the firmware, with the
|
||||
Windows calling convention the compilers already have.
|
||||
|
||||
### 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 compilers look up by name, as they look 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 compilers already know what's reached, since they compile only that.
|
||||
- C's errors about constants already name such chains.
|
||||
- **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 compilers write `_start` as they do 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` (C also its stack of frames);
|
||||
- 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 rebuild'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.
|
||||
- C writes addresses as 32-bit numbers in the same kinds of places, which need the
|
||||
same review.
|
||||
- **Not now:** code that can be placed anywhere (RIP-relative), relocatable PEs, flat
|
||||
binaries. Multiboot2 enters in 32-bit mode, which neither backend can 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.
|
||||
- Both optimizers treat each as they treat an atomic: touching all memory, so it's
|
||||
neither removed, merged nor moved.
|
||||
- An atomic already works this way, in both.
|
||||
|
||||
The table holds 28 intrinsics. The encoders gain about 20 instructions each, 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 compilers write 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`.
|
||||
- **Frames differ between the compilers.**
|
||||
- The rebuild keeps them on `rsp`, so a handler's frames go below the interrupted
|
||||
code's.
|
||||
- C keeps them on a stack of its own through `rbx`. An interrupt can't know where the
|
||||
interrupted function's frame ends, so C's handlers get a stack of frames of their
|
||||
own.
|
||||
|
||||
### 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 compilers already do 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 rebuild:**
|
||||
- **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.
|
||||
|
||||
**C:**
|
||||
- **Targets:** `context.c`'s `target_parse` and `context_build`, `table.c`'s names,
|
||||
`checker__meets`, and `native.c`'s Windows-or-else.
|
||||
- **The start and faults:** a third entry in `native.c`.
|
||||
- **Code generation:** `elf.c` for `.bss` and the base, `x64.c` for the instructions,
|
||||
`compiler.c`'s `emitter__intrinsic` and `checker.c`'s table of intrinsics, and
|
||||
`compiler.c`'s layouts.
|
||||
|
||||
**`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, in both compilers.
|
||||
- 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,
|
||||
in both compilers.
|
||||
- **Linux and Windows unchanged:**
|
||||
- the corpus in each VM and natively at each level;
|
||||
- both std suites, the rebuild's unit tests, C's `sakura_tests`;
|
||||
- the rebuild building itself to its fixed point.
|
||||
|
||||
## Phases
|
||||
|
||||
1. **The runtime split,** in both compilers and both trees, 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 each
|
||||
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 each compiler.
|
||||
3. **The hardware:** `core::x86_64` and the volatile intrinsics. About 400 lines in each
|
||||
compiler.
|
||||
4. **Layout:** `@align` and `@packed`, and the README's layout. About 250 lines in each.
|
||||
5. **Interrupts:** `@interrupt`. About 300 lines in each.
|
||||
6. **The top 2 GiB.** About 300 lines in each.
|
||||
7. **A kernel booting on QEMU,** in `test/kernel/`. This needs QEMU, and Limine's files,
|
||||
on the machine running it.
|
||||
8. **Both READMEs:** "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 both optimizers, 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.
|
||||
- **The two compilers lay frames out differently:** the rebuild on `rsp`, C on a stack of
|
||||
its own through `rbx`. Each needs its own interrupt entry.
|
||||
- **`build_options.stack` exists in both,** 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
|
||||
compilers find by name, as they find `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 compilers,** 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 compilers know 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 backends write.
|
||||
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 optimizers know what
|
||||
each does. And neither compiler has an assembler to read text with.
|
||||
7. **Interrupt handlers:**
|
||||
- **(a) `@interrupt` functions,** whose entry and exit the compilers write.
|
||||
- **(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).
|
||||
@@ -0,0 +1,71 @@
|
||||
# Where the compilers disagreed
|
||||
|
||||
The places where the C compiler and the rebuild didn't agree, as the plans and their builds
|
||||
noted them. The C compiler is frozen, so the rebuild's behavior is the language
|
||||
([roadmap.md](roadmap.md), decision 1), and the rules step 5 settled on 2026-10-20 are
|
||||
built. Probed again on 2026-10-28 with the rebuild alone: what was decided, or works in the
|
||||
rebuild, went, and what's left is where the rebuild still falls short of what C did or of
|
||||
what the README says. Probes leave out their imports. This file goes at the freeze.
|
||||
|
||||
## What runs while compiling
|
||||
|
||||
### What follows an `if const` only evaluating decides
|
||||
|
||||
```sakura
|
||||
def size_or_refuse<A, B>(): u64 {
|
||||
if const size_of::<A>() == size_of::<B>() { return size_of::<A>(); }
|
||||
compile_error("not the same size");
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
`size_or_refuse::<u64, i64>()` is refused: "not the same size (In `size_or_refuse<uint,
|
||||
int>`)". Where the checker decides an `if const` whose branch leaves, as `T is integer`,
|
||||
what follows it is compiled only where the branch isn't taken. Where only evaluating
|
||||
decides, as here, what follows is compiled either way, so its `compile_error` is reported
|
||||
whichever way the condition goes, as C reported every one. Within the branch, as
|
||||
`simd::bits` writes it, or in an `else`, it's reported only where evaluating chooses that
|
||||
branch: so since 2026-10-28, with the text it's given, in a property's accessors too.
|
||||
|
||||
### A local constant reading another
|
||||
|
||||
```sakura
|
||||
def main(): void { const a: i64[3] = [1, 2, 3]; const b := a[1]; println($"{b}"); }
|
||||
```
|
||||
|
||||
"A constant's value is known while compiling", where the constant read isn't a number. The
|
||||
same for a struct's field and a span given to a function. A global constant read this way,
|
||||
and local constants that are numbers, work.
|
||||
|
||||
### `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.
|
||||
|
||||
### An address made a number while evaluating
|
||||
|
||||
Where it happens, evaluating says only "Evaluating `h` stopped: Function does not run while
|
||||
compiling.", with a trace. C said what happened: "An address is only known where the
|
||||
program runs, so pointers and integers do not convert while compiling."
|
||||
|
||||
### A constant holding what is written through
|
||||
|
||||
```sakura
|
||||
const b: box<i64> = box::new(3);
|
||||
const s: string = string::from("abc", nothing {});
|
||||
```
|
||||
|
||||
The rebuild takes both, and a `vector<i64>` made by a function, on the machine, under
|
||||
`--checks` and in executables. The README's "a `string` doesn't" sides with C, which
|
||||
refused them: "A constant stands in memory the program only reads, so it holds `*T` and
|
||||
`&T` but not what is written through". Which is the language isn't decided.
|
||||
|
||||
### `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 no
|
||||
number, and C refused it: "`int` is built into the language, so there is no declaration of
|
||||
it to describe."
|
||||
+582
@@ -0,0 +1,582 @@
|
||||
|
||||
|
||||
|
||||
# Later
|
||||
|
||||
What the built plans left for later, and the problems they found and didn't fix. Each item
|
||||
was checked against the rebuild 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.
|
||||
|
||||
Where the C compiler and the rebuild disagreed and the rebuild still falls short, the item
|
||||
is in [inconsistencies.md](inconsistencies.md) instead. 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) gives the order the plans are built in up to the language's
|
||||
freeze. It also says which items here must come before the freeze and which can wait.
|
||||
|
||||
## 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#7-lambdas-that-own-what-they-use-decisions-2-and-3)).
|
||||
|
||||
### 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 the rules were settled (roadmap step 5). The rebuild 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.view()`, 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 rebuild
|
||||
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`.
|
||||
|
||||
### 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`.
|
||||
|
||||
### `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`.
|
||||
|
||||
### A module named as a type it declares hides the type
|
||||
|
||||
A path's first name is a module's before a type's, so `std::uri`'s `uri::parse` would look
|
||||
in the module. So `std::regex`, `std::uri` and `std::version` are `std::text`, `std::net`
|
||||
and `std::semver`. A rule reaching the type is a language addition that could come after
|
||||
the freeze.
|
||||
|
||||
### 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>`.
|
||||
|
||||
### 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.
|
||||
|
||||
## Warnings the checker misses
|
||||
|
||||
### A lambda returned through a call
|
||||
|
||||
A lambda returned directly, or in a struct literal, is warned of: "The value returned
|
||||
refers to `s`, which ends as the function returns". Returned through a call, as
|
||||
`return function::new(def() => ...)` or `return pass(def() => ...)`, it isn't. Calling it
|
||||
later reads a frame that's gone. `run --checks` misses it too, most of the time: the
|
||||
closure's frame is pushed where the ended frame was, so the address it reads lies within
|
||||
frames in use.
|
||||
|
||||
### A thread handle outliving its closure's locals
|
||||
|
||||
A function that starts a thread whose closure updates one of its locals, and returns the
|
||||
handle, gets no warning, where returning the closure itself would. `run` reads a stale
|
||||
frame, and `run --checks` prints garbage.
|
||||
|
||||
### `compile_error` at the call that made the instance
|
||||
|
||||
A `compile_error` is reported where it's written. In a generic, that's inside std, as
|
||||
`std/serial/walk.sakura:45` for `json::to_text` of a type that isn't `@serial`, not the
|
||||
user's call. `compile_error` takes a place (`at: site = call_site()`), so a library can
|
||||
point at a declaration, but std's walk passes none, and the compiler doesn't note the call
|
||||
that made the instance.
|
||||
|
||||
## The compiler
|
||||
|
||||
### 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
|
||||
half are never written: statements, type names, and declarations. Numbering only the
|
||||
nodes checking gives a type would halve `r_types`, `r_refs`, and `r_flags`.
|
||||
- **Evaluating what checking left.** Lowering it, making an interpreter, and running it
|
||||
took 5.5% of checking the compiler, and 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 `@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.
|
||||
|
||||
### What `--checks` misses
|
||||
|
||||
A reference read only by interpolation isn't checked: `val r := &v[k];`, then `v` grows,
|
||||
then `println($"{r}")` prints a stale value, where `val y: u64 = r` is stopped. Nor is a
|
||||
view's element read after the memory it covers is released, as a span after `raw_release`
|
||||
or a vector's view after `close`, at every level; reading through the pointer itself is
|
||||
stopped. The README's account of `--checks` claims more than this.
|
||||
|
||||
It stops at a read of memory nothing wrote, but not of an `undefined` number the
|
||||
optimizer holds in a register rather than in memory, and not where formatting reads a
|
||||
struct's bytes, or `==` compares arrays' bytes.
|
||||
|
||||
### 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 rebuild already leaves that
|
||||
compare out of small leaf functions.
|
||||
|
||||
### Overflow checks
|
||||
|
||||
Checked builds could stop where integer arithmetic overflows, for programs that ask for
|
||||
it. Today it wraps in every build, and `math::checked_add` and its kin are the way to
|
||||
know.
|
||||
|
||||
### 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:
|
||||
- **Files of other systems left unread.** A section's `when` is decided once its file is
|
||||
parsed, so `system/on_windows.sakura`'s 2,449 lines are parsed on Linux. The reader
|
||||
could decide a file's first `when` from its text, as it reads its first `module` line.
|
||||
- **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.
|
||||
- **Checking only what's reached.** Declarations nothing refers to would still be parsed,
|
||||
but not checked. All of std parsed with nothing declared took 37 ms, against 93 ms
|
||||
checked, so that's the most it could save over reading by reference. It matters for
|
||||
large libraries, and for `core`'s 2,590 lines of containers.
|
||||
- **`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.
|
||||
|
||||
### 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.
|
||||
|
||||
### A race checker in the machine
|
||||
|
||||
As ThreadSanitizer does. `run --checks` checks that memory is held, not who writes it
|
||||
when.
|
||||
|
||||
### 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.
|
||||
|
||||
### A failing test
|
||||
|
||||
`readers_and_writers_close_what_they_own`, of `std::io`, fails natively and on the
|
||||
machine: it expects 4 bytes written once closed. It failed with the compiler from before
|
||||
2026-10-27 too.
|
||||
|
||||
## 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, several projects built as one, and an
|
||||
index of packages by `gpid/name`.
|
||||
- **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.
|
||||
- **Native tests reading by reference.** The native backend's tests build their programs
|
||||
over every file of `core`, `system`, the runtime and std, passing over std's `tests`, as
|
||||
the compiler did before the std plan, so they take minutes where they took seconds.
|
||||
+595
@@ -0,0 +1,595 @@
|
||||
# Plan: vectors, matrices and quaternions
|
||||
|
||||
Written 2026-10-14, and brought up to date 2026-10-20 for what was built since (method
|
||||
bounds, `std::math`, `simd` and the optimizer's passes), probed and measured again.
|
||||
This is a proposal. std is yours, so the decisions at the end are yours to make. Nothing
|
||||
in std is built yet. Two compiler bugs the first probes found are fixed already (see
|
||||
"Fixed along the way").
|
||||
|
||||
**Comes after the ffi plan, now built:** `std::sys` is `system`, and `@foreign` and
|
||||
`@link` are `extern` sections.
|
||||
|
||||
**Built in the rebuild alone** ([roadmap.md](roadmap.md), decision 1). Where this plan
|
||||
says both compilers, C's half is left out. What was measured in C stays as measured.
|
||||
|
||||
**What it is:** the objects of 2D and 3D math, with their operators:
|
||||
- vectors of two, three and four numbers;
|
||||
- square matrices of two, three and four columns;
|
||||
- quaternions, for rotations;
|
||||
- transforms of a position, a rotation and a scale;
|
||||
- the camera's matrices, as Vulkan, OpenGL and Direct3D want them.
|
||||
|
||||
**Its users:**
|
||||
- programs drawing through Vulkan, whose vertices, uniforms and push constants hold
|
||||
these;
|
||||
- games and simulations: movement, collision, physics and cameras;
|
||||
- tools reading 3D formats, such as glTF, whose nodes are transforms;
|
||||
- grids and screens, with vectors of integers as keys and positions.
|
||||
|
||||
**It builds on what's built:**
|
||||
- **Operators by method** (the README's "Operators"). `a + b`, `m * v` and `q * r` are
|
||||
methods.
|
||||
- **`std::math`** (std/math/, built 2026-10-14). A length needs its `sqrt`, a rotation
|
||||
its `sin` and `cos`, and `slerp` its `acos`. Its `real` trait says which types those
|
||||
apply to. Its constants are `f64`s, so `f32` code writes `math::pi as f32`.
|
||||
- **Bounds on a generic type's methods** (built 2026-10-19), so `length` is
|
||||
`where T: real`.
|
||||
- **`simd`** (std/simd.sakura, built 2026-10-14), which `vec4` may work through
|
||||
(decision 11).
|
||||
|
||||
**Probed:** again on 2026-10-20 (`plans/linear/` in the scratchpad), under both
|
||||
compilers, in the VM and as executables at `-O2`. Every result here was the same
|
||||
everywhere. Two that weren't are under "Found along the way".
|
||||
- `struct vec3<T> : additive, indexable<u64, T> where T: numeric` with `add`, `sub`,
|
||||
`negate`, `mul` and `equals` gave `+`, `-`, `-v`, `*`, `==` and `+=`:
|
||||
- for `f32`, `f64` and `i32`;
|
||||
- with `v * 2.0` taking the constant as the vector's own number;
|
||||
- with a vector times a vector, and a vector times a number, as overloads of `mul`.
|
||||
- **A number on the left,** as `2.0f * v`, through `def f32::mul(&this, v: &vec3<f32>)`.
|
||||
But `2.0 * v` is still refused for an `f32` vector: an untyped `2.0` is an `f64`,
|
||||
which asks for `f64::mul` (decision 2).
|
||||
- **A matrix times a vector,** as columns times components, summed, and
|
||||
`mat3f::identity()` through the alias.
|
||||
- **Indexing:** `v[1] = 9`, through `indexable` and the fields read as an array, and
|
||||
`v[3]` stopping the program.
|
||||
- **A swizzle,** `a.xy`, as a property.
|
||||
- **Methods for reals alone,** as `def vec3<T>::length(&this): T where T: real`, now in
|
||||
both compilers. Asking it of a `vec3<i32>` is an error where it's written, naming the
|
||||
bound.
|
||||
- **Hashing integers alone,** as `def vec2<T>::hash(&this): u64 where T: integer`, so a
|
||||
`vec2<i32>` keys a `dict`.
|
||||
- **Constants** made by `cross` and `length`, and a Vulkan projection through
|
||||
`math::tan` with its `clip_space` defaulted, in both compilers.
|
||||
- **One type of any length,** `struct vec<T, const N: u64>` holding a `T[N]`, with its
|
||||
operators, `length`, and `cross` refusing other lengths by
|
||||
`if const N != 3 { compile_error(...) }` (decision 3).
|
||||
|
||||
**Measured** on 2026-10-20, the best of five, pinned to a performance core of a busy
|
||||
machine: ten million steps of `total = total + step * half` on `vec3<f32>`, against the
|
||||
same written as three fields. The 2026-10-14 times are in parentheses.
|
||||
|
||||
| Where | Operators | Fields |
|
||||
|---|---|---|
|
||||
| The rebuild, `-O2` | 166 ms (400) | 67 ms (60) |
|
||||
| C, `-O2` | 417 ms, the same with `0.5` written in place of `half` (430, and 2.1 s) | 159 ms (126) |
|
||||
|
||||
- **Inlining is done.** Both compilers inline `add` and `mul` at `-O2` now, with a dozen
|
||||
callers too. The rebuild moves `step * half` out of the loop, and zeroes nothing and
|
||||
checks no pointers in it.
|
||||
- **What's left is the rebuild's, for `f32` and other 4-byte numbers:**
|
||||
- each `f32` operation is still done in double precision. An add is `addsd`, then
|
||||
`cvtsd2ss` and `cvtss2sd`: three instructions for one `addss`. The fields pay it
|
||||
too, and take twice what `f64`'s do: 67 ms against 31;
|
||||
- the vector's fields are written to the stack and read back each step: 36
|
||||
instructions a step, against the fields' 12. A `vec3<i32>` does the same, 23 ms
|
||||
against 11, while a `vec3<f64>` stays in registers, its operators as fast as its
|
||||
fields: 29 ms and 31.
|
||||
- **C no longer boxes an `f32` lent by reference.** `step * 0.5` and `step.mul(0.5)` cost
|
||||
what they cost with a variable. Its code is still about 2.5 times as slow as the
|
||||
rebuild's, and does `f32` in double precision too.
|
||||
- **Lanes:** a `vec4<f32>` whose `add` and `mul` read its fields as one `f32x4` where
|
||||
`lanes_held()` took 73 ms, against 67 written as four fields, and 182 where its
|
||||
operators work field by field. The bits were the same.
|
||||
|
||||
So the types can be built today. Vectors of `f64` are as fast as written out already.
|
||||
Those of `f32` need the rebuild's code generator, or lanes for `vec4` (decision 11).
|
||||
|
||||
## What's there now
|
||||
|
||||
- **Operators by method** (the README's "Operators"), chosen by the right operand, with
|
||||
a number on the left asking its own type, and `a += b` as `a = a + b`.
|
||||
- **Numbers' methods beside the compiler's:** a program may declare `f32::mul` taking a
|
||||
vector.
|
||||
- **Bounds on a generic type's methods,** in both compilers since 2026-10-19, as
|
||||
`def vec3<T>::length(&this): T where T: real`. Only the instances meeting them have
|
||||
the method.
|
||||
- **Constant parameters and `for const`,** so `vec<T, 3>` can be written, one body for
|
||||
every length (decision 3).
|
||||
- **`indexable`, properties, `if const`, and static methods through an alias,** as
|
||||
`mat3f::identity()`. Generic types have no associated variables, so `vec3<T>::zero`
|
||||
is a function.
|
||||
- **`std::math`** (the README's "Math"): `sqrt`, `sin`, `cos`, `tan`, `acos`, `atan2`
|
||||
and `fma` of any `real`, with the same bits in the VM, in executables and in
|
||||
constants. It has no `radians`, `degrees`, `lerp`, `smoothstep` or `remap` yet.
|
||||
- **`simd<L[N]>`** (the README's "Vectors"): `f32x4` and the rest, held in registers by
|
||||
the rebuild's `-O2` executables, which `lanes_held()` says while compiling. An `f32x4`
|
||||
is 16 bytes aligned to 4, as a packed `vec4f` is.
|
||||
- **`f32` is rounded after every operation,** in the VM and in executables, so the two
|
||||
agree. Both compilers' executables work it in double precision.
|
||||
|
||||
## What it needs
|
||||
|
||||
1. **Vectors of 2, 3 and 4,** of any number: `f32` and `f64` for geometry, and integers
|
||||
for grids and pixels.
|
||||
2. **Their arithmetic as operators:** with each other component by component, with a
|
||||
number on either side, and negation.
|
||||
3. **Their geometry:** dot and cross products, length, distance, normalizing,
|
||||
interpolating, reflecting and projecting.
|
||||
4. **Matrices of 2, 3 and 4:**
|
||||
- products with each other and with vectors;
|
||||
- transposing, the determinant and the inverse;
|
||||
- translating, scaling and rotating;
|
||||
- looking at a point;
|
||||
- perspective and orthographic projections.
|
||||
5. **Quaternions:**
|
||||
- from an axis and an angle, from Euler angles, from one direction to another, and
|
||||
from a matrix;
|
||||
- composing and rotating vectors;
|
||||
- interpolating;
|
||||
- to a matrix and back.
|
||||
6. **Transforms:** a position, a rotation and a scale, combined, inverted, applied and
|
||||
interpolated.
|
||||
7. **Layouts C and the GPU read,** so a `vec3<f32>` is three floats one after another.
|
||||
8. **The same bits in the VM, in executables, and in constants.**
|
||||
9. **As fast as written out,** at `-O2`.
|
||||
|
||||
## How it fits the rules
|
||||
|
||||
- **Plain data.** Vectors, matrices and quaternions copy freely, hold nothing, close
|
||||
nothing, and are `equatable`. Vectors of integers are `hashable`, by a `hash`
|
||||
bounded `where T: integer`, so they key a `dict`.
|
||||
- **Arithmetic is operators, by method.** A vector is `additive`. It isn't `numeric`,
|
||||
since `*` between two vectors isn't a ring's product, and there's no `%`.
|
||||
- **Nothing stops the program.**
|
||||
- Normalizing a zero vector gives NaNs, as IEEE 754 does, and `normalize_or` gives a
|
||||
fallback.
|
||||
- An inverse is a `maybe`, which is `nothing` where the determinant is zero.
|
||||
- So nothing calls `contract`, and every function runs in a constant in C too, which
|
||||
refuses constants that could reach `contract`.
|
||||
- **Methods for reals alone** are bounded `where T: real`, so asking one of a `vec3i`
|
||||
is an error where it's written. Quaternions and transforms are of reals alone, bounded
|
||||
so on the type.
|
||||
- **The same bits everywhere:**
|
||||
- each operation rounds as its type does, and nothing fuses a multiply and an add but
|
||||
`math::fma`;
|
||||
- the functions are `std::math`'s, which agree by construction;
|
||||
- `simd`'s lanes give the bits the fields would, so `vec4` may take either way.
|
||||
|
||||
## The types (decisions 1 to 5)
|
||||
|
||||
```sakura
|
||||
module std::math;
|
||||
|
||||
pub struct vec2<T> : additive, indexable<u64, T> where T: numeric { pub var x: T; pub var y: T; }
|
||||
pub struct vec3<T> : additive, indexable<u64, T> where T: numeric { pub var x: T; pub var y: T; pub var z: T; }
|
||||
pub struct vec4<T> : additive, indexable<u64, T> where T: numeric { pub var x: T; pub var y: T; pub var z: T; pub var w: T; }
|
||||
|
||||
#! Column by column, as GLSL, SPIR-V and Vulkan lay them out (decision 5).
|
||||
pub struct mat2<T> where T: numeric { pub var columns: vec2<T>[2]; }
|
||||
pub struct mat3<T> where T: numeric { pub var columns: vec3<T>[3]; }
|
||||
pub struct mat4<T> where T: numeric { pub var columns: vec4<T>[4]; }
|
||||
|
||||
#! A rotation, `w` last, as glm, Eigen and glTF hold it.
|
||||
pub struct quat<T> where T: real { pub var x: T; pub var y: T; pub var z: T; pub var w: T; }
|
||||
|
||||
#! Where something is, how it's turned, and how large, applied scale first.
|
||||
pub struct transform<T> where T: real {
|
||||
pub var translation: vec3<T>;
|
||||
pub var rotation: quat<T>;
|
||||
pub var scale: vec3<T>;
|
||||
}
|
||||
|
||||
pub type vec2f = vec2<f32>; pub type vec3f = vec3<f32>; pub type vec4f = vec4<f32>;
|
||||
pub type vec2d = vec2<f64>; pub type vec3d = vec3<f64>; pub type vec4d = vec4<f64>;
|
||||
pub type vec2i = vec2<i32>; pub type vec3i = vec3<i32>; pub type vec4i = vec4<i32>;
|
||||
pub type mat3f = mat3<f32>; pub type mat4f = mat4<f32>; pub type quatf = quat<f32>;
|
||||
# and mat2f, the f64 ones, and transformf
|
||||
```
|
||||
|
||||
## The operations
|
||||
|
||||
**Vectors,** for any `T`:
|
||||
|
||||
```sakura
|
||||
a + b a - b -a a += b # component by component
|
||||
a * b a / b # component by component
|
||||
v * s v / s s * v # by a number; s * v for f32, f64 and i32
|
||||
a == b # every component equal
|
||||
v[i] # a component, read or written
|
||||
|
||||
pub def vec3<T>::dot(&this, other: &vec3<T>): T;
|
||||
pub def vec3<T>::cross(&this, other: &vec3<T>): vec3<T>; # vec3 alone
|
||||
pub def vec3<T>::length_squared(&this): T;
|
||||
pub def vec3<T>::min(&this, other: &vec3<T>): vec3<T>; # also max, clamp, abs
|
||||
pub def vec3<T>::sum(&this): T;
|
||||
pub def vec3<T>::cast<U>(&this): vec3<U>; # each as `as` converts it
|
||||
pub def vec3<T>::hash(&this): u64 where T: integer; # so integers key a dict
|
||||
pub def vec3<T>::of(xy: vec2<T>, z: T): vec3<T>; # and vec4::of(xyz, w)
|
||||
pub val vec3<T>::xy: vec2<T>; # a property; the other swizzles (decision 9)
|
||||
pub def vec3<T>::zero(): vec3<T>; # also one, x_axis, y_axis, z_axis, as vec3f::zero()
|
||||
```
|
||||
|
||||
**Vectors,** where `T` is `f32` or `f64`:
|
||||
|
||||
```sakura
|
||||
pub def vec3<T>::length(&this): T where T: real; # and so is each below
|
||||
pub def vec3<T>::distance(&this, other: &vec3<T>): T;
|
||||
pub def vec3<T>::normalize(&this): vec3<T>; # NaNs for a zero vector
|
||||
pub def vec3<T>::normalize_or(&this, fallback: vec3<T>): vec3<T>;
|
||||
pub def vec3<T>::lerp(&this, to: &vec3<T>, t: T): vec3<T>;
|
||||
pub def vec3<T>::reflect(&this, normal: &vec3<T>): vec3<T>;
|
||||
pub def vec3<T>::project_onto(&this, onto: &vec3<T>): vec3<T>;
|
||||
pub def vec3<T>::angle_to(&this, other: &vec3<T>): T; # radians
|
||||
pub def vec3<T>::near(&this, other: &vec3<T>, tolerance: T): bool;
|
||||
```
|
||||
|
||||
**Matrices:**
|
||||
|
||||
```sakura
|
||||
m * n m * v m * s m + n m - n m == n m[c] # m[c] is column c
|
||||
|
||||
pub def mat4<T>::identity(): mat4<T>;
|
||||
pub def mat4<T>::of_rows(rows: vec4<T>[4]): mat4<T>;
|
||||
pub def mat4<T>::transpose(&this): mat4<T>;
|
||||
pub def mat4<T>::determinant(&this): T;
|
||||
pub def mat4<T>::row(&this, index: u64): vec4<T>;
|
||||
pub def mat4<T>::translation(by: vec3<T>): mat4<T>;
|
||||
pub def mat4<T>::scaling(by: vec3<T>): mat4<T>;
|
||||
|
||||
# Each of these is `where T: real`.
|
||||
pub def mat4<T>::inverse(&this): maybe<mat4<T>>;
|
||||
pub def mat4<T>::rotation(axis: vec3<T>, angle: T): mat4<T>; # also rotation_x, _y, _z
|
||||
pub def mat4<T>::look_at(eye: vec3<T>, target: vec3<T>, up: vec3<T>): mat4<T>;
|
||||
pub def mat4<T>::perspective(fov_y: T, aspect: T, near: T, far: T, clip: clip_space = clip_space::vulkan): mat4<T>;
|
||||
pub def mat4<T>::orthographic(left: T, right: T, bottom: T, top: T, near: T, far: T, clip: clip_space = clip_space::vulkan): mat4<T>;
|
||||
pub def mat4<T>::transform_point(&this, point: vec3<T>): vec3<T>; # w of 1, divided through
|
||||
pub def mat4<T>::transform_direction(&this, direction: vec3<T>): vec3<T>; # w of 0
|
||||
pub def mat4<T>::normal_matrix(&this): maybe<mat3<T>>; # the inverse transposed
|
||||
|
||||
#! Where depth runs and which way y points after projecting (decision 6).
|
||||
pub enum clip_space: u8 {
|
||||
vulkan, #! depth 0 to 1, y down
|
||||
opengl, #! depth -1 to 1, y up
|
||||
direct3d, #! depth 0 to 1, y up, as Metal and WebGPU too
|
||||
}
|
||||
```
|
||||
|
||||
**Quaternions:**
|
||||
|
||||
```sakura
|
||||
q * r q * v q == r -q
|
||||
|
||||
pub def quat<T>::identity(): quat<T>;
|
||||
pub def quat<T>::of_axis_angle(axis: vec3<T>, angle: T): quat<T>;
|
||||
pub def quat<T>::of_euler(yaw: T, pitch: T, roll: T): quat<T>; # decision 8
|
||||
pub def quat<T>::between(from: vec3<T>, to: vec3<T>): quat<T>; # the shortest arc
|
||||
pub def quat<T>::look_rotation(forward: vec3<T>, up: vec3<T>): quat<T>;
|
||||
pub def quat<T>::of_matrix(m: mat3<T>): quat<T>;
|
||||
pub def quat<T>::conjugate(&this): quat<T>; # also inverse, normalize, dot, length
|
||||
pub def quat<T>::slerp(&this, to: &quat<T>, t: T): quat<T>;
|
||||
pub def quat<T>::nlerp(&this, to: &quat<T>, t: T): quat<T>;
|
||||
pub def quat<T>::matrix(&this): mat3<T>; # also matrix4
|
||||
pub def quat<T>::axis(&this): vec3<T>; # also angle, euler
|
||||
```
|
||||
|
||||
**Transforms and helpers:**
|
||||
|
||||
```sakura
|
||||
a * b # b, then a
|
||||
pub def transform<T>::identity(): transform<T>;
|
||||
pub def transform<T>::inverse(&this): transform<T>;
|
||||
pub def transform<T>::matrix(&this): mat4<T>;
|
||||
pub def transform<T>::apply(&this, point: vec3<T>): vec3<T>; # also apply_direction
|
||||
pub def transform<T>::lerp(&this, to: &transform<T>, t: T): transform<T>;
|
||||
|
||||
pub def radians<T>(degrees: T): T where T: real; # also degrees
|
||||
pub def lerp<T>(from: T, to: T, t: T): T where T: real;
|
||||
pub def smoothstep<T>(edge0: T, edge1: T, x: T): T where T: real;
|
||||
pub def remap<T>(x: T, from_low: T, from_high: T, to_low: T, to_high: T): T where T: real;
|
||||
```
|
||||
|
||||
## Using it
|
||||
|
||||
**A camera's matrices for Vulkan:**
|
||||
|
||||
```sakura
|
||||
import std;
|
||||
import std::math;
|
||||
|
||||
val view := mat4f::look_at(eye, vec3f::zero(), vec3f::y_axis());
|
||||
val projection := mat4f::perspective(math::radians(60.0f), width / height, 0.1, 100);
|
||||
val model := transform::<f32>{ translation = at, rotation = facing, scale = vec3f::one() }.matrix();
|
||||
push.mvp = projection * view * model; # a mat4f, as the shader's mat4 reads it
|
||||
```
|
||||
|
||||
**Turning, and easing between two turns:**
|
||||
|
||||
```sakura
|
||||
val quarter := quatf::of_axis_angle(vec3f::y_axis(), math::pi as f32 / 2);
|
||||
val ahead := quarter * vec3f{ x = 0, y = 0, z = -1 }; # now (-1, 0, 0)
|
||||
val halfway := facing.slerp(&target, 0.5);
|
||||
```
|
||||
|
||||
**A grid:**
|
||||
|
||||
```sakura
|
||||
var tiles := dict::<vec2i, tile>::new();
|
||||
val east := vec2i{ x = 1, y = 0 };
|
||||
tiles.set(position + east, tile::grass);
|
||||
```
|
||||
|
||||
## How each part works
|
||||
|
||||
- **Layout (decision 4):**
|
||||
- Each type is its fields one after another, as C's arrays are. A `vec3<f32>` is 12
|
||||
bytes, and a `mat4<f32>` 64, as Vulkan's vertex formats, glm and SPIR-V's storage
|
||||
buffers take them.
|
||||
- std140 uniform blocks align a `vec3` to 16. Matching that is the program's to do, as
|
||||
with any struct a shader reads.
|
||||
- A `vec4f` is laid out as an `f32x4` is, so it can be read as one (decision 11).
|
||||
- **Indexing** reads the fields as a fixed array, through a pointer to the first,
|
||||
`&this.x`, so an index out of range stops the program as any array's does, and needs
|
||||
no `contract`. (`&this` is a `&&vec3<T>`, a reference to the reference, so it isn't
|
||||
the vector's address.)
|
||||
- **A number on the left** is a method on that number: `f32::mul`, `f64::mul` and
|
||||
`i32::mul`, each taking a vector, matrix or quaternion, for the aliases above. Other
|
||||
number types put the number on the right.
|
||||
- **Reals alone:**
|
||||
- `length`, `normalize` and the rest are bounded `where T: real`, so asking them of a
|
||||
`vec3i` is a mistake where it's written, naming the bound.
|
||||
- Matrices' inverses, rotations and projections do the same. `quat` and `transform`
|
||||
are bounded `real` on the type, since a turn of integers means nothing.
|
||||
- **Named vectors** are static functions, as `vec3f::zero()` and `vec3f::y_axis()`,
|
||||
since a generic type has no associated variables.
|
||||
- **Matrices (decision 5):**
|
||||
- Column `c` is `m[c]`, and the element in row `r` of it is `m[c][r]`, as in GLSL.
|
||||
- `m * v` treats `v` as a column, and `m * n` applies `n` first. So `projection *
|
||||
view * model` reads right to left, as shaders do.
|
||||
- `inverse` is by cofactors, giving `nothing` where the determinant is exactly zero.
|
||||
- **Projections (decision 6):**
|
||||
- View space is right-handed: the camera looks down -Z, with +Y up, in every case.
|
||||
- Only the projection differs by `clip_space`:
|
||||
- `vulkan` maps near to 0 and far to 1, and negates y, since Vulkan's y points down;
|
||||
- `opengl` maps them to -1 and 1;
|
||||
- `direct3d` maps them to 0 and 1, with y up.
|
||||
- **Quaternions (decision 8):**
|
||||
- Hamilton's: `i * j` is `k`.
|
||||
- `q * r` rotates by `r` first, as matrices compose.
|
||||
- `q * v` rotates `v` by `q`, as `v + 2w(u × v) + 2u × (u × v)`, where `u` is
|
||||
`(x, y, z)`. That needs no matrix.
|
||||
- `slerp` takes the shorter way, negating one where their dot is negative. It falls
|
||||
back to `nlerp` where they're nearly the same, where `acos` loses precision.
|
||||
- `of_euler(yaw, pitch, roll)` turns by `roll` about Z, then `pitch` about X, then
|
||||
`yaw` about Y, for +Y up. `euler` gives them back, with pitch from -π/2 to π/2.
|
||||
- **Transforms** apply scale, then rotation, then translation. `a * b` applies `b`
|
||||
first.
|
||||
- `inverse` is exact where the scale is the same on every axis.
|
||||
- Otherwise the true inverse shears, which a transform can't hold. So `inverse`
|
||||
gives the nearest transform, and `matrix().inverse()` the exact matrix.
|
||||
- **Equality** is exact, so a vector holding a NaN equals nothing, itself included.
|
||||
`near` compares within a tolerance.
|
||||
- **Printing:** interpolation shows the fields, as `vec3<f32>{x = 1, y = 2, z = 3}`.
|
||||
`describe` gives `(1, 2, 3)`.
|
||||
|
||||
## Performance (decision 11)
|
||||
|
||||
What 2026-10-14 asked of the rebuild's code generator is half done, after its
|
||||
optimizer's passes of 2026-10-18 ([performance.md](performance.md)): small methods
|
||||
returning a struct are inlined, and nothing in the probe's loop is zeroed or checked for
|
||||
null. What's left is for `f32` and other 4-byte numbers:
|
||||
- **`f32` arithmetic in single precision** (built 2026-10-28, see the
|
||||
[CHANGELOG](../CHANGELOG.md)):
|
||||
- `addss`, `subss`, `mulss`, `divss` and `sqrtss` round exactly as computing in double
|
||||
and rounding does, since a double holds more than twice a float's bits.
|
||||
- So the results are the same bits, and the VM needn't change.
|
||||
- That's 1 instruction for 3, and removes the conversions' latency from every chain.
|
||||
It speeds every `f32`, not only vectors: written as fields, `f32` took twice `f64`'s
|
||||
time.
|
||||
- **Vectors of 4-byte numbers in registers,** as those of 8-byte ones are. A
|
||||
`vec3<f32>`'s and a `vec3<i32>`'s fields go to the stack and back each step, where a
|
||||
`vec3<f64>`'s stay in registers. This phase finds what keeps them in memory.
|
||||
- **Lanes for `vec4`, in std:**
|
||||
- Where `lanes_held()`, `add`, `sub`, `mul` and the rest of a `vec4` of 4-byte numbers
|
||||
read its fields as one `simd<T[4]>`, through `&this.x`, since an `f32x4` is laid out
|
||||
as a packed `vec4f` is. Elsewhere, in the VM, constants and C's executables, they
|
||||
take the fields.
|
||||
- The probe's `vec4<f32>` took 73 ms so, against 67 written as fields.
|
||||
- A `mat4`'s columns are `vec4`s, so its products would be four lanes' multiplies and
|
||||
adds.
|
||||
- `vec2` and `vec3` of `f32` aren't 16 or 32 bytes, and wait for the code generator.
|
||||
- **The target:** vector arithmetic within 1.5 times the same written as fields, at
|
||||
`-O2`, measured by the probe.
|
||||
|
||||
C's code isn't sped up here. The rebuild is the compiler that's going forward, and C's
|
||||
results are already right.
|
||||
|
||||
## Testing
|
||||
|
||||
- **`test/std/linear.sakura`, written with `std::testing`,** covers:
|
||||
- **vectors:** every operator for `f32`, `f64` and `i32`, a number on each side,
|
||||
indexing past the end stopping a forked copy, swizzles, `cast`, `hash` in a `dict`,
|
||||
and the identities: `a × b` perpendicular to both, `a · a` its length squared, and
|
||||
`normalize` of zero giving NaNs;
|
||||
- **matrices:** products against values worked out by hand, `inverse` round trips to
|
||||
within a tolerance, a singular matrix's `nothing`, and `determinant` of rotations
|
||||
being 1;
|
||||
- **projections:** for each `clip_space`, a point on the near plane mapping to its
|
||||
near depth and one on the far plane to its far depth, and y's direction;
|
||||
- **quaternions:** rotating a vector agreeing with `matrix()` doing it, `of_matrix`
|
||||
back again, `slerp` at 0, 1 and halfway, the shorter way, Euler angles round trips
|
||||
away from the poles, and `between` of opposite vectors;
|
||||
- **transforms:** `matrix()` agreeing with `apply`, and `inverse` undoing it;
|
||||
- **constants:** `const forward := vec3f::x_axis().cross(&vec3f::y_axis())` and a
|
||||
constant projection, the same in both compilers.
|
||||
- **A program of the corpus** prints the bits of many results, so the VM, executables
|
||||
and both compilers are compared exactly.
|
||||
- **Where they run:** in the VM, as executables at `-O0` and `-O2`, and with
|
||||
`run --checks`. The rebuild's analyzer must check them with 0 notes.
|
||||
- **The probe's timings** are run before and after decision 11's work.
|
||||
|
||||
## Phases
|
||||
|
||||
About 1,700 lines of std and 900 of tests. Every program's check would grow by about 5%:
|
||||
a copy of std/simd.sakura's 1,075 lines of generic methods, added to std, cost 3% of a
|
||||
one-line program's check in both compilers (2026-10-20, a busy machine). Decision 11 is
|
||||
work in the rebuild's code generator, sized once its first part, finding what keeps
|
||||
4-byte fields in memory, is done.
|
||||
|
||||
1. **Vectors,** with everything that needs no `sqrt`: operators, `dot`, `cross`,
|
||||
indexing, swizzles, `min` and `max`, and hashing.
|
||||
2. **Matrices,** with products, `transpose`, `determinant`, `inverse`, `translation` and
|
||||
`scaling`.
|
||||
3. **What needs `std::math`:** lengths, normalizing, interpolating, `look_at`, rotations,
|
||||
projections, quaternions and transforms, and the helpers.
|
||||
4. **Lanes for `vec4` and `mat4`, and the rebuild's code generator (decision 11).**
|
||||
5. **A "Vectors and matrices" section in the README,** beside its "Vectors" of `simd`.
|
||||
|
||||
Each can begin now: `std::math` was built the day this was written.
|
||||
|
||||
## Fixed along the way
|
||||
|
||||
These were found by the probes and fixed on 2026-10-14. Both compilers passed every
|
||||
check after. Both fixes still hold: the corpus program below gave its expected output
|
||||
under both compilers, in the VM and at `-O2`, on 2026-10-20.
|
||||
- **C passed 0 for a constant on the right of an operator whose method takes `&f32`.**
|
||||
`v * 2.0` on a `vec3<f32>` gave a zero vector, since the constant was lent as the
|
||||
`f64` it is alone. It's now lent as an `f32`, as a call's argument is, in `*`, in
|
||||
`*=`, and in `*=` on a property. The rebuild was right already.
|
||||
- **The rebuild called `def f32::mul(&this, v: &vec3<f32>)` a cycle.** That happened
|
||||
where `vec3`'s bound asks for `mul`, since deciding that `f32` is `numeric` worked out
|
||||
the program's methods on `f32` first, this one among them. It now asks the compiler's
|
||||
own methods on a number first, as C does.
|
||||
- **A program of the corpus covers both:**
|
||||
`operators_lend_constants_as_their_methods_take_them_1`.
|
||||
|
||||
## Found along the way
|
||||
|
||||
- **`2.0 * v` is refused for an `f32` vector,** still, in both, since an untyped
|
||||
constant on the left asks its own type, `f64`. `2.0f * v` and `v * 2.0` work. Letting
|
||||
a constant on the left take the type of a method that fits would change the README's
|
||||
rule for a number on the left (decision 2 here).
|
||||
- **The rebuild does `f32` arithmetic in double precision,** rounding after each
|
||||
operation, as C's executables do too: three instructions for one `addss`.
|
||||
- **The rebuild keeps a struct of 4-byte numbers in memory** through a loop, where one
|
||||
of 8-byte numbers stays in registers (Performance).
|
||||
- **Generic types have no associated variables,** and the compilers differ in how they
|
||||
say so. C refuses `val vec3<T>::zero := ...`. The rebuild takes the declaration, but
|
||||
reading it gives a `vec3<T>` no instance made: `val z: vec3f = vec3f::zero` is a
|
||||
mismatch, and interpolating it prints nothing. An alias's own, `val vec3f::zero :=
|
||||
...`, works in both.
|
||||
- **The rebuild doesn't report `compile_error` in a property's getter while checking.**
|
||||
For `vec<T, N>`'s `z`, guarded by `if const N < 3 { compile_error(...) }`, C reports
|
||||
the error where a `vec2`'s `z` is read. The rebuild checks it clean, and `run` stops
|
||||
with "Checking an instance lowering asked for made notes.", without the note. In a
|
||||
method, as `cross`, both report it while checking.
|
||||
- **"Vector" now names three things:** `vector<T>`, the README's "Vectors" of `simd`,
|
||||
and these.
|
||||
- **No longer so** (2026-10-20):
|
||||
- **Neither compiler inlined a small method returning a struct** at `-O2`. Both do.
|
||||
- **C boxed an `f32` temporary lent by reference,** five times the cost of lending a
|
||||
variable. It costs what a variable does.
|
||||
- **C refused bounds on a generic type's methods,** where the rebuild took them, which
|
||||
is why reals were checked inside the methods by `if const`. Both take them since
|
||||
2026-10-19.
|
||||
|
||||
## Later, where wanted
|
||||
|
||||
- **Geometry:** rays, planes, boxes, spheres and frustums, and the tests between them.
|
||||
- **Rectangular matrices,** as 3×4 for affine transforms, and matrices of any size for
|
||||
numerical work. Decision 3's (b) would bring them.
|
||||
- **Lanes for `vec2` and `vec3` of `f32`,** which aren't 16 or 32 bytes. `vec4`'s are
|
||||
in decision 11, now `simd` is built.
|
||||
- **std140 and std430 layouts,** as types padded for uniform and storage buffers.
|
||||
- **Reversed and infinite depth** in projections, for precision far away.
|
||||
- **Dual quaternions,** for skinning, and rotors, from geometric algebra.
|
||||
- **Writing vectors as arrays** in JSON, as glTF does, through a serial format option.
|
||||
- **One `lerp` for numbers and vectors,** through a trait like the README's
|
||||
`scales<S>`, which std doesn't name.
|
||||
|
||||
## Decisions for you
|
||||
|
||||
1. **Where it lives:**
|
||||
- **(a) `std::math`, beside its functions, in std/math/ (recommended).** One import
|
||||
gives a program drawing in 3D everything it uses.
|
||||
- **(b) `std::linear`, of its own.** A program wanting only `sqrt` doesn't see
|
||||
`vec3`, but most that want one want both. Neither saves checking, since every
|
||||
program is checked with all of std.
|
||||
2. **The numbers inside:**
|
||||
- **(a) Generic, as `vec3<T>`, with aliases for `f32`, `f64` and `i32`
|
||||
(recommended).** One body serves floats, doubles and grids. `2.0 * v` needs `2.0f`
|
||||
for an `f32` vector, or the rule for a number on the left changes so a constant
|
||||
there takes the type of a method that fits.
|
||||
- **(b) `f32` alone,** as many game libraries default to, with `vec3d` and `vec3i`
|
||||
written again where wanted. `2.0 * v` still needs `2.0f`.
|
||||
- **(c) Generic, with no aliases.**
|
||||
3. **Lengths,** open now that constant parameters and `for const` make the second
|
||||
possible:
|
||||
- **(a) A type for each, `vec2`, `vec3` and `vec4`, with fields (recommended).**
|
||||
Literals name the fields, `vec3f{ x = 1, y = 2, z = 3 }`, reflection and `@serial`
|
||||
see them, and `cross` and the swizzles are only where they mean something.
|
||||
- **(b) One of any length, `vec<T, const N: u64>` holding a `T[N]`, with the same
|
||||
aliases.** One body serves every length, and matrices of any shape would come with
|
||||
it. But `x` to `w` are properties, a literal is `vec3f{ c = [1, 2, 3] }`, and
|
||||
`cross`, `z` and `w` refuse the wrong lengths by `if const N != 3 {
|
||||
compile_error(...) }`, which the rebuild reports from a property only as it runs,
|
||||
without the message.
|
||||
4. **Layout:**
|
||||
- **(a) Packed, as C's arrays (recommended).** Vertex buffers and C libraries read
|
||||
them as they are, and a `vec4f` is laid out as an `f32x4` is.
|
||||
- **(b) `vec3` and `vec4` aligned to 16,** as std140 likes them. A `vec3` would take
|
||||
16 bytes, and wouldn't match a vertex format of three floats. `simd` doesn't need
|
||||
it: an `f32x4` is aligned to 4.
|
||||
5. **Matrices:**
|
||||
- **(a) Column by column, with vectors as columns, `m * v` (recommended).** As GLSL,
|
||||
SPIR-V, Vulkan, OpenGL and glm have it, so a matrix goes to a shader as it is.
|
||||
- **(b) Row by row, with vectors as rows, `v * m`,** as Direct3D's older math
|
||||
libraries have it.
|
||||
6. **Clip space:**
|
||||
- **(a) A parameter naming the API, Vulkan by default (recommended).**
|
||||
- **(b) Vulkan alone.** Simpler, but OpenGL and WebGPU programs would fix every
|
||||
projection by hand.
|
||||
- **(c) A function for each,** as `perspective_vulkan` and `perspective_gl`.
|
||||
7. **Angles:**
|
||||
- **(a) Radians, as plain numbers, with `radians` and `degrees` (recommended).** As
|
||||
`math::sin` takes them, and every library has it.
|
||||
- **(b) An `angle` type,** made by `degrees(90)` or `radians(x)`, as `duration` is
|
||||
made of a unit. Degrees can't then be passed for radians, at the cost of
|
||||
converting at every `sin`.
|
||||
8. **Euler angles:**
|
||||
- **(a) One order, yaw about Y, pitch about X and roll about Z, for +Y up
|
||||
(recommended).** That's what cameras and characters want.
|
||||
- **(b) Every order, chosen by an enum,** for tools reading other programs'
|
||||
conventions.
|
||||
- **(c) None:** axes and angles, and directions, alone.
|
||||
9. **Swizzles:**
|
||||
- **(a) The common ones as properties (recommended):** `xy`, `xz` and `yz` of a
|
||||
`vec3` or `vec4`, and `xyz` of a `vec4`.
|
||||
- **(b) Every one,** written by a tool: 336 for a `vec4`, of two to four components.
|
||||
It's about 1,000 more lines of std, which every program's check pays about 3% for,
|
||||
by the measure in "Phases".
|
||||
- **(c) A method,** as `v.swizzle(2, 0, 1)`.
|
||||
10. **What's in it:**
|
||||
- **(a) Vectors, square matrices, quaternions, transforms and the helpers, with
|
||||
geometry later (recommended).**
|
||||
- **(b) Geometry now too:** rays, planes, boxes, spheres and frustums.
|
||||
- **(c) Vectors and matrices alone.**
|
||||
11. **Speed,** where inlining is settled and `f64` vectors are as fast as written out:
|
||||
- **(a) Both, as part of this plan (recommended):** in the rebuild's code generator,
|
||||
`f32` in single precision and 4-byte fields held in registers; in std, `vec4`'s
|
||||
and `mat4`'s operations of 4-byte numbers through `simd` where `lanes_held()`.
|
||||
`f32` vector code is otherwise 2.5 times slower than the same written out.
|
||||
- **(b) Lanes alone, in std.** `vec4` is fast now, and `mat4`'s products would be
|
||||
too, but `vec2` and `vec3` of `f32` stay 2.5 times slower until the code
|
||||
generator's own plan.
|
||||
- **(c) Left to the code generator's own plan,** with `f32` vectors slow until then.
|
||||
- **(d) Accepted.**
|
||||
+428
@@ -0,0 +1,428 @@
|
||||
# Plan: logging
|
||||
|
||||
Written 2026-10-07, and brought up to date 2026-10-20 for threads, owners and
|
||||
`function`, `std::time`, and what probing both compilers 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.
|
||||
|
||||
**Built in the rebuild alone** ([roadmap.md](roadmap.md), decision 1). Where this plan
|
||||
says both compilers, C's half is left out. What was measured in C stays as measured.
|
||||
|
||||
**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 rebuild's 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/`), under both compilers: 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
|
||||
rebuild's 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 in both compilers (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 both compilers' VMs
|
||||
and executables, probed).
|
||||
- **Calls are written qualified, as `log::info(...)`.** Without the module,
|
||||
`info` is ambiguous with `std::io::info` under `import std::io;`, in both compilers
|
||||
(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, in both compilers (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`.** Neither compiler calls 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 the rebuild's `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 in the rebuild; 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 in
|
||||
both compilers), 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 shared corpus, `test/programs`,** which holds both compilers to one output:
|
||||
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 under both compilers, as executables at `-O0` and
|
||||
`-O2`, and with `run --checks`. Both compilers must check them with 0 notes and 0
|
||||
warnings.
|
||||
|
||||
## Phases
|
||||
|
||||
About 30 lines of `std::sys`, 450 of `std::log`, and 300 of tests, in both std trees,
|
||||
and no change to either compiler. The sketch probed was 200 lines of code without its
|
||||
documentation. Each phase ends with its tests passing under both compilers.
|
||||
|
||||
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, in both READMEs.
|
||||
|
||||
## 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` in both compilers
|
||||
(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 rebuild calls a lambda written in place ambiguous
|
||||
between `debug(strview)` and `debug(def(): string)`, typed or not, where C
|
||||
chooses the second (probed 2026-10-20). A function value named first works in
|
||||
both.
|
||||
- **(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,395 @@
|
||||
# Performance
|
||||
|
||||
Where the two compilers started, where they are now, and where they need work: how fast
|
||||
they check and build, how much memory they take, how large they and what they make are,
|
||||
and how fast the code each makes runs.
|
||||
|
||||
"Start" is the two compilers as committed on 2026-10-08: C at `62644a5` ("Close to
|
||||
self-hosted") and the rebuild at `e5b7636`, its first commit. "Now" is both working
|
||||
trees on 2026-10-20. Every comparison of start and now was measured on 2026-10-20, all
|
||||
four compilers 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
|
||||
VMs. Peak memory is the largest resident size of any run.
|
||||
- **The rebuild compiles on one thread here (`-j 1`),** as the start compilers and C do.
|
||||
[Threads](#threads) gives what its default of up to eight does.
|
||||
- **The compilers:**
|
||||
- C, built by gcc with `-O3 -g`, by hand as chinook would;
|
||||
- the rebuild, its own fixed point at `-O2`. "C-built" is the rebuild as C builds it,
|
||||
the same program from other code.
|
||||
- **The work:** each compiler checking and building the rebuild's sources of its day, as
|
||||
the rebuild builds itself (`entry.sakura analyzer compiler machine native`, and
|
||||
`server` now), against the rebuild's std. Those grew, so each result is also given per
|
||||
1,000 lines of what was read:
|
||||
|
||||
| | Start | Now | |
|
||||
|---|---|---|---|
|
||||
| The rebuild'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% |
|
||||
| C's own sources | 57,444 lines of C | 67,674 lines of C | +18% |
|
||||
|
||||
## At a glance
|
||||
|
||||
| | Rebuild, start | Rebuild, now | C, start | C, now |
|
||||
|---|---|---|---|---|
|
||||
| Building the rebuild | 1.78 s | 3.38 s | 1.71 s | 5.80 s |
|
||||
| · instructions per 1,000 lines | 121M | 131M (+8%) | 103M | 213M (+106%) |
|
||||
| · peak memory | 132 MB | 229 MB | 176 MB | 397 MB |
|
||||
| Checking the rebuild | 0.256 s | 0.353 s | 0.259 s | 0.623 s |
|
||||
| · instructions per 1,000 lines | 19.0M | 16.0M (−16%) | 13.0M | 18.2M (+40%) |
|
||||
| · peak memory | 42 MB | 74 MB | 127 MB | 327 MB |
|
||||
| Checking a one-line program | 0.061 s | 0.093 s | 0.066 s | 0.163 s |
|
||||
| · instructions per 1,000 lines of std | 13.7M | 11.2M (−18%) | 10.0M | 13.2M (+32%) |
|
||||
| · peak memory | 15 MB | 27 MB | 45 MB | 112 MB |
|
||||
| The compiler's executable | 11.6 MB | 8.7 MB | 5.5 MB, 1.2 MB stripped | 6.3 MB, 1.4 MB stripped |
|
||||
| A program printing a line | 274 KB | 155 KB | 588 KB | 739 KB |
|
||||
| The rebuild as each builds it, building itself | 8.63G instructions | 15.39G | 10.57G (1.22×) | 29.84G (1.94×) |
|
||||
|
||||
What it says:
|
||||
- **The rebuild 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.
|
||||
- **C's cost per line doubled for a build** and grew 40% for a check, and its memory more
|
||||
than doubled. It was level with the rebuild at the start, and is now 1.7 times its time
|
||||
to build, 1.8 times to check, and 1.7 to 4.4 times its memory.
|
||||
- **The code C makes has fallen behind:** the same program built by C ran 1.22 times
|
||||
the instructions the rebuild's build of it did at the start, and 1.94 times now. The
|
||||
rebuild gained the optimizer and back end work of 2026-10-08 to 10-18, and C only part
|
||||
of it.
|
||||
|
||||
## Speed
|
||||
|
||||
Building and checking, each compiler on the sources of its day, at 2.1 GHz:
|
||||
|
||||
| | Rebuild, start | Rebuild, now | C, start | C, now |
|
||||
|---|---|---|---|---|
|
||||
| Building: wall time, best | 1.778 s | 3.375 s | 1.710 s | 5.803 s |
|
||||
| · median | 1.787 s | 3.388 s | 1.720 s | 5.823 s |
|
||||
| · instructions | 8.63G | 15.39G | 7.36G | 24.91G |
|
||||
| · cycles | 3.49G | 6.44G | 3.40G | 11.75G |
|
||||
| Checking: wall time, best | 0.256 s | 0.353 s | 0.259 s | 0.623 s |
|
||||
| · instructions | 1.36G | 1.88G | 0.93G | 2.13G |
|
||||
| · cycles | 0.49G | 0.65G | 0.43G | 1.04G |
|
||||
| A one-line program: wall time, best | 0.061 s | 0.093 s | 0.066 s | 0.163 s |
|
||||
| · instructions | 300M | 451M | 219M | 532M |
|
||||
|
||||
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 in the rebuild now, and 4.1 ms in C,
|
||||
at this clock. Generic code costs two to three times what plain code does, mostly in
|
||||
C's instances (`checker__clone`), as `std/simd.sakura` measured on 2026-10-14.
|
||||
|
||||
### The code each makes
|
||||
|
||||
The same program, the rebuild's compiler, built by each compiler and then building the
|
||||
same sources:
|
||||
|
||||
| | Start | Now |
|
||||
|---|---|---|
|
||||
| Built by the rebuild | 1.778 s, 8.63G instructions | 3.375 s, 15.39G |
|
||||
| Built by C | 2.154 s, 10.57G | 5.593 s, 29.84G |
|
||||
| C's code against the rebuild's | 1.21× the time, 1.22× the instructions | 1.66×, 1.94× |
|
||||
|
||||
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, so the ratios are surer than the times:
|
||||
|
||||
| What | Rebuild | C | C against the rebuild | Measured |
|
||||
|---|---|---|---|---|
|
||||
| `f32` `a * b + c`, scalar | 87.9 ms | 110.7 ms | 1.3× | 10-20 |
|
||||
| The same, `f32x8` | 5.9 ms | 78.8 ms | 13× | 10-20 |
|
||||
| Finding a byte, `u8x16` | 1.78 ms | 42.9 ms | 24× | 10-20 |
|
||||
| `index_of`, a byte at the end of 1 MiB | 62 µs | 698 µs | 11× | 10-20 |
|
||||
| `is_ascii` of 1 MiB | 62 µs | 86 µs | 1.4× | 10-20 |
|
||||
| Vectors of three `f32`s, by operators | 166 ms | 417 ms | 2.5× | 10-20 |
|
||||
| Random draws, 64 bits | 2.5 ns | 5.8 ns | 2.3× | 10-20 |
|
||||
| A call through a function value | 2.72 ns | 4.61 ns | 1.7× | 10-20 |
|
||||
| A generic `F`, inlined | 0.48 ns | 1.79 ns | 3.7× | 10-20 |
|
||||
| A call through a `function` | 2.86 ns | 4.56 ns | 1.6× | 10-20 |
|
||||
| A list of 1,000,000 `box`es, ten times | 539 ms | 675 ms | 1.25× | 10-19 |
|
||||
| The same through `raw_allocate` | 414 ms | 563 ms | 1.36× | 10-19 |
|
||||
| The same in a `pool` | 209 ms | 136 ms | 0.65× | 10-19 |
|
||||
| Three relaxed atomics | 0.1 ns | 7.4 ns | 74× | 10-20 |
|
||||
| Building a `u32[16000]` constant | 0.15 s | 5.77 s | 38× | 10-20 |
|
||||
|
||||
What makes the difference:
|
||||
- **Vectors in registers.** The rebuild's `-O2` holds `simd` values in registers and
|
||||
picks AVX2 or SSE2 as the program runs. C lowers `lanes_held()` to `false`, so its
|
||||
vectors and std's text functions go through memory or a word at a time.
|
||||
- **What the rebuild's 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.
|
||||
- **C's optimizer is quadratic** in a constant array's length.
|
||||
- **C is ahead in one place:** a `pool`, 136 ms against 209.
|
||||
|
||||
### The VMs
|
||||
|
||||
Each compiler running the rebuild's compiler on its VM, which then checks a one-line
|
||||
program. The time includes checking and lowering the compiler for the VM:
|
||||
|
||||
| | Start | Now |
|
||||
|---|---|---|
|
||||
| The rebuild's VM | 2.69 s, 17.8G instructions, 122 MB | 5.00 s, 29.2G, 244 MB |
|
||||
| C's VM | 1.99 s, 8.1G, 167 MB | 6.32 s, 27.7G, 403 MB |
|
||||
|
||||
The rebuild's VM was a third slower than C's at the start, and is a fifth faster now. On
|
||||
small calls it's still slower: a call through a function value takes 81.8 ns in the
|
||||
rebuild's VM and 41.6 ns in C's, and an inlined generic call 24.5 ns and 10.8 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`). 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 rebuild compiles on threads, one for each processor up to eight. Unpinned, on this
|
||||
machine's twelve:
|
||||
|
||||
| | `-j 1` | Default | |
|
||||
|---|---|---|---|
|
||||
| Building the rebuild | 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. C compiles on one.
|
||||
|
||||
## Memory
|
||||
|
||||
Peak resident memory:
|
||||
|
||||
| | Rebuild, start | Rebuild, now | C, start | C, now |
|
||||
|---|---|---|---|---|
|
||||
| Building the rebuild | 132 MB | 229 MB | 176 MB | 397 MB |
|
||||
| · per 1,000 lines | 1.85 MB | 1.96 MB | 2.47 MB | 3.39 MB |
|
||||
| Checking the rebuild | 42 MB | 74 MB | 127 MB | 327 MB |
|
||||
| · per 1,000 lines | 0.59 MB | 0.63 MB | 1.78 MB | 2.79 MB |
|
||||
| Checking a one-line program | 15 MB | 27 MB | 45 MB | 112 MB |
|
||||
|
||||
The rebuild's memory grew as what it reads did, 6% to 7% more a line. C's grew 37% to
|
||||
57% more a line, and a check by C takes 4.4 times the rebuild's memory.
|
||||
|
||||
The rebuild has no collector since 2026-10-19, nor does C's runtime. Programs hold what
|
||||
they allocate in owners, arenas and pools, and each thread keeps a cache of free blocks.
|
||||
|
||||
## Size
|
||||
|
||||
### The compilers
|
||||
|
||||
| | Rebuild, start | Rebuild, now | C, start | C, now |
|
||||
|---|---|---|---|---|
|
||||
| Executable | 11,570,800 bytes | 8,730,512 | 5,504,368 | 6,337,928 |
|
||||
| · code | 2.52 MB | 3.01 MB | 1.03 MB | 1.20 MB |
|
||||
| · constant data | 0.60 MB | 1.02 MB | 0.07 MB | 0.08 MB |
|
||||
| · line tables, or debugging information | 8.28 MB | 4.63 MB | 4.3 MB | 4.9 MB |
|
||||
| The rebuild as C builds it | 17,064,568 bytes | 27,417,928 | | |
|
||||
| · its code | 4.62 MB | 6.70 MB | | |
|
||||
|
||||
The rebuild's executable carries its line tables, which fault traces read, as 53% of it.
|
||||
C's carries DWARF from `-g`, and is 1.4 MB stripped. The rebuild's code is 2.5 times C's,
|
||||
for a program 14% larger than C's in lines, with std's code in it too. As C builds the
|
||||
rebuild, its code is 2.2 times what the rebuild makes of the same sources.
|
||||
|
||||
### What they make
|
||||
|
||||
A program printing a line, at `-O2`:
|
||||
|
||||
| | Rebuild, start | Rebuild, now | C, start | C, now |
|
||||
|---|---|---|---|---|
|
||||
| Executable | 273,512 bytes | 154,856 | 588,032 | 738,760 |
|
||||
| · code | 36,046 | 35,618 | 78,276 | 119,713 |
|
||||
| · constant data | 24,128 | 30,616 | 199,048 | 251,784 |
|
||||
| · line tables | 203,032 | 74,296 | 248,472 | 271,200 |
|
||||
|
||||
The rebuild's 2026-10-18 optimizer drops every function nothing reaches, with its code,
|
||||
lines and symbols. C's code for the same program is 3.4 times as large.
|
||||
|
||||
## Where a build goes now
|
||||
|
||||
Each compiler building the rebuild's sources of now, profiled with callgrind: the
|
||||
rebuild on one thread, built with `-g`, 15.8G instructions in all; C, 25.8G. Shares are
|
||||
of instructions, inclusive of what each phase calls:
|
||||
|
||||
| Phase | Rebuild | C |
|
||||
|---|---|---|
|
||||
| Reading the files: lexing and parsing | 3.0% | about 2% |
|
||||
| Checking | 7.9% | 6.3% |
|
||||
| Evaluating constants | 0.9% | |
|
||||
| Lowering, less what follows | 14.8% | about 1% |
|
||||
| Working out what calls keep | 1.4%, within the rows around it | 43.9% |
|
||||
| Optimizing, inlining included | 56.5% | 24.6% |
|
||||
| Choosing code and placing values | 14.8% | 20.3% |
|
||||
| Writing the executable, closing what's left | about 1% | about 1% |
|
||||
|
||||
**C spends 44% of a build working out what each call keeps** (`compiler__find_boxes`,
|
||||
through `compiler__keeps`, `compiler__scan_body` and `compiler__receives`), which the
|
||||
rebuild does in 1.4%. C scans functions that call one another by assuming what each
|
||||
keeps and scanning again until that stops growing, and what it found within such a cycle
|
||||
is forgotten each time an enclosing one is scanned again. The compiler's checker and
|
||||
emitter are large cycles of recursive functions, so their scans repeat. The rebuild has
|
||||
worked out each group of recursive functions once, as one, since 2026-10-18. That is
|
||||
most of why C's cost per line doubled since the start: about 11 of its 26 billion
|
||||
instructions.
|
||||
|
||||
**In the rebuild, 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. **What calls keep, in C.** It's 44% of C's build, against 1.4% of the rebuild's.
|
||||
Working each function out once, and recursive ones as a group, as the rebuild does,
|
||||
would take about 40% off C's builds. C's checking costs 1.4 times a line what it did
|
||||
too, and its memory 1.4 to 1.6 times a line. See
|
||||
[Where a build goes now](#where-a-build-goes-now).
|
||||
2. **The code C makes.** The rebuild's optimizer of 2026-10-14 to 10-18 has no C
|
||||
counterpart: vectors in registers, check removal, `select`, moving work out of loops,
|
||||
dropping what nothing reaches, and the orders of atomics. C's executables run 1.94
|
||||
times the instructions, with 2.2 to 3.4 times the code. C's frames copy a word at
|
||||
a time, which keeps its AVX code slower than its SSE2 code.
|
||||
3. **Optimizing in the rebuild.** 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.
|
||||
4. **The rebuild's threads.** Eight give 1.7 times one. Checking, lowering and choosing
|
||||
code run on one thread, which caps what more processors give.
|
||||
5. **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 in the rebuild at this clock, 163 ms and
|
||||
112 MB in C. 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. In the rebuild 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.
|
||||
6. **Line tables,** 53% of the rebuild's executable and 48% of a small program's.
|
||||
7. **The rebuild's VM on calls,** at twice C's VM's time for small calls.
|
||||
8. **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 rebuild's analyzer, built by C | Checking 23,574 lines: 0.09 s, 19 MB, 495M instructions; C's checker 0.11 s, 54 MB, 363M |
|
||||
| 10-08 | The scratch arena | The rebuild 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; C 7.72G, 2.01 s, 175 MB |
|
||||
| 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 |
|
||||
|
||||
What made the rebuild 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;
|
||||
- another promotion pass late in the pipeline, which changed nothing;
|
||||
- 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;
|
||||
- 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 compilers come from the commits:
|
||||
|
||||
```sh
|
||||
git -C malunal.sakura archive 62644a5 | tar -x -C c_start
|
||||
git -C malunal.sakura.rebuild archive e5b7636 | tar -x -C r_start
|
||||
# Build c_start's sources/*.c with the chinook dependencies, -std=c11 -O3 -g.
|
||||
# Build r_start with it, then with that stage, to its fixed point:
|
||||
c_start/sakura build --std r_start/std -O2 -o r_start_c ...
|
||||
r_start_c build --std r_start/std -O2 -o r_start_s1 ...
|
||||
```
|
||||
|
||||
`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 each
|
||||
compiler's work 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.
|
||||
+469
@@ -0,0 +1,469 @@
|
||||
# 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.
|
||||
|
||||
**Built in the rebuild alone** ([roadmap.md](roadmap.md), decision 1). Where this plan
|
||||
says both compilers, C's half is left out. What was measured in C stays as measured.
|
||||
|
||||
**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:
|
||||
- with each compiler, in its machine and as executables at `-O0` and `-O2`;
|
||||
- with the rebuild's `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. Both compilers 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`. Both compilers 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 both compilers' machines and 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 the rebuild's
|
||||
were 5.3, 11 and 5.4 ns.
|
||||
|
||||
| A draw | Rebuild | C |
|
||||
|---|---|---|
|
||||
| 64 bits | 2.5 ns | 5.8 ns |
|
||||
| A number below a bound | 6.8 ns | 12 ns |
|
||||
| A real | 4.0 ns | 9.2 ns |
|
||||
|
||||
In the machines, 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 either compiler's
|
||||
`-O2` executables. A draw below a bound took 28.5 ns checked by it in the rebuild,
|
||||
against 6.8 ns checked by a plain test and `sys::abort()`, and 33 to 36 ns against 12 ns
|
||||
in C. Its default arguments, a `string` among them, are made at every call.
|
||||
|
||||
**Found: C doesn't take a range's type from where the result goes.** `val b: u8 =
|
||||
g.within(0..200)` draws a `u8` in the rebuild, while C makes `0..200` a `range<i64>` and
|
||||
refuses it. Both take `g.within::<u8>(0..200)`, a `range<u8>` variable, and
|
||||
`val b: u8 = g.below(200)`.
|
||||
|
||||
## What's there now
|
||||
|
||||
- **`hash` and `mix`** (`std/traits/hashable.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 rebuild runs a constant and stops
|
||||
where it can't go on. C decides from the call graph, so it refuses anything that could
|
||||
reach `contract::report` ([inconsistencies.md](inconsistencies.md), "Contracts in a
|
||||
constant").
|
||||
|
||||
## 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, in both compilers.
|
||||
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 both compilers' machines and 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`, C refuses every constant drawing in a range,
|
||||
and such a draw takes three to 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, in
|
||||
both compilers. The system's randomness makes a system call, or calls C on Windows,
|
||||
and the shared generator reads a global, so both compilers refuse 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`. Both compilers 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 size_of::<T>() == 4` chooses between them in both compilers, where C
|
||||
refuses `T is f32` ([inconsistencies.md](inconsistencies.md), "Testing a type
|
||||
against another type").
|
||||
- **The type comes from where the result goes,** as `val x: f32 = g.fraction();`.
|
||||
With nothing to say, both compilers ask 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 the rebuild's executables and 18 ns in C's. With four threads drawing at
|
||||
once in the rebuild's, 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`,** in both repositories,
|
||||
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, in both compilers;
|
||||
- a constant from the system or the shared generator being refused, in both
|
||||
compilers' tests.
|
||||
- **Where they run:** in each compiler's machine, as executables at `-O0` and `-O2`, and
|
||||
with `run --checks`. They're also built for `windows-x86_64`. The C compiler must
|
||||
still accept std, since it builds the rebuild.
|
||||
|
||||
## Phases
|
||||
|
||||
About 50 lines of `std::sys`, for Linux and Windows, 600 of `std::random`, and 400 of
|
||||
tests, with no change to either 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` in a constant agreed in both compilers;
|
||||
- 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 the rebuild's 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 (5.8 ns in C's executables), 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 machines, which work vector
|
||||
lanes one at a time. `std::simd` would speed it only in the rebuild's 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. C needs a range of a narrow type written as one, as
|
||||
`within::<u8>(0..200)`, until it takes the type from the declaration (found
|
||||
above).
|
||||
- **(b) Two ends, both included,** as `within(1, 6)`, as this plan first had it. It
|
||||
reads the same in both compilers, 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 in both compilers, 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.
|
||||
+741
@@ -0,0 +1,741 @@
|
||||
# Roadmap: one compiler, and a language that holds
|
||||
|
||||
Written 2026-10-20. The same day you chose the recommended answer to every decision at
|
||||
the end, and steps 1 to 6 were built. Steps 1 and 2 are commit `5a6de39`, 3 and 4
|
||||
`c61f9cd`, and 5 `f9d3a2b`. Step 6 isn't committed.
|
||||
|
||||
**What it is:** the way from today to a rebuild whose language stops changing under the
|
||||
programs written in it, and with it the end of the C compiler. Eight steps:
|
||||
1. `extern` and the `system` library (the ffi plan, built);
|
||||
2. `core`, and a std read as it's imported (the std plan, built);
|
||||
3. contracts in the language (the contracts plan, built);
|
||||
4. what the checks do (the checks plan, built);
|
||||
5. the rules the two compilers disagreed on, settled (built);
|
||||
6. properties as C# writes them, with `this` and `value` implied (built);
|
||||
7. lambdas that own what they use: the last change to the syntax;
|
||||
8. the freeze.
|
||||
|
||||
- **The C compiler gets only what it needs to build the rebuild,** as you said on
|
||||
2026-10-20. Decision 1 says whether that's nothing past today, or whatever each step's
|
||||
std needs until the freeze.
|
||||
- **Plans that only add come after the freeze:** [freestanding.md](freestanding.md), the
|
||||
library plans, [blossom.md](blossom.md) (built on 2026-10-24, at your asking), and the
|
||||
compilers' own speed (decision 5).
|
||||
- **Each step is a plan here,** except:
|
||||
- 5, 6 and 8, which are written out below;
|
||||
- 7, which gets its own plan once you've chosen a direction (decisions 2 and 3).
|
||||
|
||||
## What "stable" means
|
||||
|
||||
From the freeze on, a program the rebuild accepts:
|
||||
- is accepted by every later rebuild;
|
||||
- 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 today
|
||||
(probed).
|
||||
|
||||
Methods are the exception. `core` might later add a method to one of its own types with
|
||||
the same name as one a program declared on that type. Step 5 settles that the program's
|
||||
wins, as it does for names.
|
||||
|
||||
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.
|
||||
|
||||
That sorts everything open today:
|
||||
|
||||
| Before the freeze: it would break programs later | After, or whenever: it only adds |
|
||||
|---|---|
|
||||
| `@foreign`, `@link` and `std::sys` going (step 1) | freestanding.md: a target, attributes, `core::x86_64` |
|
||||
| Which names a file sees, `core`'s root, the types the syntax makes (step 2) | The library plans: algorithms, benchmarks, grammars, linear, logging, random, tui |
|
||||
| `std::contract` going, and what `ensures` does (step 3) | blossom.md |
|
||||
| What `x[k]` checks, zero values, and `raw_allocate` no longer clearing (step 4) | `type_of(f)::name()`, thread-locals, 128-bit integers, documentation as an intrinsic |
|
||||
| Three rules the rebuild gets wrong, two awaiting you, and which method wins (step 5) | Constants without a type, inferring through a reference, `==` of `maybe`, `equatable` for `void` |
|
||||
| `m is nothing` and `(&mut x) as u64` refused; `+=` in place (decision 7) | Rules the rebuild refuses that could be accepted (step 5) |
|
||||
| Properties with `this` and `value` implied, and the old forms refused (step 6) | A property of the type itself, marked, if one's wanted (decision 9) |
|
||||
| How a lambda owns, and whether every lambda has a type of its own (step 7) | Warnings: lambdas returned through a call, handles outliving, reading a moved local |
|
||||
| | `+` joining text, more operator traits, and the compilers' speed |
|
||||
|
||||
**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, since 2026-10-26;
|
||||
- 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.
|
||||
|
||||
## Where it stands
|
||||
|
||||
**Probed** on 2026-10-20, with the repository's `sakura-v1.0.0`, built from the working
|
||||
tree that morning:
|
||||
- **The language has 30 keywords.** The plans add one, `extern`, which nothing in std,
|
||||
the compiler, its tests or its tools uses as a name. Every other word they add means
|
||||
something only where it stands:
|
||||
- `expects`, `asserts`, `ensures` and `old`, from step 3. std has
|
||||
`contract::expects` and `contract::asserts` today.
|
||||
- `undefined`, from step 4. It has to stay that way, since the rebuild's checker
|
||||
names an error kind `ec::undefined`.
|
||||
- `none` as an `os`, from freestanding.md, inside a `when`.
|
||||
- **What each plan changes for programs:**
|
||||
|
||||
| Plan | The grammar | What else programs see |
|
||||
|---|---|---|
|
||||
| Step 1, ffi | `extern import`, `extern module ... when`. `@foreign` and `@link` go | `std::sys` is `system` |
|
||||
| Step 2, std | Nothing | Which names a file sees (decisions 4–6 and 8). The eight types the syntax makes, held by the compiler. A module's files found by its path (decision 3) |
|
||||
| Step 3, contracts | `expects`, `asserts`, `ensures` statements, `old(e)`, `r:` | `std::contract` goes |
|
||||
| Step 4, checks | `= undefined` | What `x[k]` checks (decision 1). Zero values (decision 4). `raw_allocate` stops clearing (decision 6) |
|
||||
| freestanding.md | Nothing: attributes and a target | `@interrupt`, `@align`, `@packed`, `core::x86_64`, `os == none` |
|
||||
| The seven library plans | Nothing: attributes std declares, and `keep` | std gains |
|
||||
| blossom.md | Nothing | A tool beside the compiler |
|
||||
|
||||
- **Lambdas:** there are about 340 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>`.
|
||||
`carrying<A>` stands in for a lambda that owns what it's given: it's how
|
||||
`spawn_with` works.
|
||||
- The compiler's own sources start threads with `spawn_with` three times.
|
||||
- 13 test files write a functor by hand.
|
||||
- **Properties:** there are 183, in std (115), the compiler's own sources (38) and the
|
||||
tests (30). Three are declared in traits.
|
||||
- All 184 getters are `get(&this)`.
|
||||
- All 15 setters are `set(&mut this, to)`. Four give `to` a type, always the
|
||||
property's own.
|
||||
- The only accessors that don't use `this` are one test's stub, `dot::width`.
|
||||
- No property belongs to a type rather than a value, since accessors must take
|
||||
`this`. What belongs to a type is one of 52 associated variables, as
|
||||
`val permissions::owner_read := 0o400;`.
|
||||
- **The rules the compilers disagree on:** inconsistencies.md's "Rules of the language"
|
||||
lists 15. The rebuild was wrong about 3 of them, and 2 waited on your decision. Step 5
|
||||
settled all of them.
|
||||
|
||||
## The steps
|
||||
|
||||
| # | Step | Size, rebuild only, from each plan | Two-step bootstrap |
|
||||
|---|---|---|---|
|
||||
| 0 | C's last build (decision 1) | None | — |
|
||||
| 1 | The ffi plan, all of it | About 300 lines; 4,100 moved | Yes. The attributes stay valid beside `extern` for one step (its decision 4) |
|
||||
| 2 | The std plan, phases 1 to 5 and 7 | About 700 lines; 10,000 moved | Yes, for phases 2 and 3 |
|
||||
| 3 | The contracts plan, all of it | About 400 lines | Yes, when std's `contract::` calls become statements |
|
||||
| 4 | The checks plan, all of it | Not estimated in the plan; about 1,200 lines as built | Yes, as `core` gains `checking()` and `raw_allocate_zeroed` |
|
||||
| 5 | The rules | Three fixes, a rule for methods, two decisions, three items from later.md; about 470 lines as built | None was needed: nothing std or the sources use was refused |
|
||||
| 6 | Properties | Small: the parser and checker give accessors their parameters, and a script rewrites the 183; about 150 lines as built | Yes: a first stage from copies whose accessors are written as before (later.md) |
|
||||
| 6½ | References and values, one rule | About 450 lines as built, and 130 places given `&` | Plain: today's sources build with `sakura-v1.0.0`, then with themselves |
|
||||
| 7 | Lambdas that own what they use | Its own plan | Yes, when std's `spawn` starts taking them |
|
||||
| 8 | The freeze | The README, a corpus, the bootstrap rule | — |
|
||||
|
||||
**Steps 1 to 6 are built, and so is the rule for references and values between 6 and 7.** The plans of steps 1 to 4 were deleted once built, as
|
||||
earlier plans were, and [later.md](later.md) holds what they left. Steps 5 and 6 have
|
||||
their "As built" below. later.md's "The repository's compiler" says how step 5's compiler, which
|
||||
`sakura-v1.0.0` is since it was rebuilt at 20:01, builds today's sources, and where the
|
||||
chain from the seed has a gap.
|
||||
|
||||
**The order:**
|
||||
- **The ffi plan comes first,** as each plan says.
|
||||
- **The std plan comes next.** Contracts fail through its `fault`, and every later step adds
|
||||
to the std it lays out.
|
||||
- **The checks plan follows the contracts plan.** Its decision 5 shrinks to the containers' faults
|
||||
once contracts are statements.
|
||||
- **Step 5 can run beside steps 2 to 4.** Its fixes are small, and only decisions 6 and
|
||||
7 hold it up.
|
||||
- **Step 6 can come any time after step 1.** It's small and mechanical, and only
|
||||
decisions 8 and 9 hold it up.
|
||||
- **Step 7 is last,** as you asked.
|
||||
|
||||
**The std plan's phase 6 is left until after the freeze.** That's the one moving
|
||||
`std::regex`, `std::uri`, `std::version` and the formats. It's std's business, and
|
||||
blossom fetches the packages.
|
||||
|
||||
### 0. The C compiler's last build (decision 1)
|
||||
|
||||
**Decided: (a), and done.** The seed is the rebuild's commit `420783d`, which your
|
||||
working tree matched when step 1 began. Checked on 2026-10-20:
|
||||
- C's working tree builds it;
|
||||
- that stage builds it again, and that one builds it a third time, the same to the byte.
|
||||
|
||||
C's working tree isn't committed, so commit it: the seed's builder should be a commit
|
||||
too.
|
||||
|
||||
**Under (a),** the seed is the last commit C builds.
|
||||
- From then on, each stage is built by the one before. A step that changes what std or
|
||||
the sources are written in leaves a commit that its successor is built from, as the
|
||||
bootstraps since 10-09 have.
|
||||
- `tools/bootstrap.sh` would walk that chain from C. Each link is a commit you make.
|
||||
Until it exists, the notes in later.md's "The repository's compiler" are the recipe.
|
||||
- The C repository stays as it is, with a README line saying what it builds.
|
||||
- Nothing more is mirrored into its std.
|
||||
|
||||
**Under (b),** C learns what the rebuild's own sources and the std they read use, on
|
||||
Linux, and nothing else. That means no optimizer, Windows, language-server or
|
||||
freestanding work:
|
||||
- step 1: `extern` sections, and `system`'s new paths in its table of intrinsics;
|
||||
- step 2: `core` found beside its executable, `core`'s names seen everywhere, the eight
|
||||
types, and the rules of decisions 4 to 6. That's most of the std plan's half for C, since
|
||||
the rebuild's sources read `core`;
|
||||
- step 3: the statements parsed and left out, as `--contracts off` does;
|
||||
- step 4: what std's code uses;
|
||||
- step 6: properties' new form;
|
||||
- step 7: lambdas that own, where std's `spawn` takes them.
|
||||
|
||||
The freeze's commit is then the seed.
|
||||
|
||||
### 5. The rules, settled
|
||||
|
||||
When C stops, the rebuild's behavior becomes the language unless it's changed here.
|
||||
inconsistencies.md's "Rules of the language":
|
||||
|
||||
| Rule | What the rebuild does | Settled as |
|
||||
|---|---|---|
|
||||
| Redeclaring in the same scope | Takes it | Decision 6 |
|
||||
| `&` of a union's owning field | Takes it | Decision 6 |
|
||||
| `&mut` of a union's field | Takes it | Decision 6 |
|
||||
| Returning an owning local into a union | Takes it, and closes it once | The rebuild's |
|
||||
| A function ending in `while true` | Refuses it | The rebuild's, for now. Accepting one with no `break` is an addition |
|
||||
| Type arguments given to overloads | Picks by the receiver | The rebuild's |
|
||||
| Inferring from a lambda through overloads | Refuses it | The rebuild's, for now. Accepting is an addition, and step 7 removes `spawn_with`, the reason it was wanted |
|
||||
| A range's type from where it goes | Takes the declared type | The rebuild's |
|
||||
| A float constant where `T: numeric` | Takes it | The rebuild's |
|
||||
| Comparing a `string` with a `strview` | Takes it, and answers wrong | **Fixed: refused,** as the README says |
|
||||
| A property of type `void` | Takes it | **Fixed: refused,** as it was meant to be |
|
||||
| A full path to a module not imported | Takes it | The rebuild's, by the std plan's decision 6 |
|
||||
| A generic type's own variables | Takes the declaration, and reads it wrong | **Fixed: the declaration refused.** Making it work is an addition |
|
||||
| A property as a value | Refuses it | The rebuild's. Accepting is an addition |
|
||||
| `cfn` as a key | Not hashable | The rebuild's. Making it hashable is an addition |
|
||||
|
||||
**A method a program declares on a type of `core`'s** wins over one `core` adds later
|
||||
with the same name. That makes adding methods an addition. It sits beside the std plan's
|
||||
decision 5, which says where such methods are seen.
|
||||
|
||||
**A library's child sees its root's names without an import,** as it does today. You
|
||||
decided this on 2026-10-20, the question the std plan had left open. Where the root's
|
||||
code isn't there, that must be an error that's easy to catch.
|
||||
|
||||
From later.md, decision 7 takes the items that would break programs if done later:
|
||||
- **`m is nothing` refused.** It's never true of a `maybe`, so any program writing it
|
||||
has a mistake.
|
||||
- **`(&mut x) as u64` refused.** An integer conversion of a reference written `&x` or
|
||||
`&mut x` gives the value, not the address. Converting to a pointer stays the way to
|
||||
the address.
|
||||
- **`+=` in place.** `x += y` calls the type's `add_assign`, where it has one, and is
|
||||
`x = x + y` otherwise. Done after the freeze, it would start calling a method that a
|
||||
program had named `add_assign` for its own reasons.
|
||||
|
||||
**Set aside for good:** references that are never moved. Refusing a `var` reference
|
||||
given another one would break programs walking a chain (later.md).
|
||||
|
||||
**As built,** on 2026-10-20, in the rebuild only:
|
||||
- **Refused, each with a note where it's written:**
|
||||
- **A name declared twice in one block,** including one an `is not` test names for the
|
||||
rest of the block. A parameter, a block within, a loop's body and a function within
|
||||
may still declare it again, as C has it. Each block keeps where its names begin
|
||||
(`checker::check_redeclared`).
|
||||
- **`&mut` of a union's field,** or of anything within one, and **`&`** where what it
|
||||
refers to closes (`checker::check_lends_field`). A C union's fields are lent as
|
||||
before, since it holds no tag.
|
||||
- **A property of type `void`,** and **a variable declared through a generic type.**
|
||||
- **`x is T` of a union where `T` is one of its fields' types,** as `m is nothing`. The
|
||||
note names the field. In generic code it's asked of the template, not of each
|
||||
instance.
|
||||
- **`&x as` a number, `bool` or enum.** A reference held in a variable still converts
|
||||
as its value.
|
||||
- **A `string` compared with a view,** either way round. A literal still compares with
|
||||
either.
|
||||
- **A member a program declares on `core`'s type** with a name `core` gives the type too
|
||||
is kept in a chain of its own (`decls.added`), and isn't a duplicate of `core`'s, even
|
||||
with the same parameters. Wherever it's seen, it's chosen. `core`'s overloads are tried
|
||||
only where none of the program's takes the arguments, for calls, operators and paths
|
||||
alike (`checker::overloads_for`). `core`'s own code never sees the program's, and a
|
||||
trait's conformance looks at both chains. A method and a property may share a name
|
||||
this way too. So may a type a program declares through `core`'s, as `type
|
||||
bool::storage = bit;` for a trait asking for one, which the corpus does, and a member
|
||||
or type `core` gives that name.
|
||||
- **`+=` in place:** ten names, `add_assign` to `shift_right_assign`. Where the target's
|
||||
type has one taking the value, the compound assignment calls it on the target, through
|
||||
a property or an element too, and writes nothing back. Through a property, `set` takes
|
||||
what `get` gave, changed. Elsewhere it's `x = x + y`, as before. One giving a value is
|
||||
refused. Nothing in std has one yet: `string`'s would
|
||||
come with joining text by `+` ([later.md](later.md#joining-text-with-)).
|
||||
- **A child module sees the names of those holding it,** as before. Where no file of one
|
||||
was read, as a library's root left out, "`helper` is not declared where it is used"
|
||||
goes on to say which module has no file.
|
||||
- **Almost nothing in the tree was refused:** std, the compiler, its tests and its tools
|
||||
check clean under every new rule, and one corpus program compared a `string` with a
|
||||
view, which now writes `view()`. So step 4's compiler builds step 5's sources, and no
|
||||
bootstrap step was needed.
|
||||
- **Measured:** the compiler checking itself on one core at 2.1 GHz takes 324 ms with
|
||||
step 4's checker and with step 5's alike.
|
||||
- **Checked:** the fixed point, and one built on one thread is the one built on eight;
|
||||
`sakura-v1.0.0` builds it in two steps; the unit tests, 266; the corpus, 144, in the
|
||||
VM, natively at `-O0` to `-O2`, with `run --checks` and built with `--checks`;
|
||||
`test/checked` and `test/memory`, 12 each; std's tests, 259, in the VM and natively,
|
||||
checked and not, and under `run --checks`. The compiler and std's tests build for
|
||||
Windows, where nothing was run.
|
||||
- **Tests:** seven checker tests, and a corpus program,
|
||||
`compound_assignments_change_in_place_where_a_type_can_1`, which grows a `string` in
|
||||
place through a property too.
|
||||
- **Found and fixed while building it:** `+=` in place through a property of a type
|
||||
that closes closed what `get` gave after `set` had taken it, a double free that
|
||||
`run --checks` and valgrind showed.
|
||||
|
||||
### 6. Properties, as C# writes them (decisions 8 and 9)
|
||||
|
||||
A getter always takes `&this`. A setter always takes `&mut this` and a value of the
|
||||
property's type. Nothing else is possible, so writing them out says nothing.
|
||||
|
||||
Today:
|
||||
|
||||
```sakura
|
||||
var rect::width: f32 {
|
||||
get(&this) { return this.w; }
|
||||
set(&mut this, to) { this.w = to; }
|
||||
}
|
||||
```
|
||||
|
||||
After:
|
||||
|
||||
```sakura
|
||||
var rect::width: f32 {
|
||||
get => this.w;
|
||||
set { this.w = value; }
|
||||
}
|
||||
|
||||
var rect::height: f32 {
|
||||
get => this.h;
|
||||
set => this.h = value;
|
||||
}
|
||||
|
||||
val rect::area: f32 { get => this.width * this.height; }
|
||||
|
||||
trait sized {
|
||||
val size: u64 { get; }
|
||||
}
|
||||
```
|
||||
|
||||
- **`get` has `this`, as `&this`.** **`set` has `this`, as `&mut this`, and `value`, of
|
||||
the property's type.** They're there whether the body uses them or not.
|
||||
- **An accessor has a body, `=> expression;`, or `;`,** `get` and `set` alike. The `;` is
|
||||
for a trait, as now. `=> expression` is how a lambda and a match arm already give one
|
||||
value. A setter's `set => this.h = value;` takes it too, as you asked on 2026-10-20,
|
||||
since assigning is an expression.
|
||||
- **`value` is a word only inside a `set`,** and acts as a parameter's name would.
|
||||
`result`'s field is untouched: with a parameter named `value`, `r is value(&p)` and a
|
||||
match's `value(n) =>` still work (probed).
|
||||
- **`pub get` and `pub set` keep their own visibility,** as now.
|
||||
- **The old forms, `get(&this)` and `set(&mut this, to)`,** are accepted beside the new
|
||||
for one bootstrap step, then refused (decision 8).
|
||||
- **No getter takes `&mut this`,** and none of the 184 does today. If one's wanted later,
|
||||
a written `get(&mut this)` would be an addition.
|
||||
- **Methods keep `&this` written.** A method may take `&this`, `&mut this` or neither,
|
||||
and the first two may overload each other, so there the receiver says something.
|
||||
|
||||
**A property that doesn't use `this`** (decision 9). You suggested that where neither
|
||||
accessor uses `this`, the property could also be reached through its type, as
|
||||
`rect::unit`, without being required to. The trouble is that what a property is to its
|
||||
callers would then hang on its bodies:
|
||||
- A getter that starts using `this`, say to read a field, would take `rect::unit` away
|
||||
from every caller reaching it that way. That's an edit inside a body breaking
|
||||
programs, which the freeze promise rules out.
|
||||
- A trait's `{ get; }` has no body to look at.
|
||||
- The language server would have to read bodies to offer `rect::` completions.
|
||||
|
||||
Nothing needs it yet: nothing in the tree is a property of a type, and its associated
|
||||
variables, trait constants and static functions do that job. So the recommendation is
|
||||
that a property always belongs to a value.
|
||||
|
||||
If a type's own property is wanted, it's better said in the declaration, the way a
|
||||
method without `&this` is static. For example, `get()` with an empty list takes nothing,
|
||||
so it's the type's. That can come after the freeze as an addition, or now.
|
||||
|
||||
**As built,** on 2026-10-20, in the rebuild only, with decisions 8(a) and 9(a):
|
||||
- **`get` and `set` take nothing in parentheses.** The body is a block, `=> expression;`,
|
||||
or `;` in a trait. `=>` gives what a `get` returns, and is what a `set` does, as `set =>
|
||||
this.w = value;`. The parser makes it a block holding that `return` or statement, as
|
||||
it does for `return x if c;`, so nothing after it changed.
|
||||
- **The parameters are implied:** the parser makes `this` and a `set`'s `value` itself,
|
||||
marked `implied`, with the `get` or `set` for their token, since a name comes from a
|
||||
token. `checker::param_name` gives their names where they're bound, in debugging
|
||||
information and in reflection. The language server's `local_text` gives them where it
|
||||
shows a local: hover gives `value: int` and `this: &r`, completion offers both, and
|
||||
renaming refuses both. The `get` or `set` itself is never taken for them.
|
||||
- **`value` is a word only inside a `set`.** Elsewhere it's an ordinary name, and a
|
||||
`result`'s field keeps it.
|
||||
- **The written form is refused,** with a note at its `(` showing the form now, as "A
|
||||
`set` takes no parameters written: it has `this`, and `value` of the property's type,
|
||||
as `set => this.w = value;` or `set { this.w = value; }`." It's still read, so what
|
||||
follows it is checked as it means.
|
||||
- **Rewritten by a script,** in 64 files of `core`, std, the sources, the tests and the
|
||||
corpus: 192 getters, 163 of them to `=>`, 25 blocks and 4 `get;`, and 18 setters, 14
|
||||
to `=>`, 2 blocks and 2 `set;`, with `to` renamed `value`. Nothing needed rewriting by
|
||||
hand.
|
||||
- **The decision 8 step was done another way.** Rather than one compiler accepting both
|
||||
forms, the bootstrap writes copies back to the old form for the first stage, so the
|
||||
compiler refuses the old form from the start. later.md's "The repository's compiler"
|
||||
has the recipe from `sakura-v1.0.0`, checked to reach the fixed point.
|
||||
- **No getter takes `&mut this`,** and decision 9 leaves every property a value's.
|
||||
- **Measured:** checking the compiler takes 324 ms with step 5's checker on its form of
|
||||
the sources and with step 6's on theirs.
|
||||
- **Checked:** the fixed point, one thread or eight alike; the unit tests, 268; the
|
||||
corpus, 144, in the VM, natively at `-O0` to `-O2`, with `run --checks` and built with
|
||||
`--checks`; `test/checked` and `test/memory`, 12 each; std's tests, 259, everywhere.
|
||||
The compiler and std's tests build for Windows, where nothing was run.
|
||||
- **Tests:** a parser test of both forms of body and of the written form refused, a
|
||||
checker test of `this`, `value` and their types, and a language server test of hover
|
||||
and renaming.
|
||||
|
||||
### 6½. References and values, one rule (asked on 2026-10-21)
|
||||
|
||||
Copies and moves followed one rule already: a value that closes is never copied
|
||||
implicitly. References followed two. They were read through, and taken at a call
|
||||
without `&`, as in C++, but they were also types that stacked (`&&T`), were inferred
|
||||
for `T`, were pointed elsewhere by `r = s`, and were carried along by `:=`, as in Rust.
|
||||
So `val e := v[0]` referred to the element while `val e := a[0]` of a fixed array and
|
||||
`val y := v[0].x` copied, `max(v[0], v[1])` gave a reference into `v`, and a function
|
||||
taking `&T` wasn't accepted where one taking `T`, `&mut T` or `&&T` was asked.
|
||||
|
||||
**The rule:** where a value goes says what happens to it. A reference type lends it,
|
||||
and any other type gives it: a new value moves, a place is copied where it closes
|
||||
nothing, and one that closes is refused. Only `&` or `&mut` written, or a reference
|
||||
parameter at a call, makes a reference.
|
||||
|
||||
1. **Giving:** `:=`, a `T` parameter, a field, an element, `return`, `=`, `is some(v)`,
|
||||
`for x in`, and what a lambda's `=>` gives.
|
||||
2. **Lending:** a `&T` or `&mut T` parameter, result or field, `val r := &x`,
|
||||
`is some(&v)`, `for &x in`. `&mut` needs what can be written, or what `&mut` reaches.
|
||||
3. **References never stack:** `&` of a reference is that reference.
|
||||
4. **Inference sees values:** a `T` parameter given `v[0]` takes an `i64`, and `f(&x)`
|
||||
a reference.
|
||||
5. **Assigning writes through:** `r = s` writes what `s` reaches; `r = &y` points `r`
|
||||
at `y`.
|
||||
6. **Function values are called as the type asks:** a named function given where a
|
||||
function type it doesn't match is expected is called by a function made for it,
|
||||
as a call would call it: defaults filled, arguments lent or read through, the
|
||||
overload a call chooses.
|
||||
|
||||
Asked on 2026-10-22, with it: a reference written as one is a pointer where one is
|
||||
expected, and `core` has `address(x)`, `*mut T` or `*T`, beside `through(p)`.
|
||||
|
||||
**As built,** on 2026-10-22, in the rebuild only:
|
||||
- **One decision per node.** Each place a reference is taken as its value, or `&` of
|
||||
a reference is that reference, notes it on the node (`rf::valued`, `rf::relent`).
|
||||
An instance takes the template's decision, so where `T` is a reference, a `T` is
|
||||
still the value the template meant: `vector<&T>::append` stores the reference, and
|
||||
`move(&mut x)` of a `T` moves it. Collapsing `&&T` in the types themselves broke
|
||||
exactly this, and was dropped.
|
||||
- **A reference to a trait** is taken as it is wherever a value would be, since no
|
||||
value is of a trait. Refusing it instead would have changed every
|
||||
`some(held)` of a `maybe<&mut allocator>`.
|
||||
- **Adapters** are functions the emitter makes for each place a function is named
|
||||
so: `function_value` gives one where the checker marks the node `rf::adapted`.
|
||||
`call_site()` in a default is where the function is named.
|
||||
- **Overloads:** a writable argument is better lent to a `&mut` parameter than a `&`
|
||||
one, as receivers already were, so `address(x)` of a `var` gives a `*mut`.
|
||||
- **Found by the change:** `dict`'s key and value cursors returned `&entry.key` of a
|
||||
copy once `is some(entry)` copied, which `run --checks` stopped at; they name the
|
||||
entry with `&` now. Temporary warnings listed every `var` that had held a reference,
|
||||
every assignment that had pointed one elsewhere, and every `&` of a copy, and each
|
||||
was read.
|
||||
- **Rewritten:** 120 bindings and patterns in the sources, `core`, std and the tests
|
||||
gained `&` or `&mut`, as `val syntax := &this.units[file].syntax;`, and 12 loops
|
||||
became `for &x`. The compiler errors named each of them.
|
||||
`integer::parse` and `real::parse` could take `strview` again, which is yours to
|
||||
change back.
|
||||
- **Measured:** checking the compiler takes 0.35 s, and building it at `-O2` 3.4 s,
|
||||
with the compiler from before and with this one. Built under the rule, the
|
||||
compiler is 13 KB larger, 0.15%, from the copies its bindings make now.
|
||||
- **Checked:** the two steps from `sakura-v1.0.0` to the fixed point; the unit tests,
|
||||
271, but for gdb's, which failed the same way before; the corpus, 148, in the VM,
|
||||
natively at `-O0` to `-O2`, with `run --checks` and built with `--checks`;
|
||||
`test/checked` and `test/memory`, 12 each; std's tests, 259, everywhere. The
|
||||
compiler and std's tests build for Windows, where nothing was run.
|
||||
- **Tests:** two checker tests, of the rule and of the functions called as a type
|
||||
asks, and two corpus programs, `references_are_lent_and_values_given_1` and
|
||||
`named_functions_are_called_as_the_type_asks_1`. Seven tests written for the old
|
||||
rule now say the new one, as `indexing_gives_the_reference_at_gives_1`.
|
||||
|
||||
What it left is in [later.md](later.md#references-and-values-what-the-rule-left).
|
||||
|
||||
### 7. Lambdas that own what they use (decisions 2 and 3)
|
||||
|
||||
**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)
|
||||
```
|
||||
|
||||
**Already turned down, on 2026-10-19:**
|
||||
- a list in brackets, as C++ has, either of initializers (`[count = 0]`) or of words
|
||||
(`[move log, level]`);
|
||||
- `move def`, as Rust has.
|
||||
|
||||
**What any direction 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` and only one compiler
|
||||
has to know it.
|
||||
- **`spawn` takes anything `invokable`.** `spawn_with` and `carrying` go.
|
||||
- **A lambda that refers to locals keeps today's rules,** and today's warnings.
|
||||
|
||||
**The directions** (decision 2):
|
||||
|
||||
**(a) 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.
|
||||
|
||||
**(b) Values bound by std, with no syntax.** `bind(f, values...)` gives a functor that
|
||||
holds the values and passes them by `&mut`, ahead of the call's arguments: `spawn_with`
|
||||
for any lambda.
|
||||
|
||||
```sakura
|
||||
return function::new(bind(def(count: &mut i64): i64 { count++; return count; }, 0));
|
||||
thread::spawn(bind(def(lines: &mut vector<string>) { write_all(lines); }, move(&mut lines)));
|
||||
```
|
||||
|
||||
The language doesn't change at all. The lambda's parameter types are written, as they
|
||||
are for `spawn_with` today. It could be built as well as (a), or before it.
|
||||
|
||||
**(c) Declared in the body, with a word saying they're made with the lambda:**
|
||||
|
||||
```sakura
|
||||
return def(): i64 {
|
||||
own var count := 0;
|
||||
count++; return count;
|
||||
};
|
||||
```
|
||||
|
||||
It reads like the body, but it runs at a different time than the lines under it.
|
||||
`own` would mean something only before `val` or `var`, since std uses it as a name.
|
||||
|
||||
**(d) Functors, as now.**
|
||||
|
||||
Recommended: **(a)**. It's the smallest change to the language: one rule on a list
|
||||
every lambda already has, in words the language already uses.
|
||||
|
||||
**Which lambdas get a type of their own** (decision 3):
|
||||
- Under every direction, a lambda that owns needs one.
|
||||
- Giving one to every lambda would let generic code take each lambda as its own type, so
|
||||
a lambda would cost what a functor does:
|
||||
- the adapters, which cost 4 to 9 times functors today (later.md, "Lambdas given to
|
||||
adapters");
|
||||
- a sort's order, which no optimization reaches otherwise (algorithms.md,
|
||||
decision 4).
|
||||
|
||||
A lambda would still convert to a function type wherever one is expected. 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
|
||||
```
|
||||
|
||||
Each place in the tree that gives a lambda to a variable already declares a function
|
||||
type (probed), so nothing in the tree is refused. It changes what programs mean, so it's
|
||||
now or never.
|
||||
|
||||
**Its own plan,** written once steps 5 and 6 are done, measures and builds the
|
||||
direction you choose.
|
||||
|
||||
### 8. The freeze (decision 4)
|
||||
|
||||
- **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 `test/programs` uses yet, each with its `.out`. A change that breaks one fails a
|
||||
test.
|
||||
- **inconsistencies.md goes.** Its rules are settled by step 5. Its VMs and code
|
||||
generation are C's, which decision 1 retires.
|
||||
- **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;
|
||||
- so the chain from C stops growing at the freeze.
|
||||
- **std is found as `core` is,** and `--std` and `SAKURA_STD` go. Built on 2026-10-26,
|
||||
as the README says: `--lib std=DIR`,
|
||||
else beside or above the compiler, else where `blossom install` puts it. There's one compiler by then, under
|
||||
either answer to decision 1.
|
||||
|
||||
## What this changes in the other plans
|
||||
|
||||
- **Each plan's phases say "in both compilers".** Each plan now says, beside its
|
||||
ffi line, that it's built in the rebuild alone.
|
||||
- **The bootstrapping lines change.** The std and contracts plans said "C builds the
|
||||
rebuild directly throughout". Under 1(a), the chain did that.
|
||||
- **The plans that only add** wait for the freeze (decision 5). Their "Comes after the
|
||||
ffi plan" lines still hold.
|
||||
- **inconsistencies.md:** its "What runs while compiling", "The VMs" and "The code each
|
||||
makes" stop mattering under 1(a). Only its rules are left, for step 5.
|
||||
|
||||
## Found along the way
|
||||
|
||||
- **A program's own type named as a built-in hides it.** `struct u32 { var lo: u64; }`
|
||||
builds and runs. So a built-in type, such as `i128`, can come after the freeze.
|
||||
- **`undefined` is a name in the rebuild,** `ec::undefined`, so the checks plan's
|
||||
`= undefined` must be a word only where it stands.
|
||||
- **A parameter named `value` hides nothing a setter needs.** `r is value(&p)` and a
|
||||
match's `value(n) =>` on a `result` still work beside it, so `set`'s implied `value`
|
||||
can be a plain name.
|
||||
- **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>`;
|
||||
- a `val maybe: def(): int` chosen by `?:`.
|
||||
|
||||
No array holds lambdas. So decision 3(a) refuses nothing in the tree.
|
||||
- **The built-in types are read as `module core`,** and a program with no `module` line
|
||||
is module 0, which holds every module. So a program's member on a built-in type was
|
||||
"seen" from `core`'s own code too, which step 5 had to keep to `core`'s own members.
|
||||
- **The comparison of a `string` with a view had answered right since the std plan,** by
|
||||
making a `string` of the view, which allocates. Step 5 refuses it all the same.
|
||||
- **A program's method named as a property of `core`'s,** as `string::is_empty`, was a
|
||||
duplicate reported at `core`'s line, before step 5.
|
||||
|
||||
## Decisions for you
|
||||
|
||||
**Decided 2026-10-20:** the recommended answer to each.
|
||||
|
||||
1. **Where the C compiler stops:**
|
||||
- **(a) At a seed today:** your next commit of the working tree. It's the last commit
|
||||
C builds, and the rebuild builds each one after it.
|
||||
- **(b) At the freeze,** learning until then what the rebuild's own sources and the
|
||||
std they read use, on Linux.
|
||||
|
||||
Recommended: **(a)**.
|
||||
- It saves the C half of every step: about 300 lines for the ffi plan, 700 for the std
|
||||
plan, 400 for the contracts plan, and keeping C's std in step with the rebuild's.
|
||||
- What's lost is the corpus run under two compilers, which found most of
|
||||
inconsistencies.md. The `.out` files still hold every answer.
|
||||
- Two-step bootstraps are what each change since 10-09 has needed anyway.
|
||||
2. **How a lambda owns what it uses:**
|
||||
- **(a) `val` and `var` parameters, made where the lambda is written.**
|
||||
- **(b) std's `bind`,** with no syntax.
|
||||
- **(c) `own val` and `own var` in the body.**
|
||||
- **(d) Functors, as now.**
|
||||
|
||||
Recommended: **(a)**, with (b) worth building beside it if a library wants it.
|
||||
3. **Which lambdas have a type of their own:**
|
||||
- **(a) Every lambda,** converting to a function type where one is expected.
|
||||
- **(b) Only those holding values of their own.**
|
||||
|
||||
Recommended: **(a)**. Owning lambdas need the machinery anyway, and it makes every
|
||||
lambda cost what a functor does. What it refuses doesn't occur in the tree, and it's
|
||||
now or never. The cost is an instance of generic code for each lambda given to it,
|
||||
which step 7's plan would measure.
|
||||
4. **What the freeze promises:**
|
||||
- **(a) Additions only, from then on.** A program accepted keeps being accepted and
|
||||
keeps its meaning. New words mean something only where they stand.
|
||||
- **(b) Editions:** (a) within an edition, while a new edition may change things. A
|
||||
file or blossomfile names its edition, so old programs build as they did.
|
||||
- **(c) Nothing until a 1.0 tag.** The freeze is a candidate, and changes stay
|
||||
possible while you write programs in it.
|
||||
|
||||
Recommended: **(a)**. Editions can come later without breaking it, since a file that
|
||||
names none would be of the first.
|
||||
5. **When the plans that only add are built:**
|
||||
- **(a) After the freeze.** They're then written against the language as it stays.
|
||||
- **(b) freestanding.md before the freeze, and the rest after.** It's what you want
|
||||
the language for, and it changes nothing that's there.
|
||||
- **(c) Whenever wanted,** once the std plan is built.
|
||||
|
||||
Recommended: **(a)**. Each one built first puts the freeze further off, and none of
|
||||
them needs it to wait.
|
||||
6. **Rules the rebuild accepts that C refused,** where refusing is the safer side:
|
||||
- **(a) Refuse them, as C does:**
|
||||
- `val x` declared twice in one scope;
|
||||
- `&` and `&mut` of a union's field, which lend the field without asking which
|
||||
field the union holds.
|
||||
|
||||
`is value(&p)` and `is some(&mut q)` stay the way in. Accepting either later is an
|
||||
addition.
|
||||
- **(b) Keep the rebuild's:** names redeclared in the same scope, as Rust has it,
|
||||
and a union's field lent as it is.
|
||||
- **(c) Split:** redeclaring kept, the union's fields refused.
|
||||
|
||||
Recommended: **(a)**. Step 5 counts the places std and the sources use them, and
|
||||
changes them.
|
||||
7. **later.md's items that would break programs if done later:**
|
||||
- **(a) All three before the freeze:**
|
||||
- `m is nothing` refused;
|
||||
- `(&mut x) as u64` refused;
|
||||
- `+=` calling `add_assign` where a type has one.
|
||||
- **(b) The two refusals only.** `+=` stays `x = x + y` for good.
|
||||
- **(c) None.**
|
||||
|
||||
Recommended: **(a)**. Otherwise `+=` on a `string`, or on anything else that owns
|
||||
memory, allocates every time, and building text with `+=` is common.
|
||||
8. **How accessors are written:**
|
||||
- **(a) `get` and `set` with nothing in parentheses,** and a body, `=> expression;`
|
||||
or `;`. The old forms are accepted for one bootstrap step, then refused.
|
||||
- **(b) The same, with the old forms kept** as a longer spelling.
|
||||
- **(c) Without `=>`:** bodies and `;` only.
|
||||
|
||||
Recommended: **(a)**. There's one way to write it, and `=>` is how the language
|
||||
already writes a body that gives one value.
|
||||
9. **A property that doesn't use `this`:**
|
||||
- **(a) It still belongs to a value.** What belongs to a type is an associated
|
||||
variable, a trait's constant, or a static function. A marked form, as (c), can be
|
||||
added after the freeze.
|
||||
- **(b) Inferred, as you suggested:** where no accessor uses `this`, it may be
|
||||
reached through its type as well.
|
||||
- **(c) Marked now:** `get()`, with an empty list, takes nothing, so the property is
|
||||
its type's, reached as `rect::unit`.
|
||||
|
||||
Recommended: **(a)**. Under (b), an edit inside a body could break callers, and a
|
||||
trait's property has no body to tell by. Nothing in the tree needs a type's property
|
||||
yet, and (c) stays open.
|
||||
+843
@@ -0,0 +1,843 @@
|
||||
# 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.
|
||||
|
||||
**Built in the rebuild alone** ([roadmap.md](roadmap.md), decision 1). Where this plan
|
||||
says both compilers, C's half is left out. What was measured in C stays as measured.
|
||||
|
||||
**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 compilers' 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 both
|
||||
compilers and run as an executable and in each VM, and all four 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 in both
|
||||
compilers (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 in the rebuild and 165 ms in C.
|
||||
- `std/yaml`'s 4,498 lines cost 12 ms of that in the rebuild and 24 ms in C, and
|
||||
`std/time`'s and `std/thread`'s 1,965 lines 5 and 13 ms. That's about 2.6 ms per
|
||||
1,000 lines in the rebuild, and 5 to 7 in C.
|
||||
- So the 2,500 or so lines this plan adds to std would add about 6.5 ms to checking
|
||||
every program in the rebuild, and 13 to 17 ms in C, at that clock: 7% of a one-line
|
||||
program's check in the rebuild, and 8 to 10% in C.
|
||||
|
||||
## 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 in both compilers).
|
||||
- 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 VMs 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, under both compilers.
|
||||
- **Where they run:** in the VM, under `run --checks`, and as executables at `-O0` and
|
||||
`-O2`. The rebuild's 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 each compiler, and a few lines to each
|
||||
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 both compilers and both
|
||||
runtimes.
|
||||
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, in both compilers, 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`, in both
|
||||
compilers. 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 in the rebuild and 4 to 6 in C, 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 both VMs 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 each 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 in both compilers):
|
||||
- **(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