aboutsummaryrefslogtreecommitdiff
path: root/TODO.md
diff options
context:
space:
mode:
Diffstat (limited to 'TODO.md')
-rw-r--r--TODO.md138
1 files changed, 123 insertions, 15 deletions
diff --git a/TODO.md b/TODO.md
index 844386a..e5a91a1 100644
--- a/TODO.md
+++ b/TODO.md
@@ -163,8 +163,11 @@ and pushed there.
`ZC_TEST_TIMEOUT_SCALE=4 node tests/drivers/lsp_test.js build/bin/zclsp`,
`ZC_TEST_TIMEOUT_SCALE=4 node tests/drivers/hint_fixes_test.js
build/bin/zclsp`, `make parity` (zc0 against the self-hosted compiler; by
- design differences live in `tests/parity.known`). on x86 the language server
- is interpreted and slow; `ZC_TEST_TIMEOUT_SCALE` stretches the deadlines.
+ design differences live in `tests/parity.known`). on x86-64 linux `zy` and
+ the language server now run on the x86-64 jit (o3 regions still interpreted);
+ `ZC_TEST_TIMEOUT_SCALE` stretches the deadlines on slower hosts.
+ `bash tests/drivers/jit_x64_test.sh build/bin/zyi build/bin/zy` compares the
+ jit with the interpreter (`make build/bin/zyi`) on every program.
- work was done by delegating each item to a separate agent in its own git
worktree (outside the repo, under `/workspace/tinyvm-wt/`) and merging its branch.
every brief started with "read ONBOARD.md first" plus the sections relevant
@@ -174,6 +177,94 @@ and pushed there.
- prose everywhere is lowercase with plain punctuation; `//` line comments,
`/* */` only between code; a comment above a declaration is its hover text.
+### vision and direction
+
+the coordinator's view of where zc stands and where it should go, recorded so
+the reasoning behind the open items survives the session.
+
+- what zc gets right: the compiler lives in memory next to the program, so
+ `eval`, parse words, immediate functions and library-defined syntax (actors
+ with no actor code in the compiler) fall out of the architecture: forth's
+ strength with c's syntax. the ownership analyzer infers most of what other
+ languages make you annotate (it already infers that `skip(s)` returns a
+ borrow of `s`). unchecked code falls back to a conservative collector instead
+ of undefined behavior. the language server is the real compiler in check
+ mode, so diagnostics cannot drift from compilation. one image runs on the
+ interpreter, microcore, javascript, wasm, arm64 jit and llvm.
+- what holds it back: trust and visibility. until `docs/SPEC.md` there was no
+ spec, and the two implementations disagreed (`&&`/`||`) without anyone
+ noticing. run-time failures carry no position and a wild read can exit 0.
+ "checked" is not purely static: turning the checker on inserts cleanup that
+ can change behavior (the reverted `unchecked` trial hung `share.zc`).
+ friction: the toolchain's own sources must stay in zc0's subset; word-per-
+ character strings cost eight times the memory of `bstr` and split every api
+ in two (`put_s` and `put_bs`); the compiler's state is global parallel
+ arrays; on x86 the language server was interpreted (about 18 s to check the
+ compiler) until the x86-64 jit landed.
+- priorities, in order: things that turn wrong behavior into a located,
+ reproducible failure come first, because everything else (fuzzing, a proving
+ scaffold, outside users) depends on them: runtime line tables, bounds
+ checking, and the spec with its parity runner and conformance suite. then the
+ language features that make zc pleasant (`defer`, destructors, variadics and
+ `std.print`, test blocks, borrow returns for declarations). then speed (the
+ x86-64 jit).
+- bootstrap philosophy: zc0 is an independent implementation in c that never
+ retires (like go 1.4, unlike rust's downloaded stage 0 or ocaml's and zig's
+ committed binaries), so the system builds from source with only a c compiler
+ and no committed blob. its value is being small, so it grows only where a
+ feature is cheap and produces no code of its own (tags, recasts, byte
+ strings, maybe enums and `?:`), never structs. the parity runner is a small
+ form of wheeler's diverse double-compiling: the two front ends check each
+ other.
+- managing the compiler's global state: (1) a cross-reference report of
+ writers and readers per global, checked in ci; (2) group each family of
+ parallel arrays in one place with its invariants written once, and route
+ snapshot and restore through one pair of functions; (3) the split into phase
+ files (done). do not try to make the state non-global: the single-pass design
+ is fast because of it; the goal is visible ownership of state, not removal.
+- debugging, beyond line tables and bounds checks: every effect a program has
+ goes through one syscall gate, so record and replay is cheap here (log each
+ gate result, replay a run exactly, then add tracing or watchpoints at will).
+ once line tables exist, a debug adapter for vscode (breakpoints, stepping,
+ locals) on top of the interpreter is the next step.
+- a proving scaffold (the owner asked for an opinion): yes, but check before
+ prove. a written semantics comes first (the spec, then a small executable
+ reference evaluator). grow it out of the analyzer that already exists rather
+ than beside it. order: stack-effect checking for every function and `asm`
+ block (the commonest invisible bug on a stack machine); declared side
+ effects at module boundaries (globals touched, syscalls or not) checked
+ against the effect masks the compiler already computes; `requires`/`ensures`
+ contracts compiled to run-time checks under a switch, with the easy ones
+ discharged statically from the value facts. keep the trusted base small and
+ outside the self-compiling loop (a prover inside the genome can approve its
+ own mistakes, as the fixpoint approved the precedence bug); prefer
+ translation validation of each compile over proving the compiler whole.
+- native code: the hand-written jit exists for arm64 and (phase 1, no o3
+ regions or inlined enhancements yet) x86-64 linux; the llvm backend
+ (`-DZYLLVM`) is the portable native tier but the default build leaves it
+ out. cheap win: build the llvm core by default whenever `llvm-config` is
+ found. the x86-64 port of the hand-written jit is worth it for compile
+ latency (microseconds per block against milliseconds for llvm), which
+ matters for short programs and the language server.
+
+### feature decisions (owner's requirements, settled)
+- bounds checking is on by default; `unbounded` (used like `unchecked`:
+ function prefix, block, top-level statement) turns it off; `o3` implies
+ `unbounded`.
+- `defer` runs at the end of the current block on every exit path, like the c
+ defer proposal, plus ownership awareness; destructors (`fn drop()`) exist as
+ well.
+- borrow returns: inferred from the body wherever possible; any spelling for
+ declarations must stay unobtrusive (proposed: `borrows s` after the
+ parameter list).
+- `string` is a built-in alias of `char*` (done); c typedefs (done).
+- variadics: count and per-argument types available, several packs per
+ function when element types differ (`void f(...int a, ...char b)`), a mixed
+ `...any` pack, and `...*any` for comma-free calls; `std.print` is a global,
+ javascript-like print built on it.
+- struct-level untyped constants (done), typo suggestions for members (done).
+- every new agent brief starts with "read ONBOARD.md first".
+
### done in this session (all merged)
- build from source with c23 `#embed`, everything generated under `build/`,
`ONBOARD.md`, the embed declaration (`embed "f" as [type] name;`).
@@ -194,12 +285,22 @@ and pushed there.
### in flight when this was written (not on the branch; re-brief if missing)
these were running as agents in worktrees. if their branches were not merged
before the session ended, the work is lost and each item below must be started
-again from its description in the open list.
-- spec verification (`tests/conformance/`), see "verify both compilers".
-- x86-64 jit phase 1, see "a hand-written x86-64 jit".
-- zc0 structs, enums and `?:`, see "zc0 structs".
+again from its description in the open list. a zip of the repository with every
+worktree is uploaded to the owner after each update.
+- spec verification, restarted after an interruption. the first agent's
+ partial work (runner plus sections 1 to 3, about 375 programs) is committed
+ on the local branch `worktree-agent-a020917eebd018418` (3edfbaa) and the new
+ agent continues from it; see "verify both compilers".
- runtime line tables and backtraces, see "runtime source positions".
- bounds checking with `unbounded`, see "bounds checking".
+- the cross-reference report, see "a cross-reference report".
+
+### decisions
+- no structs in zc0 (owner's call): zc0 stays the small trusted root of the
+ bootstrap. so the compiler keeps its parallel arrays; the records refactor
+ becomes grouping and documenting them (see that item). enums and `?:` in zc0
+ stay optional and low priority.
+- agents: sonnet 5.5 for the jobs; do not cancel running agents.
## open, easiest first
@@ -207,32 +308,39 @@ sorted by how hard each is to implement; the final full suite stays last.
items with an architecture note carry the design worked out so far, enough to
brief someone without re-reading the code.
-- [ ] hover on standard-library members (`std.Text.itoa`, `std.array_contains`, a group name) returns nothing in the language server, though completion shows the same documentation; a struct static function in the document itself does show its hover. find where `do_hover` resolves qualified library members and fix it, with a hover check.
-- [ ] `std.capture.end` writes its terminator at `rt.outbuf[rt.outn]`; when more than 256 characters were captured, `outn` equals the capacity and the 0 lands one word past the buffer. check and fix, with a regression program.
-- [ ] a bare call to a sibling static function inside a struct's method (`lim()` for a static `lim`) reports `lim is used but never defined`; resolve it like the bare struct constants now are (`mstruct` in the declarations part).
-- [ ] a run-only image accepts `void main()` from zc0 but the self-hosted compiler rejects it against `run.zc`'s `int main();` prototype; make the two agree.
- [ ] remaining zc0 gaps: string literals over 4095 bytes, `embed` of an array type inside a function, `x as T` with more than a single name (`x as int*`), zc0 silently accepting `.u` on a parameter, and integer literals (`010` is 8 in zc0, 10 in the compiler; zc0 saturates on overflow). `docs/history/43-stdlib/notes.md` still says zc0 reserves u/m/d: add a pointer forward rather than rewriting history.
- [ ] (in flight) verify both compilers against `docs/SPEC.md` with a fresh agent that did not write it: expectations derived from the spec text before running anything, one program per rule under `tests/conformance/<section>/`, a runner `tests/conformance/run.sh`, each failure classified as self-hosted bug, zc0 bug, or spec error, and appendix b confirmed item by item. then add the runner to `tests/test.sh`.
- [ ] fix the implementation bugs listed in `docs/SPEC.md` appendix b, once confirmed: `memdebug scrub;` rejected; enum members can't reference earlier members; a plain function redefinition silently shadows the first; a prototype after the definition hides it; `?:` with one int and one float branch gives garbage; `bool` not normalised; float global initializers rejected; a global initializer naming another global uses its address; `include std;` inside a function body; syntax-error recovery hiding later errors; unterminated `/*` and string literals; `x as int * y`; prototypes needing parameter names; `len(char*)` with typecheck off; duplicate `case` labels; local `const` in constant expressions; constant expressions without precedence (`1+2*3` is 9). fix the prose items the appendix lists too.
-- [ ] a cross-reference report: for every global of the compiler, the functions that write it and the ones that only read it. build it from the language server's references (`textDocument/references` on `build/bin/zclsp`, so scoping is exact) and classify each reference as a write when an assignment operator, `++` or `--` follows it. output under `build/xref/`; a committed baseline and a `--check` mode that fails when a new writer of a global appears, so it can run in ci. do it after the records refactor, which reshapes the globals.
-- [ ] (in flight) zc0 structs (word-sized fields only, matching the self-hosted layout of one word per field in order; reject packed small fields, nested structs by value, array fields, methods, constants and generics with clear messages), struct values, arrays of structs, `p.f`/`p->f`/`xs[i].f`, `rt.new(T)`, `sizeof`; plain enums (`name.B` access, the name as an int type); `c ? a : b` with c precedence and right associativity. zc0 needs just enough type tracking to know a name's struct. its output for the genome sources must stay byte-identical. tests `tests/programs/zc0struct.zc`, `zc0enum.zc`, `zc0cond.zc`; `make parity` should compare many more programs afterwards. this blocks the records refactor.
-- [ ] (needs zc0 structs) group the compiler's parallel per-local arrays (`lname`, `ltype`, `lstate`, `lhome`, `lown`, `lslot`, `ltag`, `lpos`, `lnsz`, `lleaf`, ...; many are declared as `word[NL] x_initial; word x = x_initial;` and grow) into one record per local with accessor functions, so a branch snapshot is one block copy and each field's invariant is written once next to the record. then symbols, then types. the genome must keep reaching its fixpoint and the analyzer's behavior must not change (rejection suites and program checks identical).
+- [ ] (in flight) a cross-reference report: for every global of the compiler, the functions that write it and the ones that only read it. build it from the language server's references (`textDocument/references` on `build/bin/zclsp`, so scoping is exact) and classify each reference as a write when an assignment operator, `++` or `--` follows it. output under `build/xref/`; a committed baseline and a `--check` mode that fails when a new writer of a global appears, so it can run in ci.
+- [ ] optional, low priority: plain enums and `?:` in zc0 (both are small and produce ordinary code), so parity covers more programs. no structs in zc0 (decided).
+- [ ] group the compiler's parallel per-local arrays (`lname`, `ltype`, `lstate`, `lhome`, `lown`, `lslot`, `ltag`, `lpos`, `lnsz`, `lleaf`, ...) without structs: declare each family together in one place, with one comment block stating each array's meaning and invariant (for example when `lhome` is meaningful), route snapshot and restore of the family through one pair of functions, and use the cross-reference report to confirm nothing else writes them. then symbols and types the same way. fixpoint and analyzer behavior unchanged.
- [ ] continue removing `unchecked` from the runtime. a reverted trial showed: `copy_w`/`fill_w` pass the analyzer when their gate stores go through `syscall(SYS_COPY, ...)`, `dgrow` with `own(w, it)` instead of `w[-2] = it`, `dpush` with `own` before the store, `dnew` as is; but the checked versions changed behavior (7 program checks failed, `tests/programs/share.zc` hung with a checked `cons`), so checked code inserts cleanup these functions can't afford. each needs its contract taught to the analyzer. `free`, `recycle`, `recycle_leaf`, `gc` are the allocator and collector the analyzer's own cleanup calls: document them as the irreducible escapes. `src/lib/actor.zc` has about 20 more.
- [ ] revise diagnostics, comments and learning/reference prose using professional compiler documentation guidance, preserving lowercase and adding message regressions. touches messages everywhere, so do it when few other compiler changes are in flight.
-- [x] `defer` statement (`kw_defer`, `defer_run`, `block_close`, `kw_return`, `kw_break`, `kw_continue`): see `docs/SPEC.md` 4.14.
- [ ] test blocks: `test "name" { ... }` with `expect(cond)`, compiled only by `zy --test file.zc`, which runs each block and prints one line per test with the position of the first failed `expect`; skipped at parse time otherwise. build it as a library through `run.syntax` and `run.statement_hook`, like `src/lib/actor.zc`.
- [ ] (in flight) bounds checking on by default, `unbounded` to turn it off (function prefix, block, top-level `unbounded;`, mirroring `unchecked`), implied by `o3`. architecture: indexing is compiled in the postfix `[` handling of the expressions part; growable arrays already check (`dat`, `range_jz`, the `outside` enhancement, `proven()` removing checks a loop test already did). fixed arrays `T[n]` with a variable index get the same inline check against the constant `n`. pointers get a runtime call (for example `rt.bchk(p, i)`) that checks only when `p` is the start of a live heap block (header check word `p ^ MAGIC`, `paylen`), skipping constant index 0 and sizes the analyzer knows (`lnsz`). reports go through `oob`. the runtime, core, compiler parts, server, `run.zc` and `build.zc` start with `unbounded;`, which zc0 accepts and ignores (genome bytes unchanged). keep std, icon and actor checked unless a function touches raw memory on purpose. measure interpreter time before and after.
- [ ] after the fuzzing work, add more general functionality to the standard library.
-- [ ] (in flight) a hand-written x86-64 jit, ported from the arm64 one in `src/core/core.c` (the `#ifdef ZYJIT` section; `ZYJIT` is only defined for `__aarch64__`). phase 1: a separate macro (for example `ZYJIT_X64`), shared architecture-neutral parts (translation table `tab`, coverage `cov`, invalidation `be_drop`, block boundaries, dispatcher) and an x86 emitter. registers: r12 memory base, r13 data stack, r14 return stack, r15 translation table, rbx state block (the arm64 x19..x23); system v calls to c helpers. semantics identical to the interpreter (wrapping, 0/1 comparisons, literal encoding, stack and `MW` checks, retranslation after stores into code). o3 regions take the portable path in phase 1. validate every `tests/programs`, `examples` and `examples/learn` program on interpreter and jit with identical output (a driver under `tests/drivers/`), the rejection suites, icon and actor fixtures; report timings for a compute example and for compiling the compiler. make it the default x86-64 linux core only when everything matches; `-DZYINTERP` still forces the interpreter. phase 2: o3 regions and inlined enhancements. note the llvm backend (`-DZYLLVM`) is the other native path; the default build could also enable it whenever `llvm-config` is found.
- [ ] struct destructors: a struct may declare `fn drop()`, called wherever the compiler frees an owned value of that type, before the memory is released. architecture: the compiler frees owned locals in `freevar` (analyzer part), called from `exit_vars`, reassignment and explicit `rt.free`/`rt.recycle` calls (`s_free`, `s_recycle` handling in the call code); when the local's static type is a pointer to a struct with a `Name.drop` method, emit a call to it first. objects freed by the collector or inside unchecked code do not run `drop`: document that. first users: file descriptors in `std.Host`, processes in `actor.zc`.
- [ ] (in flight) runtime source positions. architecture: at each statement start (`stmt()`) record (code address `here`, line); per function a permanent data block [entry, end, name, file, count, pairs...] linked into a runtime list (`rt.line_blocks`), or appended to run-only images by `build_image` like the symbol blob. `lines on;`/`lines off;` like `docs on;`; on for user programs, off for the genome unless the growth is small. a new syscall op returns the return-stack pointer (the return stack is in vm memory, 0x1A4100..0x1B40FF, growing up); implement it in `src/core/core.c`, `src/micro/micro.c`, `src/js/tinyvm.ts` and the wasm port. `rt.trace()` walks the return stack, printing ` at file:line in function` for words inside a known function range. the runtime's fatal reports (`oob`, bad heap pointer, double free, out of memory, frame overflow) print the trace after their unchanged first line. check mode skips all of it.
- [ ] borrow returns tied to an argument. inference already works for a callee defined before the call: `char* skip(char* s) { ...; return s + i; }` makes `let r = skip(t); rt.free(t); r[0]` an error. the gap: when the call comes before the callee's definition, nothing is reported and the program reads freed memory. extend the deferred effect requirements (`effect_require`, `effect_finish` at unit end) so a forward-called function whose return turns out to alias a parameter produces the same error. for bodyless declarations, externs and function types, add an unobtrusive spelling, for example a `borrows s` clause after the parameter list (`char* skip(char* s) borrows s;`), checked against the body when one exists.
- [ ] variadic arguments and `std.print`. design: a pack is passed as one hidden argument, a caller-built read-only growable-array handle (`fixed T[?]` view: [len, cap, items, element size] in the caller's frame, so `len(a)` and `a[i]` work unchanged and nothing is allocated). `...int a` is a typed pack; several packs per function when their element types differ (`void f(...int a, ...char b)`): each extra argument goes to the pack whose element type matches its static type, an ambiguous match is an error, packs come after the fixed parameters. `...any args` packs each value with a kind code (int, float, char, string, bstr, pointer, ...) and its type record: `any` is a small built-in record { kind, value, type }. `...*any args` makes the call comma-free: after the fixed arguments, the parser reads unary expressions until `)`, commas optional, so `std.print("x = " name ", age " age "\n");` works and binary expressions must be parenthesized. `std.print(...*any args)` prints each argument by its kind (`put_n`, the float printer, `put_s`, `put_bs`, a character for `char`, hex for pointers).
+- [ ] x86-64 jit phase 2: compile o3 regions to x86-64 (port `rcompile` and the region register allocation; regions now run on the region interpreter and are 2 to 4 times slower than their plain versions on this jit) and inline enhancements (lower the optimized micro-ops to x86 registers as the arm64 path does, instead of calling `xrun`). validate with `tests/drivers/jit_x64_test.sh` and `tests/bench/bench.sh`, which now has an x86-64 jit column. add the driver to `tests/test.sh` on x86-64 linux.
+- [ ] `memdebug`'s `obj_base` searches only 64 words back for a block header, so under `memdebug on` an interior access more than 64 words into a block (`buf[255]` on a 256-word block) reports "bad heap pointer". find the header from the buddy allocator's size classes instead of a bounded scan, with a regression program.
+- [ ] `defer` follow-ups (small): accept `defer if (...) ...;` and other single statements besides an expression; decide whether deferred code may name an owner declared after the `defer` (now rejected by the lexical rule; one line in `defer_one`).
+- [ ] build the llvm core by default when `llvm-config` is available (the makefile falls back to the interpreter otherwise), so x86 hosts get a native tier and the language server stops being interpreted; keep `ZYNOLLVM=1` and `-DZYINTERP` as the opt-outs.
+- [ ] stack-effect checking: every function and `asm` block declares or is inferred to have a fixed data-stack effect, and the compiler reports a block whose paths leave the stack unbalanced. the first step of a proving scaffold.
+- [ ] declared side effects at module boundaries (globals touched, syscalls or not), checked against the effect masks the compiler already computes.
+- [ ] `requires`/`ensures` contracts on functions, compiled to run-time checks under a switch, with the cases the value facts settle (constants, simple ranges) checked statically.
+- [ ] record and replay: a core option that logs every syscall gate result to a file and replays a run from the log exactly, for reproducing failures and adding tracing after the fact.
+- [ ] a debug adapter for vscode (breakpoints, stepping, locals) on the interpreter, built on the line tables.
+- [ ] reduce the cost of word-per-character strings: measure, then decide between making `bstr` the default string, unifying the two apis behind one name, or both.
- [ ] continue fuzzing the compiler, analyzer, runtime, standard library, lsp, build tools and generated artifacts, including analyzer properties, memory-limit edges, compiler image mutation and long-running lsp memory use; feed generated programs to `make parity` for differential fuzzing between zc0 and the self-hosted compiler; fix discovered bugs.
- [ ] keep improving the borrow checker: fewer annotations in ordinary code, clearer messages naming both the owner and the conflicting use, and new fixtures for each rule that changes.
- [ ] run the full suite once everything above is done (`make test JOBS=4`; `make check` is the quick one), fix what it finds, and only then tick this item.
## done in the sorted list
+- [x] `defer expr;` and `defer { ... }`: tokens grabbed at the `defer`, recompiled inline at every exit (block end through `block_close`, `return` after its value, `break`/`continue` for entries deeper than the loop), newest first; only defers reached so far register. names are lexical (a local declared after the `defer` is hidden in the replay). a deferred `rt.free(p)` is `p`'s transfer to the analyzer. each entry replays in the analyzer mode it was written in; closures get their own base through `ctx_push`. `return`, `break` and `continue` that would leave a deferred statement are rejected. a failed entry reports once. limit 256 pending per function (`DFR_MAX`). spec 4.14, learn section 34, `tests/programs/defer.zc`, seven reject fixtures.
+- [x] four small fixes: hover on standard-library members (`hover_embedded_sym` sends std/icon symbols to the library lookup; `bs_hover` renders a member hit), `capture.end`'s terminator (the buffer has `cap + 1` words; latent, since the allocator's power-of-two slack hid it; `tests/programs/capture_long.zc`), bare sibling static calls inside a struct's methods (`mstruct` set for every non-generic struct; the struct's own constant or static beats a top-level name, a local beats both; `tests/programs/struct_static_call.zc`, spec 5.5.5), and `void main()` in run-only images (`run.zc` declares an untyped `fn main();`; spec 5.2.5).
+- [x] a hand-written x86-64 jit, phase 1 (`ZYJIT_X64` in `src/core/core.c`, default on x86-64 linux; `-DZYINTERP` and `make build/bin/zyi` give the interpreter). r12 memory, r13 data stack, r14 return stack, r15 table, rbx state; stack slots addressed with a virtual offset so r13 moves only at calls and exits; shares the table, coverage map, store hook and invalidation with the arm64 jit. enhancements are called through `xrun`, o3 regions run on the region interpreter (`ZYNOO3=1` runs their vm code through the jit instead). 179 of 179 programs agree with the interpreter (`tests/drivers/jit_x64_test.sh`), the self-compile is byte-identical and about 7x faster (1.5 s against 11 s), and the rejection, learn, icon, actor, lsp and hint suites pass on it.
- [x] remove temporary markdown files (`TASKLIST.md`, `docs/design/handoff.md` deleted; `BOOTSTRAP-OWNERSHIP.md` moved to `docs/history/`).
- [x] verify every command in `ONBOARD.md` from a clean checkout and fix the ones that drifted.