| @@ -0,0 +1,83 @@ |
| 1 | +# ADR 0014: Arrays, owned extern parameters, and bigint promotion |
| 2 | + |
| 3 | +**Status:** Proposed — 2026-10-09 (issue #47); needs engineering review (#44). It changes the runtime ABI: a new block kind (arrays), owned extern parameters, and a boxed `Int` (`TL_ABI_VERSION` 2). |
| 4 | + |
| 5 | +## Context |
| 6 | +- Programs had only linked lists. Indexing was O(n), and nothing gave O(1) random access or a compact block of values. The ABI reserved `TL_SCAN_LARGE` (`scan_fsize` 0xFF: the count in `fields[0]`) for arrays, but nothing allocated such blocks. |
| 7 | +- Externs *borrow* their arguments (ABI Revision 1). A borrowed argument with `rc == 1` may still be used by the caller after the call, so the runtime cannot update it in place: ADR 0012 noted that in-place builder appends need an extern parameter that Perceus passes *owned*. Arrays need the same for `set` and `push`. |
| 8 | +- `Int` was exactly the 63-bit range, and overflow panicked (`tl_int_overflow`). The roadmap (issue #47) asks for promotion to a big integer instead. Every value that can be an `Int` would then be either a tagged word or a block, which is an ABI change. |
| 9 | + |
| 10 | +## Decision |
| 11 | + |
| 12 | +### `Array<a>`: an immutable array, updated in place when unique |
| 13 | +**Semantics.** `Array<a>` (`std/array`) is an immutable value, like `List`. Updating an array gives a new array; the old one is unchanged. When the array being updated is *unique* (its count is 1, and the caller passes its last reference), the runtime updates it in place instead of copying: Perceus FBIP, applied by the runtime. |
| 14 | + |
| 15 | +**API (`std/array`):** |
| 16 | + |
| 17 | +| Function | Behaviour | |
| 18 | +|---|---| |
| 19 | +| `empty`, `from_list`, `to_list`, `length` | | |
| 20 | +| `get(a, i) -> Option<a>` | `None` out of range | |
| 21 | +| `set(a, i, x)` | panics out of range (`array.set: index 5 out of range for length 3`); in place when unique | |
| 22 | +| `push(a, x)` | appends; in place when unique and there is spare capacity, else grows (doubling) | |
| 23 | +| `slice(a, start, end)` | both bounds clamped to `0..length`; empty when `end <= start` (as `bytes.slice`) | |
| 24 | +| `map(a, f)`, `fold(a, init, f)` | in tilcayo, over `length` and an unchecked read; effect-polymorphic like `list.map` | |
| 25 | + |
| 26 | +The type gets `Eq`, `Ord` (lexicographic), `Show` and `Debug` (`[1, 2, 3]`, like a list) and `Hash`, so types containing arrays can derive them. These are written in tilcayo in `std/array`, the type's module (ADR 0007's coherence rule). |
| 27 | + |
| 28 | +**Representation.** A `TL_TAG_ARRAY` block (`0xFF0A`) with `scan_fsize = TL_SCAN_LARGE`: |
| 29 | + |
| 30 | +``` |
| 31 | +[ header | tl_int(n) | x1 ... xn | int64 spare | spare unused slots ] |
| 32 | + fields[0] scanned raw area |
| 33 | +``` |
| 34 | + |
| 35 | +- `fields[0]` and `fields[1..=n]` follow the reserved layout, so drop, `send`'s walk and the size computation handle arrays without special cases. |
| 36 | +- The raw area is the spare capacity: a count, then that many unused slots (zeroed). Its size is `8 * (1 + spare)`, so the block still describes itself. |
| 37 | +- An in-place `push` writes the new element over the spare count and writes the decreased count one slot further: the block's size does not change. When there is no spare slot, a unique array is reallocated with twice the capacity (at least 4). |
| 38 | +- Arrays are allocated by the runtime only; `tl_alloc` still refuses `TL_SCAN_LARGE`. |
| 39 | + |
| 40 | +**Sending** follows ADR 0002 Revision 1 unchanged: a unique array is moved; one the sender keeps is copied, or promoted to shared when it is larger than 4 KiB, like strings and `Bytes`. A shared array has a negative count, so it is never updated in place: an update copies it. |
| 41 | + |
| 42 | +**Interpreter.** An array is an `Rc<Vec<Val>>`, updated with `Rc::make_mut`: in place when the interpreter holds the only reference, copied otherwise. The interpreter keeps references in its environments, so it copies more often than native code does; that changes the cost, not the result. |
| 43 | + |
| 44 | +### Owned extern parameters |
| 45 | +- `@extern(c, "sym", owned)` declares an extern whose arguments are all **owned** by the callee: it consumes each of them (stores, returns or drops it). Perceus treats its arguments as owned positions, like a closure call's: the last use of a variable is moved into the call, and any other use takes a `dup` first. Borrow inference makes a parameter passed there owned. |
| 46 | +- So, inside an owned extern, `rc == 1` means the caller has no other reference: the runtime may update the block in place and return it. |
| 47 | +- Only runtime functions use it now (`std/array`'s `set` and `push`). Other externs keep the borrowed convention. `Program::owned` lists the symbols, as `Program::blocking` does for `blocking`. |
| 48 | + |
| 49 | +### `Int` promotes to a big integer on overflow |
| 50 | +**Semantics.** `Int` is an arbitrary-precision integer. Arithmetic never overflows; division and remainder still truncate toward zero, and dividing by zero still panics. |
| 51 | + |
| 52 | +**Representation: small ints stay tagged.** |
| 53 | +- A value in the 63-bit range is always a tagged small int, as before. A value outside it is a `TL_TAG_BIGINT` block (`0xFF0B`): no scanned fields; raw area `int64 len`, then `|len|` 64-bit limbs of the magnitude, least significant first. The sign of `len` is the sign of the number. The top limb is not zero. |
| 54 | +- **Canonical form:** a result that fits in 63 bits is always returned small. So two `Int`s are equal exactly when their words are equal or both are blocks with equal limbs, a small int never equals a big one, and matching on an integer literal (`switch` on `tl_int(n)`) is unchanged. |
| 55 | + |
| 56 | +**Fast paths stay inline.** In `tilrt.h`, `tl_int_add`, `tl_int_sub` and (newly inline) `tl_int_mul` test that both arguments are small and use the overflow builtins, as before. Anything else (a block argument, or an overflow) calls the runtime's slow path (`tl_int_add_slow`, ...), which computes with bigints and returns a canonical result. The extra cost is one `and` and one branch per operation. Comparisons, division, `show` and `hash` stay runtime functions, with a branch for blocks. |
| 57 | + |
| 58 | +**Implementation.** The slow paths use the `num-bigint` crate (rust-num; pure Rust, widely used). It converts the limbs to a `BigInt`, computes, and writes a new block. Multiplication, division and decimal conversion are where hand-written bigints go wrong, and the slow path is not hot. The interpreter uses the same crate, so both backends compute, print and parse identically. |
| 59 | + |
| 60 | +**Consequences in the runtime and the interpreter:** |
| 61 | +- `tl_int_overflow` is gone. Addition, subtraction and multiplication no longer unwind, so generated code drops its yield checks after them. |
| 62 | +- `show` prints every digit; `string.parse_int` accepts any length. |
| 63 | +- `hash` of a big integer mixes its sign and limbs (FNV-1a over the limbs, then the usual mixer); both backends use the same formula. |
| 64 | +- Runtime functions that use an `Int` as an index, a count, a size or a duration (`bytes.get`, `array.slice`, `process.sleep`, `net.read`, ...) treat a big integer as the nearest 64-bit integer. An index that large is out of range like any other. |
| 65 | +- The interpreter's `Int` is an `i64` that is always within 63 bits, or an `Rc<BigInt>` outside them. |
| 66 | +- Integer literals are still limited to 63 bits (E0110 is unchanged). Larger constants are computed, or parsed with `string.parse_int`. |
| 67 | + |
| 68 | +**ABI version.** The block kind, the inline fast paths and the removal of `tl_int_overflow` make this ABI version 2. Generated `main` calls `tl_abi_check(TL_ABI_VERSION)` first, and the runtime stops when it was built for another version, as `tl_root_cap` already does for the number of `proc` operations. A stale runtime then fails with a message instead of misreading big integers. |
| 69 | + |
| 70 | +## Consequences |
| 71 | +- **Breaking:** programs that relied on the overflow panic now compute a big integer. `tests/run/panic_overflow.til` becomes a test of promotion. |
| 72 | +- **Cost of `Int`:** one more test per addition and subtraction (both arguments small); multiplication becomes inline, and the yield check after arithmetic goes away. The `arith` benchmark must not get slower (see the implementation notes). |
| 73 | +- **Arrays of `Float`** hold boxed floats; arrays of `Int` hold tagged words. There are no unboxed numeric arrays. |
| 74 | +- **C bindings** (`tilcayo-ffi`, `@extern` C code) that read an `Int` with `tl_int_get` must handle a block, or document that they take small ints. The FFI crate gets a checked accessor. |
| 75 | + |
| 76 | +## Alternatives considered |
| 77 | +- **An array header field for the capacity** (`fields[0]` holding both length and capacity). It would change the meaning of the reserved `TL_SCAN_LARGE` layout, which drop and `send` read; the spare count in the raw area keeps that layout as it is. |
| 78 | +- **Arrays as persistent vectors (RRB trees).** Cheaper copies of shared arrays, but every access walks a tree, and the unique case, the one FBIP makes common, gets slower. A plain block is simpler and fast when unique. |
| 79 | +- **`map` and `fold` in the runtime**, calling the closure from Rust. Closures can yield (preemption, panics, exit signals), so the Rust frame would have to take part in unwinding. Written in tilcayo, they are ordinary code. |
| 80 | +- **Making every extern argument owned.** Every runtime function would have to drop its arguments, and every caller would lose the borrowed fast path. Owned is opt-in, per extern. |
| 81 | +- **A hand-written bigint.** Fewer dependencies, but division and decimal conversion are subtle, and both backends would need the same code. `num-bigint` is the standard choice; `ibig`/`dashu` are faster on huge numbers, which is not the use case. |
| 82 | +- **Checked 64-bit `Int` with a panic (status quo), or wrapping arithmetic.** The roadmap asks for promotion: overflow should not crash an actor, and silent wrapping is worse. |
| 83 | +- **Boxing every `Int`.** Simplest, but every arithmetic operation would allocate. |