nish 0.20.0 → 0.21.0

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 (76) hide show
  1. package/README.md +19 -59
  2. package/docs/AI.md +56 -9
  3. package/docs/INSTALL.md +22 -10
  4. package/llms.txt +1 -1
  5. package/package.json +17 -5
  6. package/runtime/browser.d.ts +14 -0
  7. package/runtime/browser.mjs +88 -0
  8. package/runtime/core/arrays.d.ts +18 -0
  9. package/runtime/core/arrays.mjs +125 -0
  10. package/runtime/core/checks.mjs +20 -0
  11. package/runtime/core/host.d.ts +70 -0
  12. package/runtime/core/host.mjs +311 -0
  13. package/runtime/core/numbers.d.ts +53 -0
  14. package/runtime/core/numbers.mjs +316 -0
  15. package/runtime/core/result.d.ts +41 -0
  16. package/runtime/core/result.mjs +127 -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 +44 -0
  23. package/runtime/nish.h +75 -2
  24. package/runtime/nish.mjs +23 -3
  25. package/runtime/node.mjs +383 -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-os.c +1 -1
  30. package/runtime/runtime-parallel.c +1 -1
  31. package/runtime/runtime-simd.c +231 -7
  32. package/runtime/runtime-term.c +504 -0
  33. package/runtime/runtime-wasm.c +0 -11
  34. package/runtime/runtime.c +190 -6
  35. package/runtime/shim.mjs +6 -985
  36. package/runtime/sqlite/LICENSE.md +85 -0
  37. package/runtime/sqlite/README.md +45 -0
  38. package/runtime/sqlite/nish-sqlite.c +359 -0
  39. package/runtime/sqlite/sqlite3.c +271131 -0
  40. package/runtime/sqlite/sqlite3.h +14447 -0
  41. package/scripts/build.sh +261 -53
  42. package/scripts/fuzz.sh +218 -0
  43. package/scripts/gen-json-pow5.mjs +130 -0
  44. package/scripts/platform-package.mjs +3 -1
  45. package/scripts/security-scope.mjs +139 -0
  46. package/scripts/smoke.sh +3 -2
  47. package/std/LICENSE-fast-float +23 -0
  48. package/std/LICENSE-fdlibm +8 -0
  49. package/std/README.md +31 -11
  50. package/std/base64.ts +116 -0
  51. package/std/bytes.ts +256 -0
  52. package/std/cli.ts +328 -0
  53. package/std/collections.ts +6 -5
  54. package/std/crypto/LICENSE-crypt_blowfish +26 -0
  55. package/std/crypto/base64url.ts +125 -0
  56. package/std/crypto/bcrypt.ts +760 -0
  57. package/std/crypto/hmac.ts +138 -2
  58. package/std/crypto/x509.ts +11 -122
  59. package/std/json-tokenizer.ts +2998 -57
  60. package/std/json-value.ts +22 -3
  61. package/std/json.ts +83 -1
  62. package/std/math.ts +608 -0
  63. package/std/net/http1-server.ts +85 -8
  64. package/std/net/http3-server.ts +50 -12
  65. package/std/net/postgres.ts +1875 -0
  66. package/std/net/quic-listener.ts +20 -4
  67. package/std/regex.ts +4274 -0
  68. package/std/sqlite.ts +391 -0
  69. package/std/term-io.ts +978 -0
  70. package/std/term-pixels.ts +874 -0
  71. package/std/term-probe.ts +459 -0
  72. package/std/term-rate.ts +993 -0
  73. package/std/term.ts +2453 -0
  74. package/std/text.ts +90 -7
  75. package/std/yaml-lines.ts +141 -0
  76. 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`.
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
@@ -178,7 +179,7 @@ rejects. This table is the highest-value part of the page.
178
179
  | `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
180
  | `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
181
  | `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 |
182
+ | `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
183
  | `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
184
  | `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
185
  | `let x = 5; x = "s"` | `Cannot initialize …` | types never change and never convert implicitly |
@@ -1303,8 +1304,10 @@ export const main = (): i32 => {
1303
1304
  ### Calling C
1304
1305
 
1305
1306
  `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.
1307
+ does not define. The symbol is the identifier, unmangled, in any package
1308
+ (a package's own functions are prefixed, its declarations are not), and the
1309
+ call is an ordinary call. Two declarations of one name must have the same
1310
+ types.
1308
1311
 
1309
1312
  ```ts nish:ok
1310
1313
  declare function abs(n: i32): i32;
@@ -1400,6 +1403,17 @@ export const main = (): i32 => {
1400
1403
  ```
1401
1404
 
1402
1405
  - **No body, and it cannot be `export`ed.**
1406
+ - **A class with a `CPtr` field is a handle class: open one with `using`.**
1407
+ `using f = new File(p)` closes `f` once at every exit of its block (falling
1408
+ off the end, `return`, `break`, `continue`, `orReturn()`), so never call the
1409
+ close yourself. The class is checked: one `readonly` `CPtr` or
1410
+ `CPtr | null` field written once by the constructor's foreign call, read only
1411
+ as `this.f` in its own methods, and a `[Symbol.dispose]` that is exactly the
1412
+ close. A handle is never copied, stored, returned or captured: it is called
1413
+ or lent to a parameter of its type, and `new` of one appears only as a
1414
+ `using` initialiser. A panic or `process.exit` does not close it, so
1415
+ `fflush` a written `FILE *` before code that may panic. The rules:
1416
+ `LANGUAGE.md` → "A handle class".
1403
1417
  - **It costs the caller its attributes.** Nothing about a body the compiler
1404
1418
  cannot see is provable, so a function that calls C loses `readnone` and
1405
1419
  `willreturn`, and so does everything above it in the call graph. A program
@@ -2096,7 +2110,10 @@ method there is. `substring` **clamps** an out-of-range offset the
2096
2110
  way JavaScript does; `slice` instead **panics** unless
2097
2111
  `0 <= start <= end <= s.length`, and is the faster of the two when you have
2098
2112
  already established the range. Every offset is a **byte** offset, so cutting a multi-byte character
2099
- in half is possible.
2113
+ in half is possible. To count characters rather than bytes, `codePointLength(s)`
2114
+ from `nish/text` counts code points natively and, for text written in the
2115
+ source, under Node alike; under Node a string built from bytes (`String.fromBytes`,
2116
+ a `\u` escape `nish/json` decodes) is one unit per byte, and counts its bytes.
2100
2117
 
2101
2118
  **Process.** `process.exit(code)`, `process.argv` (a read-only `string[]`;
2102
2119
  `argv[0]` is the program path, one index earlier than Node),
@@ -2520,6 +2537,20 @@ never call it on secret data, because its time says where the match is.
2520
2537
  (No block: a program importing `nish/text` writes two `.ll` files;
2521
2538
  `tests/link/std_text_index_of_any` is its program.)
2522
2539
 
2540
+ **Match a pattern** — there is no `RegExp` and no `/re/` literal:
2541
+ `regexCompile(pattern, flags)` from `nish/regex` answers a
2542
+ `Result<Regex, string>`, the error text naming the byte. The syntax is
2543
+ JavaScript's with the `u` flag's strictness (a stray `{` or `]` is an
2544
+ error), the flags are `i`, `m` and `s`, and backreferences and lookaround are
2545
+ refused, because matching never backtracks: time is linear in the input for
2546
+ every pattern. `test`, `exec(text, from, m)` into a reused `RegexMatch`,
2547
+ `find`, `findAll`, `count`, `replace`, `replaceAll` (`$&`, `$1`,
2548
+ `$<name>`) and `split`; offsets are UTF-8 bytes and `\w`, `\d`, `\b` and `i`
2549
+ are ASCII. A `Regex` keeps its scratch memory, so compile once outside the
2550
+ loop and use it from one thread. (No block, as for `nish/text`;
2551
+ `tests/link/std_regex` is its program, and the user guide's [standard-library
2552
+ page](guide/using-nish/standard-library.md#nishregex) its walk-through.)
2553
+
2523
2554
  **Decode a URL or read a query** — there is no `decodeURIComponent` and no
2524
2555
  `URLSearchParams`: `nish/net/url` has both readings. `urlDecode(s, flags)` and
2525
2556
  `urlQueryGet(target, name)` answer a `string | null`; the byte API
@@ -2535,6 +2566,20 @@ most 100 pairs. (No block, as for `nish/text`; `tests/link/std_url` is its
2535
2566
  program, and the user guide's [standard-library
2536
2567
  page](guide/using-nish/standard-library.md#nishneturl) its walk-through.)
2537
2568
 
2569
+ **Draw to the whole terminal** (a game, a dashboard) — there is no curses and
2570
+ no `process.stdout.on("resize")`: `runTerminal(options, state, update, render)`
2571
+ from `nish/term-io` opens the terminal, probes what it can draw, steps
2572
+ `update(state, input)` at `options.stepsPerSecond` and calls
2573
+ `render(state, frame)` only when the link to the terminal has room, then
2574
+ leaves the terminal as it was, even on a panic. Draw cells on `frame.screen`
2575
+ or pixels on `frame.framebuffer` (sized by `options.framebufferWidth` and
2576
+ `framebufferHeight`) and never pick a backend: kitty graphics, Sixel, half
2577
+ blocks or ASCII is chosen from the probe and the measured link. It answers
2578
+ `Err` with one sentence on a pipe, so test the `Result`; it reaches `tty`.
2579
+ `NISH_TERM_GRAPHICS` and `NISH_TERM_FPS` override what it picked. (No block,
2580
+ as for `nish/text`; `examples/term-probe.ts` is its program, and the user
2581
+ guide's [terminal page](guide/using-nish/terminal.md) its walk-through.)
2582
+
2538
2583
  **Shared behaviour over several shapes** — there is no inheritance and no
2539
2584
  dispatch. Give each class the interface's fields **first**, `implements` it,
2540
2585
  and write a free function over the interface:
@@ -2702,10 +2747,12 @@ Run it. `nish file.ts --json` is one command and it is the only proof.
2702
2747
  prove is an error
2703
2748
  naming the guard ([Proving it cannot panic](#proving-it-cannot-panic)); an
2704
2749
  `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.
2750
+ 11. If you are adding to this repository: `npm run check` and the touched
2751
+ `node tests/run.js` sections green locally, every CI `test` shard green
2752
+ ([CLAUDE.md](../CLAUDE.md#definition-of-done)), and a new construct ships a
2753
+ golden `.ll`, an `llvm-as` pass, a native round trip, a negative test, its
2754
+ `LANGUAGE.md` rule and cookbook entry, and a conventional commit message,
2755
+ which is its changelog entry.
2709
2756
 
2710
2757
  Every `ts nish:ok` and `ts nish:err` block on this page is compiled by
2711
2758
  `npm test`, so an example that has gone stale is a failing test rather than a
package/docs/INSTALL.md CHANGED
@@ -224,7 +224,7 @@ routes are
224
224
  # on the musl host, with its own clang and the runtime from this repository
225
225
  clang app.ll runtime/runtime.c runtime/runtime-os.c runtime/runtime-parallel.c \
226
226
  runtime/runtime-cross.c runtime/runtime-host.c runtime/runtime-net.c \
227
- runtime/runtime-simd.c runtime/runtime-aes.c -lm -o app
227
+ runtime/runtime-simd.c runtime/runtime-aes.c runtime/runtime-term.c runtime/runtime-bytes.c -lm -o app
228
228
  ```
229
229
 
230
230
  `--link`ing inside the container is the mistake to avoid: it shells out to the
@@ -360,22 +360,25 @@ it into `build/seed/`; `NISH_BOOTSTRAP=<path>` names one you already have and
360
360
  skips the download. §2a has what the build does with it.
361
361
 
362
362
  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
363
+ `runtime/` (the C runtime — ten translation units, the wasm subset and their
364
+ header — and `runtime/sqlite/`, SQLite's vendored source),
365
+ `scripts/build.sh` (the link pipeline), `std/` (the standard library) and
366
+ `docs/AI.md` (the rules card). The
365
367
  compiler itself is not in it: it arrives as one prebuilt
366
368
  `@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/`
369
+ whichever one npm installed. That package carries its own copy of all of
370
+ these, and its `docs/AI.md` is the one an agent's `nish --help` names. `nish` locates the runtime, the script and `std/`
368
371
  relative to its own install directory, so a global install works from any
369
372
  working directory — and the binary runs from inside its own platform package
370
373
  for exactly that reason.
371
374
 
372
375
  Building the IR yourself rather than through `--link` means naming the runtime
373
- on the `clang` line, and it is eight files:
376
+ on the `clang` line, and it is ten files:
374
377
 
375
378
  ```bash
376
379
  clang app.ll runtime/runtime.c runtime/runtime-os.c runtime/runtime-parallel.c \
377
380
  runtime/runtime-cross.c runtime/runtime-host.c runtime/runtime-net.c \
378
- runtime/runtime-simd.c runtime/runtime-aes.c -lm -o app
381
+ runtime/runtime-simd.c runtime/runtime-aes.c runtime/runtime-term.c runtime/runtime-bytes.c -lm -o app
379
382
  ```
380
383
 
381
384
  `runtime.c` is the part every program touches — the arena, strings, arrays,
@@ -387,15 +390,24 @@ needs `-DNISH_THREADS=1 -pthread` on the line), `runtime-cross.c` copies
387
390
  the strings and arrays a task answers, a channel sends or a `Mutex` keeps out
388
391
  of the arena they were made in, `runtime-host.c` holds the wall clock,
389
392
  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.
393
+ `runtime-simd.c` and `runtime-aes.c` the vector text search and AES-GCM,
394
+ `runtime-term.c` the stdin reads and terminal calls of `nish:term`, and
395
+ `runtime-bytes.c` the byte-class runs of `nish/bytes`, which `nish/json` steps
396
+ over.
391
397
  They are separate so that each carries its own measured size ceiling
392
398
  ([docs/wp7-runtime.md](wp7-runtime.md)); nothing in the core calls into the
393
399
  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
400
+ program that uses none of the other eight. `scripts/build.sh` compiles the other
401
+ eight beside any
396
402
  `runtime.c` it is handed, so a build that goes through it — every `--link`,
397
403
  and every `--profile` recipe in these documents — needs to name only the one.
398
404
 
405
+ A program whose IR declares an `sqlite3_*` function also needs SQLite on a
406
+ hand-written line. `scripts/build.sh` adds it by itself; by hand, append
407
+ `runtime/sqlite/sqlite3.c` with the options `scripts/build.sh` lists under
408
+ "SQLite's compile-time options" (at least `-DSQLITE_THREADSAFE=0`, or `=2`
409
+ beside `-DNISH_THREADS=1`).
410
+
399
411
  ## 2a. What `npm run build` does
400
412
 
401
413
  `src/` is the compiler, written in Nish, and it compiles itself
@@ -506,7 +518,7 @@ Removing the directory is always safe.
506
518
  | 2 | usage error: unknown flag, missing argument, no input files |
507
519
  | 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
520
  | | `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 |
521
+ | 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
522
 
511
523
  ## Troubleshooting
512
524
 
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.21.0",
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"
@@ -77,10 +89,10 @@
77
89
  "nish"
78
90
  ],
79
91
  "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"
92
+ "@amritk/nish-x86_64-linux": "0.21.0",
93
+ "@amritk/nish-aarch64-linux": "0.21.0",
94
+ "@amritk/nish-aarch64-darwin": "0.21.0",
95
+ "@amritk/nish-x86_64-darwin": "0.21.0"
84
96
  },
85
97
  "devDependencies": {
86
98
  "@biomejs/biome": "2.5.12",
@@ -0,0 +1,14 @@
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
+ /**
7
+ * What the program's `exit(code)`, and every panic, throws: a page cannot end
8
+ * itself. Tell it apart with `instanceof`, not by its `name`.
9
+ */
10
+ export class NishExit extends Error {
11
+ /** The 8-bit status a native exit would leave: `code & 0xff`. */
12
+ readonly code: number;
13
+ constructor(code: number);
14
+ }
@@ -0,0 +1,88 @@
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, panic } from "./core/host.mjs";
20
+
21
+ /**
22
+ * What `exit(code)` throws: `code` is the 8-bit status a native exit would
23
+ * leave. Exported so a caller tells it apart with `instanceof`, which a thrown
24
+ * object that only carries the name does not pass.
25
+ */
26
+ export class NishExit extends Error {
27
+ constructor(code) {
28
+ super(`the program exited with ${code}`);
29
+ this.name = "NishExit";
30
+ this.code = code & 0xff;
31
+ }
32
+ }
33
+
34
+ /**
35
+ * One console stream, buffered to the next newline. The `"%s"` keeps a `%d`
36
+ * or `%o` in the program's text from being read as a format directive.
37
+ */
38
+ function lineStream(print) {
39
+ let pending = "";
40
+ let scheduled = false;
41
+ const flush = () => {
42
+ scheduled = false;
43
+ if (pending !== "") print("%s", pending);
44
+ pending = "";
45
+ };
46
+ return {
47
+ write(s) {
48
+ // Only the text up to the last newline is split, so a run of writes
49
+ // with no newline costs their length once, not once per write.
50
+ const text = String(s);
51
+ const last = text.lastIndexOf("\n");
52
+ if (last < 0) {
53
+ pending += text;
54
+ } else {
55
+ const lines = (pending + text.slice(0, last)).split("\n");
56
+ pending = text.slice(last + 1);
57
+ for (const line of lines) print("%s", line);
58
+ }
59
+ if (pending !== "" && !scheduled) {
60
+ scheduled = true;
61
+ queueMicrotask(flush);
62
+ }
63
+ },
64
+ flush,
65
+ };
66
+ }
67
+
68
+ const out = lineStream((...a) => console.log(...a));
69
+ const err = lineStream((...a) => console.error(...a));
70
+
71
+ installHost({
72
+ writeOut: out.write,
73
+ writeErr: err.write,
74
+ exit(code) {
75
+ out.flush();
76
+ err.flush();
77
+ throw new NishExit(code);
78
+ },
79
+ argv: () => ["main"],
80
+ call(name) {
81
+ if (name === "getenv") return null;
82
+ if (name === "monotonicNanos") return BigInt(Math.round(performance.now() * 1e6));
83
+ // A page has no terminal, which `nish:term` answers as a pipe does.
84
+ if (name === "isTerminal") return false;
85
+ if (name === "terminalSize") return [-25, 0];
86
+ return panic(`${name} is not available in a browser`);
87
+ },
88
+ });
@@ -0,0 +1,18 @@
1
+ /** The array half of the core: bounds-checked access, and the arena stubs. */
2
+ import type { i32 } 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>(xs: readonly T[], i: i32): T;
8
+ export declare function uncheckedSet<T extends number>(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
+ export declare function newArray<T>(n: number | bigint, zero: T): T[];
13
+ export declare function arenaUsed(): number;
14
+ export declare function arenaMark(): number;
15
+ export declare function arenaRelease(m?: unknown): void;
16
+ export declare function arenaReset(): void;
17
+ /** `using a = arena()`: an object whose `Symbol.dispose` does nothing. */
18
+ export declare function arena(): object;
@@ -0,0 +1,125 @@
1
+ import { panicIndex, panicSlice, toIndex } from "./checks.mjs";
2
+
3
+ // The native check compares the index as an unsigned 64-bit number, so a
4
+ // negative one fails, and prints, as that number: `-1` is 18446744073709551615.
5
+ // A NaN or infinite `number` has no such number and prints as it is.
6
+ function outOfRange(i, len) {
7
+ const n = toIndex(i);
8
+ if (typeof i !== "bigint" && !Number.isFinite(n)) panicIndex(n, len);
9
+ const k = typeof i === "bigint" ? i : BigInt(n);
10
+ panicIndex(k < 0n ? BigInt.asUintN(64, k) : k, len);
11
+ }
12
+
13
+ /** `a[i]` read with the WP4 bounds check (negative indices fail like the unsigned compare does). */
14
+ export function idx(a, i) {
15
+ const k = toIndex(i);
16
+ if (!(k >= 0 && k < a.length)) outOfRange(i, a.length);
17
+ return a[k];
18
+ }
19
+
20
+ /** `a.pop()`: the last element, or the bounds panic — Nish has no `undefined` to return. */
21
+ export function pop(a) {
22
+ if (a.length === 0) panicIndex(0, 0);
23
+ return a.pop();
24
+ }
25
+
26
+ /** `a[i] = v`: evaluates `a`, `i`, `v`, then checks and stores; yields `v`. */
27
+ export function setIdx(a, i, v) {
28
+ const k = toIndex(i);
29
+ if (!(k >= 0 && k < a.length)) outOfRange(i, a.length);
30
+ a[k] = v;
31
+ return v;
32
+ }
33
+
34
+ /**
35
+ * `a[i] op= v`: evaluates `a`, `i`, checks, loads, then `f(old)` computes the
36
+ * new element, and checks again before the store, as `f` can shrink `a`.
37
+ */
38
+ export function updIdx(a, i, f) {
39
+ const k = toIndex(i);
40
+ if (!(k >= 0 && k < a.length)) outOfRange(i, a.length);
41
+ const v = f(a[k]);
42
+ if (!(k < a.length)) outOfRange(i, a.length);
43
+ a[k] = v;
44
+ return v;
45
+ }
46
+
47
+ /** `nish:unsafe`'s `uncheckedGet(a, i)`: the element with no bounds check, as the native load is. */
48
+ export function uncheckedGet(a, i) {
49
+ return a[i];
50
+ }
51
+
52
+ /** `nish:unsafe`'s `uncheckedSet(a, i, v)`: the store with no bounds check. */
53
+ export function uncheckedSet(a, i, v) {
54
+ a[i] = v;
55
+ }
56
+
57
+ // A record an array holds inline is an object literal here, and nothing else
58
+ // is a plain object: a class instance has its class's prototype, and an array
59
+ // has Array's.
60
+ function isRecord(v) {
61
+ return v !== null && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype;
62
+ }
63
+
64
+ /** A value put into an array slot from a generic body: a copy when it is a record, as a slot holds it inline. */
65
+ export function copyIn(v) {
66
+ return isRecord(v) ? { ...v } : v;
67
+ }
68
+
69
+ /**
70
+ * `a[i] = v` from a generic body: as `setIdx`, but a record is written field
71
+ * by field into the record already in the slot, as an inline element is.
72
+ */
73
+ export function storeIdx(a, i, v) {
74
+ const k = toIndex(i);
75
+ if (!(k >= 0 && k < a.length)) outOfRange(i, a.length);
76
+ const old = a[k];
77
+ if (isRecord(old) && isRecord(v)) Object.assign(old, v);
78
+ else a[k] = v;
79
+ return v;
80
+ }
81
+
82
+ /**
83
+ * `dst.set(src, offset)` (WP34 N2): `TypedArray.prototype.set`'s copy on the
84
+ * plain array a `u8[]` is here. The source is copied first, so a self-copy or
85
+ * an overlapping one reads what was there before, as `memmove` does natively;
86
+ * a range past the end fails with the native panic and its words, where a
87
+ * typed array would throw a `RangeError` for the same offsets.
88
+ */
89
+ export function arraySet(dst, src, offset) {
90
+ // `ToIntegerOrInfinity`: NaN is 0, as `llvm.fptosi.sat` makes it natively.
91
+ // `Math.trunc` rather than `toIndex`, which converts a bigint: an `i64` or
92
+ // `u64` offset is a bigint here, and it throws the `TypeError` the typed
93
+ // array and `Array.prototype.fill` throw for one, instead of being rounded
94
+ // to the nearest double past 2^53 (docs/RUN_UNDER_NODE.md).
95
+ const at = offset === undefined ? 0 : Math.trunc(offset) || 0;
96
+ const end = at + src.length;
97
+ if (!(at >= 0 && end <= dst.length)) panicSlice(at, end, dst.length);
98
+ // Two plain arrays overlap only when they are one array, which is the one
99
+ // case that must read the source before writing it.
100
+ const from = src === dst ? src.slice() : src;
101
+ for (let i = 0; i < from.length; i++) dst[at + i] = from[i];
102
+ }
103
+
104
+ /** `new Array<T>(n)`: `n` zero-filled elements (`0`, `0n`, or `false`). */
105
+ export function newArray(n, zero) {
106
+ return new Array(toIndex(n)).fill(zero);
107
+ }
108
+
109
+ // Arena introspection has no JS counterpart: the stubs keep programs that only
110
+ // compare `Arena.used()` before/after (a "stayed flat" check) in agreement, while
111
+ // programs that print raw byte counts are listed as known differences.
112
+ //
113
+ // `nish --threads` makes the native arena thread-local (WP20 T0) and nothing
114
+ // here moves with it: a rewritten program runs on the one thread Node gives it,
115
+ // so "the arena of the calling thread" and "the arena" are the same object, and
116
+ // these stubs answer for both. If T1 ever lands a spawn the rewrite can reach,
117
+ // that is when this file grows a second arena to keep count of.
118
+ export function arenaUsed() { return 0; }
119
+ export function arenaMark() { return 0; }
120
+ export function arenaRelease() {}
121
+ export function arenaReset() {}
122
+ /** `using a = arena()`: a disposable whose disposal does nothing, because there is no arena to release. */
123
+ export function arena() {
124
+ return { [Symbol.dispose]() {} };
125
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The checks the strings and arrays share: an index as the compiler converts
3
+ * it, and the two bounds panics with their native words. Internal to the core:
4
+ * `runtime/core.mjs` does not re-export them.
5
+ */
6
+ import { panic } from "./host.mjs";
7
+
8
+ /** Index conversion as in the compiler: `sext` from i32, `fptosi` (truncation) from f64. */
9
+ export function toIndex(i) {
10
+ return typeof i === "bigint" ? Number(i) : Math.trunc(i);
11
+ }
12
+
13
+ export function panicIndex(i, len) {
14
+ panic(`index out of range: ${i} >= ${len}`);
15
+ }
16
+
17
+ /** `nish_panic_slice`: the failed range check of `s.slice(start, end)`; the offsets print signed. */
18
+ export function panicSlice(start, end, len) {
19
+ panic(`slice out of range: [${start}, ${end}) of length ${len}`);
20
+ }