diff options
29 files changed, 920 insertions, 73 deletions
@@ -7,6 +7,8 @@ # make test the whole suite (tests/test.sh) # make check the minimal suite, for iterating (tests/test.sh -q) # make test JOBS=4 the same, four sections at a time +# make parity compile the test programs with zc0 and with the self-hosted +# compiler and compare what they print (src/tools/parity.sh) # make genome build/core/genome.bin from src/, with the fixpoint check # make lsp build/bin/zclsp, the language server # make web build/web/: the page, its script and zc.wasm @@ -143,6 +145,11 @@ run: $(CC) $(CFLAGS) $(MICRO_THREADS) src/micro/micro.c $(PORT) -Isrc/core -Isrc/micro -I$(B)/run --embed-dir=$(B)/run -o $(B)/run/zymr$(EXE) @echo "built $(B)/run/zymr$(EXE)" +# the two compilers on the same programs: whatever zc0 accepts must print the same +# under both. work files go to build/parity/. +parity: $(BIN)/zc0$(EXE) $(BIN)/mkgenome$(EXE) $(BIN)/zy$(EXE) + bash src/tools/parity.sh + # JOBS sets how many sections run at once: make test JOBS=4 test: bash tests/test.sh -j $(or $(JOBS),1) @@ -154,4 +161,4 @@ check: clean: rm -rf $(B) -.PHONY: all lsp genome js lspimage vsix web run test check clean +.PHONY: all lsp genome js lspimage vsix web run parity test check clean @@ -163,6 +163,10 @@ make check make test JOBS=4 ``` +`make parity` compiles the programs in `tests/programs/` and `examples/` with zc0 and +with the self-hosted compiler and diffs their output; `tests/programs/parity_ops.zc` +pins operator precedence. it uses `build/`, and skips what zc0 rejects. + the suite builds its own map, bootstrap and cores in a scratch directory, so it does not depend on what is in `build/`. on a host without the arm64 jit the language server is interpreted and slow; `ZC_TEST_TIMEOUT_SCALE` stretches the @@ -31,13 +31,14 @@ run these commands from the repository root. everything built or generated goes make build/bin/zy < examples/hello.zc make test JOBS=4 +make parity make genome make web make js make run PROG=examples/hello.zc ``` -the cores embed their genome with c23 `#embed`, so the c compiler has to be clang 19 or gcc 15 or later. `src/tools/findcc.sh` finds one (`CC` set on the command line or in the environment is used as given, and must support it too). `make genome` bootstraps the compiler, compares two self-compiled images, and writes `build/core/genome.bin` only after they agree; `make` reruns it whenever a source of the genome changes, and the cores that embed it are rebuilt after it. `make check` runs the smaller suite while iterating. `ONBOARD.md` is a reading and verification order for getting to know the code. +the cores embed their genome with c23 `#embed`, so the c compiler has to be clang 19 or gcc 15 or later. `src/tools/findcc.sh` finds one (`CC` set on the command line or in the environment is used as given, and must support it too). `make genome` bootstraps the compiler, compares two self-compiled images, and writes `build/core/genome.bin` only after they agree; `make` reruns it whenever a source of the genome changes, and the cores that embed it are rebuilt after it. `make check` runs the smaller suite while iterating. `make parity` (`src/tools/parity.sh`, `--help` for options) compiles the test and example programs with zc0 and with the self-hosted compiler and compares what they print, which the fixpoint check cannot see; programs zc0 rejects are skipped and counted, intended differences are listed in `tests/parity.known`, and work files go to `build/parity/`. `ONBOARD.md` is a reading and verification order for getting to know the code. ### command-line help @@ -169,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. @@ -296,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 @@ -513,7 +516,7 @@ tables: `run.add_binop("**", 11, "ipow c")` adds or replaces a binary operator w ## the bootstrap -`src/tools/zc0.c` compiles the subset of zc used by `src/compiler/compiler.zc` (without the analyzer, types, quote, parse words, or block expressions, but with `enhance` and top-level `embed` declarations) into the first genome, `build/s0/genome.bin`. a core built around that image compiles `src/compiler/compiler.zc` again in the VM using the full compiler, analyzer, and native division code, and `mkgenome` accepts the result only if it is an image (a compiler that rejects its own source prints diagnostics instead, which `mkgenome` shows). a core built around the second image compiles the source a third time; the two self-compiled images must be identical, and the first becomes `build/core/genome.bin`. the test suite checks this fixpoint on the interpreter, microcore, jit and llvm backends when available. in the zc0 subset `u`, `m` and `d` are recast tags, not names. an image build (`build_image(org, dst)`) compiles with only the image's names, keywords, and built-in types visible, writes code for the requested address, and appends a symbol table containing its names and enhancements. an image build (`build_image(org, dst)`) compiles with only the image's names, keywords, and built-in types visible, writes code for the requested address, and appends a symbol table containing its names and enhancements. +`src/tools/zc0.c` compiles the subset of zc used by `src/compiler/compiler.zc` (without the analyzer, types, quote, parse words, or block expressions, but with `enhance` and top-level `embed` declarations) into the first genome, `build/s0/genome.bin`. a core built around that image compiles `src/compiler/compiler.zc` again in the VM using the full compiler, analyzer, and native division code, and `mkgenome` accepts the result only if it is an image (a compiler that rejects its own source prints diagnostics instead, which `mkgenome` shows). a core built around the second image compiles the source a third time; the two self-compiled images must be identical, and the first becomes `build/core/genome.bin`. the test suite checks this fixpoint on the interpreter, microcore, jit and llvm backends when available. zc0 reads `u`, `m` and `d` as ordinary names too: `u*x` with the star touching the letter is a recast (no code), `u * x` is a product, and `.u`, `.m` and `.d` tags are read and ignored. it packs `b"..."` byte strings like the compiler and tracks `bstr` locals, globals, parameters and returns, and `embed` declarations (arrays only at the top level). an image build (`build_image(org, dst)`) compiles with only the image's names, keywords, and built-in types visible, writes code for the requested address, and appends a symbol table containing its names and enhancements. an image build (`build_image(org, dst)`) compiles with only the image's names, keywords, and built-in types visible, writes code for the requested address, and appends a symbol table containing its names and enhancements. ## the instruction set @@ -149,11 +149,23 @@ the final full suite stays at the very end whatever its size. - [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.) -- [ ] 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] 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. -- [ ] 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. +- [ ] 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. +- [x] 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. +- [x] 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). (`src/tools/parity.sh`, `make parity`; by-design differences in `tests/parity.known`.) +- [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). +- [ ] zc0 has no `?:`; add it so parity covers conditional expressions, and grow zc0's subset where it is cheap (structs and enums are the largest group of programs parity skips today). +- [ ] remaining zc0 gaps: string literals over 4095 bytes, `embed` of an array type inside a function, `x as T` with more than a single name (`x as int*`), and zc0 silently accepting `.u` on a parameter where the self-hosted compiler rejects it; also `docs/history/43-stdlib/notes.md` still says zc0 reserves u/m/d (a history note: add a pointer forward rather than rewriting it). +- [ ] a run-only image accepts `void main()` from zc0 but the self-hosted compiler rejects it against `run.zc`'s `int main();` prototype; make the two agree. - [ ] 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 +173,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/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/src/compiler/compiler.zc b/src/compiler/compiler.zc index 8335ab9..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; } @@ -4388,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 ). @@ -5556,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); @@ -5570,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"); @@ -6485,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; @@ -7660,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); } @@ -7762,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; } @@ -8646,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; } @@ -8795,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 @@ -8850,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])) { @@ -9115,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(); @@ -9225,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(); @@ -10088,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/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/src/tools/parity.sh b/src/tools/parity.sh new file mode 100755 index 0000000..2739a85 --- /dev/null +++ b/src/tools/parity.sh @@ -0,0 +1,160 @@ +#!/bin/bash +# compiles the same programs with both compilers and compares what they print. +# zc0 (stage 0, in c) compiles runtime + program into an image that runs on a +# microcore with the image embedded; the self-hosted compiler compiles the +# same source inside the vm (build/bin/zy < prog.zc). a program zc0 rejects is +# outside its subset and is skipped. for every other program the two outputs +# must be equal. the bootstrap's fixpoint cannot see a language rule both +# compilers got wrong the same way, but this can see one they disagree on. +# +# the image is built the way src/tools/zcc builds a run-only program, on the +# default map so that it behaves like the resident compiler's programs do: +# rt.zc, core.zc, src/runtime/run.zc, a `namespace;` (the program starts in the +# global namespace, as under zy) and the program go through build/bin/zc0, +# build/bin/mkgenome checks the image, and a microcore embeds it (c23 #embed). +# the core is compiled per program (about a second); it is kept under +# build/parity/ and reused until the program, the compilers or the runtime change. +# +# stdin: zy reads the program from stdin and the program then reads what follows +# a backtick that starts a line (see examples/learn/24-backtick.zc); the image +# gets that same text, or nothing when the source has no such line. +# +# tests/parity.known lists the programs that differ on purpose (zc0 has no +# ownership analysis, for one). they are still compared and shown as known, and +# do not fail the run; one that agrees again is reported as stale. +set -e +usage() { + printf '%s\n' 'usage: src/tools/parity.sh [-v] [-t SECONDS] [FILE.zc...]' \ + 'compiles each program with zc0 and with the self-hosted compiler and compares stdout.' \ + 'without FILE the corpus is tests/programs/*.zc, examples/*.zc and examples/learn/*.zc.' \ + 'a program zc0 rejects is skipped and counted. both runs see the same stdin:' \ + 'the text after a backtick line in the source, else nothing.' \ + 'prints one line per mismatch and a summary; exit status 1 when anything differs' \ + '(programs listed in tests/parity.known are shown but do not count).' \ + 'options:' \ + ' -v also list the skipped programs and why' \ + ' -t SECONDS time limit for each run (default 30); a program that hits it on both sides is skipped' \ + ' --help, -h show this help and exit' \ + 'work files are under build/parity/. environment: CC selects the c compiler (one with #embed).' +} +verbose=0; limit=30 +while [ $# -gt 0 ]; do + case "$1" in + --help|-h) usage; exit 0 ;; + -v) verbose=1; shift ;; + -t) [ $# -ge 2 ] || { echo "parity: -t needs a number of seconds" >&2; exit 2; } + case "$2" in ''|*[!0-9]*|0) echo "parity: -t needs a positive number of seconds" >&2; exit 2 ;; esac + limit=$2; shift 2 ;; + --) shift; break ;; + -*) echo "parity: unknown option $1; use --help for usage" >&2; exit 2 ;; + *) break ;; + esac +done +cd "$(dirname "$0")/../.." +for f in "$@"; do [ -f "$f" ] || { echo "parity: no such file: $f" >&2; exit 2; }; done +if [ $# -gt 0 ]; then progs=("$@"); else progs=(tests/programs/*.zc examples/*.zc examples/learn/*.zc); fi + +make -s build/bin/zc0 build/bin/mkgenome build/bin/zy >&2 +CC=${CC:-$(sh src/tools/findcc.sh)} +root=$PWD +ZC0=build/bin/zc0; MKG=build/bin/mkgenome; ZY=build/bin/zy +W=build/parity +KNOWN=tests/parity.known +mkdir -p "$W" +# what every image starts with, and how many lines that is (zc0 counts from the top) +SRCS="src/runtime/rt.zc src/core/core.zc src/runtime/run.zc" +{ cat $SRCS; echo 'namespace;'; } > "$W/prefix.new" +if cmp -s "$W/prefix.new" "$W/prefix.zc"; then rm "$W/prefix.new"; else mv "$W/prefix.new" "$W/prefix.zc"; fi +nprefix=$(wc -l < "$W/prefix.zc") +# what the compiled image depends on besides the program +DEPS="$ZC0 $MKG $W/prefix.zc src/micro/micro.c src/micro/port_linux.c src/micro/micro_port.h src/core/fops.h src/core/bops.h src/core/stack.h src/core/genome.h build/core/map/memmap.h" + +# one line of a program's output: newlines as /, control bytes as ?, cut to 60 columns +short() { + local s + s=$(head -c 400 "$1" | tr '\n' '/' | tr -c '[:print:]' '?') + if [ ${#s} -gt 60 ]; then s="${s:0:60}..."; fi + printf '%s' "$s" +} +stale() { # $1 = built file: missing, or older than a dependency or the program $2? + local d + [ -x "$1" ] || return 0 + for d in $DEPS "$2"; do [ "$d" -nt "$1" ] && return 0; done + return 1 +} +isknown() { [ -f "$KNOWN" ] && grep -q "^$1[ #]" "$KNOWN"; } +reason() { grep "^$1[ #]" "$KNOWN" | head -n1 | sed 's/^[^#]*# *//'; } +# zc0 reports lines of the whole input; the program's own line is what helps +rebase() { + local msg=$1 re='^zc0: line ([0-9]+): (.*)$' + if [[ $msg =~ $re ]]; then msg="zc0: line $(( BASH_REMATCH[1] - nprefix )): ${BASH_REMATCH[2]}"; fi + printf '%s' "$msg" +} + +mkdir -p "$W/root" +for f in *; do [ "$f" = build ] || ln -sfn "$root/$f" "$W/root/$f"; done +compared=0; differ=0; known=0; skipped=0; timedout=0; broken=0 +skips="" +for p in "${progs[@]}"; do + name=${p%.zc}; name=${name//\//_} + d=$W/$name + mkdir -p "$d" + if ! cat "$W/prefix.zc" "$p" | "$ZC0" > "$d/img.bin" 2> "$d/zc0.err"; then + skipped=$((skipped+1)) + skips="$skips$p: $(rebase "$(head -n1 "$d/zc0.err")")"$'\n' + continue + fi + if stale "$d/run" "$p"; then + if ! "$MKG" < "$d/img.bin" > "$d/genome.bin" 2> "$d/build.err"; then + echo "broken: $p: zc0 accepts it but mkgenome rejects the image: $(head -n1 "$d/build.err")" + broken=$((broken+1)); continue + fi + if ! $CC -O2 -w -fwrapv -pthread -DZY_THREADS src/micro/micro.c src/micro/port_linux.c \ + -Isrc/core -Ibuild/core/map -Isrc/micro --embed-dir="$d" -o "$d/run" 2> "$d/build.err"; then + echo "broken: $p: the c compiler failed on the zc0 image: $(head -n1 "$d/build.err")" + broken=$((broken+1)); continue + fi + fi + # the image already holds the program. both sides then read the same stdin + sed -n '/^`/,$p' "$p" | tail -c +2 > "$d/stdin" + # from a directory that shows the repository through links, so that a program that + # reads a file by its path finds it, and one that writes a file leaves it under build/ + find "$W/root" -mindepth 1 -maxdepth 1 ! -type l -exec rm -rf {} + + case $p in /*) pabs=$p ;; *) pabs=$root/$p ;; esac + rc0=0; rcy=0 + ( cd "$W/root" && timeout -k 1 "$limit" "$root/$d/run" < "$root/$d/stdin" > "$root/$d/out0" 2> "$root/$d/err0" ) || rc0=$? + ( cd "$W/root" && timeout -k 1 "$limit" "$root/$ZY" < "$pabs" > "$root/$d/outy" 2> "$root/$d/erry" ) || rcy=$? + if [ $rc0 = 124 ] && [ $rcy = 124 ]; then + timedout=$((timedout+1)) + skips="$skips$p: no result within ${limit}s on either side"$'\n' + continue + fi + compared=$((compared+1)) + msg="" + if [ $rc0 = 124 ] || [ $rcy = 124 ]; then + [ $rc0 = 124 ] && a="(timed out after ${limit}s)" || a="[$(short "$d/out0")]" + [ $rcy = 124 ] && b="(timed out after ${limit}s)" || b="[$(short "$d/outy")]" + msg="$p: zc0 $a, self-hosted $b" + elif ! cmp -s "$d/out0" "$d/outy"; then + msg="$p: zc0 [$(short "$d/out0")], self-hosted [$(short "$d/outy")]" + fi + if [ -z "$msg" ]; then + isknown "$p" && echo "stale: $p agrees now; remove it from $KNOWN" + elif isknown "$p"; then + known=$((known+1)) + echo "known: $msg ($(reason "$p"))" + else + differ=$((differ+1)) + echo "differ: $msg" + fi +done +if [ $verbose = 1 ] && [ -n "$skips" ]; then + echo "skipped:" + printf '%s' "$skips" | sed 's/^/ /' +fi +extra="" +[ $timedout -gt 0 ] && extra="$extra, $timedout skipped (timeout)" +[ $known -gt 0 ] && extra="$extra, $known known ($KNOWN)" +[ $broken -gt 0 ] && extra="$extra, $broken did not build" +echo "parity: $compared compared, $differ differ, $skipped skipped (outside zc0)$extra" +[ $differ -eq 0 ] && [ $broken -eq 0 ] diff --git a/src/tools/zc0.c b/src/tools/zc0.c index b0ab29f..9faf883 100644 --- a/src/tools/zc0.c +++ b/src/tools/zc0.c @@ -4,8 +4,10 @@ the same image layout the resident compiler's image mode produces. the cores embed that file with #embed (src/core/genome.h). no lifetime analysis, no quote, no parse words, no block expressions: those only exist in compiler.zc. tags - (m, d, -> u) and casts (as u, as d) are parsed and recorded in signatures - but not checked. */ + (.m and .d on parameters, .u on a return) are parsed and recorded in + signatures but not checked. u, m and d are ordinary names, as in the + resident compiler: a recast is the letter with the star touching it, u*x, + and it makes no code. */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> @@ -176,7 +178,10 @@ static void next(void) ts[i] = 0; if (i == 1 && ts[0] == 'b' && src[pos] == '"') { pos++; i = 0; - while (src[pos] && src[pos] != '"' && i < 4095) ts[i++] = (char)esc(); + while (src[pos] && src[pos] != '"') { + if (i >= 4095) { die("a byte string literal is at most 4095 bytes; embed larger data"); break; } + ts[i++] = (char)esc(); + } ts[i] = 0; if (src[pos] == '"') pos++; tk = T_BSTR; return; } if (src[pos] == '.' && (!strcmp(ts,"rt") || !strcmp(ts,"run") || !strcmp(ts,"core") || !strcmp(ts,"lsp") || !strcmp(ts,"std") || !strcmp(ts,"icon"))) { @@ -187,7 +192,14 @@ static void next(void) tk = T_ID; return; } if (src[pos] == '\'') { pos++; tv = esc(); if (src[pos++] != '\'') die("bad char literal"); tk = T_NUM; strcpy(ts, "'c'"); return; } - if (src[pos] == '"') { pos++; i = 0; while (src[pos] && src[pos] != '"') ts[i++] = (char)esc(); ts[i] = 0; pos++; tk = T_STR; return; } + if (src[pos] == '"') { + pos++; i = 0; + while (src[pos] && src[pos] != '"') { + if (i >= 4095) { die("a string literal is at most 4095 bytes"); break; } + ts[i++] = (char)esc(); + } + ts[i] = 0; pos++; tk = T_STR; return; + } tk = T_OP; for (i = 0; ops3[i]; i++) if (!strncmp(src + pos, ops3[i], 3)) { strcpy(ts, ops3[i]); pos += 3; return; } for (i = 0; ops2[i]; i++) if (!strncmp(src + pos, ops2[i], 2)) { strcpy(ts, ops2[i]); pos += 2; return; } @@ -200,9 +212,16 @@ static int is(const char *s) { return (tk == T_OP || tk == T_ID) && !strcmp(ts, static int accept(const char *s) { if (is(s)) { next(); return 1; } return 0; } static void expect(const char *s) { if (!accept(s)) { char b[64]; sprintf(b, "expected '%s'", s); die(b); } } static char *ident(void) { static char b[8][256]; static int k; char *r = b[k++ & 7]; if (tk != T_ID) die("expected a name"); strcpy(r, ts); next(); return r; } +/* u, m and d are ordinary names. u*x, m*x and d*x are recasts when the star touches + the letter, which the raw character after the name tells: u * x is a product, and + so is u*=x. the current token is the name, so pos is just past it. */ +static int isrecast(void) +{ + return tk == T_ID && ts[1] == 0 && (ts[0] == 'u' || ts[0] == 'm' || ts[0] == 'd') && src[pos] == '*' && src[pos + 1] != '='; +} /* ---- symbols ---- */ -typedef struct { char name[64]; int kind, sig, defd, str; int64_t val; } Sym; /* str: a global holding a byte string */ +typedef struct { char name[64]; int kind, sig, defd, str; int64_t val; } Sym; /* str: a global holding a byte string, or a function returning one */ static Sym sy[16384]; static int nsy; typedef struct { int at, sym; } Fix; static Fix fx[65536]; static int nfx; @@ -237,7 +256,7 @@ static void fnref(const char *n) /* push a function address, fixing it up later } /* ---- locals ---- */ -typedef struct { char name[64]; int slot, arr, flt, str; } Loc; +typedef struct { char name[64]; int slot, arr, flt, str, dstr; } Loc; /* dstr: declared bstr, so always a byte string */ static Loc lo[1024]; static int nlo, nslot, infn; static Loc *findl(const char *n) { int i; for (i = nlo; i--;) if (!strcmp(lo[i].name, n)) return &lo[i]; return 0; } static void laddr(int k) { lit(ZFP); op(O_LD); if (k) { lit(k); op(O_ADD); } } @@ -349,25 +368,32 @@ static int64_t cexpr(void) for a growable handle or anything scalar. */ static int ptype0(void); static int ptype(void); +static int ptagname(void); +static int ptstr; /* the type just read is bstr itself, with no stars, brackets or parameters after it */ static int ptype1(void) { - int n, e; + int n, e, isb; + ptstr = 0; if (is("[")) { die("array types are postfix: T[N], T[] or T[?]"); return 1; } if (is("fixed")) { next(); return ptype0(); } if (is("fn")) { next(); return 1; } /* fn(int): the parameters follow, in ptype */ if (tk != T_ID) { die("a type name"); return 1; } + isb = !strcmp(ts, "bstr"); ident(); if (accept("<")) { /* generic arguments: vec<node*> */ + isb = 0; do { ptype(); } while (accept(",")); if (is(">>")) ts[1] = 0; /* >> closes two lists: leave the second > */ else expect(">"); } + ptstr = isb; return 1; } static int ptype0(void) { int n = ptype1(); while (is("*") || is("[")) { + ptstr = 0; if (accept("*")) n = 1; else { int count = 0, cap = 8, *dims = malloc(cap * sizeof(int)); @@ -390,19 +416,27 @@ static int ptype(void) { int n = ptype0(); while (accept("(")) { - if (!accept(")")) { do { ptype(); if (accept(".")) ident(); } while (accept(",")); expect(")"); } - n = 1; + if (!accept(")")) { do { ptype(); if (accept(".")) ptagname(); } while (accept(",")); expect(")"); } + n = 1; ptstr = 0; } return n; } +/* the name of an ownership tag, after its dot: 1 for m, 2 for d, 3 for u. zc0 does + nothing with them but record .m and .d on parameters and .u on a return. */ +static int ptagname(void) +{ + int t = 0; + if (is("m")) t = 1; else if (is("d")) t = 2; else if (is("u")) t = 3; else die("a tag is .u, .m or .d"); + next(); + return t; +} /* the ownership tag after a type, .u .m or .d: 0 when there is none */ static int ptag; static void ptagopt(void) { ptag = 0; if (!accept(".")) return; - if (is("m")) ptag = 1; else if (is("d")) ptag = 2; else if (is("u")) ptag = 3; else die("a tag is .u, .m or .d"); - next(); + ptag = ptagname(); } /* an optional type in front of a name. the words it needs, or -1 when there is no type here at all, which is how an untyped name is told from a type. the @@ -423,7 +457,7 @@ static int notatype(void) static int optype(void) { Lex L; int n; - if (notatype() || (tk != T_ID && !is("["))) return -1; + if (notatype() || isrecast() || (tk != T_ID && !is("["))) return -1; lexsave(&L); pguess = 1; pbad = 0; n = ptype(); ptagopt(); pguess = 0; if (tk == T_ID && !pbad) return n; lexrest(&L); @@ -451,20 +485,26 @@ static void strlit(void) /* inline word string: jump over it, push its address * for (i = 0; i < n; i++) emit((unsigned char)ts[i]); emit(0); setlit(j, here); lit(a); next(); } -/* b"...": length word, then bytes packed 8 per word, little-endian, plus a 0 */ -static void bstrlit(void) +/* a byte string's words: the length, then the bytes packed 8 per word, little-endian, + and a 0 after the last byte when the length is a multiple of 8, as bstrdata does in + compiler.zc. the result is the address of the length word, which is the string. */ +static int bstrwords(const unsigned char *b, long n) { - int j = here, a, i = 0, k, n = (int)strlen(ts); - const char *b = ts; - uint64_t w; - lit(0); op(O_JMP); a = here; + int a = here; long i = 0; int k; uint64_t w; emit(n); while (i < n) { w = 0; k = 0; - while (k < 8 && i < n) { w |= (uint64_t)(unsigned char)b[i] << (k * 8); k++; i++; } + while (k < 8 && i < n) { w |= (uint64_t)b[i] << (k * 8); k++; i++; } emit((int64_t)w); } if ((n & 7) == 0) emit(0); + return a; +} +/* b"...": the words inline, jumped over, then the address pushed */ +static void bstrlit(void) +{ + int j = here, a; + lit(0); op(O_JMP); a = bstrwords((const unsigned char *)ts, (long)strlen(ts)); setlit(j, here); lit(a); next(); } static int returns_bstr(const char *n) @@ -503,7 +543,7 @@ static void primary(void) else if (!strcmp(n, "len")) fnref("len_s"); else fnref(n); op(O_CALL); - xs = returns_bstr(n); xf = 0; + xs = returns_bstr(n) || (s && s->kind == K_FN && s->str); xf = 0; return; } fnref(n); @@ -512,7 +552,7 @@ static void incdec(int post, int d) { if (!lv) die("++/-- needs an lvalue"); lv = 0; - if (lvi >= 0) lo[lvi].str = 0; + if (lvi >= 0) lo[lvi].str = lo[lvi].dstr; xs = 0; if (post) { lit(0); op(O_PICK); op(O_LD); lit(0); op(O_PICK); lit(d); op(O_ADD); lit(2); op(O_PICK); op(O_ST); op(O_SWAP); op(O_DROP); } else { lit(0); op(O_PICK); op(O_LD); lit(d); op(O_ADD); lit(0); op(O_PICK); lit(2); op(O_PICK); op(O_ST); op(O_SWAP); op(O_DROP); } @@ -552,7 +592,7 @@ static void unary(void) else if (accept("&")) { unary(); if (!lv) die("& needs an lvalue"); lv = 0; xs = 0; } else if (accept("++")) { unary(); incdec(0, 1); } else if (accept("--")) { unary(); incdec(0, -1); } - else if (tk == T_ID && (!strcmp(ts, "u") || !strcmp(ts, "m") || !strcmp(ts, "d"))) { next(); expect("*"); unary(); } /* u*x: a recast, no code */ + else if (isrecast()) { next(); expect("*"); unary(); rval(); lvi = -1; } /* u*x: a recast, no code, and not a place to store */ else postfix(); } static void bin(int minp) @@ -586,7 +626,7 @@ static void expr(void) if (!lv) die("assignment needs an lvalue"); next(); expr(); rval(); op(O_SWAP); lit(1); op(O_PICK); op(O_SWAP); op(O_ST); lv = 0; - if (dst >= 0) { lo[dst].flt = xf; lo[dst].str = xs; } + if (dst >= 0) { lo[dst].flt = xf; lo[dst].str = xs || lo[dst].dstr; } } else if (tk == T_OP && strlen(ts) >= 2 && ts[strlen(ts) - 1] == '=' && strcmp(ts, "==") && strcmp(ts, "!=") && strcmp(ts, "<=") && strcmp(ts, ">=")) { if (!lv) die("assignment needs an lvalue"); lf = xf; strcpy(o, ts); o[strlen(o) - 1] = 0; next(); @@ -594,7 +634,7 @@ static void expr(void) if ((lf || xf) && fis(o)) fbinop(o, lf, xf); else { binop(o); xf = 0; } op(O_SWAP); lit(1); op(O_PICK); op(O_SWAP); op(O_ST); lv = 0; - if (dst >= 0) { lo[dst].flt = xf; lo[dst].str = 0; } + if (dst >= 0) { lo[dst].flt = xf; lo[dst].str = lo[dst].dstr; } } } @@ -616,6 +656,7 @@ static void asmblock(void) if (strlen(ts) == 1 && (c = strchr(mn, ts[0]))) { op((int)(c - mn)); next(); continue; } if (tk != T_ID) die("bad asm token"); if ((l = findl(ts))) { laddr(l->slot); next(); continue; } + if ((s = find(ts)) && s->kind == K_ENH) { op(22 + (int)s->val); next(); continue; } /* an enhancement is its opcode */ if ((s = find(ts)) && s->kind != K_FN) { lit(s->val); next(); continue; } if (s) { fnref(ts); next(); continue; } strcpy(rn[nr], ts); ra[nr++] = here; lit(0); next(); /* a label of this block */ @@ -631,6 +672,7 @@ static void asmblock(void) static int brk[256][64], nbrk[256], cont[256], nloop; static int epi[1024], nepi; static void stmt(void); +static void embeddecl(int local); static void block(void) { int save = nlo; @@ -652,7 +694,14 @@ static void stmt(void) if (accept(";")) return; if (is("{")) { block(); return; } { - int nw = optype(), n; + int nw = optype(), n, tstr = 0; + if (nw >= 0) tstr = ptstr; + else if (is(".")) { next(); ptagname(); nw = 1; } /* a bare tag: .m p = new(3); */ + else if (is("embed")) { /* embed "file" as [type] name; makes a local */ + Lex L; lexsave(&L); next(); + if (tk == T_STR) { embeddecl(1); return; } + lexrest(&L); + } if (nw >= 0 || accept("let") || accept("var")) { if (nw < 0) nw = 1; do { @@ -662,8 +711,8 @@ static void stmt(void) if (accept("[")) { n = cexpr(); expect("]"); nslot += n; l->slot = nslot - n; l->arr = 1; } else l->slot = nslot++; } - l->flt = 0; l->str = 0; - if (accept("=")) { expr(); rval(); laddr(l->slot); op(O_ST); l->flt = xf; l->str = xs; } + l->flt = 0; l->dstr = tstr && !l->arr; l->str = l->dstr; + if (accept("=")) { expr(); rval(); laddr(l->slot); op(O_ST); l->flt = xf; l->str = xs || l->dstr; } } while (accept(",")); expect(";"); return; } @@ -684,7 +733,7 @@ static void stmt(void) if (accept("for")) { int save = nlo; expect("("); - if (!is(";")) { if (is("let") || is("var") || tk == T_ID || is("[")) { stmt(); goto cond; } expr(); rval(); op(O_DROP); } + if (!is(";")) { if (is("let") || is("var") || tk == T_ID || is("[") || is(".")) { stmt(); goto cond; } expr(); rval(); op(O_DROP); } expect(";"); cond: c = here; if (!is(";")) { expr(); rval(); ftest(); } else { lit(1); xf = 0; } @@ -708,18 +757,18 @@ static void stmt(void) } /* ---- top level ---- */ -static void fndef(int ret) +static void fndef(int ret, int rstr) /* rstr: the return type is bstr */ { char *n = ident(); Sym *s; int np = 0, tags = 0, t, frame, i, helper, busy, done, check, node; if (dsn && !dnm[0]) strcpy(dnm, n); - char pn[16][64]; + char pn[16][64]; int pstr[16]; char full_name[256]; qualify(full_name, sizeof full_name, n); s = find_raw(full_name); if (!s || s->kind != K_FN) { s = add(n, K_FN, 0); s->defd = 0; } expect("("); if (!accept(")")) { do { - t = 0; ptag = 0; - if (optype() >= 0) t = ptag == 1 ? 1 : ptag == 2 ? 2 : 0; /* the type is read and dropped */ + t = 0; ptag = 0; pstr[np & 15] = 0; + if (optype() >= 0) { t = ptag == 1 ? 1 : ptag == 2 ? 2 : 0; pstr[np & 15] = ptstr; } /* the type is read and dropped */ else if (accept(".")) { /* .m name, .d name */ if (is("m")) t = 1; else if (is("d")) t = 2; else die("a parameter tag is .m or .d"); next(); @@ -729,7 +778,7 @@ static void fndef(int ret) } while (accept(",")); expect(")"); } - s->sig = ret + 2 * np + 64 * tags; + s->sig = ret + 2 * np + 64 * tags; s->str = rstr; if (accept(";")) return; /* prototype */ if (s->defd) die("function defined twice"); s->val = here; s->defd = 1; @@ -745,7 +794,7 @@ static void fndef(int ret) } #endif nlo = 0; nslot = 0; nepi = 0; infn = 1; - for (i = 0; i < np; i++) { strcpy(lo[nlo].name, pn[i]); lo[nlo].arr = 0; lo[nlo].flt = 0; lo[nlo].str = 0; lo[nlo++].slot = nslot++; } + for (i = 0; i < np; i++) { strcpy(lo[nlo].name, pn[i]); lo[nlo].arr = 0; lo[nlo].flt = 0; lo[nlo].dstr = lo[nlo].str = pstr[i & 15]; lo[nlo++].slot = nslot++; } /* retain the caller's pointer until the frame has its final segment. */ helper = !find("frame_busy") || !strcmp(s->name, "rt.frame_grow") || !strcmp(s->name, "rt.frame_leave"); lit(ZFP); op(O_LD); if (!helper) { lit(0); op(O_PICK); } @@ -798,6 +847,9 @@ static void enhdef(void) } /* embed "path" as [type] name; at the top level: a global holding the file's bytes, read when the image is built. the path is relative to the working directory. + in a function it declares a local: the bytes of a bstr or char* sit in the code, + jumped over, and the local starts as their address; a number is stored in the + local. an array takes the top level. bstr (the default) packs the bytes; char* keeps one character to a word; a number takes them little-endian; T[] and T[n] have one element per file chunk of T's size. the checks are the resident compiler's (kw_embed). zc0 drops @@ -813,9 +865,14 @@ static int embed_width(const char *t, int star) if (!strcmp(t, "int") || !strcmp(t, "word") || !strcmp(t, "bool") || !strcmp(t, "float") || !strcmp(t, "f64")) return 8; return 0; } -static void embeddecl(void) +static Loc *newloc(const char *n) { - char path[1024], ty[64] = "", *n; int star = 0, arr = -2, w, i, a; long len; unsigned char *buf; FILE *f; + Loc *l = &lo[nlo++]; strcpy(l->name, n); l->slot = nslot++; l->arr = l->flt = l->str = l->dstr = 0; + return l; +} +static void embeddecl(int local) +{ + char path[1024], ty[64] = "", *n; int star = 0, arr = -2, w, i, a, j; long len; unsigned char *buf; FILE *f; Loc *l; if (tk != T_STR) die("embed takes a path in quotes: embed \"file\" as name;"); snprintf(path, sizeof path, "%s", ts); next(); expect("as"); @@ -835,13 +892,23 @@ static void embeddecl(void) if (!buf || fread(buf, 1, (size_t)len, f) != (size_t)len) die("can't read the file named by embed"); fclose(f); if (arr == -2 && (!ty[0] || (!strcmp(ty, "bstr") && !star))) { - a = here; add(n, K_GVAR, a)->str = 1; emit(0); img[a - GORG] = here; emit(len); - for (i = 0; i < len; i += 8) { uint64_t u = 0; for (w = 0; w < 8 && i + w < len; w++) u |= (uint64_t)buf[i + w] << (w * 8); emit((int64_t)u); } - if (!(len & 7)) emit(0); + if (local) { + j = here; lit(0); op(O_JMP); a = bstrwords(buf, len); setlit(j, here); + l = newloc(n); l->str = l->dstr = 1; lit(a); laddr(l->slot); op(O_ST); + } else { + a = here; add(n, K_GVAR, a)->str = 1; emit(0); w = bstrwords(buf, len); img[a - GORG] = w; + } } else if (arr == -2 && !strcmp(ty, "char") && star == 1) { - a = here; add(n, K_GVAR, a); emit(0); img[a - GORG] = here; - for (i = 0; i < len; i++) emit(buf[i]); - emit(0); + if (local) { + j = here; lit(0); op(O_JMP); a = here; + for (i = 0; i < len; i++) emit(buf[i]); + emit(0); setlit(j, here); + l = newloc(n); lit(a); laddr(l->slot); op(O_ST); + } else { + a = here; add(n, K_GVAR, a); emit(0); img[a - GORG] = here; + for (i = 0; i < len; i++) emit(buf[i]); + emit(0); + } } else if (arr == -2) { uint64_t u = 0; w = embed_width(ty, star); if (!w) die("embed declares a bstr, a char*, a number or an array of numbers"); @@ -851,9 +918,15 @@ static void embeddecl(void) for (i = 0; i < len; i++) u |= (uint64_t)buf[i] << (i * 8); if (ty[0] == 'i' && w < 8 && (u >> (w * 8 - 1) & 1)) u |= ~(uint64_t)0 << (w * 8); if (!strcmp(ty, "f32")) u = fop_s2f(u); - a = here; add(n, K_GVAR, a); emit((int64_t)u); + if (local) { + l = newloc(n); l->flt = !strcmp(ty, "float") || !strcmp(ty, "f64") || !strcmp(ty, "f32"); + lit((int64_t)u); laddr(l->slot); op(O_ST); + } else { + a = here; add(n, K_GVAR, a); emit((int64_t)u); + } } else { int count; w = embed_width(ty, star); + if (local) die("zc0 embeds an array at the top level, not in a function"); if (!w) die("embed declares a bstr, a char*, a number or an array of numbers"); if (len % w) die("the embedded file's size is not a whole number of elements"); count = (int)(len / w); @@ -880,18 +953,19 @@ static void top1(void) expect(";"); return; } if (accept("include")) { do { ident(); } while (accept(",")); expect(";"); return; } - if (accept("embed")) { embeddecl(); return; } + if (accept("embed")) { embeddecl(0); return; } { if (accept("unchecked")) { top1(); return; } - if (accept("fn")) { fndef(0); return; } - if (accept(".")) { if (strcmp(ident(), "u")) die("the only return tag is .u"); fndef(1); return; } /* .u name(...) */ + if (accept("fn")) { fndef(0, 0); return; } if (accept("const")) { optype(); do { char *n = ident(); if (dsn && !dnm[0]) strcpy(dnm, n); expect("="); add(n, K_CONST, cexpr()); } while (accept(",")); expect(";"); return; } if (accept("enhance")) { enhdef(); return; } { - int nw, typed, k, a, rt; - ptag = 0; nw = optype(); typed = nw >= 0; rt = ptag == 3; + int nw, typed, k, a, rt, gstr = 0; Sym *gs; + ptag = 0; nw = optype(); typed = nw >= 0; if (typed) gstr = ptstr; else ptag = 0; + if (!typed && is(".")) { next(); ptag = ptagname(); typed = 1; nw = 1; } /* .u name(...), or a bare tag on a global */ + rt = ptag == 3; if (typed || accept("let") || accept("var")) { - if (isfn()) { fndef(rt); return; } + if (isfn()) { if (ptag && !rt) die("the only return tag is .u"); fndef(rt, gstr); return; } do { char *n = ident(); if (dsn && !dnm[0]) strcpy(dnm, n); @@ -901,9 +975,10 @@ static void top1(void) if (k > 1) { a = here; while (k--) emit(0); add(n, K_GARR, a); } else { - a = here; add(n, K_GVAR, a); emit(0); + a = here; gs = add(n, K_GVAR, a); gs->str = gstr; emit(0); if (accept("=")) { if (tk == T_STR) { int i, l = (int)strlen(ts); img[a - GORG] = here; for (i = 0; i < l; i++) emit((unsigned char)ts[i]); emit(0); next(); } + else if (tk == T_BSTR) { int d = bstrwords((const unsigned char *)ts, (long)strlen(ts)); img[a - GORG] = d; gs->str = 1; next(); } else img[a - GORG] = cexpr(); } } diff --git a/tests/drivers/cli_help_test.py b/tests/drivers/cli_help_test.py index 97eebea..1231f74 100644 --- a/tests/drivers/cli_help_test.py +++ b/tests/drivers/cli_help_test.py @@ -14,7 +14,7 @@ commands = [] if args.group in ('binaries', 'all'): commands += [[str(Path(args.bin_dir) / name)] for name in ['zy', 'zym', 'zclsp', 'zc0', 'mkgenome', 'genmap']] if args.group in ('scripts', 'all'): - commands += [['bash', name] for name in ['tinyvm.sh', 'src/tools/zcc', 'src/tools/automap.sh', 'src/tools/findcc.sh', 'src/tools/bootstrap-check.sh', 'src/tools/mklsp.sh', 'src/tools/mklspwasm.sh', 'src/tools/mkvsix.sh', 'src/web/build.sh', 'src/baremetal/run.sh']] + commands += [['bash', name] for name in ['tinyvm.sh', 'src/tools/zcc', 'src/tools/automap.sh', 'src/tools/findcc.sh', 'src/tools/bootstrap-check.sh', 'src/tools/parity.sh', 'src/tools/mklsp.sh', 'src/tools/mklspwasm.sh', 'src/tools/mkvsix.sh', 'src/web/build.sh', 'src/baremetal/run.sh']] if args.group in ('js', 'all'): commands += [['node', name] for name in [str(Path(args.js_dir) / 'tinyvm.js'), 'src/js/mklayout.js', 'src/js/extract_lsp.js']] 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/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/parity.known b/tests/parity.known new file mode 100644 index 0000000..0a73eb3 --- /dev/null +++ b/tests/parity.known @@ -0,0 +1,15 @@ +# programs where zc0 and the self-hosted compiler print different things on purpose. +# src/tools/parity.sh still runs them and shows the difference as known, and it does +# not fail the run; when one starts to agree it says so, and its line can go. +# one program per line: the path, then # and the reason. +# +# zc0 reads types and ownership tags and throws them away. it has no ownership +# analysis and no memdebug checks, so it neither warns about, traps on nor frees what +# the self-hosted compiler does. +tests/programs/doublefree.zc # memdebug on: only the self-hosted compiler emits the double free check +tests/programs/scrub.zc # ownership: the analyzer warns about the use after free, zc0 runs it +tests/programs/uaf.zc # ownership: the analyzer warns about the use after free; zc0 prints nothing +tests/programs/uaf_in.zc # memdebug on: only the self-hosted compiler emits the use after free check +examples/lists.zc # ownership: the block's owner frees at its end, zc0 never frees +# the next program reads a local it never sets when stdin is empty, so it prints stack garbage +tests/programs/bench_strings.zc # reads the repeat count from stdin; with none, acc is uninitialized diff --git a/tests/programs/bareio.zc b/tests/programs/bareio.zc index a06ef38..21d2b40 100644 --- a/tests/programs/bareio.zc +++ b/tests/programs/bareio.zc @@ -2,7 +2,7 @@ namespace; include rt; // bare-metal syscalls: clock, a RAM file, random, and the machine size. -// zc0 subset, so a run-only image can carry it. names stay off u/m/d. +// zc0 subset, so a run-only image can carry it. fn main() { let buf[16], n, t0, t1, i, fd, r, board[8]; t0 = rt.syscall(6, 0, 0, 0); diff --git a/tests/programs/parity_ops.zc b/tests/programs/parity_ops.zc new file mode 100644 index 0000000..1c3c760 --- /dev/null +++ b/tests/programs/parity_ops.zc @@ -0,0 +1,102 @@ +// operator precedence and associativity, the same in both compilers. every binary +// operator is placed next to its neighbours in the table and between two of the same +// kind, so a wrong binding changes a printed number. src/tools/parity.sh compiles +// this program with zc0 and with the self-hosted compiler and compares the output. +// it stays inside zc0's subset: no ?: (zc0 has none), no types beyond int. +// +// the table, tightest first: unary - ! ~ * &, then * / %, + -, << >>, < > <= >=, +// == !=, &, ^, |, &&, ||, then the assignments, which group to the right. every +// binary operator groups to the left. the expected output follows the c rules and +// was checked by compiling the same expressions with a c compiler. +namespace; +include rt; + +int trace, calls; +int seen(int v) { calls++; trace = trace * 10 + v; return v; } +int id(int v) { return v; } +int out(int v) { rt.put_n(v); rt.put_c(32); return v; } +int endl() { rt.put_c(10); return 0; } + +int main() { + // operands the compilers cannot fold away + int a = id(2), b = id(3), c = id(4), e = id(5), z = id(0), one = id(1); + + // * / % against + -, and left grouping + out(a + b * c); out(a * b + c); out(a - b * c); out(a * b - c); out((a + b) * c); + out(id(100) - 30 - 20); out(1 - 2 + 3); out(id(100) / 5 / 2); out(id(20) / 3 * 3); + out(a * b % c); out(id(100) % 7 % 3); out(id(100) / 10 % 4); out(id(7) % 4 * 3); + endl(); + + // + - against << >>, and left grouping + out(one << a + one); out(id(32) >> a - one); out(one << a << b); out(id(256) >> a >> one); + out(one << b * a); out(id(8) >> one << one); + endl(); + + // shifts against < > <= >=, and the relational chain + out(one << a < e); out(id(16) >> one > 7); out(a < b < c); out(e > c > b); + out(z <= e <= z); out(a >= b >= z); + endl(); + + // relations against == !=, and the equality chain + out(a < b == one); out(one == a > b); out(e == e == one); out(b != c != one); + out(id(3) > a == one < a); + endl(); + + // == against & ^ | + out(c & c == c); out(one | a == a); out(b ^ b == b); out(a == a & one); out(c != z | z); + endl(); + + // & ^ | against each other, and against + and << + out(c | b & one); out(id(7) ^ e & b); out(one | 6 ^ b); out(id(6) & b | 8); + out(a + 6 & c); out(one & b << one); out(id(12) | one << a); + endl(); + + // && and || against | & and each other; the result of both is 0 or 1 + out(one || z && z); out(z && z || one); out(z || one && one || z); out(z && one | one); + out(one || z & z); out(b && c); out(b & c); out(z || id(9)); out(id(7) && id(8) && z); + out(a < b && c < e || z); out(z == z || z && z); + endl(); + + // unary operators + out(-a * b); out(- -b); out(-a + e); out(!z + one); out(!a == z); out(!!id(7)); + out(~z & 255); out(~one + one); out(~a & 7); out(-a * -b); out(a - -b); out(-id(7) % 4); + out(!(a < b) + one); out(*&a + one); out(-*&b); + endl(); + + // assignment groups to the right and takes the whole expression on its right + int x, y, w; + x = y = w = id(7); out(x); out(y); out(w); + x = id(10); x -= 3 - 1; out(x); + x *= a + b; out(x); + x <<= one + one; out(x); + x |= one << b; out(x); + x += y -= 2; out(x); out(y); + x = id(100); x /= a * b; out(x); + x %= 7 - 2; out(x); + x = id(6); x &= 3 | 8; out(x); + x ^= 1 + 2 * 3; out(x); + x = id(255); x >>= 2 + 2; out(x); + endl(); + + // division, remainder and shifts of negative numbers + out(id(0) - 7 / 2); out((id(0) - 7) / 2); out((id(0) - 7) % 3); out(id(7) % (id(0) - 3)); + out((id(0) - 8) >> 1); out((id(0) - 8) << 1); + endl(); + + // short circuit: how many operands ran, and in what order + calls = 0; trace = 0; x = seen(0) && seen(1); out(x); out(calls); out(trace); + calls = 0; trace = 0; x = seen(1) || seen(2); out(x); out(calls); out(trace); + calls = 0; trace = 0; x = seen(1) || seen(2) && seen(3); out(x); out(calls); out(trace); + calls = 0; trace = 0; x = seen(0) || seen(2) && seen(3); out(x); out(calls); out(trace); + calls = 0; trace = 0; x = seen(0) && seen(2) || seen(3); out(x); out(calls); out(trace); + calls = 0; trace = 0; x = seen(1) && seen(0) || seen(2) && seen(3); out(x); out(calls); out(trace); + calls = 0; trace = 0; x = seen(1) | seen(2) && seen(0) & seen(3); out(x); out(calls); out(trace); + endl(); + + // operands run left to right whatever their binding + calls = 0; trace = 0; x = seen(1) + seen(2) * seen(3) - seen(4); out(x); out(calls); out(trace); + calls = 0; trace = 0; x = seen(1) << seen(2) < seen(3) == seen(4); out(x); out(calls); out(trace); + calls = 0; trace = 0; x = out(seen(1) - seen(2)) * out(seen(3)); out(x); out(calls); out(trace); + endl(); + 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/programs/zc0bstr.zc b/tests/programs/zc0bstr.zc new file mode 100644 index 0000000..bb4ffbc --- /dev/null +++ b/tests/programs/zc0bstr.zc @@ -0,0 +1,96 @@ +namespace; +include rt; + +// packed byte strings in the zc0 subset: the same program runs on the resident +// compiler and, built into a run-only image, on stage 0 (src/tools/zc0.c). it +// covers every b"..." escape, the packed layout, bstr locals, globals, +// parameters and returns, + and the six comparisons, indexing, slicing, len +// and embed. run from the repository root: the embeds read tests/data/embed. + +bstr greeting = b"hello"; +bstr shout; +bstr plain = b"plain"; +embed "tests/data/embed/text.txt" as bstr text; +embed "tests/data/embed/nul.bin" as bstr nul; +embed "tests/data/embed/text.txt" as untyped; + +bstr tag(bstr s) { return b"<" + s + b">"; } +bstr twice(bstr s); +bstr twice(bstr s) { return s + s; } +bstr pick(int n) { + bstr r; + if (n) r = b"yes"; else r = b"no"; + return r; +} +int rank(bstr a, bstr b) { return (a < b) * 8 + (a <= b) * 4 + (a == b) * 2 + (a > b); } +int count(bstr s, int c) { + int n = 0, i = 0; + while (i < len(s)) { if (s[i] == c) n++; i++; } + return n; +} +int num(int n) { rt.put_n(n); rt.put_c(32); return 0; } +int nl() { rt.put_c(10); return 0; } +int bytes(bstr s) { + int i = 0; + num(len(s)); + while (i < len(s)) { num(s[i]); i++; } + nl(); + return 0; +} +int words(bstr s) { + word* w = rt.bstr_storage(s); + int n = 1 + (w[0] >> 3) + 1, i = 0; + while (i < n) { num(w[i]); i++; } + nl(); + return 0; +} + +fn main() { + bstr a = b"abc", b, c; + bstr e = b""; + let u = b"x"; + // every escape the lexer knows: n t r 0 e, and any other character stands for itself + bytes(b"\n\t\r\e\\\"\'\q\x41"); + bytes(b"ab\0cd"); + bytes(b"\0"); + bytes(b"café"); + bytes(b"caf\303\251"); + bytes(b"quote \" inside, 'single', back\\slash"); + // the layout: a length word, bytes packed 8 to a word, a 0 word after a full last word + words(e); + words(b"a"); + words(b"abcdefg"); + words(b"abcdefgh"); + words(b"abcdefghi"); + words(b"0123456789abcdef"); + words(b"0123456789abcdefg"); + words(text); + words(nul); + // declarations, assignment later, a return value, concatenation + b = tag(a); + c = twice(b) + e + u; + rt.put_s(a); rt.put_c(32); rt.put_s(b); rt.put_c(32); rt.put_s(c); nl(); + shout = twice(greeting) + b"!"; + rt.put_s(greeting); rt.put_c(32); rt.put_s(shout); rt.put_c(32); rt.put_s(plain); nl(); + rt.put_s(tag(twice(tag(b"z")))); nl(); + rt.put_s(pick(1) + b"/" + pick(0)); nl(); + // comparisons: below, equal, above, a prefix, the empty string, a 9 byte string + num(rank(b"abc", b"abd")); num(rank(b"abc", b"abc")); num(rank(b"abd", b"abc")); + num(rank(b"ab", b"abc")); num(rank(b"", b"")); num(rank(b"", b"a")); + num(rank(b"abcdefghi", b"abcdefghi")); num(rank(b"abcdefgh", b"abcdefghi")); nl(); + num(a == b"abc"); num(a != b"abc"); num(a == b); num(a != b); + num(tag(a) == b"<abc>"); num(shout > greeting); num(greeting >= shout); num(plain <= plain); nl(); + // indexing, slicing, len + num(a[0]); num(a[2]); num(a[3]); num(len(a)); num(len(e)); num(len(c)); num(len(b"123456789")); nl(); + rt.put_s(c[1:4]); rt.put_c(32); rt.put_s(a[1:2]); rt.put_c(32); rt.put_s(a[0:0]); rt.put_c('|'); + rt.put_s(a[2:99]); rt.put_c('|'); rt.put_s(a[3:1]); rt.put_c('|'); rt.put_s((a + a)[2:4]); nl(); + num(count(c, '<')); num(count(shout, 'l')); num(count(b"mississippi", 's')); num(count(e, 'x')); nl(); + num(b"xyz"[1]); num(len(b"xyz")); num(len(a + a + a)); num(len(tag(e))); nl(); + // embed: a global of the file's bytes, with or without the type, and a local + rt.put_s(text); num(len(text)); num(text[0]); num(text == untyped); num(len(nul)); num(nul[2]); nl(); + embed "tests/data/embed/text.txt" as bstr here; + embed "tests/data/embed/answer.bin" as int answer; + embed "tests/data/embed/text.txt" as char* chars; + rt.put_s(here + b"|" + untyped); num(len(here)); num(here == text); num(answer); num(chars[6]); nl(); + return 0; +} diff --git a/tests/programs/zc0umd.zc b/tests/programs/zc0umd.zc new file mode 100644 index 0000000..9693111 --- /dev/null +++ b/tests/programs/zc0umd.zc @@ -0,0 +1,58 @@ +namespace; +include rt; + +// u, m and d are ordinary names, and a tag is written .u, .m or .d after a type. +// u*x, m*x and d*x with no space before the star is a recast, and u * x with a +// space is a product. the same program runs on the resident compiler and, built +// into a run-only image, on stage 0 (src/tools/zc0.c), which reads the tags and +// recasts and does nothing with them. + +int u = 2, m = 3; // globals +int[4] d4; +int d(int x) { return x + 1; } // a function + +int mul3(int u, int m, int d) { return u * m * d; } // parameters +int mixed(int.d u, int m, int d) { return u * m - d; } +int tagged(int(int) f, int.m x) { return f(x); } + +// owned objects through locals named for their tags +word*.u box(int v) { word* m = rt.new(2); m[0] = v; m[1] = v * 2; return u*m; } +word*.u pair(int u, int m) { + word* d = rt.new(2); + d[0] = u; d[1] = m; + return u*d; +} +.u single(int v) { let u = rt.new(1); u[0] = v; return u*u; } +int sum(word*.m m) { return m[0] + m[1]; } +int eat(word*.d d) { return d[0] + d[1]; } +int hold(.m u, .d d) { return u[0] * 100 + d[0]; } +int dig(word*.m u) { int m = u[0], d = u[1]; return m * 10 + d; } + +fn main() { + int a = 4, b = 5; + int.m n = 9; + word*.m p = box(7); + .m q = single(6); + word* r = pair(8, 9); + let c = box(10), e = pair(1, 2); + rt.put_n(u * m); rt.put_c(32); // two globals multiplied + rt.put_n(u*=m); rt.put_c(32); // u *= m is not a recast either + rt.put_n(d(u) * d(m)); rt.put_c(32); + rt.put_n(mul3(2, 3, 4)); rt.put_c(32); + rt.put_n(mixed(7, 6, 5)); rt.put_c(32); + rt.put_n(tagged(d, n)); rt.put_c(10); + { + int u = 6, m = 7, d = 8; // locals shadow the globals + rt.put_n(u * m); rt.put_c(32); + rt.put_n(u * d - m); rt.put_c(32); + rt.put_n(m * u * d); rt.put_c(32); + rt.put_n(a * u + m * b); rt.put_c(10); + } + rt.put_n(sum(p)); rt.put_c(32); + rt.put_n(q[0]); rt.put_c(32); + rt.put_n(r[0] * r[1]); rt.put_c(32); + rt.put_n(dig(c)); rt.put_c(32); + rt.put_n(hold(e, single(5))); rt.put_c(32); + rt.put_n(eat(d*p)); rt.put_c(10); + return 0; +} diff --git a/tests/test.sh b/tests/test.sh index 7ae7b9d..223c9aa 100755 --- a/tests/test.sh +++ b/tests/test.sh @@ -102,10 +102,12 @@ run(){ # $1 = vm command, $2 = label chk "$($vm < tests/programs/basics.zc | tr '\n' '/')" "285 610 42 512/hey 65 -3 -2 1024 -8/12456/757/9 100-101/5/ok/" "$l language basics" chk "$($vm < tests/programs/umd.zc)" "100 6 0 15 99 5 5" "$l u m d lifetimes" chk "$($vm < tests/programs/names.zc)" "12 1 8" "$l u, m and d are ordinary names" + chk "$($vm < tests/programs/zc0umd.zc | tr '\n' '/')" "6 6 28 24 37 10/42 41 336 59/21 6 72 120 105 21/" "$l u, m and d as names, products, recasts and tags (the zc0 subset)" chk "$($vm < tests/programs/gc.zc)" "1000 1 900 1 199900" "$l mark-sweep collector" 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" @@ -357,6 +359,9 @@ s_runonly() { runonly strings-ex examples/strings.zc runonly share tests/programs/share.zc runonly embed tests/programs/embed_top.zc + runonly zc0bstr tests/programs/zc0bstr.zc + runonly zc0umd tests/programs/zc0umd.zc + runonly wiring examples/wiring.zc d=$T/run-echo; GENMAP=$T/genmap bash src/tools/automap.sh run $d src/runtime/run.zc examples/echo.zc >/dev/null && cp src/micro/micro.c src/micro/micro_port.h src/micro/port_linux.c src/micro/port_stub.c src/core/fops.h src/core/bops.h src/core/stack.h src/core/genome.h $d/ \ && $CC -pthread -DZY_THREADS -O2 -w -fwrapv $d/micro.c $d/port_linux.c -o $T/zymr \ && chk "$(printf 'abc\n' | $T/zymr | tr '\n' '/')" "$( (cat examples/echo.zc; printf '`abc\n') | $T/zy | tr '\n' '/')" "run echo" \ 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; } |
