aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--ONBOARD.md10
-rw-r--r--README.md8
-rw-r--r--TASKLIST.md1203
-rw-r--r--TODO.md22
-rw-r--r--docs/BORROW.md2
-rw-r--r--docs/design/handoff.md20
-rw-r--r--docs/history/BOOTSTRAP-OWNERSHIP.md (renamed from docs/BOOTSTRAP-OWNERSHIP.md)0
-rw-r--r--docs/history/README.md2
-rw-r--r--editors/vscode/syntaxes/zc.tmLanguage.json2
-rw-r--r--examples/std_tour.zc61
-rw-r--r--src/compiler/compiler.zc231
-rw-r--r--src/lib/std.zc128
-rw-r--r--src/lsp/server.zc50
-rw-r--r--tests/drivers/hint_fixes_test.js4
-rw-r--r--tests/drivers/lsp_test.js18
-rw-r--r--tests/errors/static_const_typo.zc5
-rw-r--r--tests/errors/static_typo.zc5
-rw-r--r--tests/langerrors/struct_const_runtime.zc6
-rw-r--r--tests/langerrors/typedef_generic_bare.zc6
-rw-r--r--tests/langerrors/typedef_local_redefine.zc8
-rw-r--r--tests/langerrors/typedef_redefine.zc6
-rw-r--r--tests/langerrors/typedef_scope.zc8
-rw-r--r--tests/langerrors/typedef_string_redefine.zc5
-rw-r--r--tests/langerrors/typedef_tag.zc5
-rw-r--r--tests/langerrors/typedef_unknown.zc5
-rw-r--r--tests/langerrors/typedef_variable_clash.zc8
-rw-r--r--tests/langerrors/typedef_void_variable.zc5
-rw-r--r--tests/programs/struct_const.zc28
-rw-r--r--tests/programs/typedef.zc89
-rwxr-xr-xtests/test.sh2
-rw-r--r--tests/typeerrors/field_typo.zc5
-rw-r--r--tests/typeerrors/typedef_mismatch.zc6
-rw-r--r--tests/typeerrors/typedef_pointer.zc7
33 files changed, 667 insertions, 1303 deletions
diff --git a/ONBOARD.md b/ONBOARD.md
index 3bf8b0b..5b05862 100644
--- a/ONBOARD.md
+++ b/ONBOARD.md
@@ -70,7 +70,7 @@ explain why `include rt;` is required before `rt.put_n`.
## 3. ownership, the analyzer's view
-read `docs/BORROW.md`, then `docs/BOOTSTRAP-OWNERSHIP.md` (how two missing rules
+read `docs/BORROW.md`, then `docs/history/BOOTSTRAP-OWNERSHIP.md` (how two missing rules
once stopped the compiler compiling itself). run the rejection suites and read a
few of the fixtures, each of which starts with the message it expects:
@@ -81,7 +81,7 @@ bash tests/runerr.sh build/bin/zy tests/langerrors
```
in `src/compiler/compiler.zc`, find the block that starts at
-`//: the rules below are the heart of the analyzer` and read `recast`,
+`// the rules below are the heart of the analyzer` and read `recast`,
`argcheck`, `assigncheck` and `retcheck`, then `exit_vars` and the `lend_*`
helpers.
@@ -95,7 +95,7 @@ does to them.
overview. read the overview, then use the section markers to navigate:
```sh
-grep -n "^//: ----" src/compiler/compiler.zc
+grep -n "^// ----" src/compiler/compiler.zc
```
read in this order: interning and symbols, the lexer (`lex1`), expressions
@@ -175,8 +175,8 @@ headers for the llvm section.
## 9. history and open work
-`docs/history/README.md` is the scrapbook of earlier stages, `TODO.md` the
-maintenance checklist, and `TASKLIST.md` the record of past requests. read the
+`docs/history/README.md` is the scrapbook of earlier stages and `TODO.md` the
+maintenance checklist. read the
open items in `TODO.md` last: by then each one should point at code you have
seen.
diff --git a/README.md b/README.md
index 379ed5b..44ee129 100644
--- a/README.md
+++ b/README.md
@@ -170,6 +170,8 @@ fn main() {
declarations are C-style, type first: `int a = 1, b;`, `node* p = rt.new(node);`, `char[4] buf;`, `point origin;`. `let` declares without a type: it infers `char*` from a word-string literal and `bstr` from a packed byte-string literal, infers other pointers and function types from the initializer, uses a pointer alias for an in-place array or struct, and keeps numbers as plain words. `let a[10];` is an untyped array. `const k = 5;` inside a function is a local constant with no type: it takes the initializer's type, needs an initializer, and can't be assigned. statements are declarations, `if`/`else`, `while`, `do`/`while`, `for`, `switch`, `break`, `continue`, `return`, `{ }` blocks, `asm { }` and expressions. `do` body `while (` cond `);` runs the body once before the test, and `continue` jumps to the test. `enum color { RED, GREEN = 5, BLUE };` makes global constants, and `color` is a type of its own in typed code (`typecheck on;`): a member takes the enum, a plain int does not become a `color`, and a `color` still becomes an `int`. untyped code treats the members as plain ints. each member is also reached as `color.BLUE`, in an expression or a `case` label. a member can carry fields too: `enum shape { circle { int r; }, rect { int w; int h; }, dot };` makes the constructors `shape.circle(3)` and `shape.rect(4, 5)`, which return an owned `shape*`, and `shape.dot()`. the tag is the word at offset 0 of the object. a `switch` over a `shape*` matches a member with `case circle(r):`, which binds its fields in that arm only. a switch on a tagged enum that leaves out a member and has no `default` gets a warning on its line (not an error). `(T)e` is a cast with the same meaning as `e as T`: the bits stay, the type changes. it has to be a simple type the parser can see in a few tokens, `int` or `*node`, not a nested array. `include "path";` reads a file and compiles it at that point, signatures first, so a library can live in its own file. each file has its own namespace and imports; dependencies included by a file do not import into the caller. `u`, `m` and `d` are ordinary names. a tag is `.u`, `.m` or `.d`, and `u*x` with no space before the star is still a recast. `switch (e) { case 1, 2: ... default: ... }` takes constant labels, and its cases don't fall through: each ends where the next begins, and `break` leaves early. operators follow C precedence, including `c ? a : b`, plus `p.x` and `p->x` (the same thing: `.` goes through a pointer on its own), `e as T` to change a type without changing the bits, and the casts below. comparisons and `&& ||` give 0 or 1. `/`, `%` and `<<` compile to native enhancement opcodes. character literals, `0x` hex and the usual escapes are there.
+`typedef T name;` gives a type another name, as in c, at the top level or inside a function (where it lasts to the end of its block, like a local): `typedef node* link;`, `typedef int[4] quad;`, `typedef int(int, int) binop;`, `typedef list<int> ints;`. `type name = T;` says the same thing. a typedef is only a new spelling: `link` and `node*` are the very same type record, so they mix freely in declarations, parameters, results, casts, `sizeof`, struct fields, generic arguments and `typecheck on;` code, and they print as the target type. `T` can be any type the parser accepts, but not a tag (`.u`, `.m` and `.d` belong to a declaration). a typedef can't name a type that isn't declared yet, so a struct comes before the typedefs of its pointers; using a name that is already defined is an error, and a typedef of `void` is `void` (a variable of it is the usual error). `string` is built in as a typedef of `char*`, so `string s = "hi";` and `string f(string a)` work with no declaration; a function, variable or parameter of the same name shadows it.
+
functions are declared like C, return type first: `int f(int x)`, `node*.u make()`, `.u grab()` (a tag on its own), `void log(char* s)`. `fn f(a, b)` starts without explicit parameter or return types; constraints from calls and returned values propagate through callers and callees until inference reaches a fixed point, including recursive calls anchored by typed callees. conflicting argument types or an unknown reassignment leave the affected type unresolved instead of choosing a type. the learning example [32](examples/learn/32-inferred-calls.zc) shows this propagation and an owned raw-list return. a generic function lists its type parameters after its name, `T first<T>(*list<T> l)`, the same place a call gives explicit ones, `first<int>(l)`. the return type can use them before they're declared: while it's read, an unknown name is taken as a type parameter, and the list after the name has to confirm it. function types are written the same way, `int(int, *char)`, and `fn(int)` for one that returns a word. the earlier `fn f(...) -> T` spelling is gone.
array types put the element type first. `T[n]` has its size in the type and lives in place. `T[]` also lives in place; its length is inferred from an initializer such as `int[] a = {1, 2, 3};` and cannot grow. `T[?]` can also be initialized in a function with a list, such as `int[?] a = {1, 2};`. it is a growable array: a small handle object that owns its items, made with `rt.new(T[?])` or `rt.new(T[?], n)`, indexed with a bounds check, and changed with `push(a, x)`, `pop(a)` and `resize(a, n)`. `len(a)` works on both (for `T[n]` it's the constant) and `cap(a)` gives the room before the next grow. `fixed T[?]` is a `T[?]` that can't change size: `rt.new(fixed T[?], n)` needs the length, and `push`, `pop` and `resize` on it are compile errors. a `fixed T[?]` can't be passed where a `T[?]` is expected, the other way round is fine, and a constant index outside a `T[n]` is caught at compile time. the items belong to the array, so freeing it frees them, and objects stored into a `T*[?]` are its children like any container's.
@@ -194,6 +196,8 @@ a unit is read whole and scanned for function signatures before it compiles, so
the runtime api lives in the `rt` namespace and requires `include rt;`: `rt.put_c`, `rt.get_c`, `rt.eof`, `rt.put_s`, `rt.put_n`, `rt.halt`, `rt.len_w`, `rt.eq_w`, `rt.copy_w`, `rt.fill_w`, the packed-string helpers `rt.len_s`, `rt.at_s`, `rt.slice_s`, `rt.cat_s`, `rt.eq_s`, `rt.s_to_n`, `rt.n_to_s` and `rt.put_bs`, allocation and ownership helpers such as `rt.new`, `rt.new_t`, `rt.free`, `rt.gc`, `rt.memreport`, and host functions including `rt.syscall` and `rt.readfile`. their signatures and descriptions are in the runtime source comments and built-in hover table. `src/lib/std.zc` declares the `std` namespace; its static groups are called as `std.Group.name(args)`: `std.Text`, `std.Num`, `std.Host`, `std.Bytes`, `std.Arena`, and `std.Buf`. the constructors `std.arena(n)` and `std.bnew(n)` and globals such as `std.argc` and `std.argv` are plain declarations in that namespace. capture uses static functions: `std.capture.start()` begins output capture and `std.capture.end(buf)` ends it and returns the buffer.
+the standard library has seven static groups: `std.capture` (output capture), `std.Text` (char* strings), `std.Num` (integer helpers), `std.Host` (environment, clock, files and raw syscalls), `std.Bytes` (packed byte strings), `std.Arena` (word arenas) and `std.Buf` (byte buffers). the array algorithms `std.array_find`, `std.array_map`, `std.array_reduce` and the others are plain functions in the same namespace. every public declaration in `src/lib/std.zc` has a comment that the language server shows on hover. `examples/std_tour.zc` calls one or two functions from each group and the array algorithms; run it with `build/bin/zy < examples/std_tour.zc`.
+
`std.argc` and `std.argv` provide command-line arguments to `main`; `std.envc` and `std.envp` provide environment entries in `NAME=value` form. `std.argc` is an `int`, and `std.argv` is a `char*[?]`; the environment fields have matching types. `std.argv[0]` is the program path, or `<eval>` when source comes from stdin. `std.libinit()` fills all four before `main` when the program includes `std`. Since include dependencies do not import into the caller, runtime calls also require `include rt;`:
```
@@ -295,7 +299,7 @@ the kinds are `word`, `int`, `char`, `bool`, `void`, pointers `T*`, arrays `T[n]
### pointer types
-a pointer type places its star after the type, like c: `int*`, `point*`, `vec<T>*`, `vec<point*>*`, `point**`. a tag follows the stars (`vec<T>*.u`, `int*.d x`). there is no prefix form: `*int` as a type is an error, and a star in front of an expression is only ever a dereference. a pointer to an array or to a function type is spelled with a `type` alias (`type row = int[3];` then `row*`), because `int*[3]` reads as an array of pointers. `tprint`, and so error messages and reflection, print the same form.
+a pointer type places its star after the type, like c: `int*`, `point*`, `vec<T>*`, `vec<point*>*`, `point**`. a tag follows the stars (`vec<T>*.u`, `int*.d x`). there is no prefix form: `*int` as a type is an error, and a star in front of an expression is only ever a dereference. a pointer to an array or to a function type is spelled with a `type` or `typedef` alias (`type row = int[3];` or `typedef int[3] row;`, then `row*`), because `int*[3]` reads as an array of pointers. `tprint`, and so error messages and reflection, print the same form.
### methods and closures
@@ -312,6 +316,8 @@ p.dist(q);
underneath, a method is an ordinary function called `point.dist` whose first parameter is `point* this`, compiled once the struct is complete, so a method can call the ones declared after it. a field with the same name wins over a method. a method of a generic struct is a generic function over the struct's parameters, compiled for each set of arguments it is called with (the receiver says which), so `this.items[i]` and `sizeof(K)` inside it are exact.
+a `static` function (`static fn name(...)` or `static int name(...)`) has no `this` and is called as `Struct.name(args)`, or `std.Text.itoa(n, buf)` for a library group. a struct can also hold untyped constants: `struct Text { const MAX = 24, MIN = 1; int len; }` (a type before the name, as in `const int MAX = 24;`, is read and dropped). the initializers are constant expressions, a constant takes no space in the struct, it is reached as `Text.MAX` (`std.Text.MAX` from a library), and a method or static function of the struct can use the bare name `MAX`. a misspelled field, static function or constant gets the same `; did you mean 'name'?` suggestion as an undefined function, and the language server offers it as a quick fix.
+
`fn(a, b) { ... }` in an expression is a closure. the value is a heap block: word 0 is the body's entry, and its captured cell pointers start at word 3. the vm only runs code in the code area, so the block is never executed. a call through a value checks whether the callee is at or above `HEAP_LO`. a plain function is called as it is. a closure is called with the block plus 3 as its environment and jumps to the entry in word 0. captured locals and parameters share cells with the enclosing function and sibling closures, so mutations stay visible after the closure is made and after its creator returns. captured owned objects remain alive with those cells. the block is an owned object; a fresh closure can be passed directly to a proved borrower, and returning one transfers it to the caller. `examples/learn/25-closures.zc` and `examples/learn/26-closure-state.zc` cover these.
`fn:type(args)` declares a closure's result and parameter types. an owned closure can be returned from a factory with `.u`; its captured cells remain alive for the returned value. [the typed closure example](examples/learn/30-typed-closure.zc) covers this form.
diff --git a/TASKLIST.md b/TASKLIST.md
deleted file mode 100644
index 8d081d9..0000000
--- a/TASKLIST.md
+++ /dev/null
@@ -1,1203 +0,0 @@
-# TASKLIST — "Review and polish project code"
-
-Complete inventory of every request made by the user in codex session
-`01a12a7c-8c55-7873-a0ae-da32c723ce8c` (2026-10-11 → 2026-10-14, workspace
-`~/Documents/Playground/tinyvm`).
-
-Each item gives **the request in summary** followed by **the user's exact
-message, verbatim** in a blockquote. Section 14 holds the complete raw
-transcript with nothing removed.
-
----
-
-## Follow-up: found after that session
-
-Not part of the session transcript. These came out of the `src/` and history
-cleanup that followed, and they are now blocking work.
-
-### `make` cannot bootstrap from a clean checkout
-
-**Written up in [`docs/BOOTSTRAP-OWNERSHIP.md`](docs/BOOTSTRAP-OWNERSHIP.md)**,
-linked from `docs/BORROW.md`, with a TODO entry. Reproduce with
-`bash src/tools/bootstrap-check.sh`.
-
-The second bootstrap stage runs the lifetime checker over the compiler's own
-source and reports 8 errors, so `bin/mkgenome` reads the diagnostics as if they
-were an image:
-
-```
-mkgenome: input is not a genome for this map
-```
-
-Two ownership completeness limits are responsible:
-
-1. **No move between two locals.** Every accepted move originates at a call
- (`m*rt.new(...)`, `m*inc_open(...)`, `chk_resize(...)`). An owned value held
- in a local can be disposed with `d*`, but cannot be handed to another local,
- and cannot replace one. The documented `rt.free(buffer); buffer =
- replacement;` rule only fires when the replacement comes from a call.
-2. **A local cannot be lent to a global.** Redirecting the output stream at a
- scratch buffer is a borrow, but every spelling is a transfer, so the buffer
- must live at module scope — which costs reentrancy safety.
-
-Neither limit accepts an unsafe program; both refuse correct ones. So it is a
-completeness gap, not a soundness bug. A verified partial fix (promoting the
-scratch buffer to a module global, the existing `sgb` idiom) removes 5 of the
-8 errors.
-
-Also found along the way: `lookup_raw` compared against `K_VAR`, a constant that
-was never declared, so `make genome` could not run at all before that.
-
----
-
-## 0. Standing instructions (apply to everything)
-
-### Commands must be single-line
-
-> When writing commands for the user, never write them as multi-line (with
-> backslashes)
-
-(from `AGENTS.md` injected into the session)
-
-### Delegate mechanical work to subagents
-
-> if you require busywork that you consider repetitive, easy to complete, but not
-> suitable for a bash run, use a 6-luna subagent to do so.
-
-### Small test intervals, not the full suite
-
-> also, please run tests in small intervals. don't run the full suite repeatedly
-> as it takes a good couple minutes
-
-### Don't stop until done
-
-> don't stop until the todo list is done.
-
-> continue and don't stop
-
-(repeatedly set and re-set as the session goal)
-
-### Keep `TODO.md` current
-
-> write your tasks to a TODO.md file
-
-> make sure to add these to the todo file.
-
-> add these to tasks and todo.md:
-
-> don't forget to tick off tasks that you complete in TODO.md.
-
-> don't forget to update the todo.md.
-
-> re-order the todo file based on the order of tasks that you'll complete.
-
-> did you update todo?
-
-> ummm... if it's updated, why are there still headers... and, why aren't the
-> crossed off tasks all at the start, since they've been implemented already? do
-> you understand how sorting works?
-
-> add these to todo.md
-
-> update todo.md
-
-> also, add a hint for when a function argument is never used in the body. add to
-> todo.md
-
-> also add a --help to the compiler, lsp, etc. put in todo
-
-### Comment and doc style
-
-> the comments and docs shouldnt have uppercase :( follow the writing style of the
-> older comments
-
-> keep the lowercase, just remove the informal ai slop and replace it with
-> professional compiler docs and guidance prose
-
----
-
-## 1. Code review, bugs, and polish
-
-### Read the code first
-
-> read the code and familiarize yourself.
-
-### Find bugs and optimizations
-
-> - find bugs and areas for optimizations.
-
-### Clean up phrasing and dirty references
-
-> - clean up the phrasing, there are leftover dirty references such as "task X"
-> in the documentation and code.
-
-### Consistent comment style
-
-> - make the commenting style consistent, and avoid connecting comments to
-> unrelated variables.
-
-### Polish the learning documents
-
-> - polish the learning documents and ensure they're clear, direct, properly
-> sectioned, and easy to understand.
-
-### Fix the hover-renders-as-plain-text bug
-
-> - make sure this bug is fixed: hovering over something in vscode renders it as
-> plain text, rather than formatted markdown and code. this was claimed to have
-> been solved in the latest changes, but it's not a guarantee, so i need you to
-> look at it again.
-
----
-
-## 2. Memory limits, build, and run
-
-### Dynamic memory limits, adjustable at build time and run time
-
-> - ensure all memory map limits are dynamic and can be adjusted both at build
-> time and also run time.
-
-### Clarification: tables and stacks must grow too
-
-> **Grow tables and stacks too** — for runtime-adjustable limits, should running
-> programs be able to grow individual compiler tables and stacks, or is
-> configurable total VM/heap memory at startup plus heap growth sufficient?
-> Changing every region during execution requires replacing the genome's
-> fixed-address layout.
-
-### Unify Windows run files; add a Linux script
-
-> - unify the windows run files into one interactive batch file.
-> - create a similar shell script for linux.
-
-### Remove CEILINGS.md
-
-> - remove the CEILINGS.md file if it's not needed.
-
----
-
-## 3. Project layout
-
-> - the parent dir is a bit cluttered again, move source files into subdirs of
-> src/, tests under subdirs of tests, docs and designs into a docs/, and so on.
-
-> - run all core source files one by one through the lsp, and catch their errors.
-> try to replicate an editor's context. i currently get errors in src/compiler.zc,
-> for example.
-
-> have you passed your own code into the lsp???
-
----
-
-## 4. LSP / VS Code features
-
-### Type hover text (built-ins mandatory)
-
-> - add hover text for variable types, including arrays and structs and others.
-> built-in type hover texts are mandatory
-
-### `/**/` comments contribute to documentation
-
-> - /**/ comments should contribute to documentation as well. they're very useful
-> for defining comments for individual variables and arguments and the likes, in
-> a multi-variable line or expression.
-
-### Inferred types in hover
-
-> - inferred types for untyped variables, function returns and arguments and
-> other spots should be shown in hover previews in vscode.
-
-### Hover value tips
-
-> - add variable value tips when hovering. if a value is known at hover time (aka
-> constants or variables assigned to literals, hovered on a section before they're
-> modified to a non-literal), display it in the hint.
-
-### Comment-to-variable association bugs
-
-> - i still see sections starting with `--- header ---` (number of dashes can
-> vary) or comments that are unrelated to the variable/function that comes after
-> them but related to the section, with no new line in between, so they get marked
-> as the hint of that variable, which is confusing and inaccurate. fix that. i
-> also see comments coming after a variable, which are not detected and hinted
-> properly by the lsp. either put those comments before the variable, or make the
-> compiler recognize them and classify them as hints. a good example of this
-> phenomenon starts at line 221 in compiler.zc.
-
-### Code error detection too slow
-
-> add task
-> - code error detection is too slow. add streaming and context cancellation, to
-> immediately halt old requests when there is a code change.
-
-### Jump to definition / references, cross-file
-
-> - add jump to definition / references support to the lsp. support cross-file
-> references and jumps as well.
-
-### Pretty-printer / formatter (lowest priority)
-
-> - add a pretty-printer/formatter, close to how clang-format works. this is a
-> minimum priority task and goes at the end of the todo list. even if all other
-> tasks are completed, implementing this task is unnecessary.
-
-### Quick fix support
-
-> - add quick fix support, including automatically importing the relevant library
-> and whatnot
-
-### Namespace suggestions
-
-> - add namespace suggestions too. `rt.` should bring up the fns under rt
-> namesapce
-
-### Hover for `include name;`
-
-> - add hover info for the library name in `include name;`
-
-### Lifetime hover with explanations
-
-> - add inferred and described lifetimes to hover informations, with their
-> explanations. also include hints such as "this variable is passed up on line X or
-> passed down on line Y"
-
-### Cross-file F12 on `s_to_n`
-
-> - running f12 on s_to_n says no definition and does NOT bring up rt.zc
-
-### Recursive type inference
-
-> - add recursive inference. eg: in lists.zc, mklist knows cap is an int. then
-> mklist is called with n in squares, so n is an int too. and squares returns l,
-> and l is the retval of mklist. we know that's a word, so that's what's inferred
-> as the ret type of squares too.
-
-### Variable declaration hover must show the type
-
-The user pasted a brainfuck compiler to demonstrate that it uses `put_s`,
-`put_n`, and `evals` without any `include` and gets no errors:
-
-```zc
-// a brainfuck compiler. it turns a brainfuck program into zc source, hands
-// that to the compiler that's sitting in memory, and runs the result, which on
-// arm64 means native code. runs of + - < > fold into one statement each.
-// give it a program after a backtick, or it runs the hello world below.
-let out[30000], n, depth;
-void emit(s) { let i = 0; while (s[i]) { out[n] = s[i]; n++; i++; } return; }
-void emitn(int v) { if (v >= 10) emitn(v / 10); out[n] = '0' + v % 10; n++; return; }
-// how many times does c repeat from s[i]
-int run(s, int i, int c) { int k = 0; while (s[i + k] == c) k++; return k; }
-
-fn translate(s) {
- int i = 0, k;
- n = 0; depth = 0;
- emit("let t[30000], p = 0;\n");
- while (s[i]) {
- switch (s[i]) {
- case '+', '-':
- k = run(s, i, s[i]);
- emit("t[p] = (t[p] "); emit(s[i] == '+' ? "+ " : "- "); emitn(k); emit(") & 255;\n");
- i = i + k; continue;
- case '>', '<':
- k = run(s, i, s[i]);
- emit("p "); emit(s[i] == '>' ? "+= " : "-= "); emitn(k); emit(";\n");
- i = i + k; continue;
- case '[': emit("while (t[p]) {\n"); depth++;
- case ']': emit("}\n"); depth--;
- case '.': emit("put_c(t[p]);\n");
- case ',': emit("t[p] = eof() ? 0 : get_c() & 255;\n");
- }
- i++;
- }
- emit("return 0;\n");
- out[n] = 0;
- return depth;
-}
-let hello = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.";
-let prog[20000];
-fn main() {
- let src = hello, k = 0, lines = 0, i = 0;
- while (!eof() && k < 19999) { let c = get_c(); if (c != 10) { prog[k] = c; k++; } }
- prog[k] = 0;
- if (k) src = prog;
- if (translate(src)) { put_s("unbalanced brackets\n"); return 1; }
- while (out[i]) { if (out[i] == 10) lines++; i++; }
- put_s("compiled to "); put_n(lines); put_s(" lines of zc, running it:\n");
- evals(out);
- return 0;
-}
-```
-
-> this doesnt use rt.put_s or compiler.evals (actually make the compiler
-> namespace core, so it's core.evals) and doesn't even include core or rt. yet
-> it has no errors???
-
-and on the hover format itself:
-
-> also wtf is this?
-> ```
-> let hello // global; type char*
-> ```
-> hover info
-> it's supposed to be
-> ```
-> (char*) let hello // global;
-> ```
-> !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! you have not implemented everything properly
-> !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-> same with this
-> ```
-> let prog // global; type word[20000]
-> ```
-> and many other places!! dude cmon!!! i asked for something and you didn't
-> implement it fully!
-
----
-
-## 5. Diagnostics / hints presentation
-
-### Blue squiggly hints with per-file control
-
-> - compiler hints should be displayed with those squiggly blue lines instead of
-> tiny three dots. this can be turned back into the three dots at the start of the
-> range with `hints small;` placed in the file (takes effect for lines below it).
-> other values are `hints off;` which turns them off, and `hints on;` which turns
-> them on into the blue squigglies (default)
-
-### Magic-number hint escape hatch
-
-> - add an escape hatch for magic number hints when there's a /**/ comment before
-> it. so `return n + 0x40ff` gives a warning, whilst `return n + /* offset in
-> memory */ 0x40ff` does not
-
-> include the fact that an inline comment suppresses it
-
-### Professional comment and hint prose
-
-> make hints and comments more professional. when have you ever in your life seen
-> clangd say "; a const says what it means"??? read actual compiler docs to know
-> how to format documentation, comments and how to phrase things. keep the
-> lowercase, just remove the informal ai slop and replace it with professional
-> compiler docs and guidance prose
-
-### Unused-argument hint
-
-> also, add a hint for when a function argument is never used in the body. add to
-> todo.md
-
-### `_` as a discard name
-
-> unused arguments, if they're named _, they can be discarded normally
-
-> and there can be multiple _'s. they should also be usable in pattern matching
-> and tagged enums
-
-> and if a _ is used, that instead gets a warning
-
----
-
-## 6. Naming / language semantics fixes
-
-### Remove `scat`, rename builtins
-
-> - please don't leave a function called scat in the code...
-
-> - change puts to put_s, putn to put_n, scat to cat_s, and so on.
-
-### Nested call returning `u`
-
-> - when i write `puts(f(x))` when fn returns a u type, i get this error: `a new
-> object can only go straight to a d parameter; bind it to a name first`. if it's
-> intended, leave it be. otherwise, fix it.
-
-### Global assignment from inside a function
-
-> - assigning a value to global variable from inside a function requires that
-> value to be m or u. once this assignment happens, the value is recasted
-> automatically (can also be done manually) to u, and it is consumed immediately,
-> meaning no other object can use it from that reference anymore. it can still be
-> accessed from the global, though.
-
-### Typed closure returns
-
-> - typed return from closures, using `fn:type(args) { code }`. example: `let
-> double = fn:int(int a) { return a * 2; }`
-
-### `fixed` + `const` together
-
-> - make fixed and const able to be used together
-
-### String literals must never be `word`
-
-> - string literals shouldnt be auto detected as a word when untyped. `let hello =
-> b"hi";` is typed as word, which is incorrect and inaccurate.
-
-> - in general, string literals, whether packed or not, must not be marked as
-> word, ANYWHERE. find all occurrences of word in the code after you're done with
-> removing them, and ensure none are referring to strings, either as input
-> arguments, or variables, or return types.
-
-### `case` indentation in the pretty printer
-
-> - case should be on one indent more than switch, when pretty printing
-
-### Multi-include syntax
-
-> add multi-include syntax `include rt, run, core;` for example. continue with
-> your tasks
-
----
-
-## 7. Namespaces and includes (major structural change)
-
-> i still see sooo many unchecked's in just the compiler...
-
-> also, the stuff under rt should go into their own respective rt namespace
-> and lsp too
-> generally just everything in the toolchain should be in its own namespace. and
-> require an explicit include to use them. like `include lsp;` or `include rt;`
-> not just those, but the rest too. like builtin core functions should have an
-> `include core;` and so on
-
-> don't stop until the todo list is done.
-
-> actually nvm, compiler is `run` instead of `core`. `core` is for the core
-> itself
-
----
-
-## 8. Analysis features
-
-### Bounding + lifetime analysis
-
-> - after everything else has been completed, add basic bounding+ilfetime analysis
-> to detect array bounds and show warnings whenever the compiler is sure there's
-> an OOB or UAF happening. also, hovering over an array or pointer should show its
-> lifetime or size.
-
-### BORROW.md plan
-
-> - generally, i want the borrow checker and lifetime analyzer to be *less
-> annoying* and *less intrusive* than rust's, whilst still being *more
-> intelligent* than it. if you can achieve this, draft a plan in BORROW.md for me.
-
----
-
-## 9. Libraries / stdlib
-
-### 9.1 `icon.zc` — runtime self-modifying code
-
-> spawn a subagent to write an std module in src/lib/ called icon.zc, which
-> supports way more complex self-modifications for code. currently, the best
-> we've got is a few functions to find literals. this new import `include icon;`
-> will provide things such as `icon.find_replace(my_fn, ${ $int + $int}, ${ $int
-> - $int }` and so on. it should be quite powerful, enough to mold and mix and
-> match syntax. undeclare variables, change types, add new blocks, change
-> expressions, calculate parts of an expression, step through code step by step
-> and examine its locals and globals, all at run time, and all dynamically, from
-> inside the language, using the help of the compiler.
-
-> also the icon code is of subpar quality in some places (eg a variable that is
-> never read), so relaunch the agent with 6.1 sol high to look through it
-> and make the actor agent 6.1 sol high too
-
-### 9.2 `actor` — actor semantics
-
-> - subagent task: add a library called actor, which allows actor-like semantics,
-> with async threads running in the background with separate contexts and internal
-> state, so that you can spawn one: `let a = addTwo.spawn(); a.recv(fn (e) {
-> putn(e); }); a.send(2); // prints 4` and whatnot. smalltalk or obj-c like
-> semantics
-
-> not just integer messages, actors can exchange any type. they get a generic
-> with two types: one for input, one for output. `Actor<I,O>`
-
-> also, isn't `this` implicit? if not, make it implicit and don't let people
-> declare it as the first argument
-
-> oh and btw, actors are async. they can run in parallel and there can be multiple
-> of each instance. defining thems hould be syntax injected into the compiler at
-> include time as immediate, including a keyword actor which is used in place of
-> struct to declare an actor.
-
-> important, the actor library should NOT be inside the compiler. it should
-> INFLUENCE the compiler at INCLUDE TIME. it's not a "this include activates this
-> syntax because the compiler has it bundled", it's a "this include activates this
-> syntax because it's injected into the compiler's machinery at include time". if
-> the compiler is lacking the extendability required for the task, then implement
-> that inside the compiler to make it more flexible, instead of hardcoding actors
-> into it. IMPORTANT: I DO NOT WANT TO SEE ANY ACTOR RELATED CODE IN compiler.zc
-> OR ANY OTHER FILE THAT IT INCLUDES OR READS BY DEFAULT.
-
-> update todo.md
-
-### 9.3 Arrays as first-class
-
-> - add support for push and pop and find and map and filter and other stuff to
-> arrays
-
-> - arrays should also be able to act like `x.push(4)` or `x.map(fn (e) { return
-> e + 2 })`. this also comes with autocomplete support
-
-### 9.4 Stdlib docs and documentation agent
-
-> - add more docs to the stdlib using a subagent
-
-> assign the polish docs agent to update the documentation, add new examples,
-> update learn entries, nad history too.
-
----
-
-## 10. CLI
-
-> also add a --help to the compiler, lsp, etc. put in todo
-
----
-
-## 11. Testing
-
-### Write tests before doing the remaining work
-
-> write tests, both ACCEPT tests and REJECT tests and regression tests, extensively
-> for every unchecked item in the todo list, and only then should you start work,
-> and to not stop until all those tests pass.
-
-### Then extensive tests for the whole toolchain
-
-> finish these tasks, and then write extensive tests for the lsp, compiler, and
-> every other tool in the toolchain. it should not only conform FULLY to the specs
-> and the todo requirements, but also be free of errors.
-
----
-
-## 12. Additional todo items added later
-
-> add task
-> - code error detection is too slow. add streaming and context cancellation, to
-> immediately halt old requests when there is a code change.
-
-> add to todo
-> - string literals shouldnt be auto detected as a word when untyped. `let hello =
-> b"hi";` is typed as word, which is incorrect and inaccurate.
-> - running f12 on s_to_n says no definition and does NOT bring up rt.zc
-> - in general, string literals, whether packed or not, must not be marked as
-> word, ANYWHERE. find all occurrences of word in the code after you're done with
-> removing them, and ensure none are referring to strings, either as input
-> arguments, or variables, or return types.
-
----
-
-## 13. Process feedback and session management
-
-> you have a background terminal running
-
-> do some work yourself
-
-> dude why do you keep not getting jack fucking shit done im crine
-
-> oml bruh you did fuck all yourself all this time?? it's been two hours oml
-
-> connection all good?
-
-> continue working then :)
-
-> progress update?
-
-> continue!!!
-> continue
-
-> no. auto review failed DAYS AGO. now the usage limit is back. continue. and auto
-> review is off, you're on full access.
-
-> also
-
----
-
-## 14. Grouped index (lookup)
-
-| Area | Requests |
-|---|---|
-| Review & polish | find bugs, find optimizations, clean "task X" references, consistent comment style, polish learn docs |
-| Hover bug | markdown/code hover renders as plain text — verify fixed |
-| Memory/build | dynamic limits (build+runtime), grow tables & stacks, unify Windows batch file, Linux shell script, drop `CEILINGS.md` |
-| TODO.md | maintain, tick off, reorder, completed-at-top, no leftover headers |
-| Layout | `src/` subdirs, `tests/` subdirs, `docs/`; run every core source file through the LSP |
-| LSP | type hovers (mandatory for built-ins), `/**/` doc comments, inferred types, value tips, comment-association bugs, `(char*) let hello // global;` format, streaming + cancellation, jump-to-def/refs cross-file, formatter (lowest priority), quick fixes + auto-import, namespace completion, hover for `include name;`, lifetime hover with explanations, array/pointer lifetime+size hover, F12 on `s_to_n` must open `rt.zc`, recursive inference |
-| Hints | blue squigglies w/ `hints on/small/off`, magic-number suppression via `/**/`, unused-arg hint, `_` (multiple, pattern matching, tagged enums; warn on use), professional non-AI-slop phrasing |
-| Renames | remove `scat`, `puts`→`put_s`, `putn`→`put_n`, `scat`→`cat_s` |
-| Semantics | nested `u`-returning call, global assign from fn + recast to `u` + consume, string literals never `word` anywhere, `fixed`+`const` together, typed closures `fn:t(...)`, `case` indent under pretty printer, `include rt, run, core;` |
-| Namespaces | `rt`, `lsp`, `run`, `core` namespaces + explicit includes everywhere; brainfuck sample must error without includes |
-| Analysis | bounding + lifetime OOB/UAF warnings; `BORROW.md` plan (less intrusive than Rust, more intelligent) |
-| Libs | `icon.zc` (runtime self-modification, subagent, 6.1 sol high review), `actor` (async, `Actor<I,O>`, implicit `this`, `actor` keyword injected at include time, **zero actor code in the compiler**), arrays `push/pop/find/map/filter` + method syntax + autocomplete, recursive inference, more stdlib docs |
-| CLI | `--help` for compiler, LSP, etc. |
-| Tests | ACCEPT + REJECT + regression for every unchecked todo item, written *before* the work; extensive LSP/compiler/toolchain tests afterward |
-| Process | one-line commands, delegate busywork to 6-luna subagents, small test intervals, work it yourself, don't stop until done |
-| **Post-session** | **bootstrap blocked: owned values can't move between locals, and locals can't be lent to globals — see `docs/BOOTSTRAP-OWNERSHIP.md`** |
-
----
-
-## 15. Raw transcript — every user message, in order
-
-Environment/context injections are marked. Session ran 2026-10-11T10:22 through
-2026-10-14T03:00 (UTC timestamps as recorded).
-
----
-
-**1.** `2026-10-11T10:28:39` — *environment injection (AGENTS.md + env context)*
-
-> # AGENTS.md instructions
->
-> <INSTRUCTIONS>
-> When writing commands for the user, never write them as multi-line (with
-> backslashes)
-> </INSTRUCTIONS>
-> <environment_context>
-> <cwd>/Users/moonflower/Documents/Playground/tinyvm</cwd>
-> <shell>zsh</shell>
-> <current_date>2026-10-11</current_date>
-> <timezone>Asia/Tehran</timezone>
-> <filesystem><workspace_roots><root>/Users/moonflower/Documents/Playground/tinyvm</root></workspace_roots><permission_profile type="managed">…</permission_profile></filesystem>
-> </environment_context>
-
-**2.** `2026-10-11T10:28:39`
-
-> read the code and familiarize yourself.
-> if you require busywork that you consider repetitive, easy to complete, but not
-> suitable for a bash run, use a 6-luna subagent to do so.
-> then, here are your tasks:
-> - find bugs and areas for optimizations.
-> - clean up the phrasing, there are leftover dirty references such as "task X" in
-> the documentation and code.
-> - make the commenting style consistent, and avoid connecting comments to
-> unrelated variables.
-> - polish the learning documents and ensure they're clear, direct, properly
-> sectioned, and easy to understand.
-> - make sure this bug is fixed: hovering over something in vscode renders it as
-> plain text, rather than formatted markdown and code. this was claimed to have
-> been solved in the latest changes, but it's not a guarantee, so i need you to
-> look at it again.
-
-**3.** `2026-10-11T10:31:36`
-
-> another task:
-> - ensure all memory map limits are dynamic and can be adjusted both at build
-> time and also run time.
-> - unify the windows run files into one interactive batch file.
-> - create a similar shell script for linux.
-> - remove the CEILINGS.md file if it's not needed.
->
-> write your tasks to a TODO.md file
-
-**4.** `2026-10-11T10:32:11` — *answer to a question prompt*
-
-> **Grow tables and stacks too**
-
-**5.** `2026-10-11T10:44:16`
-
-> the comments and docs shouldnt have uppercase :( follow the writing style of the
-> older comments
-
-**6.** `2026-10-11T10:49:54`
-
-> continue
-
-**7.** `2026-10-11T10:53:32`
-
-> also, please run tests in small intervals. don't run the full suite repeatedly as
-> it takes a good couple minutes
-
-**8.** `2026-10-11T10:58:26`
-
-> - add hover text for variable types, including arrays and structs and others.
-> built-in type hover texts are mandatory
-
-**9.** `2026-10-11T10:59:26`
-
-> - /**/ comments should contribute to documentation as well. they're very useful
-> for defining comments for individual variables and arguments and the likes, in
-> a multi-variable line or expression.
-
-**10.** `2026-10-11T11:02:09`
-
-> - inferred types for untyped variables, function returns and arguments and other
-> spots should be shown in hover previews in vscode.
-
-**11.** `2026-10-11T11:03:42`
-
-> make sure to add these to the todo file.
-
-**12.** `2026-10-11T11:08:17`
-
-> - after everything else has been completed, add basic bounding+ilfetime analysis
-> to detect array bounds and show warnings whenever the compiler is sure there's an
-> OOB or UAF happening. also, hovering over an array or pointer should show its
-> lifetime or size.
-
-**13.** `2026-10-11T11:15:23`
-
-> - please don't leave a function called scat in the code...
-> - change puts to put_s, putn to put_n, scat to cat_s, and so on.
-
-**14.** `2026-10-11T11:18:11`
-
-> - when i write `puts(f(x))` when fn returns a u type, i get this error: `a new
-> object can only go straight to a d parameter; bind it to a name first`. if it's
-> intended, leave it be. otherwise, fix it.
-
-**15.** `2026-10-11T11:19:03`
-
-> - generally, i want the borrow checker and lifetime analyzer to be *less
-> annoying* and *less intrusive* than rust's, whilst still being *more
-> intelligent* than it. if you can achieve this, draft a plan in BORROW.md for me.
-
-**16.** `2026-10-11T11:29:54`
-
-> connection all good?
-
-**17.** `2026-10-11T11:30:13`
-
-> continue working then :)
-
-**18.** `2026-10-11T12:12:39`
-
-> add these to tasks and todo.md:
-> - the parent dir is a bit cluttered again, move source files into subdirs of
-> src/, tests under subdirs of tests, docs and designs into a docs/, and so on.
-> - run all core source files one by one through the lsp, and catch their errors.
-> try to replicate an editor's context. i currently get errors in src/compiler.zc,
-> for example.
-
-**19.** `2026-10-11T12:47:16`
-
-> don't forget to tick off tasks that you complete in TODO.md.
-
-**20.** `2026-10-11T15:42:56`
-
-> continue
-
-**21.** `2026-10-11T16:20:41`
-
-> don't forget to update the todo.md.
-
-**22.** `2026-10-11T16:28:52`
-
-> re-order the todo file based on the order of tasks that you'll complete.
-
-**23.** `2026-10-11T16:32:13`
-
-> did you update todo?
-
-**24.** `2026-10-11T16:33:07`
-
-> ummm... if it's updated, why are there still headers... and, why aren't the
-> crossed off tasks all at the start, since they've been implemented already? do
-> you understand how sorting works?
-
-**25.** `2026-10-11T16:57:02`
-
-> continue
-
-**26.** `2026-10-12T03:17:04` — *environment injection (date change, subagents)*
-
-> continue
-
-**27.** `2026-10-12T05:16:51`
-
-> continue
-
-**28.** `2026-10-12T05:27:11`
-
-> 1. you have a background terminal running
-> 2. add variable value tips when hovering. if a value is known at hover time (aka
-> constants or variables assigned to literals, hovered on a section before they're
-> modified to a non-literal), display it in the hint.
-
-**29.** `2026-10-12T05:29:13`
-
-> add task
-> - code error detection is too slow. add streaming and context cancellation, to
-> immediately halt old requests when there is a code change.
-
-**30.** `2026-10-12T05:31:05`
-
-> - i still see sections starting with `--- header ---` (number of dashes can
-> vary) or comments that are unrelated to the variable/function that comes after
-> them but related to the section, with no new line in between, so they get marked
-> as the hint of that variable, which is confusing and inaccurate. fix that. i
-> also see comments coming after a variable, which are not detected and hinted
-> properly by the lsp. either put those comments before the variable, or make the
-> compiler recognize them and classify them as hints. a good example of this
-> phenomenon starts at line 221 in compiler.zc.
-
-**31.** `2026-10-12T05:32:45`
-
-> - add jump to definition / references support to the lsp. support cross-file
-> references and jumps as well.
-
-**32.** `2026-10-12T05:34:02`
-
-> - add a pretty-printer/formatter, close to how clang-format works. this is a
-> minimum priority task and goes at the end of the todo list. even if all other
-> tasks are completed, implementing this task is unnecessary.
-
-**33.** `2026-10-12T05:40:11`
-
-> - assigning a value to global variable from inside a function requires that
-> value to be m or u. once this assignment happens, the value is recasted
-> automatically (can also be done manually) to u, and it is consumed immediately,
-> meaning no other object can use it from that reference anymore. it can still be
-> accessed from the global, though.
-
-**34.** `2026-10-12T05:42:16`
-
-> - typed return from closures, using `fn:type(args) { code }`. example: `let
-> double = fn:int(int a) { return a * 2; }`
-
-**35.** `2026-10-12T05:45:23`
-
-> - compiler hints should be displayed with those squiggly blue lines instead of
-> tiny three dots. this can be turned back into the three dots at the start of the
-> range with `hints small;` placed in the file (takes effect for lines below it).
-> other values are `hints off;` which turns them off, and `hints on;` which turns
-> them on into the blue squigglies (default)
-
-**36.** `2026-10-12T05:46:15`
-
-> - add inferred and described lifetimes to hover informations, with their
-> explanations. also include hints such as "this variable is passed up on line X or
-> passed down on line Y"
-
-**37.** `2026-10-12T05:46:24`
-
-> add these to todo.md
-
-**38.** `2026-10-13T06:33:41` — *environment injection (date change, subagents)*
-
-**39.** `2026-10-13T06:33:41`
-
-> i still see sooo many unchecked's in just the compiler...
-> also, the stuff under rt should go into their own respective rt namespace
-> and lsp too
-> generally just everything in the toolchain should be in its own namespace. and
-> require an explicit include to use them. like `include lsp;` or `include rt;`
-> not just those, but the rest too. like builtin core functions should have an
-> `include core;` and so on
-> have you passed your own code into the lsp???
->
-> ```
-> // a brainfuck compiler. it turns a brainfuck program into zc source, hands
-> // that to the compiler that's sitting in memory, and runs the result, which on
-> // arm64 means native code. runs of + - < > fold into one statement each.
-> // give it a program after a backtick, or it runs the hello world below.
-> let out[30000], n, depth;
-> void emit(s) { let i = 0; while (s[i]) { out[n] = s[i]; n++; i++; } return; }
-> void emitn(int v) { if (v >= 10) emitn(v / 10); out[n] = '0' + v % 10; n++; return; }
-> // how many times does c repeat from s[i]
-> int run(s, int i, int c) { int k = 0; while (s[i + k] == c) k++; return k; }
->
-> fn translate(s) {
-> int i = 0, k;
-> n = 0; depth = 0;
-> emit("let t[30000], p = 0;\n");
-> while (s[i]) {
-> switch (s[i]) {
-> case '+', '-':
-> k = run(s, i, s[i]);
-> emit("t[p] = (t[p] "); emit(s[i] == '+' ? "+ " : "- "); emitn(k); emit(") & 255;\n");
-> i = i + k; continue;
-> case '>', '<':
-> k = run(s, i, s[i]);
-> emit("p "); emit(s[i] == '>' ? "+= " : "-= "); emitn(k); emit(";\n");
-> i = i + k; continue;
-> case '[': emit("while (t[p]) {\n"); depth++;
-> case ']': emit("}\n"); depth--;
-> case '.': emit("put_c(t[p]);\n");
-> case ',': emit("t[p] = eof() ? 0 : get_c() & 255;\n");
-> }
-> i++;
-> }
-> emit("return 0;\n");
-> out[n] = 0;
-> return depth;
-> }
-> let hello = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.";
-> let prog[20000];
-> fn main() {
-> let src = hello, k = 0, lines = 0, i = 0;
-> while (!eof() && k < 19999) { let c = get_c(); if (c != 10) { prog[k] = c; k++; } }
-> prog[k] = 0;
-> if (k) src = prog;
-> if (translate(src)) { put_s("unbalanced brackets\n"); return 1; }
-> while (out[i]) { if (out[i] == 10) lines++; i++; }
-> put_s("compiled to "); put_n(lines); put_s(" lines of zc, running it:\n");
-> evals(out);
-> return 0;
-> }
-> ```
->
-> this doesnt use rt.put_s or compiler.evals (actually make the compiler
-> namespace core, so it's core.evals) and doesn't even include core or rt. yet
-> it has no errors???
-> don't stop until the todo list is done.
-> actually nvm, compiler is `run` instead of `core`. `core` is for the core
-> itself
-> also wtf is this?
-> ```
-> let hello // global; type char*
-> ```
-> hover info
-> it's supposed to be
-> ```
-> (char*) let hello // global;
-> ```
-> !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! you have not implemented everything properly
-> !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-> same with this
-> ```
-> let prog // global; type word[20000]
-> ```
-> and many other places!! dude cmon!!! i asked for something and you didn't
-> implement it fully!
-> also, add a hint for when a function argument is never used in the body. add to
-> todo.md
-> write tests, both ACCEPT tests and REJECT tests and regression tests, extensively
-> for every unchecked item in the todo list, and only then should you start work,
-> and to not stop until all those tests pass.
-> add to todo
-> - string literals shouldnt be auto detected as a word when untyped. `let hello =
-> b"hi";` is typed as word, which is incorrect and inaccurate.
-> - running f12 on s_to_n says no definition and does NOT bring up rt.zc
-> - in general, string literals, whether packed or not, must not be marked as
-> word, ANYWHERE. find all occurrences of word in the code after you're done with
-> removing them, and ensure none are referring to strings, either as input
-> arguments, or variables, or return types.
-
-**40.** `2026-10-13T06:34:11`
-
-> finish these tasks, and then write extensive tests for the lsp, compiler, and
-> every other tool in the toolchain. it should not only conform FULLY to the specs
-> and the todo requirements, but also be free of errors.
-
-**41.** `2026-10-13T06:35:25` — *environment injection (full access enabled)*
-
-**42.** `2026-10-13T06:35:25`
-
-> no. auto review failed DAYS AGO. now the usage limit is back. continue. and auto
-> review is off, you're on full access.
-
-**43.** `2026-10-13T06:36:54`
-
-> - add an escape hatch for magic number hints when there's a /**/ comment before
-> it. so `return n + 0x40ff` gives a warning, whilst `return n + /* offset in
-> memory */ 0x40ff` does not
-
-**44.** `2026-10-13T06:42:08`
-
-> include the fact that an inline comment suppresses it
-
-**45.** `2026-10-13T06:42:11`
-
-> also
-
-**46.** `2026-10-13T06:43:28`
-
-> make hints and comments more professional. when have you ever in your life seen
-> clangd say "; a const says what it means"??? read actual compiler docs to know
-> how to format documentation, comments and how to phrase things. keep the
-> lowercase, just remove the informal ai slop and replace it with professional
-> compiler docs and guidance prose
-
-**47.** `2026-10-13T07:02:06`
-
-> unused arguments, if they're named _, they can be discarded normally
-
-**48.** `2026-10-13T07:05:27`
-
-> and there can be multiple _'s. they should also be usable in pattern matching
-> and tagged enums
-
-**49.** `2026-10-13T07:05:45`
-
-> and if a _ is used, that instead gets a warning
-
-**50.** `2026-10-13T07:13:47`
-
-> spawn a subagent to write an std module in src/lib/ called icon.zc, which
-> supports way more complex self-modifications for code. currently, the best
-> we've got is a few functions to find literals. this new import `include icon;`
-> will provide things such as `icon.find_replace(my_fn, ${ $int + $int}, ${ $int
-> - $int }` and so on. it should be quite powerful, enough to mold and mix and
-> match syntax. undeclare variables, change types, add new blocks, change
-> expressions, calculate parts of an expression, step through code step by step
-> and examine its locals and globals, all at run time, and all dynamically, from
-> inside the language, using the help of the compiler.
-
-**51.** `2026-10-13T08:20:52`
-
-> add multi-include syntax `include rt, run, core;` for example. continue with
-> your tasks
-
-**52.** `2026-10-13T08:26:25`
-
-> continue
-
-**53.** `2026-10-13T08:26:39` — *internal goal marker*
-
-> User set the goal: "continue and don't stop"
-
-**54.** `2026-10-13T09:12:02` — *internal goal marker: paused*
-
-**55.** `2026-10-13T09:21:07`
-
-> continue
-
-**56.** `2026-10-13T09:38:22`
-
-> progress update?
-
-**57.** `2026-10-13T10:22:30`
-
-> continue
-
-**58.** `2026-10-13T10:37:58`
-
-> continue
-
-**59.** `2026-10-13T12:09:59` — *internal goal marker: active*
-
-**60.** `2026-10-13T12:10:34`
-
-> continue
-
-**61.** `2026-10-13T12:17:33`
-
-> - case should be on one indent more than switch, when pretty printing
-
-**62.** `2026-10-13T12:18:20`
-
-> - add quick fix support, including automatically importing the relevant library
-> and whatnot
-
-**63.** `2026-10-13T12:18:33`
-
-> - add namespace suggestions too. `rt.` should bring up the fns under rt
-> namesapce
-
-**64.** `2026-10-13T12:20:15`
-
-> - add more docs to the stdlib using a subagent
-
-**65.** `2026-10-13T12:25:23`
-
-> - add hover info for the library name in `include name;`
-
-**66.** `2026-10-13T12:29:04`
-
-> - add recursive inference. eg: in lists.zc, mklist knows cap is an int. then
-> mklist is called with n in squares, so n is an int too. and squares returns l,
-> and l is the retval of mklist. we know that's a word, so that's what's inferred
-> as the ret type of squares too.
-
-**67.** `2026-10-13T12:31:01`
-
-> - make fixed and const able to be used together
-
-**68.** `2026-10-13T12:32:14`
-
-> - add support for push and pop and find and map and filter and other stuff to
-> arrays
-
-**69.** `2026-10-13T12:53:04`
-
-> - arrays should also be able to act like `x.push(4)` or `x.map(fn (e) { return
-> e + 2 })`. this also comes with autocomplete support
-
-**70.** `2026-10-13T12:54:57`
-
-> - subagent task: add a library called actor, which allows actor-like semantics,
-> with async threads running in the background with separate contexts and internal
-> state, so that you can spawn one: `let a = addTwo.spawn(); a.recv(fn (e) {
-> putn(e); }); a.send(2); // prints 4` and whatnot. smalltalk or obj-c like
-> semantics
-
-**71.** `2026-10-13T13:33:03`
-
-> not just integer messages, actors can exchange any type. they get a generic
-> with two types: one for input, one for output. `Actor<I,O>`
-
-**72.** `2026-10-13T13:34:02`
-
-> also, isn't `this` implicit? if not, make it implicit and don't let people
-> declare it as the first argument
-
-**73.** `2026-10-13T13:35:17`
-
-> oh and btw, actors are async. they can run in parallel and there can be multiple
-> of each instance. defining thems hould be syntax injected into the compiler at
-> include time as immediate, including a keyword actor which is used in place of
-> struct to declare an actor.
-
-**74.** `2026-10-13T13:37:15`
-
-> important, the actor library should NOT be inside the compiler. it should
-> INFLUENCE the compiler at INCLUDE TIME. it's not a "this include activates this
-> syntax because the compiler has it bundled", it's a "this include activates this
-> syntax because it's injected into the compiler's machinery at include time". if
-> the compiler is lacking the extendability required for the task, then implement
-> that inside the compiler to make it more flexible, instead of hardcoding actors
-> into it. IMPORTANT: I DO NOT WANT TO SEE ANY ACTOR RELATED CODE IN compiler.zc
-> OR ANY OTHER FILE THAT IT INCLUDES OR READS BY DEFAULT.
-
-**75.** `2026-10-13T13:37:46`
-
-> update todo.md
-
-**76.** `2026-10-13T13:50:28`
-
-> do some work yourself
-
-**77.** `2026-10-13T13:51:39` — *internal goal marker: paused*
-
-**78.** `2026-10-13T13:51:39`
-
-> also the icon code is of subpar quality in some places (eg a variable that is
-> never read), so relaunch the agent with 6.1 sol high to look through it
-> and make the actor agent 6.1 sol high too
-
-**79.** `2026-10-13T13:52:12` — *internal goal marker: active*
-
-**80.** `2026-10-13T13:52:14`
-
-> assign the polish docs agent to update the documentation, add new examples,
-> update learn entries, nad history too.
-
-**81.** `2026-10-13T14:20:14`
-
-> continue
-
-**82.** `2026-10-13T14:20:23`
-
-> dude why do you keep not getting jack fucking shit done im crine
-
-**83.** `2026-10-13T15:55:37`
-
-> oml bruh you did fuck all yourself all this time?? it's been two hours oml
-
-**84.** `2026-10-13T17:04:03`
-
-> continue!!!
-
-**85.** `2026-10-13T18:01:45`
-
-> also add a --help to the compiler, lsp, etc. put in todo
-
-**86.** `2026-10-14T02:57:56` — *environment injection (date change, subagents)*
-
-**87.** `2026-10-14T02:57:56`
-
-> continue
-
----
-
-*End of transcript. 87 user turns recorded in the session (88 user-role messages
-including the initial `AGENTS.md` injection).* \ No newline at end of file
diff --git a/TODO.md b/TODO.md
index 321fa20..db93fcb 100644
--- a/TODO.md
+++ b/TODO.md
@@ -137,7 +137,7 @@
- [x] implement `include actor;` as a library that injects actor syntax into the compiler through the generic include-time extension interface: `actor` declarations in place of `struct`, implicit `this`, and generic `Actor<I,O>` input/output types. Provide asynchronous parallel execution with independent state and multiple instances; keep actor-specific code out of `compiler.zc` and every file it includes or reads by default, and cover syntax activation, execution, messaging and type safety with tests.
- [x] implement and integrate `src/lib/icon.zc` with structured runtime syntax transformations, template matching, execution inspection and stepping, with explicit contracts and comprehensive tests.
- [x] change the producer of the genome header (`build/core/genome.h`) to emit a c translation unit that embeds the compiler, core and runtime zc sources with a `#embed` directive instead of concatenating them into a 1.5 mb generated header; keep the `.zc` sources as the single source of truth and extend the fixpoint check in `make genome` so it still verifies the emitted genome without materializing a header at all.
-- [x] close the two ownership completeness limits that stop the compiler compiling itself, so `make genome` completes from a clean checkout: allow an owned value held in a local to move into another local when the destination's previous owner is released in the same statement list, and allow a global to hold a bounded borrow of a local so an output stream can be redirected at a scratch buffer without a module-level variable. also give `rt.code_blocks = m*block;` a supported spelling and fix the `only a named owned object can be recast` diagnostic, which does not describe the real constraint. written up in `docs/BOOTSTRAP-OWNERSHIP.md`, which also records a verified partial fix that removes five of the eight current errors.
+- [x] close the two ownership completeness limits that stop the compiler compiling itself, so `make genome` completes from a clean checkout: allow an owned value held in a local to move into another local when the destination's previous owner is released in the same statement list, and allow a global to hold a bounded borrow of a local so an output stream can be redirected at a scratch buffer without a module-level variable. also give `rt.code_blocks = m*block;` a supported spelling and fix the `only a named owned object can be recast` diagnostic, which does not describe the real constraint. written up in `docs/history/BOOTSTRAP-OWNERSHIP.md`, which also records a verified partial fix that removes five of the eight current errors.
- [x] bring documentation, examples, learn entries, history notes and test fixtures in line with the include and namespace format and the other language changes made alongside it: qualify runtime built-ins as `rt.put_s`, `rt.put_n`, `rt.put_c`, `rt.eof` and `rt.get_c`, require the explicit `include` each module needs, and remove the remaining bare builtin names so every shipped sample, every documented snippet and every expected-output fixture compiles and runs against the current compiler. the learn guide and `README.md` snippets are checked by the suite, so they are the gate, but the prose and the non-exercised samples are not.
- [x] add accept, reject and regression coverage for the actor and icon libraries once each is finished: for actors, syntax activation through the include-time extension, spawn/recv/send across input and output types, multiple instances of one actor, parallel execution, implicit `this`, and confirmation that no actor code is reachable from the compiler or anything it reads by default; for icon, find/replace over real syntax, undeclaring names, changing types, adding and rewriting blocks, evaluating parts of an expression, and stepping execution while reading locals and globals, including the failure cases for each.
@@ -147,13 +147,22 @@ every item still to do, including the ones added after the list above. sorted
by how hard each is to implement, so the large language features come last.
the final full suite stays at the very end whatever its size.
-- [ ] remove temporary markdown files: decide on `TASKLIST.md` (a record of an earlier session's requests), `docs/BOOTSTRAP-OWNERSHIP.md` (its problem is resolved) and `docs/design/handoff.md`, keeping anything still referenced from `README.md` or `ONBOARD.md`.
-- [ ] verify every command in `ONBOARD.md` from a clean checkout and fix the ones that drifted.
-- [ ] add `string` as a built-in alias of `char*`, in types, hovers and completions.
-- [ ] untyped constants inside structs: `struct Text { const MAX = 24; }`, reached as `std.Text.MAX`, with the same rules as a local or top-level `const k = 5;`.
+- [x] remove temporary markdown files: decide on `TASKLIST.md` (a record of an earlier session's requests), `docs/BOOTSTRAP-OWNERSHIP.md` (its problem is resolved) and `docs/design/handoff.md`, keeping anything still referenced from `README.md` or `ONBOARD.md`.
+- [x] verify every command in `ONBOARD.md` from a clean checkout and fix the ones that drifted. (`make check` is left to the final suite run below.)
+- [x] add `string` as a built-in alias of `char*`, in types, hovers and completions.
+- [x] untyped constants inside structs: `struct Text { const MAX = 24; }`, reached as `std.Text.MAX`, with the same rules as a local or top-level `const k = 5;`.
- [ ] typo suggestions for field and method names: `p.lenght` and `std.Text.itao` suggest the closest member, with the language server's change-to quick fix.
+- [ ] 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.
+- [ ] packed byte strings and `u`/`m`/`d` in zc0: match the self-hosted compiler's `bstr` support, and treat `u`, `m`, `d` as ordinary names (a recast is the letter directly followed by `*`; tags are accepted and ignored), keeping zc0's genome image byte-identical.
+- [ ] write `docs/SPEC.md`, the language specification, from the self-hosted compiler as the reference, with the zc0 subset marked and every disagreement between prose and code listed.
+- [ ] verify both compilers against `docs/SPEC.md` with a fresh agent: one test program per rule, run on both, every deviation reported and triaged.
- [ ] a `make parity` runner that compiles the zc0-compatible programs (and the genome sources) with zc0 and with the self-hosted compiler, runs both images and compares output, so the two front ends can't disagree silently again (the `&&`/`||` precedence bug).
-- [ ] c typedefs: `typedef T name;` declares a type alias, including pointer, array and function types, usable everywhere a type is, shown in hovers.
+- [x] c typedefs: `typedef T name;` declares a type alias, including pointer, array and function types, usable everywhere a type is, shown in hovers.
+- [ ] split `src/compiler/compiler.zc` into files by phase (lexer, types, expressions, statements, analyzer, declarations, check mode, image), listed in order in one place; the concatenation must reproduce the old file exactly so every image stays byte-identical. update every consumer: the makefile, tool scripts, the language server's embedded copy, tests, docs.
+- [ ] a cross-reference report: for every global of the compiler, the functions that write it and the ones that only read it, built from the language server's references so scoping is exact, runnable as a script and in ci so a new writer of core state shows up in review.
+- [ ] group the compiler's parallel per-local arrays (`lname`, `ltype`, `lstate`, `lhome`, `lown`, ...) 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 do the same for symbols and types. the genome must keep reaching its fixpoint, and the analyzer's behavior must not change (all rejection suites and the program checks identical).
- [ ] continue removing `unchecked` from the remaining runtime boundaries by teaching the analyzer the missing ownership and drop contracts; document any irreducible low-level escapes. the compiler, standard library and lsp no longer disable checking for their functions. status, from a trial that was reverted: with `unchecked` removed, `copy_w` and `fill_w` pass the analyzer once their gate stores go through `syscall(SYS_COPY, ...)`, `dgrow` once `w[-2] = it` becomes `own(w, it)`, `dpush` once `own(x, h[2])` comes before the store, and `dnew` as is. but the checked versions changed run-time behavior: 7 of the 87 program checks in `tests/test.sh` failed (closure cells, the proved-loop bounds check) and `tests/programs/share.zc` hung with a checked `cons`. so checked code in these functions inserts cleanup the runtime can't afford, and each one needs its contract taught to the analyzer, not just a rewrite that compiles. `free`, `recycle`, `recycle_leaf` and `gc` are the allocator and collector that the analyzer's own cleanup calls, so they stay unchecked and need to be documented as the irreducible escapes. `src/lib/actor.zc` has about 20 more.
- [ ] document the public standard-library apis with concise descriptions of behavior, parameters, ownership and return values where applicable; update reference and learning entries, add executable examples and record implemented changes in history; keep prose lowercase and verify docs appear in hovers.
- [ ] revise diagnostics, comments and learning/reference prose using professional compiler documentation guidance, preserving lowercase and adding message regressions.
@@ -161,6 +170,7 @@ the final full suite stays at the very end whatever its size.
- [ ] 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. built as a library through `run.syntax` and `run.statement_hook`, like actors.
- [ ] bounds checking on by default for indexing heap pointers (checked against the block header's payload size) and typed arrays (`T[n]`, `T[?]`), stopping with the index, the length and the source line. a keyword `unbounded`, used like `unchecked` (function, block, or top-level for the rest of the unit), turns it off. `o3` implies `unbounded`, so o3 code never pays for bounds checks. constant indexes into fixed arrays are checked at compile time and emit nothing.
- [ ] after the compiler namespace and fuzzing work, add more general functionality to the standard library.
+- [ ] a hand-written x86-64 jit, ported from the arm64 one: phase 1 translates ordinary blocks (shared translation table, coverage and invalidation; x86 emitter and instruction selection), validated program by program against the interpreter, and becomes the default x86-64 linux core when it matches everywhere. phase 2 compiles o3 regions and inlines enhancements like the arm64 backend does.
- [ ] struct destructors: a struct may declare `fn drop()`, which the compiler calls wherever it frees an owned value of that type (scope end, reassignment, `rt.free`), before the memory is released. use it for file descriptors in `std.Host` and processes in `actor.zc`. decide and document what happens when an owner with a `drop` passes into unchecked code.
- [ ] runtime source positions: a line table per function (code offset to source position) stored in the image, behind a `lines on;` switch like `docs on;`. faults, failed bounds checks and a new `rt.trace()` print `file:line in function` for every frame on the interpreter, microcore and javascript vm; the jit and llvm backends map native addresses back to vm code.
- [ ] borrow returns tied to an argument, with syntax that stays out of the way: a function can return a pointer into one of its parameters (`find`, `skip_space`, `first`), the caller's analyzer treats the result as a borrow of whatever was passed, and freeing or moving that argument while the result is live is an error. the callee is checked to return only borrows of that parameter. prefer inference from the body over annotation; when a spelling is needed, keep it to the parameter's name.
diff --git a/docs/BORROW.md b/docs/BORROW.md
index f270574..64a3183 100644
--- a/docs/BORROW.md
+++ b/docs/BORROW.md
@@ -45,7 +45,7 @@ the compiler functions, standard library, and language server currently run with
the analysis runs with the existing parser, ownership checker, and lifetime records; it does not have a separate source parser or a complete path-sensitive proof. snapshots conservatively join branches and loops. low-level and unknown boundaries can hide behavior, so a quiet diagnostic set is not a whole-program safety proof. zc is single-threaded; shared closure cells do not define concurrent mutation rules.
-two completeness limits once stopped the compiler from compiling itself: an owner held in a local could not move into another local, and a local could not be lent to a global. the replacement and lend rules above close them; `docs/BOOTSTRAP-OWNERSHIP.md` keeps the record.
+two completeness limits once stopped the compiler from compiling itself: an owner held in a local could not move into another local, and a local could not be lent to a global. the replacement and lend rules above close them; `docs/history/BOOTSTRAP-OWNERSHIP.md` keeps the record.
the maintained regressions cover these cases:
diff --git a/docs/design/handoff.md b/docs/design/handoff.md
deleted file mode 100644
index 0b08048..0000000
--- a/docs/design/handoff.md
+++ /dev/null
@@ -1,20 +0,0 @@
-# implementation notes
-
-this note summarizes implemented language and tooling features that were previously tracked across design documents. feature details live in the project readme and examples.
-
-## language and library
-
-- struct methods and static functions support typed parameters and return types. the existing untyped form remains available.
-- `src/lib/std.zc` groups helpers in structs of static functions, called with `Group.name(args)`. `Text`, `Bytes`, `Host`, `Arena` and `Buf` provide string, byte, host, arena and buffer helpers. linux `syscall` is host-only and bypasses vm checks.
-- tagged enums support payload members, constructors that return owned enum pointers, and `case member(fields)` bindings in ordinary `switch` statements. omitted members produce a warning when there is no `default`.
-- struct values can cross native calls on x86-64 sysv and linux arm64 aapcs64 for the interpreter, o3, llvm and jit paths described in the readme. apple arm64 remains unchecked.
-
-## language server
-
-the language server runs the compiler in check mode, so diagnostics and semantic highlighting use the same parser and symbol tables as compilation. hover supports declarations, parameters, locals, built-ins and documented keywords. it does not follow declarations reached through `include` yet.
-
-## optimization
-
-o3 remains the explicit way to request native regions; automatic tiering was dropped. llvm inlining and global copy propagation are implemented. see [tiering](tiering.md) for the rationale and [struct-by-value](struct-by-value.md) for native aggregate limits.
-
-the runtime memory map is generated from a preset. fixed code and compiler tables have finite capacity; the heap grows within the configured machine memory. see the project readme's memory map section for the current build controls.
diff --git a/docs/BOOTSTRAP-OWNERSHIP.md b/docs/history/BOOTSTRAP-OWNERSHIP.md
index 6cc61ce..6cc61ce 100644
--- a/docs/BOOTSTRAP-OWNERSHIP.md
+++ b/docs/history/BOOTSTRAP-OWNERSHIP.md
diff --git a/docs/history/README.md b/docs/history/README.md
index ead4aa0..5ab6766 100644
--- a/docs/history/README.md
+++ b/docs/history/README.md
@@ -54,3 +54,5 @@ the code folders are snapshots. they're not built or tested from here, the top l
- 51 llvm-inline-stdlib: llvm inlining of o3 calls, stdlib text and num helpers, host syscalls through SYS_RAW, and the fuzz campaign's findings
- 52 closures: closure calls work (the block is never run; a call into a heap closure goes through its entry word), captures chain through enclosing closures, and the closure test joins the suite
- 53 typed source: every function, local and global in the compiler, the runtime and the language server is typed (zc0's image does not change), and the extension caches diagnostics by a sha256 of the tree they cover
+- 54 stdlib docs: the standard library api in src/lib/std.zc is documented, every public declaration has a comment above it, and examples/std_tour.zc calls one or two functions from each group
+- BOOTSTRAP-OWNERSHIP.md: notes only (the two ownership rules that let the compiler compile itself, the partial fix before them, and the diagnostic that was reworded)
diff --git a/editors/vscode/syntaxes/zc.tmLanguage.json b/editors/vscode/syntaxes/zc.tmLanguage.json
index 36f1c63..6f76e03 100644
--- a/editors/vscode/syntaxes/zc.tmLanguage.json
+++ b/editors/vscode/syntaxes/zc.tmLanguage.json
@@ -87,7 +87,7 @@
},
{
"name": "keyword.declaration.zc",
- "match": "\\b(fn|let|struct|type|enum|const|enhance|micro|vm)\\b"
+ "match": "\\b(fn|let|struct|type|typedef|enum|const|enhance|micro|vm)\\b"
},
{
"name": "keyword.other.zc",
diff --git a/examples/std_tour.zc b/examples/std_tour.zc
new file mode 100644
index 0000000..df4d02b
--- /dev/null
+++ b/examples/std_tour.zc
@@ -0,0 +1,61 @@
+namespace;
+include rt, std;
+
+// a tour of the standard library: one or two functions from each group, printing
+// what they return. run it with: build/bin/zy < examples/std_tour.zc
+
+int big(int x) { return x > 2; }
+int dbl(int x) { return x * 2; }
+int add(int a, int b) { return a + b; }
+
+fn main() {
+ // text: char* strings, one character per word
+ let buf[32];
+ std.Text.itoa(0 - 42, buf); rt.put_s(buf); rt.put_c(10); // -42
+ rt.put_n(std.Text.find("needle in a haystack", "hay")); rt.put_c(10); // 12
+
+ // num: integer helpers
+ rt.put_n(std.Num.gcd(84, 36)); rt.put_c(' '); // 12
+ rt.put_n(std.Num.pow(2, 10)); rt.put_c(10); // 1024
+
+ // host: the clock and the environment; this variable is not set
+ rt.put_n(std.Host.now() > 0); rt.put_c(' '); // 1
+ let v[16];
+ rt.put_n(std.Host.env("STD_TOUR_UNSET_VARIABLE", v, 16)); rt.put_c(10); // -1
+
+ // bytes: packed byte strings, from b"..." literals
+ rt.put_n(std.Bytes.len(b"packed")); rt.put_c(' '); // 6
+ rt.put_n(std.Bytes.find(b"needle", b"ed")); rt.put_c(' '); // 2
+ rt.put_bs(std.Bytes.itoa(7)); rt.put_c(10); // 7
+
+ // arena: a region of words, handed out in pieces and freed all at once
+ let a = std.arena(8);
+ rt.put_n(std.Arena.alloc(a, 4) != 0); rt.put_c(' '); // 1
+ rt.put_n(std.Arena.alloc(a, 100) == 0); rt.put_c(10); // 1
+ std.Arena.reset(a);
+
+ // buf: byte buffers from bnew
+ let b = std.bnew(8);
+ std.Buf.set(b, 0, 65); std.Buf.set(b, 1, 66);
+ rt.put_n(std.Buf.length(b)); rt.put_c(' '); // 2
+ rt.put_c(std.Buf.get(b, 1)); rt.put_c(10); // B
+
+ // capture: send the output into a string instead of the terminal
+ let out = std.capture.start();
+ rt.put_n(42);
+ std.capture.end(out);
+ rt.put_s("captured: "); rt.put_s(out); rt.put_c(10); // captured: 42
+
+ // array algorithms: one function per step, applied to an array of words
+ int[?] xs = rt.new(int[?], 0);
+ push(xs, 1); push(xs, 3); push(xs, 5);
+ rt.put_n(std.array_find(xs, 3)); rt.put_c(' '); // 1
+ rt.put_n(std.array_count(xs, big)); rt.put_c(' '); // 2
+ rt.put_n(std.array_reduce(xs, 0, add)); rt.put_c(10); // 9
+ let doubled = std.array_map(xs, dbl);
+ rt.put_n(doubled[2]); rt.put_c(10); // 10
+
+ // the command line: std.libinit() fills argc before main runs
+ rt.put_n(std.argc > 0); rt.put_c(10); // 1
+ return 0;
+}
diff --git a/src/compiler/compiler.zc b/src/compiler/compiler.zc
index 86e00c5..ac504d7 100644
--- a/src/compiler/compiler.zc
+++ b/src/compiler/compiler.zc
@@ -285,8 +285,12 @@ int fldst, fldi; // the one struct a bare address's field name resolved to
char*[8] tpn; int ntp; // type parameters in scope
// reading a return type: unknown names are type parameters declared after the function's name
int tvauto;
+// the typedefs of the blocks being compiled: three words each (the symbol, the block depth and the
+// compile context it was made in), newest last. a block's end unlinks them from their names.
+word tdstk; int ntd, tdcap;
word readonly_types;
int dty, dtag; // result of dtype()
+int s_typedef;
int s_lt, s_gt, s_shr, s_le, s_ge, s_eqeq, s_ne, s_plus, s_struct, s_type, s_typecheck, s_docs, s_small, s_std, s_icon, s_on, s_off, s_new, s_new_t;
int s_o3, s_lfa, s_outside, s_new_raw, s_new_oz, s_oob;
int s_ld8, s_st8, s_ld16, s_st16, s_ld32, s_st32;
@@ -1102,6 +1106,7 @@ int source_lookup(char* name) {
// drop the symbols above index to, which ends a scope.
int popsyms(int to) {
while (nsym > to) { nsym--; sname[nsym][-1] = snext[nsym]; }
+ while (ntd && tdstk[ntd * 3 - 3] >= to) ntd--; // local typedefs made above to went with them
return 0;
}
// look a name up from a plain string.
@@ -2952,6 +2957,7 @@ int block_close(int save) {
while (i < save) { if (lhome[i] >= fdepth) { lstate[i] = S_DEAD; lhome[i] = fdepth - 1; } i++; }
local_drop(save);
fdrop(save);
+ td_end(fdepth);
return 0;
}
@@ -3981,6 +3987,44 @@ int dtype() {
}
return 0;
}
+// the struct whose body or methods are being compiled, when it declares constants: a bare
+// name there is looked up as Struct.name before the global scope
+char* mstruct;
+// does a constant declaration start in a struct body? const NAME = e; const T NAME = e;
+// (a field of a const type has no initializer, so the = tells them apart)
+int struct_const_start() {
+ if (!is_id(s_const)) return 0;
+ peekat(0); if (pk_tk != T_ID) return 0;
+ peekat(1);
+ if (pk_tk == T_OP && pk_tv == s_eq) return 1;
+ if (pk_tk == T_ID) { peekat(2); return pk_tk == T_OP && pk_tv == s_eq; }
+ if (pk_tk == T_OP && pk_tv == s_star) { peekat(2); if (pk_tk != T_ID) return 0; peekat(3); return pk_tk == T_OP && pk_tv == s_eq; }
+ return 0;
+}
+// const NAME = e, NAME = e; inside struct sn: a compile-time constant named Struct.NAME that takes no
+// space in the layout. the optional type is read and dropped, as in gconst.
+int struct_const(char* sn) {
+ int off, s; char* cn;
+ next();
+ if (tk == T_ID) { peekat(0); if (pk_tk == T_ID || (pk_tk == T_OP && pk_tv == s_star)) ptype(); }
+ mstruct = sn;
+ while (1) {
+ off = toff; cn = name();
+ s = lookup(methname(sn, cn));
+ if (s >= ubase && s >= 0) serrn(cn, "is defined twice in this struct");
+ expect(s_eq);
+ s = addsym(methname(sn, cn), K_CONST, cexpr());
+ rs_put(off, RS_SYM, rs_sym(s), s);
+ if (!is_op(s_comma) && !is_op(s_semi)) { // a call or a variable's value follows what cprim could read
+ serr("a struct constant must be a constant expression");
+ while (!is_op(s_semi) && !is_op(s_rb) && tk != T_EOF) next();
+ break;
+ }
+ if (!accept(s_comma)) break;
+ }
+ accept(s_semi);
+ return 0;
+}
// struct name { type field, ... } or struct name<A, B> { ... }
// the struct keyword. fields go in a scratch buffer first (name, type pairs),
// then are laid out: each field takes tsz(type) words, so offsets are words.
@@ -3989,7 +4033,7 @@ int dtype() {
// and call its siblings. a generic struct keeps its fields unresolved and
// can't have methods; each instance is laid out later by tresolve.
int kw_struct() {
- char* n; word t; int s, nf = 0; word buf = chk_resize(0, 0, 64); int bufcap = 64, i; word fs; int off = 0, gen = 0, ft, nm = 0, mcap = STRUCT_METHODS; char** mn = chk_resize(0, 0, mcap); word mq = chk_resize(0, 0, mcap), mst = chk_resize(0, 0, mcap), mty = chk_resize(0, 0, mcap), mrt = chk_resize(0, 0, mcap), mrg = chk_resize(0, 0, mcap); int bo, k, stat = 0; char* fname = 0;
+ char* n; word t; int s, nf = 0; word buf = chk_resize(0, 0, 64); int bufcap = 64, i; word fs; int off = 0, gen = 0, ft, nm = 0, mcap = STRUCT_METHODS; char** mn = chk_resize(0, 0, mcap); word mq = chk_resize(0, 0, mcap), mst = chk_resize(0, 0, mcap), mty = chk_resize(0, 0, mcap), mrt = chk_resize(0, 0, mcap), mrg = chk_resize(0, 0, mcap); int bo, k, stat = 0; char* fname = 0; char* msv = mstruct;
next();
n = module_symbol(name());
if (is_op(s_lt)) { // generic
@@ -4011,6 +4055,7 @@ int kw_struct() {
while (!is_op(s_rb)) {
if (tk == T_EOF) { die("missing }"); break; }
stat = 0;
+ if (struct_const_start()) { struct_const(n); continue; }
if (is_id(s_unchecked)) { next(); stat = 2; }
if (is_id(s_static)) { // static fn name(params) { body }, or static T name(params) { body }: a function of the struct, called as Struct.name(args), with no this
next();
@@ -4099,6 +4144,7 @@ int kw_struct() {
i = 0;
while (i < nm) { fn_method_compile = 1; methdef(n, mn[i], mq[i], mst[i], mty[i], mrt[i], mrg[i]); fn_method_compile = 0; i++; }
mdg = 0;
+ mstruct = msv;
return s;
}
// ---- methods ----
@@ -4348,6 +4394,89 @@ int kw_type() {
expect(s_semi);
return 0;
}
+// does a parameter start with a type? a type name straight before , or ) is the parameter's
+// own name (fn f(string)), not a type, since a typed parameter always has a name after it.
+int paramstart() {
+ if (tk == T_OP) return tv == s_lk;
+ if (tk != T_ID) return 0;
+ if (tv == s_fn) return 1;
+ if (!istypename(tv)) return 0;
+ peek();
+ return !(pk_tk == T_OP && (pk_tv == s_comma || pk_tv == s_rp));
+}
+// does a typedef start here? typedef followed by a name is one, so typedef can still be
+// a variable or a function's name.
+int typedef_ahead() {
+ if (tk != T_ID || tv != s_typedef) return 0;
+ peekat(0);
+ return pk_tk == T_ID;
+}
+// unlink the symbol s from its name, leaving the rest of the name's chain as it was.
+int td_unlink(int s) {
+ char* nm = sname[s]; int i = nm[-1] - 1;
+ if (i == s) { nm[-1] = snext[s]; return 0; }
+ while (i >= 0 && snext[i] - 1 != s) i = snext[i] - 1;
+ if (i >= 0) snext[i] = snext[s];
+ return 0;
+}
+// end the scope of the local typedefs made at block depth depth or deeper in this
+// compile context (and of any made in a context nested inside it).
+int td_end(int depth) {
+ int k;
+ while (ntd) {
+ k = ntd * 3 - 3;
+ if (tdstk[k + 2] < ctxsp || (tdstk[k + 2] == ctxsp && tdstk[k + 1] < depth)) break;
+ td_unlink(tdstk[k]);
+ ntd--;
+ }
+ return 0;
+}
+// is the name q (as a symbol is named) already a typedef of the block being compiled?
+int td_here(char* q) {
+ int k = ntd;
+ while (k) {
+ k--;
+ if (tdstk[k * 3 + 2] != ctxsp || tdstk[k * 3 + 1] != fdepth) break;
+ if (sname[tdstk[k * 3]] == q) return 1;
+ }
+ return 0;
+}
+// typedef T name;
+// the C spelling of type name = T;. name becomes another way to write T: the very same
+// type record, so the two are interchangeable everywhere. at the top level the name is
+// global; in a function it lasts to the end of its block, like a local. a name that is
+// already in use is an error, except the same type under the same name again. a tag
+// (.u, .m, .d) belongs to a declaration, not to a type, so a typedef has none.
+int kw_typedef() {
+ char* n; char* q; word t; int s, at, clash = 0, local = infn;
+ next();
+ t = ptype();
+ if (panic) return 0;
+ if (is_op(s_dot)) { die("a typedef names a type, which has no tag: .u, .m and .d go on a declaration"); return 0; }
+ at = toff; n = name();
+ if (panic) return 0;
+ q = module_symbol(n);
+ if (local) {
+ s = findloc(n);
+ if ((s >= 0 && lhome[s] >= fdepth) || td_here(q)) clash = 1;
+ } else {
+ s = lookup_raw(q);
+ if (s < 0 && module_name) { s = lookup_raw(n); if (s >= 0 && skind[s] != K_TYPE && skind[s] != K_KW) s = 0 - 1; }
+ if (s >= 0 && skind[s] == K_TYPE && sval[s] == t) return expect(s_semi); // the same typedef again
+ if (s >= 0) clash = 1;
+ }
+ if (clash) serrn(n, "already defined");
+ else {
+ s = addsym(n, K_TYPE, t);
+ rs_put(at, RS_SYM, rs_sym(s), s);
+ if (local) {
+ if (ntd == tdcap) { if (tdcap) tdcap = tdcap * 2; else tdcap = 16; tdstk = chk_resize(tdstk, ntd * 3, tdcap * 3); }
+ tdstk[ntd * 3] = s; tdstk[ntd * 3 + 1] = fdepth; tdstk[ntd * 3 + 2] = ctxsp; ntd++;
+ }
+ }
+ expect(s_semi);
+ return 0;
+}
// (T) or (T*) ahead of the current '(', within the lookahead we have
// the parser sees ( and has to decide between a parenthesized expression and a
// cast. a cast is ( type stars ) so peek ahead through the stars to the ).
@@ -5516,6 +5645,7 @@ int types_init() {
addsym(tword[2], K_TYPE, tword); addsym(tint[2], K_TYPE, tint); addsym(tchar[2], K_TYPE, tchar);
addsym(tbool[2], K_TYPE, tbool); addsym(tvoid[2], K_TYPE, tvoid); addsym(tfloat[2], K_TYPE, tfloat);
addsym(intern("f64"), K_TYPE, tfloat);
+ addsym(intern("string"), K_TYPE, tptr(tchar)); // string is char*, as if by typedef char* string;
// f32: single precision. a variable holds the rounded value as a double; an element
// of an array or pointer of f32 is packed two to a word, like the sized integers
f32p = tnew(TY_FLOAT, 1, intern("f32"), 0);
@@ -5530,7 +5660,7 @@ int types_init() {
s_le = intern("<=");
s_ge = intern(">=");
s_eqeq = intern("=="); s_ne = intern("!="); s_plus = intern("+");
- s_struct = intern("struct"); s_type = intern("type"); s_typecheck = intern("typecheck"); s_docs = intern("docs"); s_std = intern("std"); s_icon = intern("icon"); s_small = intern("small");
+ s_struct = intern("struct"); s_type = intern("type"); s_typedef = intern("typedef"); s_typecheck = intern("typecheck"); s_docs = intern("docs"); s_std = intern("std"); s_icon = intern("icon"); s_small = intern("small");
s_on = intern("on");
s_off = intern("off");
s_new = intern("rt.new");
@@ -6445,7 +6575,7 @@ int closure() {
while (1) {
pty[np] = tword;
if (expected && expected[0] == TY_FN && np < expected[3]) pty[np] = expected[7 + np];
- if (!is_op(s_dot) && ((tk == T_OP && tv == s_lk) || (tk == T_ID && (tv == s_fn || istypename(tv))))) {
+ if (!is_op(s_dot) && paramstart()) {
pty[np] = ptype(); if (pty[np][0] == TY_ARR) pty[np] = decay(pty[np]);
}
tag = 0;
@@ -6800,6 +6930,7 @@ int primary() {
return C_PLAIN;
}
s = source_lookup(n);
+ if (mstruct && !ginst) { ms = lookup(methname(mstruct, n)); if (ms >= 0 && skind[ms] == K_CONST) s = ms; }
if (s < 0 && rt.eq_w(n, "new")) s = source_lookup(s_new);
if (s >= 0) rs_put(toff, RS_SYM, rs_sym(s), s);
if (s >= 0 && skind[s] == K_KW) {
@@ -6812,8 +6943,8 @@ int primary() {
c = toff + toklen;
next();
if (probe_off >= 0 && cmode && !dry && !ginst && incdepth == 0 && probe_off >= c && ((tk == T_ID && probe_off <= toff + toklen) || (tk != T_ID && probe_off <= toff))) { probe_static = n; probe_has = 3; chkabort = 1; }
- k = toff; mn = name();
- ms = lookup(methname(n, mn));
+ k = toff; sv = tpack(); mn = name();
+ ms = lookup(methname(sname[s], mn));
if (ms >= 0) rs_put(k, RS_SYM, rs_sym(ms), ms);
if (ms >= 0 && skind[ms] == K_CONST) { // Enum.MEMBER
xvk = 1; xvv = sval[ms];
@@ -6829,7 +6960,11 @@ int primary() {
if (!is_op(s_lp)) die("a static function is called with ( after its name");
return call(ms);
}
- serrn(mn, "is not a static function of this struct");
+ if (!panic && !dry) {
+ c = tpack(); tunpack(sv); // the error sits on the member name, where the quick fix replaces it
+ errat(); rt.put_s(mn); rt.put_s(": is not a static function of this struct"); suggest_member(sname[s], 0, mn, 1); errend();
+ tunpack(c);
+ }
lit(0);
xty = tword;
return C_PLAIN;
@@ -6949,7 +7084,7 @@ int incdec(int post, int dlt) {
word field(int c) {
int readonly = treadonly(xty);
if_value = 0;
- int n, fieldoff; word st;
+ int n, fieldoff, fieldpos, sv; word st;
word borrowed = xaf, base_mask = effect_mask(c); af_use(xaf, tpack(), c); xaf = 0; xvk = 0; int i, b = xbor, k = 0, scanned = 0, ms, de, pmatch = 0;
de = toff + toklen;
next();
@@ -6958,7 +7093,7 @@ word field(int c) {
if (tk == T_ID) { if (probe_off <= toff + toklen) pmatch = 1; }
else if (probe_off <= toff) pmatch = 1;
}
- n = name(); fieldoff = nameoff;
+ fieldpos = tpack(); n = name(); fieldoff = nameoff;
st = xty;
if (st[0] == TY_ARR || st[0] == TY_DYN) {
if (pmatch) probe_member(st);
@@ -7023,7 +7158,11 @@ word field(int c) {
}
if (scanned) i = fldi; else i = tfindfield(st, n);
if (i < 0) {
- if (!panic && !dry) { errat(); tprint(st); rt.put_s(" has no field "); rt.put_s(n); errend(); }
+ if (!panic && !dry) {
+ sv = tpack(); tunpack(fieldpos); // the error sits on the field name, where the quick fix replaces it
+ errat(); tprint(st); rt.put_s(" has no field "); rt.put_s(n); suggest_member(st[2], st, n, 0); errend();
+ tunpack(sv);
+ }
xty = tword; lv = 1; lvk = LV_OTHER; xbor = -1; return C_PLAIN;
}
rs_put(fieldoff, RS_FIELD, field_decl(st, n), st[4][i * 3 + 1]);
@@ -7611,7 +7750,7 @@ word stmtstart() {
int s;
if (tk == T_OP) return tv == s_semi || tv == s_lb || tstart();
if (tk != T_ID || findloc(tv) >= 0) return 0;
- if (tstart()) return 1;
+ if (tstart() || typedef_ahead()) return 1;
s = lookup(tv);
return s >= 0 && skind[s] == K_KW && !(sflag[s] & F_EXPR);
}
@@ -7651,6 +7790,7 @@ word cprim() {
if (accept(s_lp)) { v = cexpr(); expect(s_rp); return v; }
if (tk == T_ID) {
s = lookup(tv);
+ if (mstruct && !ginst) { mc = lookup(methname(mstruct, tv)); if (mc >= 0 && skind[mc] == K_CONST) s = mc; }
if (s >= 0 && (skind[s] == K_CONST || skind[s] == K_GARR || (skind[s] == K_FN && (sflag[s] & F_DEF)) || skind[s] == K_GVAR)) {
next();
return sval[s];
@@ -7712,6 +7852,7 @@ int stmt_inner() {
if (s >= 0 && skind[s] == K_KW && (sflag[s] & F_STMT)) { kwcall(s, 0); return 0; }
}
if (untyped_const()) { next(); localdecl(2); return 0; }
+ if (typedef_ahead() && findloc(tv) < 0) return kw_typedef();
if (tstart()) { localdecl(1); return 0; }
if (tk == T_OP) {
if (tv == s_semi) { next(); return 0; }
@@ -8596,7 +8737,7 @@ int prescan(int kind, int obj) {
if (is_op(s_lb)) depth++;
else if (is_op(s_rb)) { depth--; pend = 0; po3 = 0; }
else if (depth <= 0) {
- if (is_id(s_type)) { while (tk != T_EOF && !is_op(s_semi)) next(); if (is_op(s_semi)) next(); pend = 0; po3 = 0; continue; }
+ if (is_id(s_type) || typedef_ahead()) { while (tk != T_EOF && !is_op(s_semi)) next(); if (is_op(s_semi)) next(); pend = 0; po3 = 0; continue; }
if (tk == T_ID && rt.eq_w(tv, "namespace")) { kw_namespace(); continue; }
if (is_op(s_semi)) { pend = 0; po3 = 0; }
else if (is_op(s_dot)) { peek(); if (pk_tk == T_ID && pk_tv == s_u) pend = 1; }
@@ -8745,6 +8886,7 @@ int epilogue() {
infn = 0;
local_drop(lbase);
fdrop(lbase);
+ td_end(0);
return 0;
}
// the statements of a function between its braces, then the end-of-function
@@ -8800,7 +8942,7 @@ int fndef(int chk, int rty, int ret, int n) {
t = 0;
pty[np] = tword;
pk = 0;
- if (!is_op(s_dot) && ((tk == T_OP && tv == s_lk) || (tk == T_ID && (tv == s_fn || istypename(tv))))) {
+ if (!is_op(s_dot) && paramstart()) {
pty[np] = ptype(); typed = 1; pk = 1;
if (pty[np][0] == TY_ARR) pty[np] = decay(pty[np]);
if (isagg(pty[np])) {
@@ -9065,7 +9207,7 @@ int topsync() {
while (tk != T_EOF) {
if (is_op(s_lb)) depth++;
else if (is_op(s_rb)) { depth--; if (depth < 0) depth = 0; }
- else if (!depth && tk == T_ID && (tv == s_fn || tv == s_var || tv == s_const || tv == s_struct || tv == s_type
+ else if (!depth && tk == T_ID && (tv == s_fn || tv == s_var || tv == s_const || tv == s_struct || tv == s_type || tv == s_typedef
|| tv == s_enhance || tv == s_typecheck || tv == s_docs || tv == s_unchecked || tv == s_immediate || tv == s_o3
|| tv == s_memdebug || tv == s_enum || tv == s_include)) break;
next();
@@ -9175,6 +9317,7 @@ int topitem1() {
if (is_id(s_var)) return gdecl(0);
if (is_id(s_struct)) { kw_struct(); return 0; }
if (is_id(s_type)) return kw_type();
+ if (typedef_ahead()) return kw_typedef();
if (is_id(s_typecheck)) return kw_typecheck();
if (is_id(s_docs)) return kw_docs();
if (is_id(s_memdebug)) return kw_memdebug();
@@ -9572,6 +9715,66 @@ int similar(int n) {
if (bd > lim) return 0;
return best;
}
+// the field or method of struct sn closest to n (statics is 0), or the static function or constant
+// (statics is 1), when it is close enough to be a likely typo. the limits are those of similar.
+char* similar_member(char* sn, word st, char* n, int statics) {
+ int j, bd = 99, dist, k, ln = rt.len_w(sn), lim = rt.len_w(n) / 3, nf; char* best = 0; char* tail;
+ if (rt.len_w(n) < 3) return 0;
+ if (lim < 1) lim = 1;
+ if (lim > 3) lim = 3;
+ if (!statics && st && st[0] == TY_STRUCT) {
+ nf = st[3]; k = 0;
+ while (k < nf) {
+ tail = st[4][k * 3]; dist = editdist(n, tail);
+ if (dist == 2 && swapped(n, tail)) dist = 1;
+ if (dist > 0 && dist < bd) { bd = dist; best = tail; }
+ k++;
+ }
+ }
+ j = 0;
+ while (j < nsym) {
+ k = skind[j];
+ if (((k == K_FN && ((sflag[j] & F_STATIC) != 0) == statics) || (statics && k == K_CONST)) && rt.len_w(sname[j]) > ln + 1 && sname[j][ln] == '.') {
+ tail = sname[j] + ln + 1;
+ if (has_prefix(sname[j], sn, ln) && !has_dot(tail)) {
+ dist = editdist(n, tail);
+ if (dist == 2 && swapped(n, tail)) dist = 1;
+ if (dist > 0 && dist < bd) { bd = dist; best = tail; }
+ }
+ }
+ j++;
+ }
+ if (bd > lim) return 0;
+ return best;
+}
+// are a and b the same but for two neighbouring chars swapped (itao for itoa)? a swap counts as one typo.
+int swapped(char* a, char* b) {
+ int i = 0, la = rt.len_w(a);
+ if (la != rt.len_w(b)) return 0;
+ while (a[i] && a[i] == b[i]) i++;
+ if (!a[i] || !a[i + 1] || a[i] != b[i + 1] || a[i + 1] != b[i]) return 0;
+ i = i + 2;
+ while (a[i] && a[i] == b[i]) i++;
+ return !a[i];
+}
+// does s start with the first n chars of p?
+int has_prefix(char* s, char* p, int n) {
+ int i = 0;
+ while (i < n && s[i] == p[i]) i++;
+ return i == n;
+}
+// does the string contain a dot?
+int has_dot(char* s) {
+ int i = 0;
+ while (s[i]) { if (s[i] == '.') return 1; i++; }
+ return 0;
+}
+// ends an error message with "; did you mean 'x'?" when a member of struct sn is close to n
+int suggest_member(char* sn, word st, char* n, int statics) {
+ char* best = similar_member(sn, st, n, statics);
+ if (best) { rt.put_s("; did you mean '"); rt.put_s(best); rt.put_s("'?"); }
+ return 0;
+}
// a copy of s[a..e) as a string
char* lib_copy(char* s, int a, int e) {
char* b = chk_resize(0, 0, e - a + 1); rt.copy_w(b, s + a, e - a); b[e - a] = 0;
@@ -9978,7 +10181,7 @@ int zc_init() {
poolend = R_POOLEND; poolblocks = 0; namecount = 0;
rt.fill_w(namehash, 0, hashcap);
nsym = 0; nfixu = 0; fixfree = 0; nbin = 0; nun = 0; nasg = 0; nkop = 0; seqtop = 0;
- lsp = 0; ctxsp = 0; snaptop = 0; nloc = 0; lbase = 0; npm = 0; npe = 0; rt.fill_w(lkeys, 0, lkeycap); lkeyn = 0;
+ lsp = 0; ctxsp = 0; ntd = 0; snaptop = 0; nloc = 0; lbase = 0; npm = 0; npe = 0; rt.fill_w(lkeys, 0, lkeycap); lkeyn = 0;
s_lp = intern("("); s_rp = intern(")"); s_lb = intern("{"); s_rb = intern("}");
s_lk = intern("["); s_rk = intern("]"); s_comma = intern(","); s_semi = intern(";");
s_eq = intern("="); s_arrow = intern("->"); s_inc = intern("++"); s_dec = intern("--");
diff --git a/src/lib/std.zc b/src/lib/std.zc
index f0bc390..33ab1e9 100644
--- a/src/lib/std.zc
+++ b/src/lib/std.zc
@@ -20,9 +20,14 @@ include rt, run;
// these and the runtime calls it before main, if the program has one (an
// image built by build_image, or a check-mode document, does not).
+// the number of command line arguments, set by libinit().
int argc;
+// the command line arguments, one string each. argv[0] is the program path,
+// or <eval> when the source came from stdin.
char*[?] argv;
+// the number of environment entries, set by libinit().
int envc;
+// the environment, one NAME=value string per entry, set by libinit().
char*[?] envp;
// one entry of a vector syscall, as a fresh string, or 0 past the end.
@@ -64,25 +69,24 @@ int libinit() {
// capture.start() redirects everything the program writes into a string and
// returns it. writes go to the buffer instead of the terminal until end()
// stops it, so the buffer is a string once end() has run:
-// let buf = capture.start();
+// let buf = std.capture.start();
// rt.put_s("hello world!"); // nothing on the terminal
-// capture.end(buf);
-// rt.put_s(buf); // hello world
+// std.capture.end(buf);
+// rt.put_s(buf); // hello world!
+// the buffer holds 256 characters, and output past that is dropped.
// one capture at a time, and the buffer belongs to whoever holds it.
-
struct capture {
- // redirects program output into a collector-managed character buffer.
- // returns the buffer; call end(buffer) before reading its terminator.
- // returns: the buffer used for this capture
+ // starts a capture: output goes into a new buffer instead of the terminal.
+ // returns: the buffer, managed by the collector; read it after end(buffer)
static char* start() {
int cap = 256;
rt.outmode = 2; rt.outn = 0; rt.outcap = cap;
rt.outbuf = rt.new(cap);
return rt.outbuf;
}
- // stops output capture, terminates the buffer, and returns the collected text.
- // buffer: the buffer returned by start
- // returns: the same buffer, now terminated
+ // stops the capture and ends the buffer with a 0.
+ // buffer: the buffer that start returned
+ // returns: the same buffer, now a string
static char* end(char* buffer) {
rt.outbuf[rt.outn] = 0;
rt.outmode = 0; rt.outbuf = 0; rt.outn = 0; rt.outcap = 0;
@@ -92,6 +96,8 @@ struct capture {
// ---- character strings ----
+// helpers for char* strings: one character per word, ended by a 0 word.
+// called as std.Text.name(args).
struct Text {
// the number written in decimal at the start of s. a leading '-' makes it
// negative and the first character that is not a digit ends it.
@@ -106,7 +112,7 @@ struct Text {
// writes n in decimal into dst, with a 0 after it.
// n: the number
- // dst: where the text goes; 24 words is always enough
+ // dst: where the text goes; 21 words is always enough (20 characters and the 0)
// returns: how many characters were written, not counting the 0
static int itoa(int n, char* dst) {
int b[24], i = 0, j = 0, neg = 0;
@@ -120,7 +126,7 @@ struct Text {
return j;
}
- // joins two strings.
+ // joins two strings into dst.
// dst: where the result goes, with room for both and a 0; not a or b
// a: the first string
// b: the second string
@@ -248,9 +254,8 @@ struct Text {
// ---- numbers ----
-// plain integer helpers. none of them can fail: an out of range result wraps
-// the same way the arithmetic does.
-
+// plain integer helpers, called as std.Num.name(args). none of them can fail:
+// an out of range result wraps the same way the arithmetic does.
struct Num {
// the absolute value of n, using wrapping word arithmetic. the minimum
// word remains negative because its positive value cannot fit in a word.
@@ -298,7 +303,8 @@ struct Num {
return a;
}
- // b raised to the power e. e below 0 gives 1; the result wraps as a word.
+ // b raised to the power e, by one multiply per step of e, so a large e is slow.
+ // e below 0 gives 1, and the result wraps as a word.
// b: the base
// e: the exponent
// returns: b to the power e, or 1 when e is negative
@@ -333,18 +339,18 @@ struct Num {
// ---- the host ----
-// the argument block for Host.raw: the number, then its six arguments.
+// the argument block for Host.raw: word 0 is the syscall number, words 1 to 6
+// are its arguments. Host.raw fills it on each call.
int rawblk[7];
+// calls into the host that runs the vm: the environment, the clock, files and
+// raw system calls. called as std.Host.name(args).
struct Host {
// calls any linux system call on the host. this is the escape hatch below
// the named helpers: the number is the kernel's, so the meaning of each
- // argument depends on the call. a pointer argument is an address in the
- // program's memory, and only the host reads it, so a string or buffer has
- // to be passed as its address.
- // it runs the call on the real machine, not inside the vm, so a program
- // that uses it can do whatever the process can do. only use it where that
- // is wanted.
+ // argument depends on the call. the words reach the kernel unchanged, so a
+ // pointer is a host address to it, not a place in the vm's memory. the call
+ // runs on the real machine, so only use it where that is wanted.
// nr: the syscall number (x86-64 and arm64 numbers differ, so check the host)
// a..f: the six arguments, unused ones 0
// returns: the kernel's result, -errno on failure, or -1 on unsupported hosts
@@ -354,18 +360,20 @@ struct Host {
return rt.syscall(rt.SYS_RAW, rawblk, 0, 0);
}
- // the value of an environment variable.
+ // copies the value of an environment variable into dst, as a 0-terminated string.
// name: the variable's name
- // dst: where the value goes, a zero-terminated character string
- // n: how many words dst has
- // returns: the length of the value, -1 if the variable is not set
+ // dst: where the value goes
+ // n: the size of dst in words, the 0 included
+ // returns: how many characters were copied, at most n - 1, so a longer value
+ // is cut short; -1 if the variable is not set or n is below 1
static int env(char* name, char* dst, int n) { return rt.syscall(rt.SYS_GETENV, name, dst, n); }
// the clock.
// returns: the time in seconds since 1970
static int now() { return rt.syscall(rt.SYS_TIME, 0, 0, 0); }
- // writes a string to a file, replacing what was there.
+ // writes a string to a file, replacing what was there. the file is created if
+ // it is missing.
// path: the file's name
// s: the text to write
// returns: how many bytes were written, -1 if the file could not be opened
@@ -380,9 +388,8 @@ struct Host {
// ---- byte strings ----
-// the same helpers for packed byte strings. character-string helpers above are unchanged.
-// a packed byte string has type bstr; len_s reads its stored byte length.
-
+// the same helpers as Text, for packed byte strings of type bstr (b"..."
+// literals). len reads the stored byte length. called as std.Bytes.name(args).
struct Bytes {
// reads a decimal number at the start of s; a leading '-' makes it
// negative, and the first non-digit ends the number.
@@ -392,7 +399,7 @@ struct Bytes {
// like Text.itoa, but the text is made fresh.
// n: the number
- // returns: a new byte string
+ // returns: a new byte string, managed by the collector; the caller does not free it
static bstr itoa(int n) { return rt.n_to_s(n); }
// like Text.starts, for byte strings.
@@ -448,14 +455,15 @@ struct Bytes {
return 1;
}
- // like Host.env, for byte strings.
+ // like Host.env, for byte strings. the value is written into the bytes of dst,
+ // and the length of dst is not changed, so make dst big enough first.
// name: the variable's name, a byte string
- // dst: the packed byte string whose payload receives the value
- // n: the maximum number of bytes to write
- // returns: the length of the value, -1 if the variable is not set
+ // dst: the byte string that receives the value
+ // n: the most bytes dst may use, the 0 after the value included
+ // returns: how many bytes were copied, at most n - 1; -1 if the variable is not set or n is below 1
static int env(bstr name, bstr dst, int n) { return rt.bgetenv(name, dst, n); }
- // like Host.writefile, for a byte string.
+ // like Host.writefile, for a byte string. the file is replaced, or created.
// path: the file's name, a byte string
// s: the bytes to write
// returns: how many bytes were written, -1 if the file could not be opened
@@ -470,16 +478,17 @@ struct Bytes {
// ---- arenas ----
-// a region that is freed all at once.
+// a region of n words that Arena.alloc hands out and Arena.reset frees all at once.
// n: its capacity in words; values below 1 allocate one word
// returns: the arena, owned by the caller
int .u arena(int n) { return rt.arena_new(n); }
+// helpers for an arena made by std.arena. called as std.Arena.name(args).
struct Arena {
// takes n zeroed words from an arena.
// a: the arena
// n: how many words
- // returns: the first word, or 0 when n words do not fit
+ // returns: the first word; 0 when n words do not fit, or n is negative
static int alloc(word a, int n) { return rt.arena_alloc(a, n); }
// gives every block of an arena back at once. pointers returned by alloc
@@ -491,10 +500,10 @@ struct Arena {
// ---- growable byte buffers ----
-// a byte buffer stores its length and capacity in two words, followed by the
-// bytes, packed.
+// makes an empty byte buffer with room for n bytes. the buffer keeps its length
+// and capacity in two words, followed by the bytes, packed.
// n: the capacity in bytes; a negative value is treated as 0
-// returns: an empty buffer with that capacity, owned by the caller
+// returns: the buffer, owned by the caller
word .u bnew(int n) {
int words;
word p;
@@ -506,25 +515,27 @@ word .u bnew(int n) {
return u*p;
}
+// byte buffers made by bnew. the length grows as bytes are set, up to the
+// capacity, which is fixed. called as std.Buf.name(args).
struct Buf {
// how many bytes a buffer holds.
- // b: the buffer
+ // b: the buffer, from bnew
// returns: its length
static int length(word b) { return b[0]; }
// how many bytes a buffer can hold.
- // b: the buffer
+ // b: the buffer, from bnew
// returns: its capacity
static int capacity(word b) { return b[1]; }
// one byte of a buffer.
// b: the buffer
// i: the position
- // returns: the byte, 0 when i is outside the buffer
+ // returns: the byte, 0 when i is outside the buffer (below 0, or at or past the length)
static int get(word b, int i) { if (i < 0 || i >= b[0]) return 0; return rt.ld8(rt.addr_b(b + 2) + i); }
- // sets one byte of a buffer. setting the byte at the current length makes the
- // buffer one longer.
+ // sets one byte of a buffer. a write at or past the length makes the length
+ // i + 1, and the bytes skipped over are left at 0.
// b: the buffer
// i: the position, below the capacity
// v: the value; only its low 8 bits are kept
@@ -542,28 +553,41 @@ struct Buf {
// with the collector, so freeing the input does not invalidate the result.
// the first index equal to value, or -1 when no element matches.
+// source: the array, only read
+// value: the element to find
int array_find<T>(fixed T[?].m source, T value) {
int length = len(source);
for (int i = 0; i < length; i++) if (source[i] == value) return i;
return -1;
}
// true when an element equals value.
+// source: the array, only read
+// value: the element to find
int array_contains<T>(fixed T[?].m source, T value) { return array_find(source, value) >= 0; }
// the first index whose predicate is true, or -1 when none matches.
+// source: the array, only read
+// predicate: called on each element; nonzero means a match
int array_find_if<T>(fixed T[?].m source, int(T).m predicate) {
int length = len(source);
for (int i = 0; i < length; i++) if (predicate(source[i])) return i;
return -1;
}
// true when any element satisfies predicate; false for an empty array.
+// source: the array, only read
+// predicate: called on each element; nonzero means a match
int array_any<T>(fixed T[?].m source, int(T).m predicate) { return array_find_if(source, predicate) >= 0; }
// true when every element satisfies predicate, including an empty array.
+// source: the array, only read
+// predicate: called on each element; nonzero means a match
+// returns: 1 or 0
int array_all<T>(fixed T[?].m source, int(T).m predicate) {
int length = len(source);
for (int i = 0; i < length; i++) if (!predicate(source[i])) return 0;
return 1;
}
// the number of elements satisfying predicate.
+// source: the array, only read
+// predicate: called on each element; nonzero means a match
int array_count<T>(fixed T[?].m source, int(T).m predicate) {
int length = len(source);
int count = 0;
@@ -572,6 +596,9 @@ int array_count<T>(fixed T[?].m source, int(T).m predicate) {
}
// apply transform once to each element and return the transformed array.
// the result element type follows the callback's return type.
+// source: the array, only read
+// transform: called once on each element, in order
+// returns: a new array of the results, owned by the caller
U[?].u array_map<T,U>(fixed T[?].m source, U(T).m transform) {
int length = len(source);
U[?] result = rt.new(U[?]);
@@ -579,6 +606,9 @@ U[?].u array_map<T,U>(fixed T[?].m source, U(T).m transform) {
return result;
}
// copy elements satisfying predicate into a new array, preserving order.
+// source: the array, only read
+// predicate: called on each element; nonzero keeps it
+// returns: the new array, owned by the caller
T[?].u array_filter<T>(fixed T[?].m source, int(T).m predicate) {
int length = len(source);
T[?] result = rt.new(T[?]);
@@ -587,6 +617,10 @@ T[?].u array_filter<T>(fixed T[?].m source, int(T).m predicate) {
}
// fold elements from left to right, starting with initial; an empty array
// returns initial without calling combine.
+// source: the array, only read
+// initial: the starting value
+// combine: called as combine(total, element) for each element, in order
+// returns: the folded value
A array_reduce<T,A>(fixed T[?].m source, A initial, A(A,T).m combine) {
int length = len(source);
for (int i = 0; i < length; i++) initial = combine(initial, source[i]);
diff --git a/src/lsp/server.zc b/src/lsp/server.zc
index 1608c4c..3262e39 100644
--- a/src/lsp/server.zc
+++ b/src/lsp/server.zc
@@ -390,7 +390,7 @@ int isopc(int c) {
int iskeyword(int n) {
return n == run.s_fn || n == run.s_var || n == run.s_const || n == run.s_else || n == run.s_as || n == run.s_unchecked || n == run.s_immediate
|| n == run.s_case || n == run.s_default || n == run.s_do || n == run.s_while || n == run.s_enum || n == run.s_include || n == run.s_memdebug
- || n == run.s_enhance || n == run.s_micro || n == run.s_vm || n == run.s_struct || n == run.s_type || n == run.s_typecheck || n == run.s_static;
+ || n == run.s_enhance || n == run.s_micro || n == run.s_vm || n == run.s_struct || n == run.s_type || n == run.s_typedef || n == run.s_typecheck || n == run.s_static;
}
// the record of the name at byte offset o (see rs_note in the compiler), or -1.
// the records are sorted by offset, so this is a binary search.
@@ -934,7 +934,7 @@ int reply_error(int code) {
return 0;
}
-int hs_name = -1, hs_first = -1, hs_const;
+int hs_name = -1, hs_first = -1, hs_const, hs_typedef, hs_tname;
int bs_k, bs_off; // the embedded source and name offset found by bs_find
// ---- hover ----
@@ -999,8 +999,8 @@ word hover_decl(int base, int ls, int le) {
// it (hcs is -1 when none) which runs to the line at hdl. a declaration needs
// no comment, so the signature still shows without one.
int hover_scan(int i) {
- hs_name = -1; hs_first = -1; hs_const = 0;
- if (hover_source_decl(i) || hover_source_function(i)) return 1;
+ hs_name = -1; hs_first = -1; hs_const = 0; hs_typedef = 0;
+ if (hover_typedef(i) || hover_source_decl(i) || hover_source_function(i)) return 1;
int base = doff[i], size = dsize[i], ls = 0, le, cs = 0 - 1, c0;
while (ls < size) {
le = ls;
@@ -1182,6 +1182,12 @@ int hover_docs(int i, int head, int name, int length, int tail) {
int hover_fill(int i) {
int base = doff[i], o = hdl, c, cs, ls, typed = 0, k, run.start, end;
hn = 0;
+ if (hs_typedef) { // typedef T name; as written, from its first word to its ;
+ hov_text("```zc\n"); c = hdl;
+ while (c < hdle) { hov_put(dc(base, c)); c++; }
+ hov_text("\n```"); hover_docs(i, hdl, hdl, 0 - 1, hdle);
+ return hn;
+ }
if (hs_name >= 0) {
hov_text("```zc\n"); c = hdl;
while (c < hs_first) { hov_put(dc(base, c)); c++; }
@@ -1624,9 +1630,11 @@ int hover_type_span(int i) {
}
if (best < 0) return 0;
t = run.ht_type[best];
+ // a typedef name is shown as its typedef, then the type it stands for
+ if (width == rt.len_w(hname) && run.ht_start[best] == hoff && hover_typedef(i)) { hover_fill(i); hover_type_info(t); return 1; }
hov_text("```zc\n"); hov_type(t); hov_text("\n```"); hover_type_info(t);
k = kwtext();
- if (k && (hname_is("word") || hname_is("int") || hname_is("char") || hname_is("bool") || hname_is("void") || hname_is("float") || hname_is("f32") || hname_is("f64") || hname_is("byte") || hname_is("u8") || hname_is("i8") || hname_is("u16") || hname_is("i16") || hname_is("u32") || hname_is("i32"))) {
+ if (k && (hname_is("word") || hname_is("int") || hname_is("char") || hname_is("bool") || hname_is("void") || hname_is("float") || hname_is("f32") || hname_is("f64") || hname_is("byte") || hname_is("string") || hname_is("u8") || hname_is("i8") || hname_is("u16") || hname_is("i16") || hname_is("u32") || hname_is("i32"))) {
while (*k && *k != '~') k++;
if (*k) { hov_text("\n\n"); hov_text(k + 1); }
}
@@ -1686,6 +1694,8 @@ char* kwtext() {
if (hname_is("return")) return "return e; or return;~leaves the function with a value, or leaves a void function. returning an owned local transfers it to the caller automatically.";
if (hname_is("enum")) return "enum name { A, B = 5 };~global constants. under typecheck on they are a type of their own, and a member can carry fields to make a constructor.";
if (hname_is("struct")) return "struct name { fields };~a record type. struct name<T> { } makes it generic, one copy for each set of type arguments.";
+ if (hname_is("typedef")) return "typedef T name;~an alias for a type, the same as type name = T; but in C order. the name is another way to write T, not a new type. inside a function it lasts to the end of its block.";
+ if (hname_is("string")) return "string~a built-in alias for char*, a word string, as if typedef char* string; were written.";
if (hname_is("type")) return "type name = T;~an alias for a type, such as type row = int[3]; for a pointer to an array.";
if (hname_is("include")) return "include \"path\"; / include std;~compiles a file or the embedded standard library at that point, its signatures first.";
if (hname_is("embed")) return "embed \"path\" as [type] name;~declares name with the bytes of the file at path, read when the unit is compiled. with no type, or bstr, name is a byte string; char* holds one character per word; a number type reads the bytes little-endian; T[] and T[n] lay them out as array elements.";
@@ -2160,6 +2170,7 @@ int bs_name(char* path) {
}
// the offset of the name a declaration line declares: the word before its first delimiter
int decl_off(int base, int ls, int le) {
+ if (hs_typedef) return hs_tname;
if (hs_name >= 0) return hs_name;
int dl = ls, e, b;
while (dl < le && !hdelim(dc(base, dl))) dl++;
@@ -2441,6 +2452,35 @@ int hover_source_function(int i) {
}
return 0;
}
+// the statement typedef T name; that declares hname, found by tokens, at the top level or in a block
+// (the last such one before the cursor, else the first). hdl and hdle are the typedef word and the end
+// of the ;, and hs_tname is where the name is.
+int hover_typedef(int i) {
+ int t = 0, w, depth, last, found = -1, first = -1, fend, fname, hend, hname_at;
+ fm_lex(i);
+ while (t < fm_nt) {
+ if (fm_k[t] == 7) break;
+ if (!fm_is(i, t, "typedef")) { t++; continue; }
+ w = t + 1; depth = 0; last = -1;
+ while (w < fm_nt && fm_k[w] != 7) {
+ if (fm_k[w] == 6 && fm_o[w] == 2 && !depth) break;
+ if (fm_k[w] == 6 && (fm_o[w] == 5 || fm_o[w] == 6)) break;
+ if (fm_k[w] == 6 && fm_o[w] == 3) depth++;
+ else if (fm_k[w] == 6 && fm_o[w] == 4) depth--;
+ else if (fm_k[w] == 1 && !depth) last = w;
+ w++;
+ }
+ if (w < fm_nt && fm_k[w] == 6 && fm_o[w] == 2 && last > t && hs_match(i, last)) {
+ if (first < 0) { first = t; fend = fm_e[w]; fname = fm_s[last]; }
+ if (fm_s[t] <= hcursor) { found = t; hend = fm_e[w]; hname_at = fm_s[last]; }
+ }
+ t = w + 1;
+ }
+ if (first < 0) return 0;
+ if (found < 0) { found = first; hend = fend; hname_at = fname; }
+ hdl = fm_s[found]; hdle = hend; hs_tname = hname_at; hs_typedef = 1; hs_name = -1; hs_first = -1; hs_const = 0; hcs = -1;
+ return 1;
+}
int hover_source_decl(int i) {
int t = 0, head = -1, first = -1, candidate = -1, depth = 0, brackets = 0, init = 0, constant = 0, matched = 0, tail, prev = -1;
fm_lex(i);
diff --git a/tests/drivers/hint_fixes_test.js b/tests/drivers/hint_fixes_test.js
index 20d3dd1..a388911 100644
--- a/tests/drivers/hint_fixes_test.js
+++ b/tests/drivers/hint_fixes_test.js
@@ -76,5 +76,9 @@ fixes('a misspelled local function is corrected', 'int count_items() { return 1;
'int count_items() { return 1; }\nfn main() {\n\treturn count_items();\n}\n', 'change to `count_items`');
fixes('a qualified name from a file library adds its include', 'include rt;\nfn main() {\n\treturn actor.vector();\n}\n', 'actor', 0,
'include rt;\ninclude actor;\nfn main() {\n\treturn actor.vector();\n}\n', 'include actor');
+fixes('a misspelled field is corrected', 'include rt;\nstruct point { int length, width; }\nfn main() {\n\tpoint* p = rt.new(point);\n\treturn p.lenght;\n}\n', 'lenght', 0,
+ 'include rt;\nstruct point { int length, width; }\nfn main() {\n\tpoint* p = rt.new(point);\n\treturn p.length;\n}\n', 'change to `length`');
+fixes('a misspelled static function of a library group is corrected', 'include rt;\ninclude std;\nfn main() {\n\treturn std.Text.itao(5, 0);\n}\n', 'itao', 0,
+ 'include rt;\ninclude std;\nfn main() {\n\treturn std.Text.itoa(5, 0);\n}\n', 'change to `itoa`');
console.log(ok + ' hint fix checks passed, ' + bad + ' failed');
process.exit(bad ? 1 : 0);
diff --git a/tests/drivers/lsp_test.js b/tests/drivers/lsp_test.js
index 18d8bf7..0f4abe1 100644
--- a/tests/drivers/lsp_test.js
+++ b/tests/drivers/lsp_test.js
@@ -250,5 +250,23 @@ check(hcv && hcv.includes('parameter'), 'hover on a use of a parameter named lik
hcv = hover(scp, 4, at(scp, 4, 'len'));
check(hcv && hcv.includes('the number of items'), 'hover on the built-in still shows its text where no local shadows it', hcv);
+// typedefs: the name shows its declaration, at the declaration, at a use in a declaration, and in a block
+const tdsrc = 'struct node { int v; node* next; };\n// another name for node*\ntypedef node* link;\ntypedef int(int, int) binop;\nlink head(link n) { return n; }\nint use(string s) {\n\ttypedef int cell;\n\tcell c = 1;\n\tbinop f = 0;\n\treturn c;\n}\n';
+hv = hover(tdsrc, 2, at(tdsrc, 2, 'link'));
+check(hv && hv.includes('typedef node* link;') && hv.includes('another name for node*'), 'hover on the name in a typedef shows the typedef and its doc', hv);
+hv = hover(tdsrc, 4, at(tdsrc, 4, 'link'));
+check(hv && hv.includes('typedef node* link;') && hv.includes('a pointer to `node`'), 'hover on a typedef name used as a type shows the typedef and the type', hv);
+hv = hover(tdsrc, 4, at(tdsrc, 4, 'link', 1));
+check(hv && hv.includes('typedef node* link;'), 'hover on a typedef name used as a parameter type shows the typedef', hv);
+hv = hover(tdsrc, 3, at(tdsrc, 3, 'binop'));
+check(hv && hv.includes('typedef int(int, int) binop;'), 'hover on a function type typedef shows the whole typedef', hv);
+hv = hover(tdsrc, 7, at(tdsrc, 7, 'cell'));
+check(hv && hv.includes('typedef int cell;'), 'hover on a typedef made in a block shows the typedef', hv);
+hv = hover(tdsrc, 5, at(tdsrc, 5, 'string'));
+check(hv && hv.includes('char*') && hv.includes('built-in alias'), 'hover on string shows char* and what string is', hv);
+hv = hover(tdsrc, 2, 3);
+check(hv && hv.includes('typedef T name;') && hv.includes('type name = T;'), 'hover on the typedef keyword explains it', hv);
+check(tokens(tdsrc).includes('typedef:keyword'), 'typedef is highlighted as a keyword', tokens(tdsrc));
+
console.log(ok + ' lsp checks passed, ' + bad + ' failed');
process.exit(bad ? 1 : 0);
diff --git a/tests/errors/static_const_typo.zc b/tests/errors/static_const_typo.zc
new file mode 100644
index 0000000..c7f2b7b
--- /dev/null
+++ b/tests/errors/static_const_typo.zc
@@ -0,0 +1,5 @@
+namespace;
+
+// expect: MAXX: is not a static function of this struct; did you mean 'MAX'?
+struct Text { const MAX = 24; int len; };
+fn main() { return Text.MAXX; }
diff --git a/tests/errors/static_typo.zc b/tests/errors/static_typo.zc
new file mode 100644
index 0000000..97f6513
--- /dev/null
+++ b/tests/errors/static_typo.zc
@@ -0,0 +1,5 @@
+namespace;
+
+// expect: itao: is not a static function of this struct; did you mean 'itoa'?
+struct Text { int len; static int itoa(int n) { return n; } };
+fn main() { return Text.itao(1); }
diff --git a/tests/langerrors/struct_const_runtime.zc b/tests/langerrors/struct_const_runtime.zc
new file mode 100644
index 0000000..b55626e
--- /dev/null
+++ b/tests/langerrors/struct_const_runtime.zc
@@ -0,0 +1,6 @@
+namespace;
+
+// expect: a struct constant must be a constant expression
+int f(int x) { return x; }
+struct Text { const MAX = f(3); int len; }
+fn main() { return 0; }
diff --git a/tests/langerrors/typedef_generic_bare.zc b/tests/langerrors/typedef_generic_bare.zc
new file mode 100644
index 0000000..5f3e906
--- /dev/null
+++ b/tests/langerrors/typedef_generic_bare.zc
@@ -0,0 +1,6 @@
+namespace;
+
+// expect: expected '<', found 'plain'
+struct box<T> { T item; };
+typedef box plain;
+fn main() { return 0; }
diff --git a/tests/langerrors/typedef_local_redefine.zc b/tests/langerrors/typedef_local_redefine.zc
new file mode 100644
index 0000000..e51c32f
--- /dev/null
+++ b/tests/langerrors/typedef_local_redefine.zc
@@ -0,0 +1,8 @@
+namespace;
+
+// expect: cell: already defined
+fn main() {
+ typedef int cell;
+ typedef char* cell;
+ return 0;
+}
diff --git a/tests/langerrors/typedef_redefine.zc b/tests/langerrors/typedef_redefine.zc
new file mode 100644
index 0000000..05085ec
--- /dev/null
+++ b/tests/langerrors/typedef_redefine.zc
@@ -0,0 +1,6 @@
+namespace;
+
+// expect: num: already defined
+typedef int num;
+typedef char* num;
+fn main() { return 0; }
diff --git a/tests/langerrors/typedef_scope.zc b/tests/langerrors/typedef_scope.zc
new file mode 100644
index 0000000..833e30e
--- /dev/null
+++ b/tests/langerrors/typedef_scope.zc
@@ -0,0 +1,8 @@
+namespace;
+
+// expect: expected ';', found 'x'
+fn main() {
+ { typedef int cell; cell a = 1; }
+ cell x = 2;
+ return 0;
+}
diff --git a/tests/langerrors/typedef_string_redefine.zc b/tests/langerrors/typedef_string_redefine.zc
new file mode 100644
index 0000000..226a94e
--- /dev/null
+++ b/tests/langerrors/typedef_string_redefine.zc
@@ -0,0 +1,5 @@
+namespace;
+
+// expect: string: already defined
+typedef int string;
+fn main() { return 0; }
diff --git a/tests/langerrors/typedef_tag.zc b/tests/langerrors/typedef_tag.zc
new file mode 100644
index 0000000..70ab491
--- /dev/null
+++ b/tests/langerrors/typedef_tag.zc
@@ -0,0 +1,5 @@
+namespace;
+
+// expect: a typedef names a type, which has no tag
+typedef char*.u owned;
+fn main() { return 0; }
diff --git a/tests/langerrors/typedef_unknown.zc b/tests/langerrors/typedef_unknown.zc
new file mode 100644
index 0000000..8076e86
--- /dev/null
+++ b/tests/langerrors/typedef_unknown.zc
@@ -0,0 +1,5 @@
+namespace;
+
+// expect: missing_t: isn't a type
+typedef missing_t thing;
+fn main() { return 0; }
diff --git a/tests/langerrors/typedef_variable_clash.zc b/tests/langerrors/typedef_variable_clash.zc
new file mode 100644
index 0000000..2c843f2
--- /dev/null
+++ b/tests/langerrors/typedef_variable_clash.zc
@@ -0,0 +1,8 @@
+namespace;
+
+// expect: count: already defined
+fn main() {
+ int count = 1;
+ typedef int count;
+ return count;
+}
diff --git a/tests/langerrors/typedef_void_variable.zc b/tests/langerrors/typedef_void_variable.zc
new file mode 100644
index 0000000..c5c7ced
--- /dev/null
+++ b/tests/langerrors/typedef_void_variable.zc
@@ -0,0 +1,5 @@
+namespace;
+
+// expect: a variable can't be void
+typedef void nothing;
+fn main() { nothing x; return 0; }
diff --git a/tests/programs/struct_const.zc b/tests/programs/struct_const.zc
new file mode 100644
index 0000000..59af8fd
--- /dev/null
+++ b/tests/programs/struct_const.zc
@@ -0,0 +1,28 @@
+namespace;
+include rt;
+
+struct Text {
+ const MAX = 24, MIN = 1;
+ const int WIDE = MAX * 2;
+ int len, tag;
+ static int top() { return MAX; }
+ static int span() { return MAX - MIN; }
+ int room() { return MAX - this.len; }
+ int total() { int[MIN + 2] a; a[2] = WIDE; return a[2] + this.tag; }
+}
+
+const MAX = 99;
+
+int main() {
+ Text t;
+ t.len = 5; t.tag = 7;
+ rt.put_n(Text.MAX); rt.put_c(32);
+ rt.put_n(Text.MIN + Text.WIDE); rt.put_c(32);
+ rt.put_n(Text.top()); rt.put_c(32);
+ rt.put_n(Text.span()); rt.put_c(32);
+ rt.put_n(t.room()); rt.put_c(32);
+ rt.put_n(t.total()); rt.put_c(32);
+ rt.put_n(t.len + t.tag); rt.put_c(32);
+ rt.put_n(MAX); rt.put_c(10);
+ return 0;
+}
diff --git a/tests/programs/typedef.zc b/tests/programs/typedef.zc
new file mode 100644
index 0000000..307ef75
--- /dev/null
+++ b/tests/programs/typedef.zc
@@ -0,0 +1,89 @@
+namespace;
+include rt;
+typecheck on;
+
+// typedef T name; makes name another way to write T: the same type, so the two mix freely
+struct node { int v; node* next; };
+struct pair<A, B> { A a; B b; };
+
+typedef int count;
+typedef char* label;
+typedef node* link;
+typedef link* links;
+typedef int[4] quad;
+typedef int(int, int) binop;
+typedef pair<int, int> ipair;
+typedef int[?] ints;
+typedef count counter;
+
+struct box { count n; link head; ipair p; };
+
+count twice(count x) { return x + x; }
+count add(int a, int b) { return a + b; }
+count apply(binop f, count a, count b) { return f(a, b); }
+count sum(link n) { count s = 0; while (n) { s += n.v; n = n.next; } return s; }
+label hello() { return "hello"; }
+string greet(string s) { return s; }
+// string is only a type where a type is expected: an untyped parameter can still be called string
+fn twice_name(string) { return string + string; }
+count first_of(links ls) { return ls[0].v; }
+T pick<T>(T x) { typedef T item; item y = x; return y; }
+count scoped() {
+ count total = 0;
+ { typedef int cell; cell c = 3; total += c; }
+ { typedef char* cell; cell c = "ab"; total += rt.len_w(c); }
+ return total;
+}
+count scoped_again() { typedef quad cell; cell c; c[2] = 7; return c[2] + sizeof(cell); }
+
+// a link is a node*: every use below mixes the two
+count same_ptr(node* p, link q) { return p == q; }
+count casts(link p) {
+ word w = p as word;
+ link back = w as link;
+ node* n = (node*)back;
+ return back.v + ((link)n == p);
+}
+count boxed(link p) {
+ box bx; bx.n = 6; bx.head = 0; bx.p.a = 1; bx.p.b = 2;
+ pair<link, count> pl; pl.a = 0; pl.b = 5;
+ return bx.n + p.v + bx.p.a + bx.p.b + pl.b + !bx.head + !pl.a;
+}
+count by_ref(links ls) { return first_of(ls); }
+
+fn main() {
+ link a = rt.new(node), b = rt.new(node);
+ a.v = 3; b.v = 4; a.next = b;
+ rt.put_n(sum(a)); rt.put_c(' ');
+ rt.put_n(same_ptr(a, a)); rt.put_c(' ');
+ rt.put_n(twice(21)); rt.put_c(' ');
+ rt.put_n(apply(add, 2, 3)); rt.put_c(' ');
+ binop op = add;
+ rt.put_n(op(10, 20)); rt.put_c(10);
+
+ quad q; q[3] = 9;
+ rt.put_n(q[3] + sizeof(quad)); rt.put_c(' ');
+ rt.put_n(sizeof(count) + sizeof(link) + sizeof(ipair)); rt.put_c(' ');
+ rt.put_n(boxed(a)); rt.put_c(' ');
+ ints xs = {1, 2, 3};
+ push(xs, 4);
+ rt.put_n(len(xs)); rt.put_c(10);
+
+ rt.put_n(casts(a)); rt.put_c(' ');
+ counter k = (count)3;
+ rt.put_n(k); rt.put_c(' ');
+ links ls = &a;
+ rt.put_n(by_ref(ls)); rt.put_c(' ');
+ rt.put_n(pick<count>(11) + pick(1)); rt.put_c(10);
+
+ rt.put_n(scoped()); rt.put_c(' ');
+ rt.put_n(scoped_again()); rt.put_c(10);
+
+ string s = "hi";
+ label l = s;
+ char* c = l;
+ rt.put_s(s); rt.put_s(l); rt.put_s(c); rt.put_s(hello()); rt.put_s(greet("ok")); rt.put_c(10);
+ rt.put_n(twice_name(4)); rt.put_c(10);
+ rt.free(d*a);
+ return 0;
+}
diff --git a/tests/test.sh b/tests/test.sh
index 46625a6..709d09c 100755
--- a/tests/test.sh
+++ b/tests/test.sh
@@ -106,6 +106,7 @@ run(){ # $1 = vm command, $2 = label
chk "$($vm < tests/programs/meta.zc | tr '\n' '/')" "1024 19/unless ok/rrr/15 42/7/42/7/144/" "$l parse words, quote, eval, load, operator tables"
chk "$($vm < tests/programs/misc.zc | tr '\n' '/')" "45/54321/ok/" "$l compile-time eval, patched mnemonics, unchecked"
chk "$($vm < tests/programs/types.zc | tr '\n' '/')" "12 5 2 15 56 42 7 14 3/rect rect* list<int>* list<T>*.u(int) T(list<T>*) fn(word.d)/a:point@0 b:point@2 tag:int@4 /point 1 1/" "$l types, generics, reflection"
+ chk "$($vm < tests/programs/typedef.zc | tr '\n' '/')" "7 1 42 5 30/13 4 19 4/4 3 3 12/5 11/hihihihellook/8/" "$l typedef, global and local, in every place a type goes, and string"
chk "$($vm < tests/programs/typeok.zc)" "14" "$l a program the typechecker accepts"
chk "$($vm < tests/programs/typeoff.zc)" "6" "$l the typechecker is off by default"
chk "$($vm < tests/programs/enhance.zc)" "100 0 343 3,2 5 -2 0" "$l virtual enhancements"
@@ -123,6 +124,7 @@ run(){ # $1 = vm command, $2 = label
chk "$($vm < tests/programs/generics.zc | md5sum)" "$(md5sum < tests/programs/generics.expected)" "$l generic functions are compiled per type arguments"
chk "$($vm < tests/programs/genmeth.zc | md5sum)" "$(md5sum < tests/programs/genmeth.expected)" "$l methods of generic structs are compiled per type arguments"
chk "$($vm < tests/programs/static.zc)" "14 5 9" "$l static functions of a struct are called as Struct.name(args)"
+ chk "$($vm < tests/programs/struct_const.zc)" "24 49 24 23 19 55 12 99" "$l constants declared in a struct are reached as Struct.NAME, and by bare name in its methods"
chk "$($vm < tests/programs/methodown.zc)" "7 9" "$l struct methods and functions return owned objects (.u)"
chk "$($vm < tests/programs/typedmethods.zc)" "14 5 13" "$l struct methods declare a return type and typed parameters"
chk "$($vm < tests/programs/enumscope.zc)" "0 5 6 blue" "$l enum members are reached as Enum.MEMBER, also in a case"
diff --git a/tests/typeerrors/field_typo.zc b/tests/typeerrors/field_typo.zc
new file mode 100644
index 0000000..aa64209
--- /dev/null
+++ b/tests/typeerrors/field_typo.zc
@@ -0,0 +1,5 @@
+namespace;
+
+// expect: point has no field lenght; did you mean 'length'?
+struct point { int length, width; };
+fn main() { point* p; return p.lenght; }
diff --git a/tests/typeerrors/typedef_mismatch.zc b/tests/typeerrors/typedef_mismatch.zc
new file mode 100644
index 0000000..26453dd
--- /dev/null
+++ b/tests/typeerrors/typedef_mismatch.zc
@@ -0,0 +1,6 @@
+namespace;
+
+// expect: type error: initializer: expected int, got char*
+typecheck on;
+typedef int count;
+fn main() { count c = "text"; return 0; }
diff --git a/tests/typeerrors/typedef_pointer.zc b/tests/typeerrors/typedef_pointer.zc
new file mode 100644
index 0000000..5dbbb17
--- /dev/null
+++ b/tests/typeerrors/typedef_pointer.zc
@@ -0,0 +1,7 @@
+namespace;
+
+// expect: type error: initializer: expected node*, got int*
+typecheck on;
+struct node { int v; };
+typedef node* link;
+fn main() { int n = 0; link p = &n; return 0; }