| @@ -0,0 +1,342 @@ |
| 1 | +# Code health audit (issue #62) |
| 2 | + |
| 3 | +> **Status.** This audit was written against `main` at `f2b02b7`, before the v1 feature stack (packages, FFI callbacks and bindgen, multi-parameter traits, HKT, derives, arrays, bigint, HTTP limits, `defer`, multi-shot) landed. Line numbers refer to that commit. Each finding's checkbox is ticked as the cleanliness PRs land; a finding or part of one that is deliberately not done carries a note saying why. |
| 4 | + |
| 5 | +Audit of `main` at `f2b02b7` (2026-10-09). It covers the compiler crates, `runtime/tilrt`, `runtime/tilcayo-ffi`, `std/`, `scripts/` and the test harnesses. Every finding was checked against the code. Two findings (H2, M5) were reproduced by running `tilc` on small programs, written outside the repository. |
| 6 | + |
| 7 | +## Summary |
| 8 | + |
| 9 | +The codebase is in good shape for a three-day-old v0. Several things are already better than usual: |
| 10 | +- **Lints:** clippy is clean with `-D warnings`, and `clippy::undocumented_unsafe_blocks` is enforced, so every `unsafe` block in `tilrt` has a `SAFETY` comment. |
| 11 | +- **Module docs:** every source file starts with a module doc (`//!`). |
| 12 | +- **Diagnostics:** all 51 codes are listed in `docs/reference/diagnostics.md`. |
| 13 | +- **Testing:** differential testing (interpreter against native code, with a leak oracle), loom models of the scheduler hand-offs, and ASan/UBSan runs in CI. |
| 14 | + |
| 15 | +The debt is structural and concentrated in a few places: |
| 16 | + |
| 17 | +1. **The runtime contract has no single source of truth.** One std extern, one `proc` operation or one std constructor is described by hand in up to seven places: `std/*.til`, `tilrt`, `tilrt.h`, two hand-kept lists in codegen, the interpreter, and the docs. Nothing checks that these agree. One of the lists, `PANICKING`, decides whether generated code checks for unwinding after a call. Forgetting to update it compiles silently into wrong code (H1). |
| 18 | +2. **The checker accepts programs that lowering cannot handle.** Attributes are unvalidated strings. A function without a body passes `tilc check`, then crashes `tilc run` (H2). |
| 19 | +3. **Security-relevant runtime code has no tests.** HTTP request framing has no unit tests and no test of any path that rejects a request (H3). More broadly, `tilrt` has 9 unit tests for 5.8k lines; most of it is covered only end to end. |
| 20 | +4. **Layering and size.** Codegen depends on the whole front end through `tilc_db`. `tilc_core` mixes the IR, lowering and the interpreter. Five files are over 1,200 lines. |
| 21 | + |
| 22 | +The reference interpreter duplicates the runtime's semantics on purpose: it is the test oracle. That is not a defect (see "Deliberate choices"). The pure leaf helpers both copies share are a different matter: they are duplicated by accident, and they have already drifted apart (M3). |
| 23 | + |
| 24 | +**Sizes:** S is half a day or less; M is 1 to 3 days; L is more than 3 days. |
| 25 | +**PRs:** (1) front end: syntax, hir, types; (2) core, perceus, codegen; (3) runtime `tilrt`; (4) driver, LSP, std, scripts, docs index. |
| 26 | + |
| 27 | +--- |
| 28 | + |
| 29 | +## Findings |
| 30 | + |
| 31 | +### High |
| 32 | + |
| 33 | +- [ ] **H1. Adding a std extern means hand-syncing up to 7 places, and one omission compiles silently into wrong code.** Size **M**, PRs **(2)** and **(3)**. |
| 34 | + - **The touch points for a new `tl_foo`:** |
| 35 | + 1. `std/<module>.til`: `@extern(c, "tl_foo")`. |
| 36 | + 2. `runtime/tilrt/src/<module>.rs`: the `#[unsafe(no_mangle)] extern "C" fn tl_foo`. Int and float arithmetic are instead `static inline` functions in `tilrt.h`. |
| 37 | + 3. `runtime/tilrt/include/tilrt.h`: the prototype. Today this step is optional, and 16 exported functions have none: all of `tl_bytes_*`, `tl_hash_bytes` and `tl_string_join`. |
| 38 | + 4. `crates/tilc_codegen_c/src/emit.rs:90` `DECLARED`, if the header declares it. |
| 39 | + 5. `crates/tilc_codegen_c/src/emit.rs:74` `PANICKING`, if it may panic or park the actor. |
| 40 | + 6. `crates/tilc_core/src/interp.rs:580` `call_extern`, or `:753` `bytes_extern`. |
| 41 | + 7. `docs/runtime-abi.md`. |
| 42 | + |
| 43 | + A new `proc` operation has its own set: `std/process.til`, `tilc_core/src/sched.rs:336` `request`, `tilrt/src/process.rs:30` `PROC_OPS` and `:49` `CLAUSES`, and a second `PROC_OPS` in `tilc_codegen_c/src/lib.rs:149`. |
| 44 | + - **The problem:** nothing checks that these places agree. |
| 45 | + - **Missing step 6:** the interpreter fails only at run time, with "unknown extern", and only when a program calls the extern. |
| 46 | + - **Missing step 5 (the hazard):** `may_unwind` (`emit.rs:810-822`) returns false, so the generated code has no `TL_YIELDING` check after the call (`emit.rs:648-650`). After a panic or a park, the caller keeps running with a meaningless result. The only thing that catches this is a test that panics through that exact extern. All current externs are listed correctly; I checked every runtime function that calls `panic_with`, `tl_panic_str` or `park`. The risk is to future additions. |
| 47 | + - **The same hole exists for user FFI.** `tl_panic_str` is in the public `tilrt.h:171`, but ADR 0005 (Revision 1) forbids panics only in `blocking` externs. A non-blocking binding that panics gets no yield check. |
| 48 | + - **A misplaced comment:** the doc comment meant for `DECLARED` sits on `PANICKING` (`emit.rs:72-73`). |
| 49 | + - **The fix:** |
| 50 | + 1. **One table of std externs.** Put it in `tilc_core` (e.g. `externs.rs`) or a leaf crate: `struct Extern { sym, arity, may_unwind, in_header }`. Codegen derives `PANICKING` and `DECLARED` from it. The interpreter's dispatch is keyed on it. `PROC_OPS` moves next to it, so codegen and `tilrt` share one list. |
| 51 | + 2. **A consistency test.** Parse every `@extern` in `std/*.til` and assert that each one: |
| 52 | + - is in the table with the right arity; |
| 53 | + - is handled by the interpreter; |
| 54 | + - is exported by `tilrt` (against an `EXPORTS` list, or `nm libtilrt.a`); |
| 55 | + - is declared in `tilrt.h`. |
| 56 | + 3. **Foreign externs:** either treat them as may-unwind (one predictable branch per call), or add a `panics` option next to `blocking`. Document the rule in ADR 0005 and `tilrt.h`. |
| 57 | + 4. Until this lands, add an "Adding a std extern" checklist to `docs/runtime-abi.md`. |
| 58 | + |
| 59 | +- [ ] **H2. Attributes are unvalidated strings: functions without a body pass `tilc check` and crash `tilc run`.** Size **S**, PR **(1)** (with the readers in (2)). |
| 60 | + - **The paths:** |
| 61 | + - attributes are read by string at `tilc_hir/src/lower.rs:86`, `tilc_types/src/env.rs:662`, `tilc_types/src/send.rs:115` and `tilc_core/src/lower.rs:347-368`; |
| 62 | + - the crash is the `self.fn_ids[&def]` lookup at `tilc_core/src/lower.rs:1552`. |
| 63 | + - **Reproduced (in a scratch directory):** |
| 64 | + - `fn p(x: Int) -> Int` with no body and no attribute: `tilc check` exits 0, then `tilc run` panics with `no entry found for key` at `lower.rs:1552:32`. |
| 65 | + - A typo, `@extrn(c, "tl_println")`, and `@extern(c)` without a symbol: both crash the same way. |
| 66 | + - `@extern(c, "tl_println", blockng)` is accepted and silently not blocking. `note_blocking` matches the string `"blocking"` (`lower.rs:365`). |
| 67 | + - `@builtin`, used in `std/prelude.til:8`, `std/process.til:8,61` and `std/ffi.til:8`, is not read by any compiler code. It looks semantic, but it is a comment. |
| 68 | + - **The problem:** lowering assumes "the input is free of errors" (`tilc_core/src/lower.rs:24`), but the checker never establishes these invariants. |
| 69 | + - **The fix:** |
| 70 | + - Parse attributes once in `tilc_hir` into a typed enum: `Extern { abi, symbol, blocking }`, `Derive(..)`, `ThreadSafe`, `Test { should_panic }`, `Builtin`. |
| 71 | + - Report these as diagnostics: an unknown attribute or option, a malformed `@extern`, and a function without a body that is not `@extern`. Add the new codes to `diagnostics.md`, with `tests/ui` cases. |
| 72 | + - Lowering then reads typed fields instead of strings. |
| 73 | + - Either give `@builtin` a meaning, or remove it. |
| 74 | + |
| 75 | +- [ ] **H3. HTTP framing and the runtime's pure functions have no tests of their rejecting paths.** Size **S**, PRs **(3)** and **(4)**. |
| 76 | + - **The code at stake:** |
| 77 | + - `tilrt/src/net.rs:347` `tl_http_parse_request` rejects a non-decimal `Content-Length` and conflicting duplicates. That is the defence against request smuggling on kept-alive connections, as its own doc says. |
| 78 | + - `net.rs:407` `tl_http_parse_chunk` handles chunked bodies. |
| 79 | + - `std/http.til:239-249` answers `Content-Length` together with `Transfer-Encoding` with 400, and an unsupported `Transfer-Encoding` with 501. |
| 80 | + - **The problem:** |
| 81 | + - None of these rejecting paths is tested anywhere. `crates/tilc/tests/cli.rs` sends only valid requests: one `Content-Length: 5` request and one chunked body. |
| 82 | + - More broadly, `tilrt` has 9 `#[test]`s for 5,848 lines. `prims.rs`, `bytes.rs`, `net.rs`, `heap.rs`, `process.rs`, `sched.rs` and `handlers.rs` have none. Differential tests cover most of this end to end, but the parsers and `url_decode` (`prims.rs:694`) have no direct tests. |
| 83 | + - **The fix:** |
| 84 | + 1. Factor the pure parsing out of the two externs into Rust functions over `&[u8]` that return Rust enums. The externs only build the cells. |
| 85 | + 2. Unit-test those functions: partial input, invalid input, duplicate and conflicting `Content-Length`, an oversized chunk, and offsets past the end. |
| 86 | + 3. Add `cli.rs` cases that send malformed and smuggling-shaped requests, and expect 400 or 501 with the connection closed. |
| 87 | + |
| 88 | +### Medium |
| 89 | + |
| 90 | +- [ ] **M1. Codegen owns the C build driver, so it depends on the whole front end.** Size **S**, PRs **(2)** and **(4)**. |
| 91 | + - **The paths:** `crates/tilc_codegen_c/Cargo.toml` depends on `tilc_db` and `toml`. |
| 92 | + - The only use of `tilc_db` is `driver.rs:7` (`NativeDep`, `NativeKind`). |
| 93 | + - The only use of `toml` is reading a binding crate's `Cargo.toml` (`driver.rs:252-283`). |
| 94 | + - `cargo tree -p tilc_codegen_c` shows codegen → `tilc_db` → syntax, hir and types: the back end depends on the front end. |
| 95 | + - `driver.rs:286` is a third copy of FNV-1a (see M3). |
| 96 | + - **The fix:** move `driver.rs` into the `tilc` driver: compiler invocation, native dependencies, cargo and pkg-config. Codegen keeps `generate`/`generate_entries` → C text, and depends only on `tilc_core`, `tilc_perceus` and `tilc_span`. |
| 97 | + |
| 98 | +- [ ] **M2. `tilc_core` mixes the IR, lowering and the interpreter.** Size **M**, PR **(2)**. |
| 99 | + - **The paths:** `crates/tilc_core/src` holds `ir.rs` (411 lines), `lower.rs` (2,002), `interp.rs` (929) and `sched.rs` (586). |
| 100 | + - **The problem:** `tilc_perceus` and `tilc_codegen_c` need only `ir`. Through `tilc_core` they also depend on `tilc_hir`, `tilc_types` and `corosensei`. A change in the interpreter rebuilds the back end. |
| 101 | + - **The fix:** split `interp.rs` and `sched.rs` into a `tilc_interp` crate, used by the driver and the tests. Keep `ir` and `lower` in `tilc_core`. If the front-end dependency of Perceus matters later, move `ir` to its own crate. |
| 102 | + |
| 103 | +- [ ] **M3. The interpreter and the runtime duplicate pure helpers, and they have already drifted.** Size **S**, PRs **(2)** and **(3)**. |
| 104 | + - **The duplicated code:** |
| 105 | + |
| 106 | + | Helper | Interpreter (`tilc_core/src/interp.rs`) | Runtime (`tilrt/src/prims.rs`) | |
| 107 | + |---|---|---| |
| 108 | + | `mix` | `:917` | `:95` | |
| 109 | + | FNV-1a `hash_bytes` | `:873` | `:399` (third copy: `tilc_codegen_c/src/driver.rs:286`) | |
| 110 | + | `url_decode` | `:882` | `:694` | |
| 111 | + | HTML escaping | `:696` | `:438` | |
| 112 | + | `random_bytes` | `:906` | `:637` | |
| 113 | + | `string_split` semantics | `:642` | `:335` | |
| 114 | + |
| 115 | + The 63-bit Int range is spelled out 8 times: `interp.rs:594,665`, `emit.rs:493`, `tilc_hir/src/lower.rs:1066`, `prims.rs:87,367`, `net.rs:365,419`. |
| 116 | + - **The drift:** `tl_random_int` uses rejection sampling in the runtime (`prims.rs:648-664`), but plain modulo, which is biased, in the interpreter (`interp.rs:724-731`). |
| 117 | + - **Why this is accidental, not deliberate:** the interpreter is the oracle for the compiler (lowering, Perceus, codegen). For leaf functions over bytes, a second copy adds no oracle value; it only drifts. |
| 118 | + - **The fix:** a dependency-free crate (e.g. `crates/tilc_prims`) holding: |
| 119 | + - the pure kernels: `mix`, `hash_bytes`, `hash_combine`, `url_decode`, `html_escape`, `split`, `random_below`; |
| 120 | + - `INT_MIN` and `INT_MAX` with a `checked_int` helper. |
| 121 | + |
| 122 | + Both `tilrt` and the interpreter call it. Value marshalling stays separate in each. |
| 123 | + |
| 124 | +- [ ] **M4. Std items are identified by name and constructor position across all layers.** Size **M**, PRs **(1)**, **(2)** and **(3)**. |
| 125 | + - **Effect names as strings:** |
| 126 | + - codegen: `"std/process.proc"` (`lib.rs:172`) and `"std/ref.*"` (`emit.rs:816,968-978`); |
| 127 | + - interpreter: `sched.rs:85`; |
| 128 | + - lowering: `module_by_path("std/ref")` and `("std/html")` (`lower.rs:1149,1170`); |
| 129 | + - types: `send.rs:35-46`, alongside the `WellKnown` table (`env.rs:40-66`), which already resolves some of these. |
| 130 | + - **Constructor tags hard-coded in the runtime:** |
| 131 | + - `Ok`/`Error` = 0/1 (`values.rs:95-103`); |
| 132 | + - `Nil`/`Cons` (`values.rs:108-111`, again by hand in `prims.rs:343-353`); |
| 133 | + - `Lt`/`Eq`/`Gt` (`prims.rs:77`); |
| 134 | + - `Head` and `Chunk` tags 0-3 (`net.rs:353-427`, against `std/http.til:343-360`); |
| 135 | + - and the same tags again in the interpreter (`interp.rs:799+`, `:835+`). |
| 136 | + - **The problem:** reordering the constructors of a std type silently breaks both back ends. Only the constructors `tilrt/src/process.rs` builds (`Option` and the `std/process` types) are covered by a test, per its module doc (`:14-22`). For `proc`, the runtime checks only the number of operations (`tl_root_cap(ctx, PROC_OPS.len())`, `emit.rs:223`), not their order. |
| 137 | + - **The fix:** |
| 138 | + - Extend `WellKnown` into one resolved table of the std items the back ends know: types, effects, constructors. |
| 139 | + - Carry it into Core, e.g. `EffectDecl::builtin: Option<BuiltinEffect>`, so codegen and the interpreter match on an enum. |
| 140 | + - Add one test asserting the tag of every constructor the runtime builds against the analysed std. |
| 141 | + |
| 142 | +- [ ] **M5. Which module a path denotes is decided in four places, and one of them is wrong.** Size **S**, PR **(4)**. |
| 143 | + - **The four places:** |
| 144 | + - `crates/tilc/src/main.rs:142` `add_target`; |
| 145 | + - `main.rs:336-354`, inside `test`; |
| 146 | + - `main.rs:294` `package_natives`; |
| 147 | + - `crates/tilc_lsp/src/lib.rs:234` `open`. |
| 148 | + - **The bug, reproduced:** in a package with `src/main.til` and `src/util.til`, `tilc test src/util.til` printed `test main.in_main ... ok`. It ran `main`'s tests and skipped `util`'s, whose test would have failed: `add_target` returns `"main"` for any file under `src/` (`main.rs:153`). |
| 149 | + - **A related problem:** the LSP discards manifest errors (`let _ = self.db.load_package(&root)`, `tilc_lsp/src/lib.rs:241`), so a broken `tilcayo.toml` shows up as unresolved imports. Manifest errors are plain `String`s (`tilc_db/src/manifest.rs:109,117,198`), not diagnostics. |
| 150 | + - **The fix:** |
| 151 | + - Add `Db::add_target(path) -> Result<Target, LoadError>` in `tilc_db`. It loads the package or the file, and returns the module(s) the path names, from its place under `src/` or `test/`. The driver subcommands and the LSP all use it. |
| 152 | + - Make manifest errors diagnostics pointing into `tilcayo.toml`, so the CLI and the LSP both report them. |
| 153 | + |
| 154 | +- [ ] **M6. Oversized files and functions.** Size **M**, PRs **(1)**, **(2)** and **(3)** (mechanical moves along existing section comments). |
| 155 | + - `tilc_core/src/lower.rs` (2,002 lines). Its `// ----` sections are already in place, so the split is mechanical: |
| 156 | + - move "derived impls" (`:679-988`) to `lower/derive.rs`; |
| 157 | + - move "HTML" (`:1164-1290`) to `lower/html.rs`; |
| 158 | + - move "patterns" (the decision tree, `:1667-2002`) to `lower/pattern.rs`. |
| 159 | + - `tilc_types/src/infer.rs` (1,567 lines): move `handle` (176 lines, `:1266`) and `region` to `infer/handlers.rs`, and patterns (`:1443+`) to `infer/pat.rs`. `FnInfer::new` and `check_body_against` take 8 and 10 arguments (`#[allow(clippy::too_many_arguments)]`, `infer.rs:93`, `lib.rs:577`); pass a context struct instead. |
| 160 | + - `tilc_codegen_c/src/emit.rs` (1,227 lines): |
| 161 | + - `value` is 271 lines (`:826`); move its `Perform`, `Handle` and `Region` arms to `emit/effects.rs`; |
| 162 | + - move the 60-line C `PRELUDE` string (`:16-70`) to `prelude.h`, pulled in with `include_str!`. It can then be read and compiled as C. |
| 163 | + - `tilrt/src/sched.rs` (1,367 lines) holds five concerns. Split them into: |
| 164 | + - `actor.rs`: actor state and the mailbox (`Proc`, `Mailbox`, `Cell`, `:85-330`); |
| 165 | + - `reactor.rs`: the reactor and I/O (`:1031-1170`); |
| 166 | + - `clock.rs`: the clock and timers (`:1172-1250`); |
| 167 | + - `sched.rs` keeps the queues and workers (`:826-1018`) and the C entry points (`:1252-1367`). |
| 168 | + - `tilc_core/src/sched.rs` `request` (218 lines): one function per operation, as `tilrt/src/process.rs` already does. |
| 169 | + - Leave as they are: `tilc_hir/src/lib.rs` `collect_items` (175 lines) and `tilc_types/src/lib.rs` `infer_scc` (173 lines) are long, but each is one linear pipeline. |
| 170 | + |
| 171 | +- [ ] **M7. The `unsafe` boundary is not where the pointers are dereferenced.** Size **M**, PR **(3)**; needs engineering review. |
| 172 | + - **What works:** every `unsafe` block has a `SAFETY` comment (CI enforces it). |
| 173 | + - **What does not:** |
| 174 | + - **`prims::dup` (`prims.rs:101`)** is a *safe* function that dereferences any `Value` as a block. It also duplicates `heap::dup_value` (`heap.rs:127`), which is correctly `unsafe`. |
| 175 | + - **Safe functions dereference `ctx`.** `tl_int_mul`, `tl_int_div` and `tl_int_rem` (`prims.rs:224-243`) and `tl_random_int` (`:648`) are safe `extern "C"` functions. They call `panic_with` (`prims.rs:21`, also safe), which passes `ctx` to `tl_panic_str`, and that dereferences it. Likewise `values::cell`, `ok`, `error` and `list` are safe and take `*mut Ctx`. So safe Rust can cause UB with a null `ctx`. The rule for which functions are `unsafe` follows the `Value` arguments, but not `ctx`. |
| 176 | + - **Thread-locals and fibers.** The `SAFETY` comment on `unsafe impl Send for Fiber` (`sched.rs:87-95`) relies on no thread-local address being reused across a fiber switch. The scheduler's `LOCAL` accessors are `#[inline(never)]` (`sched.rs:334-350`). The leak counter `stats::MINE` (`heap.rs:340-350`) is `#[inline]`, and it is reached from allocation paths in runtime functions that also `park`. The comment names neither variable. Reading the code cannot settle whether this is safe: it depends on whether the optimiser may keep a thread-local's address across the switch. |
| 177 | + - **The fix:** |
| 178 | + - Adopt one rule: every function that may dereference `ctx` or a `Value` is `unsafe`. Better, have the entry points turn `*mut Ctx` into `&mut Ctx` once, under one `SAFETY` comment, with helpers taking `&mut Ctx`. |
| 179 | + - Delete `prims::dup` and use `heap::dup_value`. |
| 180 | + - Mark the panicking arithmetic `unsafe extern "C"`. C callers are unaffected. |
| 181 | + - Extend the `Fiber` `SAFETY` argument to cover `LOCAL` and `stats::MINE`: make `stats::add` `#[inline(never)]`, or explain why it is not needed. Have it reviewed. |
| 182 | + |
| 183 | +- [ ] **M8. The test harnesses duplicate the pipeline and the expectation format.** Size **S**, PRs **(2)** and **(4)**. |
| 184 | + - **The pipeline** (analyse → errors → `lower` → `entry`) is copied 7 times: |
| 185 | + - `tilc/src/main.rs:235,360`; |
| 186 | + - `tilc_core/tests/run.rs:28-38` and `lowering.rs:33`; |
| 187 | + - `tilc_perceus/tests/programs.rs:11-18`; |
| 188 | + - `tilc_codegen_c/tests/native.rs:26-40` and `lines.rs:25`. |
| 189 | + - **The expectation format** (`//>` lines and `//! panic:`) is parsed 4 times: `run.rs:44-53`, `native.rs:73-90`, `scripts/stress.sh:15` and `scripts/bench.sh:34`. |
| 190 | + - **Leftover scaffolding:** `NOT_YET` is empty (`native.rs:21-22`), but its handling remains (`:110-125`), along with "M5 part 1" comments. |
| 191 | + - **The fix:** |
| 192 | + - Add a dev-only `crates/tilc_testkit` with `compile(path) -> Compiled { db, analysis, program, entry }` and `Expectations::parse(text)`. |
| 193 | + - Remove `NOT_YET`. |
| 194 | + - Document the `//>` format once, in `tests/README.md`, which the scripts point to. |
| 195 | + |
| 196 | +- [ ] **M9. Smaller test gaps.** Size **S** each, PRs **(1)** and **(2)**. |
| 197 | + - **Diagnostic codes:** 6 of the 51 are never asserted by any test: `E0109`, `E0112`, `E0211`, `E0212`, `E0405` (orphan impls) and `E0411`. Add `tests/ui` cases. |
| 198 | + - **The unifier and row operations** (`tilc_types/src/ty.rs`: `unify`, row rewriting) are tested only through whole programs (4 unit tests in a 4.6k-line crate). A handful of table-driven tests would pinpoint regressions in the subtlest code. |
| 199 | + - **Match compilation** (`tilc_core/src/lower.rs:1667+`) is checked only by running programs. One snapshot test exists (`tests/lowering.rs`, 42 lines). Add snapshots of decision trees: or-patterns, nested constructors, literals. |
| 200 | + - **`tilc_perceus::verify`** runs only in `tilc_perceus/tests/programs.rs`. Run it under `cfg(debug_assertions)` in `generate_entries` (`tilc_codegen_c/src/lib.rs:93`), so every program compiled in debug builds is checked. |
| 201 | + |
| 202 | +- [ ] **M10. `runtime-abi.md`, the ADR statuses and module docs contradict themselves.** Size **M**, PR **(3)** for the runtime docs, PR **(4)** for the ADR index. |
| 203 | + - **`docs/runtime-abi.md` reads as an append-only log**, so a reader cannot tell the current ABI from the superseded ones: |
| 204 | + - Revision 1 says unwinding is table-driven, with `-fexceptions` and `_Unwind_ForcedUnwind` (`:179-183`). "Unwinding (part 2)" (`:201-204`) and the code (`emit.rs:649`) use yield checks. |
| 205 | + - `:217` says the threads "share one round-robin queue"; `:230` says (correctly) that each thread has a FIFO queue. |
| 206 | + - **The `tilrt/src/sched.rs:4` module doc** says "a round-robin run queue, shared by the scheduler threads", while its own `:16-19` describes per-thread queues with stealing. |
| 207 | + - **ADR statuses disagree with each other:** |
| 208 | + - ADRs 0001-0004 say "Accepted … including Revision 1" in their header, but their Revision 1 status lines (`0001:59`, `0002:55`, `0003:46`, `0004:108`) still say "Proposed … needs engineering review (#2)"; |
| 209 | + - `docs/adr/README.md:9` lists what awaits review, but omits ADR 0005 Revision 1 (`0005:68`, Proposed); |
| 210 | + - ADR 0006 (`:58`) names an API (`parse(file)`, `interface(module)`, `check_item(item)`) that does not exist; `Db` has `analyze()`. |
| 211 | + - **`tilrt.h` does not separate audiences.** It mixes the API for generated code with the API for bindings, without saying which is which. It also lacks the 16 exported functions listed in H1. |
| 212 | + - **The fix:** |
| 213 | + - Split `runtime-abi.md` into "Current ABI" (normative, matching `tilrt.h`) and "History" (or move the history into the ADR revisions). |
| 214 | + - Fix the `sched.rs` doc. |
| 215 | + - Give each ADR section exactly one status, and make the index match it. |
| 216 | + - Mark the binding-facing part of `tilrt.h`. |
| 217 | + |
| 218 | +### Low |
| 219 | + |
| 220 | +- [ ] **L1. Stale user-facing text.** Size **S**, PRs **(4)** and **(2)**. |
| 221 | + - The `tilc run --native` help says "(M5: programs without `ctl`, `final ctl` or actors)" (`tilc/src/main.rs:39-40`). Everything compiles natively now. |
| 222 | + - The `tilc_lsp` crate doc (`lib.rs:3-5`) lists 6 features. The server implements 10: references, formatting, inlay hints and semantic tokens are missing from the list. |
| 223 | +- [ ] **L2. Small dead code and internal duplication.** Size **S**, PRs **(2)** and **(3)**. |
| 224 | + - **Unused or redundant code:** |
| 225 | + - `check_supported` has an unused `_reachable` parameter (`tilc_codegen_c/src/lib.rs:168`); |
| 226 | + - `prims::text_of` only forwards to `text` (`prims.rs:51-64`). |
| 227 | + - **Duplication inside `tilrt`:** |
| 228 | + - `fn string` is defined twice (`prims.rs:67`, `net.rs:431`); |
| 229 | + - `tl_string_split` (`prims.rs:343-354`), `tl_os_env` (`:683`) and `tl_string_parse_int` (`:368`) build cells by hand instead of using `values::list` and `values::cell`. |
| 230 | +- [ ] **L3. A hand-copied ABI constant with no compile-time check.** Size **S**, PR **(2)**. `XARGS = 26` is in `emit.rs:14` ("must match"), `abi.rs:92` and `tilrt.h:119`. The Rust and C sides are asserted against each other; codegen is not. The fix: emit `_Static_assert(TL_XARGS == 26, …)` in the generated prelude. |
| 231 | +- [ ] **L4. Stringly-typed errors in crate APIs.** Size **S**, PR **(4)**. |
| 232 | + - `tilc_core::entry` and `runnable` (`lib.rs:27`), `manifest::{load, parse, closure}` and `tilc_perceus::verify` all return `Result<_, String>`. |
| 233 | + - Native test failures are forced into `interp::RtError::Panic` (`main.rs:456-475`). |
| 234 | + - Add typed errors when a second consumer appears. For manifests, do it now (M5). |
| 235 | +- [ ] **L5. `tilc test --native` leaves `$TMPDIR/tilc-test-<pid>/` behind** (`main.rs:442-446`). `run_native` cleans up after itself (`:316`). Size **S**, PR **(4)**. |
| 236 | + |
| 237 | +--- |
| 238 | + |
| 239 | +## Deliberate choices, not defects |
| 240 | + |
| 241 | +- **The reference interpreter and its scheduler** (`tilc_core/src/interp.rs`, `sched.rs`) re-implement what `tilrt` does. They are the oracle: `tilc_codegen_c/tests/native.rs` runs every `tests/run` program natively with `TILC_THREADS=1`, and requires the same `//>` output and zero live blocks. Keep them. Share only the pure leaf helpers (M3). |
| 242 | +- **The ABI layout is written twice:** `tilrt.h` by hand, next to `abi.rs`. Both sides are checked by `_Static_assert` (`tilrt.h:38,76-77,131-136`) and Rust assertions (`abi.rs:103`). That is the right way to mirror a C ABI without bindgen. |
| 243 | +- **There are two parsers.** The rowan parser is the compiler's; the tree-sitter grammar (`editors/tree-sitter-tilcayo`) serves editors. A test keeps them in step: the grammar must parse every `.til` file in the repository (`bindings/rust/lib.rs:78`), and CI regenerates it and diffs. |
| 244 | +- **No query framework; the whole package is re-analysed** (ADR 0006), with a stated condition for revisiting. |
| 245 | +- **`runtime/spike/spike.c`** is the M0 ABI spike. It is still CI's C-side ABI smoke test, including under ASan/UBSan (`scripts/ci.sh`), so it is not dead code. Its name suggests a throwaway, though; consider renaming it `runtime/abi-test`. |
| 246 | +- **Two failure policies in the runtime:** `expect("tilrt: …")` aborts on a runtime invariant violation, while user errors go through `tl_panic`. This is documented (`runtime-abi.md:175`). |
| 247 | +- **The runtime's own context switch** (ADR 0011) is assembly on x86_64 Linux, with corosensei elsewhere. The fallback is type-checked for aarch64 in CI. |
| 248 | +- **Per-thread leak counters with plain stores** (`heap.rs:320-352`; ADR 0002, implementation note) are a measured performance trade-off. The `stats` feature is on by default. See M7 for the open review point. |
| 249 | +- **`let _ = writeln!(…)` appears 104 times in `emit.rs`.** Writing to a `String` cannot fail. |
| 250 | +- **The interpreter dispatches externs by their C symbol.** The symbol is the interface. This is fine once H1's table exists. |
| 251 | +- **The std library is embedded with `include_str!`** (`tilc_db/src/lib.rs:23-46`), which keeps the toolchain a single binary. Adding a std module touches only that list. |
| 252 | +- **Large exhaustive `match`es over Core nodes** in emit, Perceus and the interpreter. They are the visitor; the compiler checks that each is exhaustive. |
| 253 | + |
| 254 | +## Metrics and method |
| 255 | + |
| 256 | +**Tools:** `cargo tree` (normal edges and `-d`), the crates' `Cargo.toml` files, `cargo clippy --workspace --all-targets` (default lints, and `-W clippy::pedantic`), `wc -l`, a small script measuring function length (from `fn` to the closing brace at the same indentation), and `grep` counts. Every finding was confirmed by reading the code. H2 and M5 were also reproduced with `tilc check`, `run` and `test` on scratch programs. Builds used a separate target directory, and nothing in the repository was modified. |
| 257 | + |
| 258 | +**Size per crate** (lines in `src/`, lines in `tests/`, number of `#[test]` functions; most tests are data-driven over `tests/run` (25 programs), `tests/ui` (13 files) and 18 snapshot files): |
| 259 | + |
| 260 | +| Crate | src | tests/ | `#[test]` | |
| 261 | +|---|---:|---:|---:| |
| 262 | +| tilc_span | 155 | 0 | 2 | |
| 263 | +| tilc_diag | 155 | 0 | 1 | |
| 264 | +| tilc_syntax | 3,359 | 507 | 20 | |
| 265 | +| tilc_hir | 2,570 | 225 | 11 | |
| 266 | +| tilc_types | 4,647 | 128 | 4 | |
| 267 | +| tilc_core | 4,048 | 124 | 2 | |
| 268 | +| tilc_perceus | 1,183 | 211 | 6 | |
| 269 | +| tilc_codegen_c | 1,699 | 377 | 6 | |
| 270 | +| tilc_db | 2,195 | 151 | 16 | |
| 271 | +| tilc_lsp | 712 | 399 | 3 | |
| 272 | +| tilc (driver) | 581 | 514 | 12 | |
| 273 | +| tilrt | 5,848 | 0 | 9 | |
| 274 | +| tilcayo-ffi | 95 | 0 | 1 | |
| 275 | + |
| 276 | +The std library is 2,718 lines of tilcayo across 19 modules. There are 2,307 lines of `.til` test programs. |
| 277 | + |
| 278 | +**Files over 800 lines:** |
| 279 | + |
| 280 | +| File | Lines | |
| 281 | +|---|---:| |
| 282 | +| `tilc_core/src/lower.rs` | 2,002 | |
| 283 | +| `tilc_types/src/infer.rs` | 1,567 | |
| 284 | +| `tilc_hir/src/lower.rs` | 1,391 | |
| 285 | +| `tilrt/src/sched.rs` | 1,367 | |
| 286 | +| `tilc_codegen_c/src/emit.rs` | 1,227 | |
| 287 | +| `tilc_core/src/interp.rs` | 929 | |
| 288 | +| `tilc_syntax/src/ast.rs` | 902 (macro-generated accessors; fine) | |
| 289 | +| `tilc_types/src/env.rs` | 826 | |
| 290 | +| `tilc_types/src/lib.rs` | 812 | |
| 291 | + |
| 292 | +**Functions over 100 lines** (17 non-test functions; clippy pedantic `too_many_lines`, threshold 100): |
| 293 | + |
| 294 | +| Function | Lines | |
| 295 | +|---|---:| |
| 296 | +| `emit.rs` `value` | 271 | |
| 297 | +| `tilc_core` `sched.rs` `request` | 218 | |
| 298 | +| `emit.rs` `expr` | 205 | |
| 299 | +| `infer.rs` `handle` | 176 | |
| 300 | +| `tilc_hir` `collect_items` | 175 | |
| 301 | +| `tilc_types` `infer_scc` | 173 | |
| 302 | +| `interp.rs` `call_extern` | 169 | |
| 303 | +| `lower.rs` `expr_kind` | 149 | |
| 304 | +| `lower.rs` `compile` | 139 | |
| 305 | +| `infer.rs` `infer_expr` | 129 | |
| 306 | +| `tilc_perceus` `expr` | 121 | |
| 307 | +| `check_impls` | 115 | |
| 308 | +| `infer.rs` `call` | 115 | |
| 309 | +| `tilc_hir` `lower_expr` | 108 | |
| 310 | +| `verify` `expr` | 106 | |
| 311 | +| `resolve_imports` | 105 | |
| 312 | +| `lower.rs` `call` | 104 | |
| 313 | + |
| 314 | +**Dependencies:** |
| 315 | +- The layers are respected (syntax → hir → types → core → perceus → codegen → driver), with one exception: codegen → `tilc_db` (M1). |
| 316 | +- `tilc_types` uses `tilc_syntax` only as a dev-dependency. |
| 317 | +- The only duplicated third-party crate is `winnow` (0.7 and 1.0, both through `toml`), which is harmless. |
| 318 | +- `Cargo.lock` has 135 packages. |
| 319 | + |
| 320 | +**Lints:** |
| 321 | +- Default clippy: 0 warnings (CI runs it with `-D warnings`). |
| 322 | +- Pedantic, library targets: 290 warnings, mostly casts (75 `usize → u32`, 18 `usize → i64`, 27 sign or truncation casts), `single_match_else` (20) and `redundant_closure` (17). None of them points to a defect worth a PR, apart from the long functions above. |
| 323 | +- `#[allow]`s: 5 in the whole workspace, each justified. |
| 324 | +- No `TODO`, `FIXME`, `todo!` or `unimplemented!`. |
| 325 | + |
| 326 | +**Unsafe code in `tilrt`:** |
| 327 | + |
| 328 | +| Construct | Count | |
| 329 | +|---|---:| |
| 330 | +| `unsafe { … }` blocks | 212 | |
| 331 | +| `SAFETY:` comments | 220 | |
| 332 | +| `unsafe fn` | 155 | |
| 333 | +| `extern "C"` functions | 122 | |
| 334 | +| `unsafe impl Send` / `Sync` | 8 | |
| 335 | + |
| 336 | +`# Safety` doc sections cover every public `unsafe fn` (clippy `missing_safety_doc`). About 70 `SAFETY:` comments say "caller guarantees …" or "forwarded caller guarantee", which is appropriate for C entry points (M7). |
| 337 | + |
| 338 | +**Documentation:** |
| 339 | +- 100% of source files have a module doc. |
| 340 | +- The 51 diagnostic codes are all documented; 45 of them are tested (M9). |
| 341 | +- Names of `tl_*` runtime functions in the docs were cross-checked against the code. The only names that do not exist are the planned `Bytes` accessors (`runtime-abi.md`, listed as not yet implemented) and the superseded `tl_bytes_alloc` and `tl_string_alloc` (ADR 0005, roadmap v0). |
| 342 | +- Exports in `tilrt.h` versus the runtime versus std externs: 16 runtime exports are missing from the header (H1). |