| @@ -1,13 +1,35 @@ |
| 1 | | −# Runtime ABI v0 |
| 1 | +# Runtime ABI |
| 2 | 2 | |
| 3 | | −The contract between C emitted by `tilc` and the Rust runtime `tilrt`. It covers value representation, heap layout, the execution context, calling conventions and unwinding. |
| 3 | +The contract between C emitted by `tilc` and the Rust runtime `tilrt`. It covers value representation, heap layout, the execution context, calling conventions, unwinding, and what the runtime does for actors, handlers and the standard library. |
| 4 | 4 | |
| 5 | | −- **Normative source:** [`runtime/tilrt/include/tilrt.h`](../runtime/tilrt/include/tilrt.h). This document explains it. |
| 5 | +- **Normative source:** [`runtime/tilrt/include/tilrt.h`](../runtime/tilrt/include/tilrt.h). This document explains it. The header says which part C bindings may use; the rest is for generated code. |
| 6 | 6 | - **Rust mirror:** `runtime/tilrt/src/abi.rs` mirrors the layouts. Both sides assert them at compile time. |
| 7 | | −- **Change rule:** change both together and bump `TL_ABI_VERSION`. |
| 8 | | −- **Status:** v0, validated by the [M0 spike](#validation-the-m0-spike). Accepted 2026-10-08 by the project owner (issue #2), including Revision 1. |
| 7 | +- **Version:** `TL_ABI_VERSION` is **2**. Generated `main` calls `tl_abi_check(TL_ABI_VERSION)` first, and a runtime built for another version stops with a message. |
| 8 | +- **Change rule:** change the header and `abi.rs` together, and bump `TL_ABI_VERSION` when a layout or a calling convention changes. |
| 9 | 9 | - **Targets:** 64-bit only (x86_64 and aarch64 Linux first). |
| 10 | 10 | |
| 11 | +The sections below describe the ABI as the code implements it. How it got there, and which decisions superseded which, is in [History](#history). Rationale lives in the ADRs. |
| 12 | + |
| 13 | +## Status |
| 14 | + |
| 15 | +The ADRs are the source of truth for statuses ([`docs/adr/README.md`](adr/README.md)); where this document and an ADR differ, the ADR wins. |
| 16 | + |
| 17 | +| Part | Decided in | Status | |
| 18 | +|---|---|---| |
| 19 | +| Values, heap blocks, the context, reference counting, yield-bubbling unwinding, preemption | ABI v0 and Revision 1; ADRs 0002–0004 | Accepted 2026-10-08 (issue #2) | |
| 20 | +| Unwinding by yield checks rather than tables | ADR 0003, Revision 2 | Proposed | |
| 21 | +| `ctl` handlers on fibers, the runtime's context switch | ADRs 0010, 0011 | Proposed; needs engineering review (#44) | |
| 22 | +| Multi-threaded scheduler, sending, timers, real time with sockets | ADR 0004, Revisions 1–5 | Proposed; needs engineering review (#2, #44) | |
| 23 | +| Extern convention, blocking pool, resources | ADR 0005, Revision 1 | Proposed | |
| 24 | +| Perceus optimisations | ADR 0002, Implementation (v1) | Proposed; needs engineering review (#44) | |
| 25 | +| `Bytes`, builders, HTTP | ADR 0012 and its Revision 1 | Proposed; needs engineering review (#44) | |
| 26 | +| Arrays, owned externs, big integers (ABI version 2) | ADR 0014 | Proposed; needs engineering review (#44) | |
| 27 | +| Callbacks from C | ADR 0015 | Proposed; needs engineering review (#44) | |
| 28 | +| `defer`, multi-shot continuations | ADRs 0016, 0017 | Proposed; needs engineering review (#44) | |
| 29 | +| `#line` directives in generated C | issue #35 | Proposed; accepted by the project owner; needs engineering review (#44) | |
| 30 | + |
| 31 | +ADRs 0002–0004 call their Revision 1 accepted in their headers but proposed in the revisions themselves; settling that is the ADR index work of the code health audit (`docs/code-health.md`, M10). |
| 32 | + |
| 11 | 33 | ## Values |
| 12 | 34 | |
| 13 | 35 | A `tl_value` is one machine word: |
| @@ -17,9 +39,7 @@ A `tl_value` is one machine word: |
| 17 | 39 | | `1` | 63-bit signed small int: `n << 1 \| 1`. Also used for `Bool` (0/1), `()` (0), and **nullary constructors**, which are encoded as their constructor index. | |
| 18 | 40 | | `0` | Pointer to an 8-byte aligned heap block. | |
| 19 | 41 | |
| 20 | | −**Int arithmetic:** |
| 21 | | −- In ABI v0 and 1, `Int` was exactly the 63-bit range, and overflow panicked. |
| 22 | | −- Since ABI version 2, overflow promotes to a big integer block (`TL_TAG_BIGINT`): see [Big integers](#big-integers-abi-version-2-issue-47-proposed-needs-engineering-review). |
| 42 | +**An `Int` is a small int or a `TL_TAG_BIGINT` block.** A value in the 63-bit range is always small (canonical form), so word equality decides every comparison with a small int, and a `switch` on an integer literal needs no special case. See [Big integers](#big-integers). |
| 23 | 43 | |
| 24 | 44 | ## Heap blocks |
| 25 | 45 | |
| @@ -33,6 +53,7 @@ A `tl_value` is one machine word: |
| 33 | 53 | **`rc`, the reference count:** |
| 34 | 54 | - `> 0` means a local count, with `1` meaning unique. |
| 35 | 55 | - `< 0` means *shared*: reachable from more than one actor. The count is `-rc` and is updated atomically. |
| 56 | +- `0` means *immortal*: a static literal (strings, floats) or a constant dictionary. `tl_dup`, `tl_drop`, `send` and the runtime leave it alone, and nothing may write to it (it may live in read-only memory). |
| 36 | 57 | - An object only ever moves from local to shared, never back. That makes a plain load enough to test the sign. |
| 37 | 58 | |
| 38 | 59 | **`tag`:** |
| @@ -46,20 +67,21 @@ A `tl_value` is one machine word: |
| 46 | 67 | | `FLOAT` | 0 | `double` | |
| 47 | 68 | | `CLOSURE` | captured env | code pointer (`tl_closure_fn`) | |
| 48 | 69 | | `REF` | 1 (the cell) | — | |
| 70 | +| `REGION` | 0 | runtime-private: the references made in the region | |
| 71 | +| `FRAME` | 0 | runtime-private: a running `ctl` handler | |
| 72 | +| `RESOURCE` | 0 | `void *ptr`, then its finalizer | |
| 49 | 73 | | `CAP` | a handler's clauses, then its marker | — | |
| 50 | | −| `ARRAY` | `TL_SCAN_LARGE`: the count, then the elements | `i64 spare`, then `spare` unused slots ([ADR 0014](adr/0014-arrays-and-bigint.md)) | |
| 74 | +| `ARRAY` | `TL_SCAN_LARGE`: the count, then the elements | `i64 spare`, then `spare` unused slots ([Arrays](#arrays-and-owned-externs)) | |
| 51 | 75 | | `BIGINT` | 0 | `i64 len` (`\|len\|` limbs, the sign of the number), then `uint64` limbs, least significant first | |
| 52 | | −| `BUILDER` | 0 | `i64 len`, `i64 cap`, then `cap` bytes (the first `len` used): `bytes.Builder` ([ADR 0012](adr/0012-bytes-and-http.md), Revision 1) | |
| 76 | +| `BUILDER` | 0 | `i64 len`, `i64 cap`, then `cap` bytes (the first `len` used): `bytes.Builder` | |
| 53 | 77 | |
| 54 | | −**`scan_fsize`:** |
| 55 | | −- The number of scanned fields. |
| 56 | | −- `0xFF` (`TL_SCAN_LARGE`) is reserved for arrays: `fields[0]` then holds the count. It is not allocatable in v0; since issue #47 the runtime allocates arrays with it (`tl_alloc` still refuses it). |
| 78 | +**`scan_fsize`:** the number of scanned fields. `0xFF` (`TL_SCAN_LARGE`) is reserved for arrays: `fields[0]` then holds the count. Only the runtime allocates such blocks; `tl_alloc` refuses it. |
| 57 | 79 | |
| 58 | 80 | **Why blocks describe themselves:** drop, the move/share/copy walk of `send` and debugging can walk any value without type information. |
| 59 | 81 | |
| 60 | | −**`flags`:** `PINNED` marks a value that must not be deep-copied to another actor, such as non-thread-safe FFI resources (M7). |
| 82 | +**`flags`:** `PINNED` marks a value that must not be copied to another actor, such as a resource that is not thread-safe. |
| 61 | 83 | |
| 62 | | −**Allocation** (`runtime/tilrt/src/heap.rs`): every block is allocated by `tl_alloc` (or the runtime, through the same function) and freed by `tl_free` or the drop worklist. |
| 84 | +**Allocation** (`runtime/tilrt/src/heap.rs`): every block is allocated by `tl_alloc` (or by the runtime, the same way) and freed by `tl_free` or the drop worklist. |
| 63 | 85 | - Blocks come from **mimalloc**, called directly, when `tilrt` is built with its `mimalloc` feature (the default). Without it they come from the system allocator. Only blocks change allocator; the runtime's own Rust allocations use Rust's global allocator either way. |
| 64 | 86 | - A block may be freed on another thread than the one that allocated it: actors move between scheduler threads, and messages move between actors. Both allocators allow this. |
| 65 | 87 | - **Sanitizers:** ASan only sees memory from `malloc`, so a program built with `-fsanitize=address` must link a runtime built without mimalloc: `cargo build -p tilrt --no-default-features --features stats --target-dir target/sanitize`, then `TILRT_LIB_DIR=target/sanitize/debug`. `scripts/ci.sh` and `scripts/spike.sh --asan` do this. With mimalloc, ASan misses errors on blocks (a use-after-free of a block goes unreported) instead of reporting false ones. ThreadSanitizer needs an instrumented runtime and standard library (nightly `-Zbuild-std`), and C built without TSan's function entry/exit hooks, which `musttail` loops overflow: `scripts/tsan.sh` does both (ADR 0004, Revision 5). |
| @@ -68,38 +90,41 @@ A `tl_value` is one machine word: |
| 68 | 90 | |
| 69 | 91 | ```c |
| 70 | 92 | typedef struct tl_ctx { |
| 71 | | − int32_t yielding; // tl_yield_kind |
| 72 | | − int32_t reductions; // preemption budget |
| 73 | | − uint64_t yield_marker; // FINAL: target handler |
| 74 | | − tl_value yield_value; // owned payload / reason |
| 75 | | − void *evv; // evidence vector (defined in M3/M5) |
| 76 | | − void *rt; // runtime-private: the owning actor |
| 93 | + int32_t yielding; // tl_yield_kind |
| 94 | + int32_t reductions; // preemption budget |
| 95 | + uint64_t yield_marker; // FINAL: target handler |
| 96 | + tl_value yield_value; // owned payload / reason |
| 97 | + void *evv; // unused (null): handlers are values (ADR 0010) |
| 98 | + void *rt; // runtime-private: the owning actor |
| 99 | + tl_value xargs[TL_XARGS]; // call arguments after the sixth (26) |
| 77 | 100 | } tl_ctx; |
| 78 | 101 | ``` |
| 79 | 102 | |
| 80 | 103 | **Ownership and placement:** |
| 81 | 104 | - There is **one context per actor**, passed as the first argument of every generated function. |
| 82 | | −- It is never stored in thread-local storage. An actor's code must not depend on which OS thread runs it, so moving actors between threads stays possible later. C compilers may also cache TLS addresses across calls, which breaks if a fiber resumes on another thread. |
| 105 | +- It is never stored in thread-local storage. An actor may resume on another OS thread after any suspension, and C compilers may cache TLS addresses across calls, which breaks when a fiber resumes on another thread. The runtime's own thread-locals follow the same rule (`Fiber` in `tilrt/src/sched.rs`). |
| 83 | 106 | |
| 84 | 107 | ## Calling convention |
| 85 | 108 | |
| 86 | | −**Arguments and results:** |
| 87 | | −- Every function returns a `tl_value`. |
| 109 | +**One signature.** Every generated function is a `tl_fn`: `tl_value f(tl_ctx *ctx, tl_value a0, ..., tl_value a5)`. Arguments after the sixth go to `ctx->xargs` (26 slots), and the callee copies them on entry. One signature is what allows `musttail` on every tail call. |
| 110 | + |
| 111 | +**Ownership:** |
| 112 | +- Every function returns a `tl_value`, owned by the caller. |
| 88 | 113 | - Parameters are **owned** by default. The callee must consume them: drop them, store them, or pass them on. |
| 89 | | −- Results are owned by the caller. |
| 90 | | −- For *direct* calls only, the compiler may make a parameter *borrowed*, as decided by Perceus borrow inference. Both caller and callee agree because the signature is known statically. See [Borrowed parameters](#borrowed-parameters-v1-proposed) for the rules as implemented. |
| 114 | +- For *direct* calls only, Perceus may make a parameter *borrowed* ([Borrowed parameters](#borrowed-parameters)). |
| 115 | +- **Externs borrow.** Functions declared `@extern`, and the runtime functions generated code calls, borrow their arguments and return owned results, unless declared `owned` ([Arrays and owned externs](#arrays-and-owned-externs)). |
| 91 | 116 | |
| 92 | | −**Closure calls:** |
| 93 | | −- Closures are always called with owned arguments, **including `self`**. |
| 117 | +**Closures:** |
| 118 | +- Closures are always called with owned arguments, **including `self`**, which closure code receives as its first value. |
| 94 | 119 | - The code pointer is cast to its exact arity first, e.g. `tl_value (*)(tl_ctx*, tl_value self, tl_value a)`. A variadic pointer type is never used. |
| 95 | 120 | |
| 96 | | −**Tail calls:** |
| 97 | | −- Self tail calls compile to `goto` (see `runtime/spike/spike.c`). |
| 98 | | −- Other tail calls use `musttail` where available (M5). |
| 121 | +**Tail calls:** a self tail call is a `goto`; every other tail call is emitted with `musttail`. |
| 122 | + |
| 123 | +**Entry functions** (`main`, a test) receive the actor's root `proc` capability; when an entry function borrows it, `tl_entry` drops it after the call. |
| 99 | 124 | |
| 100 | 125 | ## Reference counting |
| 101 | 126 | |
| 102 | | −`tl_dup` and `tl_drop` are inline. Only the following go out of line: |
| 127 | +`tl_dup` and `tl_drop` are inline, and leave immortal blocks (`rc == 0`) alone without a call. Only the following go out of line: |
| 103 | 128 | |
| 104 | 129 | | Function | When it is called | |
| 105 | 130 | |---|---| |
| @@ -107,199 +132,185 @@ typedef struct tl_ctx { |
| 107 | 132 | | `tl_dup_shared` | A block is shared. | |
| 108 | 133 | | `tl_free` | Perceus has moved a unique cell's children out (drop specialisation). | |
| 109 | 134 | |
| 110 | | −**Freeing is iterative.** Dead blocks go onto a per-actor worklist, so dropping a million-element list never recurses. This is essential on small fiber stacks. |
| 135 | +**Freeing is iterative.** Dead blocks go onto a per-actor worklist, so dropping a million-element list never recurses. This is essential on fiber stacks. |
| 136 | + |
| 137 | +**Leak oracle:** with the `stats` feature (on by default), `tl_stats_live_blocks()` counts live blocks, and `TILRT_LEAKS` makes `tl_report_leaks` print it at exit. Tests require 0. |
| 111 | 138 | |
| 112 | | −**In-place reuse:** when `tl_is_unique(v)` holds, generated code may overwrite a block's fields and keep the block (FBIP reuse). See [Drop specialisation and reuse](#drop-specialisation-and-reuse-v1-proposed) for the generated code. |
| 139 | +### Perceus optimisations (v1, issue #34; proposed, needs engineering review) |
| 140 | +These change what generated code does with counts, not the layouts. Rationale and measurements: [ADR 0002, Implementation (v1)](adr/0002-memory-model.md#implementation-v1--2026-10-09). |
| 141 | + |
| 142 | +#### Borrowed parameters |
| 143 | +- A function called only directly (never made into a closure) may *borrow* some parameters: `FnDecl::borrowed` in Core, decided by `tilc_perceus` and printed `^v` by `tilc core`. |
| 144 | +- The caller keeps its reference across the call and releases it as usual afterwards. The callee must neither drop nor consume a borrowed parameter: to store it, return it or pass it to an owned position it takes a `dup` first. |
| 145 | +- A borrowed parameter is not one of the frame's references: unwinding (preemption, panics, exit signals, `final ctl`) does not drop it. |
| 146 | +- The C signature is unchanged (`tl_fn`); only the ownership of the argument differs. A self tail call (`goto entry`) passes borrowed arguments in borrowed parameters. |
| 147 | +- Closures, effect clauses, externs and runtime functions keep their conventions (owned for closures and clauses, borrowed for externs). |
| 148 | +- **Projections borrow.** In Core after Perceus, `let a = x.i` reads the field without a `dup` (C: `a = tl_as_block(x)->fields[i]`); a `dup a` follows when `a` must be owned. A projection of a borrowed value stays borrowed, so a borrowed structure is walked without counting. |
| 113 | 149 | |
| 114 | | −**Leak oracle:** with the `stats` feature (on by default for now), `tl_stats_live_blocks()` counts live blocks. Tests require it to be 0 at exit. |
| 150 | +#### Drop specialisation and reuse |
| 151 | +`release x [i: a, ...]` (Core `Expr::Release`) ends `x`'s reference after its fields `a`, ... were projected: |
| 152 | + |
| 153 | +```c |
| 154 | +if (tl_is_unique(x)) { |
| 155 | + tl_as_block(x)->fields[i] = TL_UNIT; /* moved out to a, ... */ |
| 156 | + tl_free_moved(ctx, tl_as_block(x), moved); /* tl_free, or tl_drop_slow if other fields remain */ |
| 157 | +} else { |
| 158 | + tl_dup(a); ... |
| 159 | + tl_drop(ctx, x); |
| 160 | +} |
| 161 | +``` |
| 162 | + |
| 163 | +With reuse (`release x [...] reuse as t`), the unique branch keeps the cell instead, `t = tl_reuse_token(ctx, b)`: its remaining fields are dropped and every field is unit, so a token is an ordinary owned value (a unique block of units, or `TL_UNIT`) and dropping it is safe. A later `reuse t in C(...)` (Core `Value::Reuse`) writes the cell in place when `t` is a block with as many fields as `C`, setting its `tag`; otherwise it drops `t` and allocates. Tokens are only taken from values a `switch` matched (user constructor cells: no raw area, flags 0); `tl_reuse_token` frees a runtime block instead. `tl_free_moved` and `tl_reuse_token` are inline helpers in the generated prelude. |
| 164 | + |
| 165 | +#### Constant dictionaries |
| 166 | +A trait dictionary without constraints (`Num<Int>`) is emitted as `static const` immortal blocks: a tuple (`tag` 0) of closures without captures (`TL_TAG_CLOSURE`, `scan_fsize` 0, the code pointer in the raw area). Since issue #61, the C backend calls the methods of such dictionaries directly, or inlines them, and specialises functions for them ([ADR 0013](adr/0013-numeric-code.md)); the dictionaries remain for the calls it cannot resolve. |
| 115 | 167 | |
| 116 | 168 | ## Unwinding |
| 117 | 169 | |
| 118 | | −Three things abort part of an actor's stack. All three use **yield-bubbling**: |
| 170 | +Several things abort part of an actor's stack. All of them use **yield-bubbling** (ADR 0003, Revision 2): no unwind tables, no `-fexceptions`. |
| 119 | 171 | |
| 120 | 172 | | `yielding` | Cause | Stopped by | |
| 121 | 173 | |---|---|---| |
| 122 | 174 | | `FINAL` | a `final ctl` op (`tl_yield_final`) | the handler frame whose marker matches (`tl_catch_final`) | |
| 123 | | −| `PANIC` | a division by zero (overflow before ABI 2), a failed match, or `panic` (`tl_panic`) | the actor root, where the actor crashes | |
| 175 | +| `PANIC` | a division by zero, a failed match, or `panic` (`tl_panic`, `tl_panic_str`) | the actor root, where the actor crashes | |
| 124 | 176 | | `KILL` | an exit signal delivered at a safe point | the actor root | |
| 177 | +| `CANCEL` | a suspended `ctl` handler body that will never be resumed | the handler (`tl_handle_ctl`) | |
| 178 | + |
| 179 | +Two more values are passes over a suspended `multi ctl` continuation, not unwindings the program can observe ([Multi-shot continuations](#multi-shot-continuations)): `CLONE` and `DISCARD`. |
| 125 | 180 | |
| 126 | 181 | **Protocol:** |
| 127 | 182 | 1. The operation sets `ctx->yielding` (and the payload), then returns `TL_UNIT`. |
| 128 | | −2. After every call that may yield, generated code tests `TL_YIELDING(ctx)`. If it is set, the code drops its owned locals and returns `TL_UNIT`. |
| 129 | | −3. A handler frame calls `tl_catch_final(ctx, marker, &payload)` after its body. If that returns true, unwinding stops there and the clause runs. |
| 183 | +2. After every call that may unwind, generated code tests `TL_YIELDING(ctx)`. If it is set, the code drops its owned references (with `TL_UNWIND_DROP`) and returns `TL_UNIT`. |
| 184 | +3. A handler frame calls `tl_catch_final(ctx, marker, &payload)` after its body. If that returns true, unwinding stops there and the clause runs. A handler capability stores the handler's marker after its clauses; `final ctl` yields a payload (the operation's index, then its arguments) to that marker. |
| 130 | 185 | 4. Return values produced while unwinding are always `TL_UNIT`, so dropping them is a no-op. |
| 186 | +5. `tl_main_program` reports a panic of `main` as `error: panic: <message>`, with exit code 101. |
| 131 | 187 | |
| 132 | | −**Which calls need the check.** Panics and kills unwind through *any* frame, so the check is needed after every call except to a callee proven never to yield. A callee qualifies only if all three hold: |
| 188 | +**Which calls need the check.** Panics and kills unwind through *any* frame, so the check is needed after every call except to a callee proven never to unwind. A callee qualifies only if all three hold: |
| 133 | 189 | - it has no `TL_ENTER`, |
| 134 | 190 | - it has no operation that can panic, |
| 135 | | −- every call it makes is itself to a never-yield function. |
| 191 | +- every call it makes is itself to a never-unwinding function. |
| 192 | + |
| 193 | +In practice that means small leaf functions, which are inlining candidates anyway. Since issue #61 the C backend finds them (`tilc_codegen_c/src/unwind.rs`, ADR 0003's implementation note): their calls have no check, and they have no preemption point. Effect rows alone cannot drop the check. |
| 136 | 194 | |
| 137 | | −In practice that means small leaf functions, which are inlining candidates anyway. Since issue #61 the C backend finds them (`tilc_codegen_c/src/unwind.rs`, ADR 0003's implementation note): their calls have no check, and they have no preemption point (no `TL_ENTER`). Effect rows alone cannot drop the check. This corrects the plan's "only open or `final ctl` rows" rule (see [ADR 0003](adr/0003-effect-lowering.md)). |
| 195 | +**Externs.** The backend checks `yielding` after every extern outside the runtime, so a binding's shim may panic with `tl_panic_str` (not in a `blocking` extern). The prefix `tl_` is reserved for the runtime, whose functions are listed, with whether they may unwind, in `tilc_core::externs` ([Adding a runtime extern](#adding-a-runtime-extern)). |
| 138 | 196 | |
| 139 | | −**Cost of the check:** one load, one compare and one predicted branch per call. The drop paths add code size, not time. |
| 197 | +**Cost of the check:** one load, one compare and one predicted branch per call. The drop paths add code size, not time. The compiler emits the checks in Core *before* Perceus runs ([ADR 0003](adr/0003-effect-lowering.md)), so Perceus computes the drops on the unwinding path the same way as on any other path. |
| 140 | 198 | |
| 141 | | −The compiler emits these checks in Core *before* Perceus runs ([ADR 0003](adr/0003-effect-lowering.md)), so Perceus computes the drops on the unwind path the same way as on any other path. |
| 199 | +**Cleanups (`defer`, [ADR 0016](adr/0016-defer.md)).** Generated code calls the body closure, then `tl_defer(ctx, result, cleanup)`, which consumes both: |
| 200 | +- it saves `yielding`, `yield_marker` and `yield_value`, clears them, and calls the cleanup; |
| 201 | +- if the cleanup unwinds (a panic, or a kill at one of its safe points), that unwinding continues: the saved payload and `result` are dropped, and it returns unit; |
| 202 | +- otherwise it restores the saved state and returns `result`. The yield check after the call continues any unwinding. |
| 203 | + |
| 204 | +Cancelling a `ctl` body follows the same rule: if the cancelled code ends with a panic or a kill instead of `CANCEL`, that unwinding replaces the caller's, and `tl_handle_ctl` returns unit. |
| 142 | 205 | |
| 143 | 206 | ## Preemption and exit signals |
| 144 | 207 | |
| 145 | 208 | `TL_ENTER(ctx, label)` appears at every function entry and loop back-edge: |
| 146 | 209 | 1. It decrements `ctx->reductions`. |
| 147 | | −2. When the budget (4000) is spent, it calls `tl_preempt`, which suspends the actor's fiber back to the scheduler. |
| 210 | +2. When the budget is spent, it calls `tl_preempt`, which suspends the actor's fiber back to the scheduler. The budget is 2,000 entries (`REDUCTIONS`), refreshed whenever the actor is scheduled and at every `proc` operation. |
| 148 | 211 | 3. A pending exit signal is turned into `yielding = KILL` on resume, and the code jumps to `label`, which drops the owned locals. |
| 149 | 212 | |
| 150 | | −The yielding test sits on the slow path, so the fast path is a decrement and a branch. |
| 213 | +The yielding test sits on the slow path, so the fast path is a decrement and a branch. A loop that makes no calls is therefore still preemptible and killable. |
| 151 | 214 | |
| 152 | | −A loop that makes no calls is therefore still preemptible and killable. |
| 215 | +## Effect handlers |
| 153 | 216 | |
| 154 | | −## Actors (ABI v0 scope) |
| 217 | +- **Handler capabilities** ([ADR 0010](adr/0010-lexical-handlers.md)) are ordinary `CAP` blocks holding the clause closures, then the handler's marker. A `fn` operation calls its clause directly. |
| 218 | +- **`ctl` handlers** (`tilrt/src/handlers.rs`) use stack switching: |
| 219 | + - `tl_handle_ctl` runs the body on a fiber of its own (a lazily committed 16 MiB stack); |
| 220 | + - `tl_perform_ctl` suspends the fiber with `(op, args)` for the handler's marker, and handlers in between forward the request; |
| 221 | + - `resume` is a runtime closure, valid once per suspension; |
| 222 | + - a body that is never resumed is cancelled with `CANCEL`, so generated code unwinds it and every reference is dropped; |
| 223 | + - preemption inside a fiber is forwarded up to the actor's own stack. |
| 224 | +- **Context switch** ([ADR 0011](adr/0011-context-switch.md)): the runtime's own assembly on x86_64 Linux, corosensei elsewhere. An aarch64 Linux switch exists but is untested on hardware, so it is used only with `--cfg tilrt_aarch64_switch`. |
| 225 | +- **Regions** (ADR 0002, Revision 1): `tl_region_new`, `tl_ref_new`, `tl_ref_get`, `tl_ref_set` and `tl_region_end`. A region holds a count on each of its references until it ends; ending it clears them, which breaks cycles through them. |
| 226 | + |
| 227 | +### Multi-shot continuations |
| 228 | +[ADR 0017](adr/0017-multishot.md). `tl_handle_multi` is `tl_handle_ctl` for an effect with `multi ctl` operations, with one more argument: a mask whose bit `i` is set if operation `i` is one (operations are still performed with `tl_perform_ctl`). Copying a continuation needs generated code to: |
| 229 | +- release what a frame holds on its unwinding paths with `TL_UNWIND_DROP(ctx, v)`, which dups instead when `yielding == TL_YIELD_CLONE` (a *copying pass*), including a `fn` or `final ctl` handler's capability when the handler is left; |
| 230 | +- leave a region with `tl_region_exit(ctx, region)` (consumes it), which ends the region only when its last copy leaves; |
| 231 | +- reuse a token only if it is unique (`tl_is_unique`), since copies share tokens. |
| 232 | + |
| 233 | +`TL_YIELD_DISCARD` releases a continuation whose copies ran: frames unwind as usual, and `tl_defer` drops the cleanup without running it. Neither mode is an unwinding the program can observe: no handler catches it, and the runtime restores the previous state afterwards. |
| 234 | + |
| 235 | +## Actors |
| 236 | + |
| 237 | +The native scheduler (`tilrt/src/sched.rs`, [ADR 0004](adr/0004-actor-model.md)) implements `std/process` with the interpreter's semantics. |
| 155 | 238 | |
| 156 | 239 | **Fibers:** |
| 157 | | −- Each actor runs on its own fiber (`tilrt/src/fiber.rs`, [ADR 0011](adr/0011-context-switch.md)) with a 256 KiB stack and a guard page. |
| 158 | | −- A fiber is **never dropped while suspended**: its frames would never release what they hold. Killed actors therefore always run to completion via `KILL` unwinding. That run is also what releases everything the actor owns. |
| 240 | +- Each actor runs on its own fiber with a guard page: the root actor on a lazily committed 1 GiB stack, other actors of compiled programs on 64 MiB ones (committed lazily, and reused), so native recursion depth matches the interpreter's. The M0 spike's actors (`tl_spawn`) get 256 KiB. |
| 241 | +- A fiber is **never dropped while suspended**: its frames would never release what they hold. A killed actor exits logically at once (links and monitors are notified), then its fiber runs once more to unwind, which releases everything it owns. |
| 159 | 242 | |
| 160 | | −**Shutdown:** when the root actor (`tl_main`'s entry) returns, every remaining actor is killed and driven to completion. |
| 243 | +**The `proc` capability.** Every actor receives a root `proc` capability, built by `tl_root_cap`, whose clauses are runtime closures (`tilrt/src/process.rs`), one per operation in `std/process.til`'s declaration order. Generated code passes the number of operations it was compiled for, and the runtime stops on a mismatch. |
| 161 | 244 | |
| 162 | | −**v0 scope:** `tl_spawn` moves its closure and there is a single scheduler thread. Mailboxes, deep-copy send, links, monitors and multiple threads arrive in M6 ([ADR 0004](adr/0004-actor-model.md)). |
| 245 | +**Sending: move, share or copy** (`tilrt/src/send.rs`). `send` and `spawn` walk the message (or the spawned closure) once, iteratively: |
| 246 | +- a unique block (`rc` 1) is moved and its fields are walked; |
| 247 | +- a block the sender also reaches (`rc` > 1) is copied, with a forwarding table so sharing inside the message is kept. It is promoted to shared instead when it reaches more than 64 blocks, holds a string, `Bytes`, builder or array over 4 KiB, or is a resource: its whole subgraph gets negative counts; |
| 248 | +- immortal and shared blocks are kept; |
| 249 | +- `Ref`, regions, handler capabilities and frames, and `PINNED` resources stop the walk, and the sender panics (`cannot send a mutable reference`, ...). The interpreter refuses the same values. |
| 163 | 250 | |
| 164 | | −## Validation: the M0 spike |
| 251 | +This makes every message safe to own on another thread. |
| 165 | 252 | |
| 166 | | −`runtime/spike/spike.c` is hand-written C in exactly the shape `tilc` will emit. `scripts/spike.sh` (also run by `scripts/ci.sh`) links it against `libtilrt.a` in debug, release, and clang ASan+UBSan builds. It checks: |
| 253 | +**Threads** (ADR 0004, Revisions 2 and 4): |
| 254 | +- `TILC_THREADS` scheduler threads (default: one per core) each have a FIFO run queue; an idle thread steals from the shared queue, then from the others. An actor may resume on another thread after each suspension. With `TILC_THREADS=1` there is one queue, the order is the interpreter's and outputs match it exactly; the differential tests run that way, and check that 4 threads end the same way without leaks. |
| 255 | +- What other actors touch (mailbox, links, monitors, wait state) is behind the actor's own lock; sockets and blocking calls behind one control lock. No lock is held while actor code runs. |
| 256 | +- A wake-up queues an actor only if it is suspended. If it is still on its way to parking, the thread running it queues it when it yields (`handoff::RunState`, checked with loom). |
| 257 | +- When nothing can run, one thread waits on the reactor for sockets, finished blocking calls (they signal a `mio::Waker`) or the next deadline. It gives up as soon as an actor is queued elsewhere, and only declares a deadlock when, under one lock, nothing runs, nothing is queued and nothing outside can wake an actor. |
| 258 | +- Mailboxes are indexed by subject tag, so receiving from one subject does not scan the others' messages. |
| 167 | 259 | |
| 168 | | −- 1M-element lists are summed, consumed and dropped on a fiber stack (iterative drop). |
| 169 | | −- FBIP: a unique list is updated fully in place; a shared one is copied. |
| 170 | | −- A `final ctl` op unwinds 500 frames, each owning a list. The handler catches it, and live blocks return to 0. |
| 171 | | −- 1000 actors are preempted round-robin. One actor panics (on overflow in ABI v0; on a division by zero since ABI 2) and crashes alone. 500 are killed mid-loop and release their lists. |
| 172 | | −- (ABI 2) An overflow promotes to a big integer block, and subtracting back gives the small int. |
| 173 | | −- The root exits, the remaining actors are killed, and the process ends with 0 live blocks and 0 actors. |
| 260 | +**Time and timers** (ADR 0004, Revisions 3 and 5). Time is virtual: when no actor can run, the clock jumps to the next deadline. Once the program opens a socket, the clock follows real time instead: it is counted between slices, and due timers fire then, even if no thread ever idles. Timers are in a heap per scheduler thread, with a lock-free bound on the earliest deadline (`tilrt/src/timers.rs`). |
| 174 | 261 | |
| 175 | | −## Known limitations (v0) |
| 262 | +**Exits** follow Erlang: an abnormal exit stops linked actors, or sends them an `ExitSignal` if they trap exits; monitors receive `Down`. When the root actor returns, every remaining actor is killed and driven to completion. |
| 176 | 263 | |
| 177 | | −- Cycles through mutable `Ref`s leak. Reference counting cannot reclaim them; this is documented, not detected. |
| 178 | | −- An `rc` overflow beyond 2^31 references is not handled. |
| 179 | | −- The runtime must be built with `panic = "unwind"` semantics confined to Rust frames. A Rust panic inside an `extern "C"` entry point aborts the process. That is acceptable for runtime bugs, but not for user errors, which use `tl_panic`. |
| 180 | | − |
| 181 | | −## Revision 1 — 2026-10-09 (proposed; implemented in M5) |
| 182 | | −These decisions (ADRs 0002–0004, Revision 1) change this ABI. The sections above describe ABI v0 as validated by the M0 spike. |
| 183 | | − |
| 184 | | −- **Unwinding:** the yield flag checked after calls (`TL_YIELDING`) is replaced by table-driven unwinding. |
| 185 | | − - Generated C is compiled with `-fexceptions`, with owned locals marked `cleanup`. |
| 186 | | − - Panics, exit signals and `final ctl` operations walk the stack with `_Unwind_ForcedUnwind` until the handler frame (recorded when it is installed) or the actor root. |
| 187 | | − - The fast path loses its per-call branch; raising gets slower. |
| 188 | | −- **Calling convention:** all generated functions share one C signature, `tl_value f(tl_ctx *ctx, tl_value a0, ..., tl_value a5)`, with further arguments in a context area. This is what allows `musttail` on every tail call. |
| 189 | | −- **Context switch:** the runtime's own symmetric switch, which can be moved between threads, replaces corosensei. It is used for actors and for `ctl` handler fibers. |
| 190 | | −- **Sending:** move, share or copy per part of the message, using the `PINNED` and shared-`rc` bits already defined above. |
| 191 | | − |
| 192 | | −The M0 spike is redone against this revision at the start of M5. |
| 193 | | − |
| 194 | | −### Implemented in M5 part 1 (`TL_ABI_VERSION` 1) |
| 195 | | −- **Calls:** |
| 196 | | − - all generated functions have the signature `tl_fn`; |
| 197 | | − - arguments after the sixth go to `ctx->xargs` (26 slots), and the callee copies them on entry; |
| 198 | | − - closure code receives the closure as its first value. |
| 199 | | − |
| 200 | | − Every tail call is emitted with `musttail`; a self tail call is a jump. |
| 201 | | −- **Externs borrow.** Functions declared `@extern`, and the runtime functions generated code calls, borrow their arguments and return owned results (unless declared `owned`: see [Arrays and owned externs](#arrays-and-owned-externs-issue-47-proposed-needs-engineering-review)). Perceus (`tilc_perceus`) relies on this. `tl_println` changed accordingly. |
| 202 | | −- **Immortal blocks.** Blocks with `rc == 0` are static literals (strings, floats) and constant dictionaries (v1, below). `tl_dup` and `tl_drop` leave them alone. |
| 203 | | −- **Regions:** `tl_region_new`, `tl_ref_new`, `tl_ref_get`, `tl_ref_set` and `tl_region_end` (tag `TL_TAG_REGION`). A region holds a count on each of its references until it ends. |
| 204 | | −- **Handler capabilities** (ADR 0010) are ordinary blocks holding the clause closures. A `fn` operation calls its clause directly. |
| 205 | | −- **Unwinding (part 2).** Unwinding uses yield checks, not tables (ADR 0003, Revision 2, proposed): |
| 206 | | − - after a call that may unwind, the code tests `ctx->yielding`; if it is set, it drops the frame's references and returns; |
| 207 | | − - a handler capability stores the handler's marker after its clauses; `final ctl` yields a payload (the operation's index, then its arguments) to that marker; |
| 208 | | − - `tl_main_program` reports a panic of `main` as `error: panic: <message>` with exit code 101. |
| 209 | | −- **The root actor** gets a 1 GiB lazily committed stack, so native recursion depth matches the interpreter's. |
| 210 | | − |
| 211 | | −- **`ctl` handlers (part 3).** These use stack switching, implemented in `tilrt/src/handlers.rs`: |
| 212 | | − - `tl_handle_ctl` runs the body on a fiber of its own (with a lazily committed 16 MiB stack); |
| 213 | | − - `tl_perform_ctl` suspends the fiber with `(op, args)` for the handler's marker, and handlers in between forward the request; |
| 214 | | − - `resume` is a runtime closure, valid once per suspension; |
| 215 | | − - a body that is never resumed is cancelled with `TL_YIELD_CANCEL`, so generated code unwinds it and every reference is dropped; |
| 216 | | − - preemption inside a fiber is forwarded up to the actor's own stack. |
| 264 | +## Native dependencies |
| 217 | 265 | |
| 218 | | − Fibers switch with the runtime's own assembly on x86_64 Linux, and with corosensei elsewhere ([ADR 0011](adr/0011-context-switch.md)). An aarch64 Linux switch exists but is untested on hardware, so it is used only with `--cfg tilrt_aarch64_switch`. |
| 219 | | − |
| 220 | | −- **Cleanups (`defer`, v1; [ADR 0016](adr/0016-defer.md), proposed).** Generated code calls the body closure, then `tl_defer(ctx, result, cleanup)`, which consumes both: |
| 221 | | − - it saves `yielding`, `yield_marker` and `yield_value`, clears them, and calls the cleanup; |
| 222 | | − - if the cleanup unwinds (a panic, or a kill at one of its safe points), that unwinding continues: the saved payload and `result` are dropped, and it returns unit; |
| 223 | | − - otherwise it restores the saved state and returns `result`. The yield check after the call continues any unwinding. |
| 224 | | − |
| 225 | | − Cancelling a `ctl` body follows the same rule: if the cancelled code ends with a panic or a kill instead of `CANCEL`, that unwinding replaces the caller's, and `tl_handle_ctl` returns unit. |
| 226 | | − |
| 227 | | −- **Multi-shot continuations (v1; [ADR 0017](adr/0017-multishot.md), proposed).** `tl_handle_multi` is `tl_handle_ctl` for an effect with `multi ctl` operations, with one more argument: a mask whose bit `i` is set if operation `i` is one (operations are still performed with `tl_perform_ctl`). Copying a continuation needs generated code to: |
| 228 | | − - release what a frame holds on its unwinding paths with `TL_UNWIND_DROP(ctx, v)`, which dups instead when `yielding == TL_YIELD_CLONE` (a *copying pass*), including a `fn` or `final ctl` handler's capability when the handler is left; |
| 229 | | − - leave a region with `tl_region_exit(ctx, region)` (consumes it), which ends the region only when its last copy leaves; |
| 230 | | − - reuse a token only if it is unique (`tl_is_unique`), since copies share tokens. |
| 231 | | − |
| 232 | | − `TL_YIELD_DISCARD` releases a continuation whose copies ran: frames unwind as usual, `tl_defer` drops the cleanup without running it. Neither mode is an unwinding the program can observe: no handler catches it, and the runtime restores the previous state afterwards. |
| 233 | | − |
| 234 | | −- **Actors (M6 parts 1 and 5).** The native scheduler implements `std/process` with the interpreter's semantics: |
| 235 | | − - `TILC_THREADS` scheduler threads (default: one per core) share one round-robin queue, so an actor may resume on another thread. With `TILC_THREADS=1` the order is the interpreter's and outputs match it exactly; the differential tests run that way, and check that 4 threads end the same way without leaks; |
| 236 | | − - a 2000-entry reduction budget, refreshed at every scheduling point and `proc` operation; |
| 237 | | − - a virtual clock; |
| 238 | | − - Erlang exits. |
| 239 | | − |
| 240 | | − Every actor receives a root `proc` capability, built by `tl_root_cap`, whose clauses are runtime closures (`tilrt/src/process.rs`). Generated code passes the number of `proc` operations it was compiled for, and the runtime stops on a mismatch. A killed actor exits logically at once and then unwinds. |
| 241 | | −- **Sending: move, share or copy (M6 part 3, `tilrt/src/send.rs`).** `send` and `spawn` walk the message (or the spawned closure) once, iteratively: |
| 242 | | − - a unique block (`rc` 1) is moved and its fields are walked; |
| 243 | | − - a block the sender also reaches (`rc` > 1) is copied, with a forwarding table so sharing inside the message is kept. It is promoted to shared instead when it reaches more than 64 blocks, holds a string over 4 KiB, or is a resource: its whole subgraph gets negative counts; |
| 244 | | − - immortal and shared blocks are kept; |
| 245 | | − - `Ref`, regions, handler capabilities (`CAP`) and frames, and `PINNED` resources stop the walk, and the sender panics (`cannot send a mutable reference`, ...). The interpreter refuses the same values. |
| 246 | | − |
| 247 | | − This makes every message safe to own on another thread. |
| 248 | | −- **Threads (M6 part 5; [ADR 0004](adr/0004-actor-model.md) Revision 2, `tilrt/src/sched.rs`).** |
| 249 | | − - Each scheduler thread has a FIFO run queue; idle threads steal. One thread means one queue, in the interpreter's order. |
| 250 | | − - What other actors touch (mailbox, links, monitors, wait state) is behind the actor's own lock; sockets and blocking calls behind one control lock. Timers are in a heap per thread, with a lock-free bound on the earliest deadline (`tilrt/src/timers.rs`, ADR 0004 Revision 5). No lock is held while actor code runs. |
| 251 | | − - A wake-up queues an actor only if it is suspended. If it is still on its way to parking, the thread running it queues it when it yields (`handoff::RunState`, checked with loom). |
| 252 | | − - When nothing can run, one thread waits on the reactor for sockets, finished blocking calls (they signal a `mio::Waker`) or the next deadline. It gives up as soon as an actor is queued elsewhere, and only declares a deadlock when, under one lock, nothing runs, nothing is queued and nothing outside can wake an actor. |
| 253 | | − - A socket event that arrives before its actor parks is remembered, and the actor retries instead of parking. |
| 254 | | − - Mailboxes are indexed by subject tag, so receiving from one subject does not scan the others' messages. |
| 255 | | − |
| 256 | | −- **Native dependencies (M7):** the extern convention, the blocking pool and resources (ADR 0005, Revision 1). |
| 257 | | −- **Sockets (M8, `tilrt/src/net.rs`).** |
| 258 | | − - Sockets are non-blocking. They are registered once, edge-triggered, with a mio reactor owned by the scheduler. |
| 259 | | − - An operation that would block parks the actor on the socket's token. A spurious wake-up only retries it. |
| 260 | | − - The scheduler polls the reactor without waiting between slices. When nothing can run, it waits for events until the next timer deadline. |
| 261 | | − - Once the first socket opens, the clock follows real time: it is counted between slices, and due timers fire then, even if no thread ever idles (ADR 0004, Revision 3). Programs without sockets keep the virtual clock. |
| 262 | | − - Request heads are parsed by `httparse`, Rust's port of picohttpparser. |
| 263 | | − |
| 264 | | −- **`Bytes` (issue #36, ADR 0012, proposed).** |
| 265 | | − - `Bytes` blocks use the layout reserved above (`TL_TAG_BYTES`: an `i64` length, then the bytes, no NUL). The functions of `std/bytes` live in `tilrt/src/bytes.rs`. Each returns a fresh block; slices are copies. |
| 266 | | − - The network reads and writes `Bytes` (`tl_net_write_string` sends a string). `tl_http_parse_request` and `tl_http_parse_chunk` take a buffer and an offset, and return offsets. |
| 267 | | − - `tl_string_join` joins a `List<String>` in one allocation. |
| 268 | | − - The value layout and the calling convention are unchanged; only these std externs changed. |
| 266 | +[ADR 0005](adr/0005-ffi.md), Revision 1. |
| 267 | +- **Extern convention.** A C function bound with `@extern(c, "sym")` has the convention of `tilrt.h`: `tl_value sym(tl_ctx *ctx, tl_value a, ...)`, with borrowed arguments and an owned result, built with the functions the header lists for bindings. |
| 268 | +- **Blocking externs** (`@extern(c, "sym", blocking)`) are called through a generated thunk on the blocking pool (`tl_call_blocking`, `tilrt/src/blocking.rs`) while the actor is parked. They must not panic, perform operations or drop values. |
| 269 | +- **Resources** (`tl_resource_new`, `tl_resource_get`) wrap a foreign pointer with a finalizer, called when the last reference is dropped. A resource that is not thread-safe is `PINNED`. |
| 269 | 270 | |
| 270 | | −### Perceus optimisations (v1, issue #34; proposed, needs engineering review) |
| 271 | | −These change what generated code does with counts, not the layouts: `TL_ABI_VERSION` stays 1. Rationale and measurements: [ADR 0002, Implementation (v1)](adr/0002-memory-model.md#implementation-v1--2026-10-09). |
| 271 | +**Callbacks from C** ([ADR 0015](adr/0015-c-callbacks-and-bindings.md), `tilrt/src/callback.rs`): |
| 272 | +- **`tl_callback`** (24 bytes: the actor's `ctx`, the closure, a runtime-private thread token) is the `void *` environment a shim passes C with its trampoline, for one extern call. `tl_callback_begin(ctx, &cb, f)` sets it up; `tl_callback_call(&cb, argc, args)` calls `f` (borrowed by the extern, duplicated per call) with owned arguments and returns an owned result; `tl_callback_end(&cb, result)` returns `result`, or drops it and returns unit after a panic. `tl_callback_failed` (inline) tells whether one happened. |
| 273 | +- **Panics:** a callback's panic unwinds to `tl_callback_call` and stays pending in `ctx->yielding`. Further calls return unit without running anything; once the extern returns, the generated code unwinds. |
| 274 | +- **No suspension inside the call:** the actor counts its calls in progress. Meanwhile `tl_preempt` only refills the budget, so exit signals wait; `tl_call_blocking` runs the thunk inline; parking aborts. |
| 275 | +- **Guards** (abort): a call on another thread or after `tl_callback_end`, `tl_callback_begin` on the blocking pool, more than 31 arguments. |
| 272 | 276 | |
| 273 | | −#### Borrowed parameters (v1, proposed) |
| 274 | | −- A function called only directly (never made into a closure) may *borrow* some parameters: `FnDecl::borrowed` in Core, decided by `tilc_perceus` and printed `^v` by `tilc core`. |
| 275 | | −- The caller keeps its reference across the call and releases it as usual afterwards. The callee must neither drop nor consume a borrowed parameter: to store it, return it or pass it to an owned position it takes a `dup` first. |
| 276 | | −- A borrowed parameter is not one of the frame's references: unwinding (preemption, panics, exit signals, `final ctl`) does not drop it. |
| 277 | | −- The C signature is unchanged (`tl_fn`); only the ownership of the argument differs. A self tail call (`goto entry`) passes borrowed arguments in borrowed parameters. |
| 278 | | −- Closures, effect clauses, externs and runtime functions keep their conventions (owned for closures and clauses, borrowed for externs). When an entry function (`main`, a test) borrows its root capability, `tl_entry` drops it after the call. |
| 279 | | −- **Projections borrow.** In Core after Perceus, `let a = x.i` reads the field without a `dup` (C: `a = tl_as_block(x)->fields[i]`); a `dup a` follows when `a` must be owned. A projection of a borrowed value stays borrowed, so a borrowed structure is walked without counting. |
| 277 | +## The standard library in the runtime |
| 280 | 278 | |
| 281 | | −#### Drop specialisation and reuse (v1, proposed) |
| 282 | | −`release x [i: a, ...]` (Core `Expr::Release`) ends `x`'s reference after its fields `a`, ... were projected: |
| 279 | +Like every extern, these borrow their arguments unless declared `owned`, and must behave like the interpreter's (`tilc_interp`): the differential tests compare both. Their pure kernels (hashes, `split`, `html_escape`, `url_decode`, random numbers) are shared with it in `runtime/tilrt-prims`. |
| 283 | 280 | |
| 284 | | −```c |
| 285 | | −if (tl_is_unique(x)) { |
| 286 | | − tl_as_block(x)->fields[i] = TL_UNIT; /* moved out to a, ... */ |
| 287 | | − tl_free_moved(ctx, tl_as_block(x), moved); /* tl_free, or tl_drop_slow if other fields remain */ |
| 288 | | −} else { |
| 289 | | − tl_dup(a); ... |
| 290 | | − tl_drop(ctx, x); |
| 291 | | −} |
| 292 | | −``` |
| 281 | +**Constructors the runtime builds** follow the declaration order in `std/`: `Ok`/`Error` (0/1), `Nil`/`Cons` (the small int 0, then tag 1), `None`/`Some`, `Lt`/`Eq`/`Gt` (0/1/2), tuples (tag 0), and the types of `std/process` and `std/http` (`Head`, `Chunk`). Reordering one of these breaks both back ends (code health audit, M4). |
| 293 | 282 | |
| 294 | | −With reuse (`release x [...] reuse as t`), the unique branch keeps the cell instead, `t = tl_reuse_token(ctx, b)`: its remaining fields are dropped and every field is unit, so a token is an ordinary owned value (a unique block of units, or `TL_UNIT`) and dropping it is safe. A later `reuse t in C(...)` (Core `Value::Reuse`) writes the cell in place when `t` is a block with as many fields as `C`, setting its `tag`; otherwise it drops `t` and allocates. Tokens are only taken from values a `switch` matched (user constructor cells: no raw area, flags 0); `tl_reuse_token` frees a runtime block instead. `tl_free_moved` and `tl_reuse_token` are inline helpers in the generated prelude. |
| 283 | +### `Bytes` and builders |
| 284 | +[ADR 0012](adr/0012-bytes-and-http.md). |
| 285 | +- `Bytes` blocks (`TL_TAG_BYTES`: an `i64` length, then the bytes, no NUL) are made by `tilrt/src/bytes.rs`. Each operation returns a fresh block; slices are copies. |
| 286 | +- A `bytes.Builder` is a `TL_TAG_BUILDER` block (`tilrt/src/builder.rs`). Its appends and `build` are owned externs: a unique builder grows in place, and `build` turns it into a `TL_TAG_BYTES` block in place (moving the bytes over the capacity word, then shrinking the block). A shared builder is copied first. |
| 287 | +- `tl_string_join` joins a `List<String>` in one allocation. |
| 295 | 288 | |
| 296 | | −#### Constant dictionaries (v1, proposed) |
| 297 | | −A trait dictionary without constraints (`Num<Int>`) is emitted as `static const` immortal blocks: a tuple (`tag` 0) of closures without captures (`TL_TAG_CLOSURE`, `scan_fsize` 0, the code pointer in the raw area). They live in read-only memory, so nothing may write to a block with `rc == 0`: `tl_dup`, `tl_drop`, `send` and the runtime already leave them alone. `tl_dup` and `tl_drop` now test `rc != 0` inline instead of calling `tl_dup_shared` / `tl_drop_slow` for immortal blocks. Since issue #61, the C backend calls the methods of such dictionaries directly, or inlines them, and specialises functions for them ([ADR 0013](adr/0013-numeric-code.md)); the dictionaries remain for the calls it cannot resolve. |
| 289 | +### Sockets and HTTP |
| 290 | +- **Sockets** (`tilrt/src/net.rs`) are non-blocking, registered once, edge-triggered, with a mio reactor owned by the scheduler. An operation that would block parks the actor on the socket's token; a spurious wake-up only retries it. The network reads and writes `Bytes` (`tl_net_write_string` sends a string). |
| 291 | +- **HTTP framing** (`tilrt/src/http.rs`): `tl_http_parse_request` and `tl_http_parse_chunk` take a buffer and an offset, and return offsets, parsed by `httparse` (Rust's port of picohttpparser). A `Content-Length` that is not a decimal number, or two that differ, make a request invalid; `std/http` answers 400 to a request with both `Content-Length` and `Transfer-Encoding`, 501 to a coding other than `chunked`, and 413 to a body over its limit, and closes the connection after each. |
| 298 | 292 | |
| 299 | | −### Source lines in generated C (issue #35) |
| 300 | | −**Status:** Proposed; accepted by the project owner on 2026-10-09 (PRs #54–#59); needs engineering review (#44). |
| 293 | +### Arrays and owned externs |
| 294 | +[ADR 0014](adr/0014-arrays-and-bigint.md). |
| 295 | +- **`TL_TAG_ARRAY` blocks** have `scan_fsize = TL_SCAN_LARGE`: `fields[0]` is `tl_int(n)`, `fields[1..=n]` the elements. The raw area is the spare capacity: an `i64` count, then that many zeroed slots, so a block of capacity `cap` is `2 + cap` words and still describes itself. Drop and `send` need nothing specific. The functions of `std/array` live in `tilrt/src/array.rs`. |
| 296 | +- **Owned externs.** An extern declared `@extern(c, "sym", owned)` takes its arguments *owned*: it must consume each (store, return or drop it), like a closure. Perceus moves a variable's last use into the call and `dup`s other uses. With an owned argument, `rc == 1` means the caller kept no reference, so the runtime may update the block in place: `tl_array_set` and `tl_array_push` do, and copy a block whose count is not 1. An owned extern that panics drops its arguments first. |
| 301 | 297 | |
| 302 | | −Generated C carries `#line` directives, so C compiler errors, sanitizer reports and debuggers (with `-g`) show `.til` files and lines instead of the generated file's. |
| 298 | +### Big integers |
| 299 | +[ADR 0014](adr/0014-arrays-and-bigint.md). |
| 300 | +- **Fast paths:** `tl_int_add`, `tl_int_sub`, `tl_int_mul`, `tl_int_div`, `tl_int_rem`, `tl_int_eq` and `tl_int_compare` are inline. When both arguments are small and the result is small, they compute it inline; otherwise they call the `_slow` function of the same name (`tilrt/src/int.rs`), which returns a canonical result. Addition, subtraction and multiplication never unwind, so generated code has no yield check after them; division and remainder panic on zero. |
| 301 | +- `tl_int_show` and `tl_hash_int` take big integers too. |
| 302 | +- **Runtime functions that take an `Int` as an index, a count, a size or a duration** read a big integer as the nearest `i64` (saturating). |
| 303 | +- **C bindings:** `tl_int_get` reads small ints only. `tl_int_to_i64` reads any `Int` that fits in 64 bits, and `tl_int_from_i64` makes one (`tilcayo-ffi`: `int_i64`, `int_from_i64`). |
| 304 | + |
| 305 | +### Adding a runtime extern |
| 306 | +- The runtime's externs are listed once, in `crates/tilc_core/src/externs.rs`, with whether each may unwind (panic or park the actor), is `blocking` or is `owned`. Codegen decides from it which calls get a yield check and which symbols `tilrt.h` declares; the interpreter must implement every one. |
| 307 | +- Adding `tl_foo` therefore touches: its `@extern` in `std/<module>.til`; the `#[unsafe(no_mangle)] pub unsafe extern "C"` function in `tilrt`, with a `# Safety` section (or a `static inline` one in `tilrt.h`); its prototype in `tilrt.h`; the interpreter (`tilc_interp`, `externs.rs`); and the table. `crates/tilc_codegen_c/tests/externs.rs` fails if any of them is missing or disagrees (options, interpreter, `libtilrt.a` exports, header), so the one silent mistake left is a wrong `may_unwind`: mark it whenever the function can reach `tl_panic_str` or park. |
| 308 | +- A new `proc` operation is added to `PROC_OPS` (`runtime/tilrt-prims`), which both codegen and the runtime's clause table read, and to the interpreter's scheduler (`tilc_interp`, `sched.rs`). |
| 309 | +- A pure kernel the interpreter needs too (a hash, a string or byte transformation) goes in `runtime/tilrt-prims`, which both call. |
| 310 | + |
| 311 | +## Source lines in generated C |
| 312 | + |
| 313 | +Issue #35. Generated C carries `#line` directives, so C compiler errors, sanitizer reports and debuggers (with `-g`) show `.til` files and lines instead of the generated file's. This changes no layout or convention. |
| 303 | 314 | |
| 304 | 315 | - **Where lines come from.** Core keeps a source span on each `let` (the innermost expression it was lowered for; a `let` pattern's bindings are at the pattern) and on each function (its definition, or the lambda or call site it was made for). Dictionaries and derived methods have none. The C backend turns a span into a line with the file's line index (`tilc_span`), and points at the file by the path the compiler was given (`<std/list.til>` for the embedded standard library). |
| 305 | 316 | - **Shape of the file.** Glue comes first and keeps its own C line numbers: the prelude, literals, prototypes, constant dictionaries, closure entries, `tl_entry` and `main`, then functions without a span. Functions with a span come last, each starting with `#line N "file"`, so no directive ever points back into the generated file. |
| @@ -308,36 +319,37 @@ Generated C carries `#line` directives, so C compiler errors, sanitizer reports |
| 308 | 319 | - **Turning it off.** Setting `TILC_NO_LINE_DIRECTIVES` (to any value) leaves the directives out, to read, grep or debug the generated C by its own lines. The library API takes the source files as an option (`tilc_codegen_c::generate(program, entry, Some(sources))`); `None` also leaves them out. |
| 309 | 320 | - **Tests.** `crates/tilc_codegen_c/tests/lines.rs` checks where the C lines of a function point (its prologue, a call and the yield check after it, a `musttail` call, a `release` and a `reuse`), a C compiler error pointing at the `.til` call, and (with clang) a UBSan report from generated code pointing at the `.til` line. |
| 310 | 321 | |
| 311 | | −### Arrays and owned externs (issue #47; proposed, needs engineering review) |
| 312 | | −Rationale: [ADR 0014](adr/0014-arrays-and-bigint.md). |
| 313 | | −- **`TL_TAG_ARRAY` blocks** have `scan_fsize = TL_SCAN_LARGE`: `fields[0]` is `tl_int(n)`, `fields[1..=n]` the elements. The raw area is the spare capacity: an `i64` count, then that many zeroed slots, so a block of capacity `cap` is `2 + cap` words and still describes itself. Drop and `send` need nothing specific. `send` promotes (shares) an array over 4 KiB that the sender keeps, like strings. The functions of `std/array` live in `tilrt/src/array.rs`. |
| 314 | | −- **Owned externs.** An extern declared `@extern(c, "sym", owned)` takes its arguments *owned*: it must consume each (store, return or drop it), like a closure. Perceus moves a variable's last use into the call and `dup`s other uses. With an owned argument, `rc == 1` means the caller kept no reference, so the runtime may update the block in place: `tl_array_set` and `tl_array_push` do, and copy a block whose count is not 1. An owned extern that panics drops its arguments first. Every other extern still borrows. |
| 322 | +## Validation |
| 315 | 323 | |
| 316 | | −### Big integers (ABI version 2, issue #47; proposed, needs engineering review) |
| 317 | | −Rationale: [ADR 0014](adr/0014-arrays-and-bigint.md). |
| 318 | | −- **`TL_ABI_VERSION` is 2.** Generated `main` calls `tl_abi_check(TL_ABI_VERSION)` first; a runtime built for another version stops with a message. |
| 319 | | −- **An `Int` is a small int or a `TL_TAG_BIGINT` block.** A value in the 63-bit range is always small (canonical form), so word equality decides every comparison with a small int, and a `switch` on an integer literal is unchanged. |
| 320 | | −- **Fast paths:** `tl_int_add`, `tl_int_sub`, `tl_int_mul`, `tl_int_div`, `tl_int_rem`, `tl_int_eq` and `tl_int_compare` are inline. When both arguments are small and the result is small, they compute it inline (with a test that both are small); otherwise they call the `_slow` function of the same name (`tilrt/src/int.rs`), which returns a canonical result. Addition, subtraction and multiplication never unwind, so generated code has no yield check after them; division and remainder still panic on zero. `tl_int_overflow` is gone. |
| 321 | | −- `tl_int_show` and `tl_hash_int` take big integers too. |
| 322 | | −- **Runtime functions that take an `Int` as an index, a count, a size or a duration** read a big integer as the nearest `i64` (saturating). |
| 323 | | −- **C bindings:** `tl_int_get` reads small ints only. `tl_int_to_i64` reads any `Int` that fits in 64 bits, and `tl_int_from_i64` makes one (`tilcayo-ffi`: `int_i64`, `int_from_i64`). |
| 324 | +- **The M0 spike.** `runtime/spike/spike.c` is hand-written C in the shape `tilc` emits. `scripts/spike.sh` (also run by `scripts/ci.sh`) links it against `libtilrt.a` in debug, release, and clang ASan+UBSan builds. It checks that 1M-element lists are summed, consumed and dropped on a fiber stack (iterative drop); FBIP (a unique list is updated in place, a shared one copied); that a `final ctl` op unwinds 500 frames, each owning a list, to its handler, with live blocks back to 0; that 1,000 actors are preempted round-robin, one panics on a division by zero and crashes alone, and 500 are killed mid-loop and release their lists; that an overflow promotes to a big integer and subtracting back gives the small int; and that the process ends with 0 live blocks and 0 actors. |
| 325 | +- **Differential tests.** `crates/tilc_codegen_c/tests/native.rs` runs every `tests/run` program natively, and requires the interpreter's output and zero live blocks. |
| 326 | +- **Sanitizers and models.** CI runs native programs under ASan and UBSan, and loom models of the scheduler's hand-offs and timers; `TILC_CI_TSAN=1` adds ThreadSanitizer. |
| 327 | +- **Extern table.** `crates/tilc_codegen_c/tests/externs.rs` checks the runtime's externs across the table, std, the interpreter, `libtilrt.a` and `tilrt.h`. |
| 328 | +- **Runtime unit tests** (`cargo test -p tilrt -p tilrt-prims`) cover the pure kernels and HTTP framing, and run small scenarios as a root actor under the leak oracle. |
| 324 | 329 | |
| 325 | | −### Bytes builders (issue #47; proposed, needs engineering review) |
| 326 | | −- A `bytes.Builder` is a `TL_TAG_BUILDER` block (`tilrt/src/builder.rs`). Its appends and `build` are owned externs: a unique builder grows in place, and `build` turns it into a `TL_TAG_BYTES` block in place (moving the bytes over the capacity word, then shrinking the block). A shared builder is copied first. `send` promotes a builder over 4 KiB that the sender keeps, like `Bytes`. |
| 330 | +## Known limitations |
| 327 | 331 | |
| 328 | | −**Not yet implemented:** |
| 329 | | −- accessors for `Bytes` in C bindings (`tl_bytes_ptr`, `tl_bytes_len`, `tl_bytes_from`). |
| 330 | | − |
| 331 | | −### Callbacks from C (issue #48) |
| 332 | | −**Status:** Proposed ([ADR 0015](adr/0015-c-callbacks-and-bindings.md)); needs engineering review (#44). The value layout and the calling convention are unchanged: `TL_ABI_VERSION` stays 1. |
| 333 | | − |
| 334 | | −- **`tl_callback`** (24 bytes: the actor's `ctx`, the closure, a runtime-private thread token) is the `void *` environment a shim passes C with its trampoline, for one extern call. `tl_callback_begin(ctx, &cb, f)` sets it up; `tl_callback_call(&cb, argc, args)` calls `f` (borrowed by the extern, duplicated per call) with owned arguments and returns an owned result; `tl_callback_end(&cb, result)` returns `result`, or drops it and returns unit after a panic. `tl_callback_failed` (inline) tells whether one happened. |
| 335 | | −- **Panics:** a callback's panic unwinds to `tl_callback_call` and stays pending in `ctx->yielding`. Further calls return unit without running anything; once the extern returns, the generated code unwinds. |
| 336 | | −- **Every extern may unwind.** The backend checks `yielding` after every extern outside the runtime (the runtime's functions are prefixed `tl_`, and listed with whether they may unwind in `tilc_core::externs`), so a shim may also panic with `tl_panic_str`. The prefix `tl_` is reserved for the runtime. |
| 337 | | −- **No suspension inside the call:** the actor counts its calls in progress. Meanwhile `tl_preempt` only refills the budget, so exit signals wait; `tl_call_blocking` runs the thunk inline; parking aborts. |
| 338 | | −- **Guards** (abort): a call on another thread or after `tl_callback_end`, `tl_callback_begin` on the blocking pool, more than 31 arguments. |
| 339 | | − |
| 340 | | −### Adding a runtime extern (issue #62) |
| 341 | | −- The runtime's externs are listed once, in `crates/tilc_core/src/externs.rs`, with whether each may unwind (panic or park the actor), is `blocking` or is `owned`. Codegen decides from it which calls get a yield check and which symbols `tilrt.h` declares; the interpreter must implement every one. |
| 342 | | −- Adding `tl_foo` therefore touches: its `@extern` in `std/<module>.til`; the `#[unsafe(no_mangle)] extern "C"` function in `tilrt` (or a `static inline` one in `tilrt.h`); its prototype in `tilrt.h`; the interpreter (`tilc_interp`, `externs.rs`); and the table. `crates/tilc_codegen_c/tests/externs.rs` fails if any of them is missing or disagrees (options, interpreter, `libtilrt.a` exports, header), so the one silent mistake left is a wrong `may_unwind`: mark it whenever the function can reach `tl_panic_str` or park. |
| 343 | | −- A new `proc` operation is added to `PROC_OPS` (`runtime/tilrt-prims`), which both codegen and the runtime's clause table read, and to the interpreter's scheduler (`tilc_interp`, `sched.rs`). |
| 332 | +- A cycle through `Ref`s lives until its region ends, which clears the region's references (ADR 0002, Revision 1); reference counting alone cannot reclaim it. |
| 333 | +- An `rc` overflow beyond 2^31 references is not handled. |
| 334 | +- A Rust panic inside an `extern "C"` entry point aborts the process. That is acceptable for runtime bugs (`expect("tilrt: ...")`), but not for user errors, which use `tl_panic`. |
| 335 | +- C bindings have no accessors for `Bytes` yet (`tl_bytes_ptr`, `tl_bytes_len`, `tl_bytes_from` are planned). |
| 336 | + |
| 337 | +## History |
| 338 | + |
| 339 | +What changed, in order. Each step's rationale is in the ADR it names. |
| 340 | + |
| 341 | +- **ABI v0 (M0)**, validated by the M0 spike and accepted on 2026-10-08 (issue #2): the values, blocks, context, reference counting, yield-bubbling unwinding and preemption above, with a single scheduler thread and corosensei fibers. |
| 342 | +- **Revision 1** (ADRs 0002–0004, Revision 1; accepted with v0, implemented in M5), `TL_ABI_VERSION` 1: |
| 343 | + - one C signature for every generated function, with `ctx->xargs`, so every tail call can be `musttail`; |
| 344 | + - externs borrow; immortal blocks; regions; handler capabilities; |
| 345 | + - the runtime's own context switch (implemented on x86_64 Linux: ADR 0011); |
| 346 | + - sending by move, share or copy, and threads (M6). |
| 347 | + - Revision 1 also replaced yield checks with table-driven unwinding (`-fexceptions`, `_Unwind_ForcedUnwind`). That part was never implemented: ADR 0003, Revision 2 keeps yield checks, which [Unwinding](#unwinding) describes. |
| 348 | +- **M7, M8:** the extern convention, the blocking pool and resources (ADR 0005, Revision 1); sockets on a mio reactor, and real time once a socket opens (ADR 0004, Revision 3). |
| 349 | +- **Issue #36:** `Bytes`, keep-alive HTTP framing on buffers and offsets, `tl_string_join` (ADR 0012). |
| 350 | +- **Issue #34:** the Perceus optimisations (borrowed parameters, drop specialisation and reuse, constant dictionaries); `tl_dup` and `tl_drop` test `rc != 0` inline. |
| 351 | +- **Issue #47, `TL_ABI_VERSION` 2:** arrays and owned externs, big integers (overflow promotes instead of panicking; `tl_int_overflow` is gone), builders, `tl_abi_check` (ADR 0014; ADR 0012, Revision 1). |
| 352 | +- **Issue #48:** callbacks from C and generated bindings (ADR 0015). No layout change. |
| 353 | +- **Issue #35:** `#line` directives in generated C. |
| 354 | +- **v1 effects:** `defer` (`tl_defer`, ADR 0016) and multi-shot continuations (`tl_handle_multi`, `TL_YIELD_CLONE`, `TL_YIELD_DISCARD`, `tl_region_exit`, ADR 0017). |
| 355 | +- **Issues #61 and #45:** never-unwinding calls lose their yield check, constant dictionaries are called directly, fewer wake-ups (ADR 0004, Revision 4), per-thread timers and ThreadSanitizer (Revision 5). |