nish 0.20.0 → 0.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.md +23 -59
  2. package/docs/AI.md +74 -9
  3. package/docs/INSTALL.md +52 -10
  4. package/llms.txt +1 -1
  5. package/package.json +20 -5
  6. package/runtime/browser.d.ts +6 -0
  7. package/runtime/browser.mjs +77 -0
  8. package/runtime/core/arrays.d.ts +36 -0
  9. package/runtime/core/arrays.mjs +153 -0
  10. package/runtime/core/checks.mjs +20 -0
  11. package/runtime/core/host.d.ts +80 -0
  12. package/runtime/core/host.mjs +325 -0
  13. package/runtime/core/numbers.d.ts +66 -0
  14. package/runtime/core/numbers.mjs +343 -0
  15. package/runtime/core/result.d.ts +45 -0
  16. package/runtime/core/result.mjs +140 -0
  17. package/runtime/core/strings.d.ts +14 -0
  18. package/runtime/core/strings.mjs +169 -0
  19. package/runtime/core.d.ts +9 -0
  20. package/runtime/core.mjs +55 -0
  21. package/runtime/host.d.ts +6 -0
  22. package/runtime/nish.d.ts +46 -2
  23. package/runtime/nish.h +75 -2
  24. package/runtime/nish.mjs +23 -3
  25. package/runtime/node.mjs +386 -0
  26. package/runtime/runtime-bytes.c +401 -0
  27. package/runtime/runtime-cross.c +1 -1
  28. package/runtime/runtime-host.c +1 -1
  29. package/runtime/runtime-net.c +12 -1
  30. package/runtime/runtime-os.c +1 -1
  31. package/runtime/runtime-parallel.c +1 -1
  32. package/runtime/runtime-simd.c +231 -7
  33. package/runtime/runtime-term.c +504 -0
  34. package/runtime/runtime-wasm.c +0 -11
  35. package/runtime/runtime.c +190 -6
  36. package/runtime/shim.mjs +6 -985
  37. package/runtime/sqlite/LICENSE.md +85 -0
  38. package/runtime/sqlite/README.md +45 -0
  39. package/runtime/sqlite/nish-sqlite.c +359 -0
  40. package/runtime/sqlite/sqlite3.c +271131 -0
  41. package/runtime/sqlite/sqlite3.h +14447 -0
  42. package/scripts/build.sh +311 -59
  43. package/scripts/check-hardening.mjs +202 -0
  44. package/scripts/fuzz.sh +218 -0
  45. package/scripts/gen-json-pow5.mjs +130 -0
  46. package/scripts/platform-package.mjs +3 -1
  47. package/scripts/security-scope.mjs +139 -0
  48. package/scripts/smoke.sh +3 -2
  49. package/std/LICENSE-fast-float +23 -0
  50. package/std/LICENSE-fdlibm +8 -0
  51. package/std/README.md +32 -12
  52. package/std/base64.ts +116 -0
  53. package/std/bytes.ts +256 -0
  54. package/std/cli.ts +344 -0
  55. package/std/collections.ts +6 -5
  56. package/std/crypto/LICENSE-crypt_blowfish +26 -0
  57. package/std/crypto/base64url.ts +125 -0
  58. package/std/crypto/bcrypt.ts +1557 -0
  59. package/std/crypto/hmac.ts +138 -2
  60. package/std/crypto/x509.ts +11 -122
  61. package/std/json-tokenizer.ts +2998 -57
  62. package/std/json-value.ts +22 -3
  63. package/std/json.ts +87 -8
  64. package/std/math.ts +608 -0
  65. package/std/net/http1-server.ts +282 -40
  66. package/std/net/http1.ts +40 -21
  67. package/std/net/http3-server.ts +50 -12
  68. package/std/net/postgres.ts +2294 -0
  69. package/std/net/prefork.ts +23 -3
  70. package/std/net/quic-listener.ts +20 -4
  71. package/std/random.ts +66 -4
  72. package/std/regex.ts +4274 -0
  73. package/std/sqlite.ts +391 -0
  74. package/std/term-io.ts +978 -0
  75. package/std/term-pixels.ts +874 -0
  76. package/std/term-probe.ts +459 -0
  77. package/std/term-rate.ts +993 -0
  78. package/std/term.ts +2453 -0
  79. package/std/text.ts +90 -7
  80. package/std/yaml-lines.ts +141 -0
  81. package/std/yaml.ts +4675 -0
package/README.md CHANGED
@@ -332,64 +332,23 @@ buys is the output: no GC, no runtime, and the sizes under
332
332
  ## Command line
333
333
 
334
334
  ```
335
- nish <entry.ts> [more.ts ...] [options]
336
- nish run [options] <file.ts> [args ...]
337
- nish --version | --help
338
- -o, --output <file.ll> output path for a single module (default: <input>.ll)
339
- -o, --output <dir>/ output directory: one <dir>/<module>.ll per module
340
- --link <exe> build a native binary from every module + runtime/runtime.c
341
- (entry module must declare `export const main`)
342
- --profile speed|size|debug|wasi
343
- build profile for --link (default: speed; wasi: a wasm32-wasi module)
344
- --cpu x86-64-v3 link module and runtime for x86-64-v3 (AVX2, BMI2, FMA); the one level
345
- --fix apply every machine-applicable fix to the named files, then report
346
- what is left (writes no IR)
347
- --no-strict-exports every function is an external symbol (default: non-exported
348
- functions get `internal` linkage)
349
- --number-mode i32|f64 lowering of `number` (default: i32)
350
- --plain no performance attributes or alignment hints
351
- --runtime-decls always emit the runtime ABI prelude (arena + strings)
352
- --emit-header <file.h> also write a C header for the callable functions
353
- --emit-dts <file.d.ts> also write TypeScript declarations for the wasm exports, plus
354
- <file>.mjs, a loader that marshals typed arrays
355
- --emit-napi <shim.c> also write an N-API shim (build with --profile napi)
356
- --emit-napi-async <shim.c> the same shim plus a promise-returning form of each export, run off
357
- the event loop
358
- --emit-panics <file.json> also write every panic site, per function, proven or not
359
- --deny-panics refuse every panic site of the entry package a proof does not remove
360
- --deny-retention refuse arena memory the entry package keeps after nothing can reach it
361
- --emit-arena <file.json> also write every allocation site and where its memory goes
362
- --emit-capabilities <file.json>
363
- also write the capabilities (fs, net, clock, ...) each function reaches
364
- --capabilities print the program's capabilities in one line on stderr
365
- --allow <cap>[,<cap>...] refuse a program whose entry reaches a capability not listed
366
- --deny <cap>[,<cap>...] refuse a program whose entry reaches a listed capability
367
- --unchecked-indexing deprecated: drop the bounds checks of the entry package's modules
368
- (use uncheckedGet/uncheckedSet from nish:unsafe)
369
- --target <triple>|host emit `target datalayout`/`target triple` for that machine
370
- (x86_64-unknown-linux-gnu, aarch64-unknown-linux-gnu, x86_64-apple-darwin,
371
- aarch64-apple-darwin, wasm32-unknown-unknown, wasm32-wasi); default: target-neutral IR
372
- --wrapping deprecated: signed add/sub/mul of the entry package's modules wrap
373
- (default: an operation not proven to fit is checked and panics on
374
- overflow; use wrappingAdd/wrappingSub/wrappingMul from nish:unsafe)
375
- --no-stack-alloc keep every allocation in the arena (disables escape-analysed allocas)
376
- --threads give every thread its own arena and random seed; the runtime is
377
- built to match by --link (importing nish/threads turns it on)
378
- --no-warn-performance do not report the `performance` diagnostics (they are on by default,
379
- print on stderr, and never change the exit code)
380
- --warn-portability report the `portability` diagnostics: where the program's TypeScript
381
- reading answers differently (off by default; never changes the exit code)
382
- -g emit DWARF debug info (!dbg locations, variables); kept by --link
383
- --json print diagnostics as one JSON object per line on stdout (no excerpt)
384
- --emit-ast print the syntax tree of every module to stdout instead of IR
385
- --emit-checked print the checker's tables (signatures, locals, structs, facts) instead of IR
386
- -v, --version print the nish version and exit
387
- -h, --help print the usage on stdout and exit 0
335
+ usage: nish <file.ts> [more.ts ...] [flags] compile to LLVM IR
336
+ nish run [flags] <file.ts> [args ...] build, cache and run it
337
+ nish -v, --version | -h, --help
388
338
  ```
389
339
 
340
+ `nish --help` prints every flag, grouped by what it is for (Build, Check,
341
+ Capabilities, Interop, Inspect, Code generation), then the exit codes and a
342
+ few examples; it is coloured on a terminal and plain when piped, under
343
+ `NO_COLOR` or when a coding agent runs it. An unknown flag is refused in one
344
+ line that points at `--help`. [The CLI](docs/guide/using-nish/cli.md) walks
345
+ through the flags you will reach for.
346
+
390
347
  Exit codes: `0` success, `1` compile error (`file:line:col: error: ...` plus
391
348
  a caret excerpt), `2` usage error, `3` toolchain error, `70` internal
392
- compiler error (please report it; `NISH_DEBUG=1` adds the stack trace).
349
+ compiler error (please
350
+ [report it](https://github.com/amritk/nish/issues/new/choose) with the input and
351
+ the command line).
393
352
  A compile that fails reports every error it found (statement by statement,
394
353
  declaration by declaration), in source order, up to 20 before `...and N more
395
354
  errors`; `--json` gives editors and tools the same list as
@@ -455,7 +414,7 @@ dynamically linked (`npm run size-report`):
455
414
  | `wasm` | 279 | Freestanding `wasm32` module, every function exported, stripped. |
456
415
  | `wasi` | 42,228 (`argv.ts`) | `wasm32-wasi` command module: the runtime linked against wasi-libc, `_start` runs `main`; needs a WASI sysroot ([INSTALL.md](docs/INSTALL.md#wasi-optional-for---profile-wasi)). |
457
416
 
458
- `hello.ts` with `--link` is 4,712 bytes. The runtime is eight translation units
417
+ `hello.ts` with `--link` is 4,712 bytes. The runtime is ten translation units
459
418
  with a measured ceiling each, so that the core does not grow every time the
460
419
  language reaches further into the operating system, and section GC drops
461
420
  whatever a program does not call: `runtime.c` is the 3,606 bytes every program
@@ -464,10 +423,11 @@ JavaScript-exact number formatting, string parsing, `Math.random`,
464
423
  `process.argv`, array growth, the panic paths), `runtime-os.c` the 1,530 bytes
465
424
  that wrap a system call (exit, files, directories, subprocesses, the
466
425
  environment, the clock), and `runtime-parallel.c`, `runtime-cross.c`,
467
- `runtime-host.c`, `runtime-net.c`, `runtime-simd.c` and `runtime-aes.c` hold
468
- threads, the copies that cross between their arenas, the host calls (wall
469
- clock, entropy, signals), `nish:net`'s sockets, the vector text search and
470
- AES-GCM — see
426
+ `runtime-host.c`, `runtime-net.c`, `runtime-simd.c`, `runtime-aes.c`,
427
+ `runtime-term.c` and `runtime-bytes.c` hold threads, the copies that cross between
428
+ their arenas, the host calls (wall clock, entropy, signals), `nish:net`'s sockets,
429
+ the vector text search, AES-GCM, `nish:term`'s stdin and terminal and the
430
+ byte-class runs JSON steps over — see
471
431
  [docs/wp7-runtime.md](docs/wp7-runtime.md#runtime-additions-and-budget) for the
472
432
  budgets and the reasoning. `Math.*` calls are LLVM intrinsics, so pure functions
473
433
  stay `readnone`.
@@ -522,6 +482,10 @@ The supported direction is Node importing Nish:
522
482
  `double sumF64(const nish_array *xs);`) next to `runtime/nish.h`, the
523
483
  public runtime ABI (arena, strings, arrays, `nish_reset_arena`,
524
484
  `nish_arena_mark` / `nish_arena_release` for a host that manages batches).
485
+ - `--emit-ts <dir>` writes the program back out as TypeScript that Node 22.18+
486
+ runs with type stripping, one file per module plus an `entry.ts`, importing
487
+ its builtins from `nish/runtime`; overflow and bounds checks stay, as
488
+ helpers (`docs/guide/using-nish/to-typescript.md`).
525
489
  - An N-API call costs about 30 ns and a wasm call about 2 ns before any work
526
490
  is done; one call with a 1M-element `Float64Array` runs at 0.5 ns/element
527
491
  (`node bench/ffi.mjs`), so pass whole buffers, not elements.
package/docs/AI.md CHANGED
@@ -40,7 +40,8 @@ nish program.ts -o out.ll # emit LLVM IR
40
40
  nish program.ts --link prog # build a native binary (needs clang)
41
41
  nish run program.ts a b # build into a cache, then run it with `a b`
42
42
  # (the C runtime is cached too: ~/.cache/nish/runtime)
43
- nish --help # the full flag list, stdout, exit 0
43
+ nish --help # the full flag list, stdout, exit 0; plain text
44
+ # under an agent (NISH_AGENT=1, CLAUDECODE, GEMINI_CLI)
44
45
  ```
45
46
 
46
47
  `--json` is the surface to automate against. One flat object per line on
@@ -92,6 +93,24 @@ compiles and the warning would be printed: `NL9007`'s inserts the guard that
92
93
  proves an index in range (not under `--no-warn-performance`), and `NL7002`'s
93
94
  migrates a site off `--unchecked-indexing` (below).
94
95
 
96
+ When it compiles, **check the native build against the program's TypeScript
97
+ reading**. Run the project's tests natively; where it has none, write the
98
+ program back out and run both:
99
+
100
+ ```bash
101
+ nish program.ts --emit-ts out/ # the program as TypeScript, plus out/entry.ts
102
+ node out/entry.ts # Node 22.18 or newer; compare with the binary
103
+ ```
104
+
105
+ The two must print the same and exit the same, a panic included: `--emit-ts`
106
+ keeps the overflow and bounds checks the native build makes, but not a ranged
107
+ integer's range (`integer<0, 255>` is a plain `number`). Where they differ,
108
+ the difference is a row of [the user guide's table](guide/using-nish/to-typescript.md),
109
+ or a bug in `nish` worth reporting. A program on `nish:net`, the signal
110
+ descriptor or a C declaration (NL4010, NL4011), a compound assignment whose
111
+ index would run twice (NL4012) or a generic whose element type decides its
112
+ code (NL4013, NL4014) is refused and has no TypeScript to run.
113
+
95
114
  Two more surfaces worth knowing: `nish --emit-ast f.ts` prints what was parsed
96
115
  and `nish --emit-checked f.ts` prints the side tables the emitter reads. Both
97
116
  are one node per line, which is to say diffable.
@@ -178,7 +197,7 @@ rejects. This table is the highest-value part of the page.
178
197
  | `import d from "./m"`, `import * as m from "./m"`, `import "./m"`, `import type { T } from "./m"` | `` Default imports are not supported; use `import { d } from "./m"` `` / `` Namespace imports (`import * as m`) are not supported; import functions by name `` / `` Side-effect imports (`import "./m"`) are not supported; modules have no top-level code `` / `Type-only imports are not supported` | `import { d, T } from "./m"`, naming what you use |
179
198
  | `total += xs[i]` in a loop, with `i` from somewhere the compiler cannot bound | it compiles, with an `NL9007` performance warning: `` `i` is not proven to be in range for `xs` here, so this access keeps its bounds check `` | a guard before the statement, `if (!(i >= 0 && i < toI32(xs.length))) { panic("index out of range") }`, which proves both ends in either number mode; `nish --fix` inserts it where it changes nothing the program does |
180
199
  | `new Date()` | `` `new Date()` is refused: Nish has no `Date` object; the one `Date` member is `Date.now()`, the wall clock in milliseconds `` | `Date.now()` for the wall clock, `monotonicNanos()` for elapsed time; there is no calendar |
181
- | `JSON.parse`, `RegExp`, `Promise` | unknown / forbidden | none of these exist; write them or restructure |
200
+ | `JSON.parse`, `RegExp`, `/re/` literals, `Promise` | unknown / forbidden | none of these are built in: `regexCompile(pattern, flags)` from `nish/regex` for a pattern, `jsonDecode` from `nish/json-typed` for JSON; restructure around `Promise` |
182
201
  | `for (const [k, v] of m)`, `m.forEach(...)`, `new Map(entries)` | each refused by name | `Map` and `Set` exist, with `size`, `get`, `set` / `add`, `has`, `delete`, `clear`, and `keys()` / `values()` in a `for...of` — see [Map and Set](#map-and-set) |
183
202
  | `let v = m.get(k)`, `f(m.get(k))`, `m.get(k) + 1` | `` `m.get(k)` is `i32 \| undefined` and cannot be held in a `let` `` (and one message per place) | `m.get(k) ?? 0`, or `const v = m.get(k); if (v !== undefined) { … }` |
184
203
  | `let x = 5; x = "s"` | `Cannot initialize …` | types never change and never convert implicitly |
@@ -1303,8 +1322,10 @@ export const main = (): i32 => {
1303
1322
  ### Calling C
1304
1323
 
1305
1324
  `declare function name(params): T;` declares a C function this program calls but
1306
- does not define. The symbol is the identifier, unmangled, and the call is an
1307
- ordinary call.
1325
+ does not define. The symbol is the identifier, unmangled, in any package
1326
+ (a package's own functions are prefixed, its declarations are not), and the
1327
+ call is an ordinary call. Two declarations of one name must have the same
1328
+ types.
1308
1329
 
1309
1330
  ```ts nish:ok
1310
1331
  declare function abs(n: i32): i32;
@@ -1400,6 +1421,17 @@ export const main = (): i32 => {
1400
1421
  ```
1401
1422
 
1402
1423
  - **No body, and it cannot be `export`ed.**
1424
+ - **A class with a `CPtr` field is a handle class: open one with `using`.**
1425
+ `using f = new File(p)` closes `f` once at every exit of its block (falling
1426
+ off the end, `return`, `break`, `continue`, `orReturn()`), so never call the
1427
+ close yourself. The class is checked: one `readonly` `CPtr` or
1428
+ `CPtr | null` field written once by the constructor's foreign call, read only
1429
+ as `this.f` in its own methods, and a `[Symbol.dispose]` that is exactly the
1430
+ close. A handle is never copied, stored, returned or captured: it is called
1431
+ or lent to a parameter of its type, and `new` of one appears only as a
1432
+ `using` initialiser. A panic or `process.exit` does not close it, so
1433
+ `fflush` a written `FILE *` before code that may panic. The rules:
1434
+ `LANGUAGE.md` → "A handle class".
1403
1435
  - **It costs the caller its attributes.** Nothing about a body the compiler
1404
1436
  cannot see is provable, so a function that calls C loses `readnone` and
1405
1437
  `willreturn`, and so does everything above it in the call graph. A program
@@ -2096,7 +2128,10 @@ method there is. `substring` **clamps** an out-of-range offset the
2096
2128
  way JavaScript does; `slice` instead **panics** unless
2097
2129
  `0 <= start <= end <= s.length`, and is the faster of the two when you have
2098
2130
  already established the range. Every offset is a **byte** offset, so cutting a multi-byte character
2099
- in half is possible.
2131
+ in half is possible. To count characters rather than bytes, `codePointLength(s)`
2132
+ from `nish/text` counts code points natively and, for text written in the
2133
+ source, under Node alike; under Node a string built from bytes (`String.fromBytes`,
2134
+ a `\u` escape `nish/json` decodes) is one unit per byte, and counts its bytes.
2100
2135
 
2101
2136
  **Process.** `process.exit(code)`, `process.argv` (a read-only `string[]`;
2102
2137
  `argv[0]` is the program path, one index earlier than Node),
@@ -2520,6 +2555,20 @@ never call it on secret data, because its time says where the match is.
2520
2555
  (No block: a program importing `nish/text` writes two `.ll` files;
2521
2556
  `tests/link/std_text_index_of_any` is its program.)
2522
2557
 
2558
+ **Match a pattern** — there is no `RegExp` and no `/re/` literal:
2559
+ `regexCompile(pattern, flags)` from `nish/regex` answers a
2560
+ `Result<Regex, string>`, the error text naming the byte. The syntax is
2561
+ JavaScript's with the `u` flag's strictness (a stray `{` or `]` is an
2562
+ error), the flags are `i`, `m` and `s`, and backreferences and lookaround are
2563
+ refused, because matching never backtracks: time is linear in the input for
2564
+ every pattern. `test`, `exec(text, from, m)` into a reused `RegexMatch`,
2565
+ `find`, `findAll`, `count`, `replace`, `replaceAll` (`$&`, `$1`,
2566
+ `$<name>`) and `split`; offsets are UTF-8 bytes and `\w`, `\d`, `\b` and `i`
2567
+ are ASCII. A `Regex` keeps its scratch memory, so compile once outside the
2568
+ loop and use it from one thread. (No block, as for `nish/text`;
2569
+ `tests/link/std_regex` is its program, and the user guide's [standard-library
2570
+ page](guide/using-nish/standard-library.md#nishregex) its walk-through.)
2571
+
2523
2572
  **Decode a URL or read a query** — there is no `decodeURIComponent` and no
2524
2573
  `URLSearchParams`: `nish/net/url` has both readings. `urlDecode(s, flags)` and
2525
2574
  `urlQueryGet(target, name)` answer a `string | null`; the byte API
@@ -2535,6 +2584,20 @@ most 100 pairs. (No block, as for `nish/text`; `tests/link/std_url` is its
2535
2584
  program, and the user guide's [standard-library
2536
2585
  page](guide/using-nish/standard-library.md#nishneturl) its walk-through.)
2537
2586
 
2587
+ **Draw to the whole terminal** (a game, a dashboard) — there is no curses and
2588
+ no `process.stdout.on("resize")`: `runTerminal(options, state, update, render)`
2589
+ from `nish/term-io` opens the terminal, probes what it can draw, steps
2590
+ `update(state, input)` at `options.stepsPerSecond` and calls
2591
+ `render(state, frame)` only when the link to the terminal has room, then
2592
+ leaves the terminal as it was, even on a panic. Draw cells on `frame.screen`
2593
+ or pixels on `frame.framebuffer` (sized by `options.framebufferWidth` and
2594
+ `framebufferHeight`) and never pick a backend: kitty graphics, Sixel, half
2595
+ blocks or ASCII is chosen from the probe and the measured link. It answers
2596
+ `Err` with one sentence on a pipe, so test the `Result`; it reaches `tty`.
2597
+ `NISH_TERM_GRAPHICS` and `NISH_TERM_FPS` override what it picked. (No block,
2598
+ as for `nish/text`; `examples/term-probe.ts` is its program, and the user
2599
+ guide's [terminal page](guide/using-nish/terminal.md) its walk-through.)
2600
+
2538
2601
  **Shared behaviour over several shapes** — there is no inheritance and no
2539
2602
  dispatch. Give each class the interface's fields **first**, `implements` it,
2540
2603
  and write a free function over the interface:
@@ -2702,10 +2765,12 @@ Run it. `nish file.ts --json` is one command and it is the only proof.
2702
2765
  prove is an error
2703
2766
  naming the guard ([Proving it cannot panic](#proving-it-cannot-panic)); an
2704
2767
  `uncheckedGet` or `uncheckedSet` behind its `nish:unsafe` import is allowed.
2705
- 11. If you are adding to this repository: `npm run check` and `npm test` green,
2706
- and a new construct ships a golden `.ll`, an `llvm-as` pass, a native round
2707
- trip, a negative test, its `LANGUAGE.md` rule and cookbook entry, and a
2708
- conventional commit message, which is its changelog entry.
2768
+ 11. If you are adding to this repository: `npm run check` and the touched
2769
+ `node tests/run.js` sections green locally, every CI `test` shard green
2770
+ ([CLAUDE.md](../CLAUDE.md#definition-of-done)), and a new construct ships a
2771
+ golden `.ll`, an `llvm-as` pass, a native round trip, a negative test, its
2772
+ `LANGUAGE.md` rule and cookbook entry, and a conventional commit message,
2773
+ which is its changelog entry.
2709
2774
 
2710
2775
  Every `ts nish:ok` and `ts nish:err` block on this page is compiled by
2711
2776
  `npm test`, so an example that has gone stale is a failing test rather than a
package/docs/INSTALL.md CHANGED
@@ -143,6 +143,36 @@ for — which catches a truncated download, a tarball built for another
143
143
  architecture, and an asset whose name does not match what is inside it — and
144
144
  only then swapped in. If any of that fails the install you had is untouched.
145
145
 
146
+ **Every download is checked before it is unpacked.** install.sh compares the
147
+ tarball's SHA-256 with the release's `SHA256SUMS` (or with the digest pinned
148
+ for releases that predate it) and refuses a mismatch. For releases after
149
+ 0.21.0 it also checks the release's **build provenance attestation** when a
150
+ signed-in GitHub CLI is present whose `gh attestation verify` takes the
151
+ options below. The attestation
152
+ is a Sigstore-signed statement, made by `actions/attest-build-provenance` in
153
+ the release workflow, that every file in `SHA256SUMS` was built by
154
+ `.github/workflows/release.yml` at the release's tag on a GitHub-hosted
155
+ runner. A failed verification refuses the install; with no `gh`, a signed-out
156
+ one or one too old for those options, the check is skipped with a note saying so, and the
157
+ SHA-256 still applies. The same command by hand, on a tarball you downloaded:
158
+
159
+ ```bash
160
+ gh attestation verify nish-<version>-<asset>.tar.gz \
161
+ --repo amritk/nish \
162
+ --signer-workflow amritk/nish/.github/workflows/release.yml \
163
+ --source-ref refs/tags/v<version> \
164
+ --deny-self-hosted-runners
165
+ ```
166
+
167
+ It works on any file the release attaches, the npm tarballs included. Each
168
+ release also attaches `nish-<version>.spdx.json`, an SPDX 2.3 software bill of
169
+ materials: every attached file with its SHA-256, the clang, linker, Node.js
170
+ and seed compiler that built each tarball (recorded by the build row itself),
171
+ and the vendored code from
172
+ [THIRD_PARTY_NOTICES.md](../THIRD_PARTY_NOTICES.md) that each of them contains.
173
+ How these fit the rest of the release's defences is
174
+ [docs/security/supply-chain.md](security/supply-chain.md).
175
+
146
176
  The npm route installs the **native** compiler, and it is a download rather than a
147
177
  build: nothing is compiled on your machine. The package declares one
148
178
  `nish-<os>-<arch>` package per supported platform as an `optionalDependencies`
@@ -224,7 +254,7 @@ routes are
224
254
  # on the musl host, with its own clang and the runtime from this repository
225
255
  clang app.ll runtime/runtime.c runtime/runtime-os.c runtime/runtime-parallel.c \
226
256
  runtime/runtime-cross.c runtime/runtime-host.c runtime/runtime-net.c \
227
- runtime/runtime-simd.c runtime/runtime-aes.c -lm -o app
257
+ runtime/runtime-simd.c runtime/runtime-aes.c runtime/runtime-term.c runtime/runtime-bytes.c -lm -o app
228
258
  ```
229
259
 
230
260
  `--link`ing inside the container is the mistake to avoid: it shells out to the
@@ -360,22 +390,25 @@ it into `build/seed/`; `NISH_BOOTSTRAP=<path>` names one you already have and
360
390
  skips the download. §2a has what the build does with it.
361
391
 
362
392
  The published package ships `bin/` (the `nish` command, which is a launcher),
363
- `runtime/` (the C runtime — eight translation units, the wasm subset and their header),
364
- `scripts/build.sh` (the link pipeline) and `std/` (the standard library). The
393
+ `runtime/` (the C runtime — ten translation units, the wasm subset and their
394
+ header — and `runtime/sqlite/`, SQLite's vendored source),
395
+ `scripts/build.sh` (the link pipeline), `std/` (the standard library) and
396
+ `docs/AI.md` (the rules card). The
365
397
  compiler itself is not in it: it arrives as one prebuilt
366
398
  `@amritk/nish-<asset>` package per platform, and `bin/nish` hands over to
367
- whichever one npm installed. `nish` locates the runtime, the script and `std/`
399
+ whichever one npm installed. That package carries its own copy of all of
400
+ these, and its `docs/AI.md` is the one an agent's `nish --help` names. `nish` locates the runtime, the script and `std/`
368
401
  relative to its own install directory, so a global install works from any
369
402
  working directory — and the binary runs from inside its own platform package
370
403
  for exactly that reason.
371
404
 
372
405
  Building the IR yourself rather than through `--link` means naming the runtime
373
- on the `clang` line, and it is eight files:
406
+ on the `clang` line, and it is ten files:
374
407
 
375
408
  ```bash
376
409
  clang app.ll runtime/runtime.c runtime/runtime-os.c runtime/runtime-parallel.c \
377
410
  runtime/runtime-cross.c runtime/runtime-host.c runtime/runtime-net.c \
378
- runtime/runtime-simd.c runtime/runtime-aes.c -lm -o app
411
+ runtime/runtime-simd.c runtime/runtime-aes.c runtime/runtime-term.c runtime/runtime-bytes.c -lm -o app
379
412
  ```
380
413
 
381
414
  `runtime.c` is the part every program touches — the arena, strings, arrays,
@@ -387,15 +420,24 @@ needs `-DNISH_THREADS=1 -pthread` on the line), `runtime-cross.c` copies
387
420
  the strings and arrays a task answers, a channel sends or a `Mutex` keeps out
388
421
  of the arena they were made in, `runtime-host.c` holds the wall clock,
389
422
  entropy, file times and signals, `runtime-net.c` the sockets of `nish:net`,
390
- and `runtime-simd.c` and `runtime-aes.c` the vector text search and AES-GCM.
423
+ `runtime-simd.c` and `runtime-aes.c` the vector text search and AES-GCM,
424
+ `runtime-term.c` the stdin reads and terminal calls of `nish:term`, and
425
+ `runtime-bytes.c` the byte-class runs of `nish/bytes`, which `nish/json` steps
426
+ over.
391
427
  They are separate so that each carries its own measured size ceiling
392
428
  ([docs/wp7-runtime.md](wp7-runtime.md)); nothing in the core calls into the
393
429
  others, so a line that names only `runtime.c` and `runtime-os.c` still links a
394
- program that uses none of the other six. `scripts/build.sh` compiles the other
395
- seven beside any
430
+ program that uses none of the other eight. `scripts/build.sh` compiles the other
431
+ eight beside any
396
432
  `runtime.c` it is handed, so a build that goes through it — every `--link`,
397
433
  and every `--profile` recipe in these documents — needs to name only the one.
398
434
 
435
+ A program whose IR declares an `sqlite3_*` function also needs SQLite on a
436
+ hand-written line. `scripts/build.sh` adds it by itself; by hand, append
437
+ `runtime/sqlite/sqlite3.c` with the options `scripts/build.sh` lists under
438
+ "SQLite's compile-time options" (at least `-DSQLITE_THREADSAFE=0`, or `=2`
439
+ beside `-DNISH_THREADS=1`).
440
+
399
441
  ## 2a. What `npm run build` does
400
442
 
401
443
  `src/` is the compiler, written in Nish, and it compiles itself
@@ -506,7 +548,7 @@ Removing the directory is always safe.
506
548
  | 2 | usage error: unknown flag, missing argument, no input files |
507
549
  | 3 | toolchain error: `--link` found no `clang` (`CC` overrides), or `scripts/build.sh` failed (its output is shown; the `.ll` files are still written) — or the `nish` command found no prebuilt compiler for this platform, or one that would not start. Under `--json` all of these are one `NL0002` object |
508
550
  | | `nish run` answers these codes until the program starts, and the program's own exit status (`128 + n` for a signal) after that. With neither `HOME` nor `XDG_CACHE_HOME` set to an absolute path it answers 3 |
509
- | 70 | internal compiler error: an unexpected exception. Please report it at <https://github.com/amritk/nish/issues> with the input and command line; `NISH_DEBUG=1` prints the stack trace |
551
+ | 70 | internal compiler error: a broken invariant in the compiler. Please report it at <https://github.com/amritk/nish/issues> with the input and command line; the compiler is self-hosted and has no stack trace to print, so the message it prints is the whole report |
510
552
 
511
553
  ## Troubleshooting
512
554
 
package/llms.txt CHANGED
@@ -27,7 +27,7 @@ the compiler.
27
27
  - [User guide](https://raw.githubusercontent.com/amritk/nish/main/docs/guide/index.md): the language taught page by page for people writing programs — getting started, the language, the CLI, the standard library, interop and threads. Every marked example program is compiled by `npm test`.
28
28
  - [Language reference](https://raw.githubusercontent.com/amritk/nish/main/docs/LANGUAGE.md): normative and exhaustive. Every rule cites the test that pins it and quotes the exact rejection message. Settles any disagreement with the rules card.
29
29
  - [Ambient declarations](https://raw.githubusercontent.com/amritk/nish/main/runtime/nish.d.ts): reference this from `tsconfig.json` and `tsc --strict`, your editor and your language server accept `Result<T, E>`, `i32` and the rest. `nish` is still the authority — `tsc` cannot see the flow rules.
30
- - [Standard library](https://raw.githubusercontent.com/amritk/nish/main/std/README.md): `std/testing`, a suite a program drives to check itself and answer an exit code; `std/text`, the `split` / `trim` / `replace` the language does not have; `std/json`, the value of one field of one flat JSON object — enough to read this compiler's own `--json` output; `nish/crypto`, SHA-256, SHA-384 and SHA-512, HMAC, HKDF, a constant-time compare, base64url, X25519, ChaCha20-Poly1305, AES-GCM, P-256 ECDSA and X.509 certificates, one module each (`nish/crypto/sha256` and so on), plus SHA-1 for WebSocket's handshake only; `nish/net`, the protocols written on them — the TLS 1.3 server handshake and record layer, TLS over TCP, QUIC, HPACK, the HTTP/1.1 parser, WebSocket framing, and percent-decoding and query strings (`nish/net/url`); `nish/threads`, a parallel map and reduce. Source rather than a built library, imported as `nish/<module>`, and shipped in the npm package under `std/`.
30
+ - [Standard library](https://raw.githubusercontent.com/amritk/nish/main/std/README.md): `std/testing`, a suite a program drives to check itself and answer an exit code; `std/text`, the `split` / `trim` / `replace` the language does not have; `std/json`, the value of one field of one flat JSON object — enough to read this compiler's own `--json` output; `nish/crypto`, SHA-256, SHA-384 and SHA-512, HMAC, HKDF, a constant-time compare, base64url, X25519, ChaCha20-Poly1305, AES-GCM, P-256 ECDSA and X.509 certificates, one module each (`nish/crypto/sha256` and so on), plus SHA-1 for WebSocket's handshake only; `nish/net`, the protocols written on them — the TLS 1.3 server handshake and record layer, TLS over TCP, QUIC, HPACK, the HTTP/1.1 parser, WebSocket framing, percent-decoding and query strings (`nish/net/url`), and a PostgreSQL client (`nish/net/postgres`); `nish/threads`, a parallel map and reduce. Source rather than a built library, imported as `nish/<module>`, and shipped in the npm package under `std/`.
31
31
  - [FAQ](https://raw.githubusercontent.com/amritk/nish/main/docs/FAQ.md): why no `any`, why `i32`, how to get JavaScript numbers, why no GC, why signed overflow panics and how to wrap on purpose, what errors look like.
32
32
  - [Install](https://raw.githubusercontent.com/amritk/nish/main/docs/INSTALL.md): prerequisites per OS, hello world, exit codes, troubleshooting.
33
33
 
package/package.json CHANGED
@@ -1,11 +1,23 @@
1
1
  {
2
2
  "name": "nish",
3
- "version": "0.20.0",
3
+ "version": "0.22.1",
4
4
  "description": "Nish: an ahead-of-time compiler from a static subset of TypeScript to LLVM IR",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "exports": {
8
8
  "./package.json": "./package.json",
9
+ "./runtime": {
10
+ "types": "./runtime/core.d.ts",
11
+ "default": "./runtime/core.mjs"
12
+ },
13
+ "./runtime/node": {
14
+ "types": "./runtime/host.d.ts",
15
+ "default": "./runtime/node.mjs"
16
+ },
17
+ "./runtime/browser": {
18
+ "types": "./runtime/browser.d.ts",
19
+ "default": "./runtime/browser.mjs"
20
+ },
9
21
  "./runtime/*": "./runtime/*",
10
22
  "./scripts/*": "./scripts/*",
11
23
  "./*": "./std/*.ts"
@@ -23,6 +35,9 @@
23
35
  "!scripts/check-filenames.mjs",
24
36
  "!scripts/changelog-gen.test.mjs",
25
37
  "!scripts/sync-main.mjs",
38
+ "!scripts/sbom.mjs",
39
+ "!scripts/rebuild-compare.sh",
40
+ "!scripts/ddc-chain.sh",
26
41
  "std",
27
42
  "README.md",
28
43
  "LICENSE",
@@ -77,10 +92,10 @@
77
92
  "nish"
78
93
  ],
79
94
  "optionalDependencies": {
80
- "@amritk/nish-x86_64-linux": "0.20.0",
81
- "@amritk/nish-aarch64-linux": "0.20.0",
82
- "@amritk/nish-aarch64-darwin": "0.20.0",
83
- "@amritk/nish-x86_64-darwin": "0.20.0"
95
+ "@amritk/nish-x86_64-linux": "0.22.1",
96
+ "@amritk/nish-aarch64-linux": "0.22.1",
97
+ "@amritk/nish-aarch64-darwin": "0.22.1",
98
+ "@amritk/nish-x86_64-darwin": "0.22.1"
84
99
  },
85
100
  "devDependencies": {
86
101
  "@biomejs/biome": "2.5.12",
@@ -0,0 +1,6 @@
1
+ /**
2
+ * `nish/runtime/browser`: importing it installs the browser host on the core
3
+ * in `nish/runtime` (docs/guide/using-nish/to-typescript.md).
4
+ */
5
+
6
+ export { NishExit } from "./core/host.js";
@@ -0,0 +1,77 @@
1
+ /**
2
+ * The browser host (WP33 R3): importing this installs, on the core in
3
+ * `runtime/core.mjs`, the answers a web page can give. It names no `node:`
4
+ * module and reads only web globals (`console`, `performance`,
5
+ * `queueMicrotask`), so it loads in a page, a worker or any engine that has
6
+ * those.
7
+ *
8
+ * - Output goes to the console a line at a time: what `write` leaves without
9
+ * a newline waits for the next one, for `exit`, or for the program to yield.
10
+ * - `exit(code)` throws a `NishExit` carrying the code, since a page cannot
11
+ * end itself; the caller that started the program catches it, and does
12
+ * not call the module again (docs/security/runtime-browser.md, BROWSER-2).
13
+ * - `monotonicNanos` reads `performance.now()`, `getenv` answers `null`,
14
+ * `isTerminal` answers `false` and `terminalSize` `[-25, 0]`, and `argv()`
15
+ * is the program alone.
16
+ * - Every file-system, process and machine call panics, naming itself and
17
+ * the browser.
18
+ */
19
+ import { installHost, NishExit, panic } from "./core/host.mjs";
20
+
21
+ export { NishExit };
22
+
23
+ /**
24
+ * One console stream, buffered to the next newline. The `"%s"` keeps a `%d`
25
+ * or `%o` in the program's text from being read as a format directive.
26
+ */
27
+ function lineStream(print) {
28
+ let pending = "";
29
+ let scheduled = false;
30
+ const flush = () => {
31
+ scheduled = false;
32
+ if (pending !== "") print("%s", pending);
33
+ pending = "";
34
+ };
35
+ return {
36
+ write(s) {
37
+ // Only the text up to the last newline is split, so a run of writes
38
+ // with no newline costs their length once, not once per write.
39
+ const text = String(s);
40
+ const last = text.lastIndexOf("\n");
41
+ if (last < 0) {
42
+ pending += text;
43
+ } else {
44
+ const lines = (pending + text.slice(0, last)).split("\n");
45
+ pending = text.slice(last + 1);
46
+ for (const line of lines) print("%s", line);
47
+ }
48
+ if (pending !== "" && !scheduled) {
49
+ scheduled = true;
50
+ queueMicrotask(flush);
51
+ }
52
+ },
53
+ flush,
54
+ };
55
+ }
56
+
57
+ const out = lineStream((...a) => console.log(...a));
58
+ const err = lineStream((...a) => console.error(...a));
59
+
60
+ installHost({
61
+ writeOut: out.write,
62
+ writeErr: err.write,
63
+ exit(code) {
64
+ out.flush();
65
+ err.flush();
66
+ throw new NishExit(code);
67
+ },
68
+ argv: () => ["main"],
69
+ call(name) {
70
+ if (name === "getenv") return null;
71
+ if (name === "monotonicNanos") return BigInt(Math.round(performance.now() * 1e6));
72
+ // A page has no terminal, which `nish:term` answers as a pipe does.
73
+ if (name === "isTerminal") return false;
74
+ if (name === "terminalSize") return [-25, 0];
75
+ return panic(`${name} is not available in a browser`);
76
+ },
77
+ });
@@ -0,0 +1,36 @@
1
+ /** The array half of the core: bounds-checked access, and the arena stubs. */
2
+ import type { i32, i64 } from "./numbers.js";
3
+ export declare function idx<T>(a: readonly T[], i: number | bigint): T;
4
+ export declare function pop<T>(a: T[]): T;
5
+ export declare function setIdx<T>(a: T[], i: number | bigint, v: T): T;
6
+ export declare function updIdx<T>(a: T[], i: number | bigint, f: (old: T) => T): T;
7
+ export declare function uncheckedGet<T extends number | bigint>(xs: readonly T[], i: i32): T;
8
+ export declare function uncheckedSet<T extends number | bigint>(xs: T[], i: i32, v: T): void;
9
+ export declare function copyIn<T>(v: T): T;
10
+ export declare function storeIdx<T>(a: T[], i: number | bigint, v: T): T;
11
+ export declare function arraySet<T>(dst: T[], src: readonly T[], offset?: number): void;
12
+ /** `dst.set(src, offset)` as `--emit-ts` writes it: a 64-bit offset is a bigint, checked exactly. */
13
+ export declare function arraySetAt<T>(dst: T[], src: readonly T[], offset?: number | bigint): void;
14
+ /** `new Array<T>(n)`: `--emit-ts` writes `T` out, so the zero it fills with is not what `T` is read from. */
15
+ export declare function newArray<T>(n: number | bigint, zero: unknown): T[];
16
+ export declare function arenaUsed(): i64;
17
+ export declare function arenaMark(): i64;
18
+ export declare function arenaRelease(m?: unknown): void;
19
+ export declare function arenaReset(): void;
20
+ /**
21
+ * The protocol `using` reads, declared here as `nish.d.ts` does, so `using a =
22
+ * arena()` type-checks with no `"esnext.disposable"` in a program's `lib`.
23
+ */
24
+ declare global {
25
+ interface SymbolConstructor {
26
+ readonly dispose: unique symbol;
27
+ }
28
+ }
29
+
30
+ /** What `arena()` answers: its `Symbol.dispose` does nothing. */
31
+ export interface ArenaHandle {
32
+ [Symbol.dispose](): void;
33
+ }
34
+
35
+ /** `using a = arena()`: the arena is the collector's, so leaving it frees nothing. */
36
+ export declare function arena(): ArenaHandle;