@amritk/nish-aarch64-linux 0.39.0 → 0.40.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 (54) hide show
  1. package/INSTALL.md +74 -129
  2. package/bin/nish +0 -0
  3. package/docs/AI.md +112 -33
  4. package/package.json +1 -1
  5. package/runtime/nish.d.ts +21 -17
  6. package/runtime/nish.h +10 -0
  7. package/runtime/page-frame.d.ts +123 -0
  8. package/runtime/page-frame.mjs +736 -0
  9. package/runtime/page-game.d.ts +132 -0
  10. package/runtime/page-game.mjs +738 -0
  11. package/runtime/runtime-aes.c +85 -8
  12. package/runtime/runtime-bytes.c +88 -4
  13. package/runtime/runtime-net.c +32 -0
  14. package/runtime/runtime-sandbox.c +55 -28
  15. package/runtime/runtime-wasm.c +422 -0
  16. package/runtime/vite.mjs +1 -1
  17. package/scripts/build.sh +15 -0
  18. package/std/README.md +73 -87
  19. package/std/array.ts +36 -3
  20. package/std/collections.ts +51 -0
  21. package/std/crypto/hmac.ts +37 -10
  22. package/std/crypto/p256.ts +1388 -2664
  23. package/std/crypto/pki.ts +116 -4
  24. package/std/crypto/sha256.ts +34 -6
  25. package/std/crypto/x509.ts +7 -0
  26. package/std/host/game.ts +273 -0
  27. package/std/input.ts +56 -0
  28. package/std/json-tokenizer.ts +325 -112
  29. package/std/json-typed.ts +43 -8
  30. package/std/json-value.ts +144 -3
  31. package/std/json.ts +63 -8
  32. package/std/net/fetch.ts +22 -4
  33. package/std/net/http-server.ts +3382 -0
  34. package/std/net/http1-client-codec.ts +6 -2
  35. package/std/net/http1-codec.ts +137 -12
  36. package/std/net/http1-server.ts +83 -29
  37. package/std/net/http2.ts +47 -14
  38. package/std/net/http3-server.ts +29 -3
  39. package/std/net/http3.ts +180 -7
  40. package/std/net/quic-recovery.ts +240 -9
  41. package/std/net/quic-stream.ts +21 -1
  42. package/std/net/quic.ts +98 -4
  43. package/std/net/router.ts +378 -31
  44. package/std/net/serve.ts +873 -65
  45. package/std/net/tls/verify.ts +19 -1
  46. package/std/net/url.ts +83 -35
  47. package/std/net/websocket.ts +74 -1
  48. package/std/net/webtransport.ts +7 -1
  49. package/std/raster.ts +837 -0
  50. package/std/release.ts +593 -0
  51. package/std/synth.ts +143 -0
  52. package/std/threads.ts +298 -0
  53. package/std/yaml-json.ts +368 -28
  54. package/std/yaml.ts +122 -27
package/docs/AI.md CHANGED
@@ -53,7 +53,7 @@ stdout, nothing on stderr, every field 1-based with `endLine`/`endColumn`
53
53
  exclusive:
54
54
 
55
55
  ```json
56
- {"file":"p.ts","line":3,"column":17,"endLine":3,"endColumn":23,"severity":"error","code":"NL2249","message":"Unknown method `reduce` on i32[] (supported: push, pop, indexOf, join, set, fill, sort, map, filter, some, every, findIndex, slice)"}
56
+ {"file":"p.ts","line":3,"column":17,"endLine":3,"endColumn":23,"severity":"error","code":"NL2249","message":"Unknown method `reduce` on i32[] (supported: push, pop, indexOf, join, set, fill, sort, map, filter, some, every, findIndex, forEach, slice)"}
57
57
  ```
58
58
 
59
59
  - **Key on `code`, never on `message`.** A code is a promise: `NL2249` means
@@ -153,7 +153,7 @@ everywhere, a template literal instead of `String(n)`.
153
153
 
154
154
  - A module is one `.ts` file. At the top level it may hold **only**
155
155
  declarations: `const` arrows (functions), `class`, `interface`, module
156
- `const`s, `type` aliases, numeric `enum`s, and `import`s. There is no
156
+ `const`s, `type` aliases, `enum`s (numeric or string), and `import`s. There is no
157
157
  top-level code, so there is no initialisation order to think about. The
158
158
  one exception is an entry module with no `main`: its top-level statements
159
159
  run as `main` (`docs/LANGUAGE.md` → "Top-level code"). Declare every
@@ -177,7 +177,7 @@ rejects. This table is the highest-value part of the page.
177
177
  | `x == y` | `Loose equality is forbidden` | `x === y` |
178
178
  | `throw new Error(m)` | `` `throw` is forbidden `` | `return Err(m)`, or `panic(m)` to end the process |
179
179
  | `try { … } catch { … }` | `` `try`/`catch`/`finally` is forbidden `` | `Result<T, E>` and `isErr()` |
180
- | `xs.reduce(f)`, `.forEach`, `.shift` | `` Unknown method `reduce` on i32[] (supported: push, pop, indexOf, join, set, fill, sort, map, filter, some, every, findIndex, slice) `` | a `for` loop; `map`, `filter`, `some`, `every`, `findIndex` and `slice` work, with a one- or two-parameter callback |
180
+ | `xs.reduce(f)`, `.shift` | `` Unknown method `reduce` on i32[] (supported: push, pop, indexOf, join, set, fill, sort, map, filter, some, every, findIndex, forEach, slice) `` | a `for` loop; `map`, `filter`, `forEach`, `some`, `every`, `findIndex` and `slice` work, with a one- or two-parameter callback |
181
181
  | `xs.find(f)` | `` `find` is not supported: TypeScript types its answer `T \| undefined` … `` (NL2697) | `const i = xs.findIndex(f); if (i >= 0) { ... xs[i] ... }` |
182
182
  | `s.toUpperCase()`, `s.split()`, `s.trim()`, `s.replace()` | `` Unknown method … on string `` | index bytes with `charCodeAt` / `substring` |
183
183
  | `x.toFixed(2)`, `s.split(sep, limit)` | `` Unknown method `toFixed` on f64 `` | `toFixed(x, 2)` and `splitLimit(s, sep, limit)` from `nish/text` |
@@ -200,7 +200,8 @@ rejects. This table is the highest-value part of the page.
200
200
  | `keyof T`, `<T = i32>` (a default type argument) | `` Unsupported type `keyof T` (Phase 1 supports …) `` / `a default type argument … is not supported` | name the type; a type argument is always inferred |
201
201
  | `class B extends A` | `` `extends` is not supported: Nish has no inheritance `` | repeat the fields and `implements` an interface |
202
202
  | `static` members, `get x()` / `set x(v)` | `` … `static` members are not supported `` / `` Getters and setters are not supported in class `C` (use a method) `` | module `const`s and plain methods |
203
- | `const [a, b] = xs`, `({ x }: Point) =>`, `(n?: i32)`, `(n = 1)`, `f(...xs)` | `Destructuring is not supported` / `Destructured parameters are not supported` / `Optional parameters are not supported` / `` Parameter `n` has a default and no type annotation `` / `Spread arguments are not supported` | one name per binding; `n: i32 = 1` (a constant or an earlier parameter) for a default, `o: Opts | null = null` for an options argument; `...ns: i32[]` as the last parameter, or pass the array itself |
203
+ | `[a, b] = [b, a]`, `const { x = 0 } = p`, `({ x }: Point) =>`, `(n?: i32)`, `(n = 1)`, `f(...xs)` | `Destructuring assignment is not supported` / `A default in a destructuring pattern is not supported` / `Destructured parameters are not supported` / `Optional parameters are not supported` / `` Parameter `n` has a default and no type annotation `` / `Spread arguments are not supported` | one name per binding; `n: i32 = 1` (a constant or an earlier parameter) for a default, `o: Opts | null = null` for an options argument; `...ns: i32[]` as the last parameter, or pass the array itself |
204
+ | `const { a, b } = config` at module level | `Destructured constants are not supported` | one module `const` per name (a module constant is a compile-time value folded into each use, with nothing at run time for a pattern to read), or destructure inside a function |
204
205
  | `function f(): void;` (an overload), `export default function ()` | `Functions must have a body` / `Functions must be named` | one named function, with its body |
205
206
  | a method in an `interface` | `` Interface `I` cannot declare methods (interfaces describe layout only) `` | fields only; a top-level function over the interface |
206
207
  | `abstract class`, a `declare class` with methods, `constructor(public x: i32)`, `interface B extends A`, `[k: string]: T` | `Abstract classes are not supported` / `` `declare class Point` cannot have a method or accessor `` (a `declare class` is a C struct: fields only) / `Parameter properties … are not supported; declare the field and assign it` / ``Interface inheritance (`extends`) is not supported; list every field`` / `Index signatures are not supported …` | a plain class with its fields declared and assigned in the constructor; every field listed; a `Map` for a keyed table |
@@ -218,7 +219,7 @@ rejects. This table is the highest-value part of the page.
218
219
  | `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 |
219
220
  | `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 |
220
221
  | `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` |
221
- | `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) |
222
+ | `for (const [k, v] of m)`, `m.entries()`, `new Map(entries)` | each refused by name | `Map` and `Set` exist, with `size`, `get`, `set` / `add`, `has`, `delete`, `clear`, `forEach`, and `keys()` / `values()` in a `for...of` — see [Map and Set](#map-and-set) |
222
223
  | `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) { … }` |
223
224
  | `let x = 5; x = "s"` | `Cannot initialize …` | types never change and never convert implicitly |
224
225
 
@@ -293,6 +294,7 @@ compatible only when their types are identical.
293
294
  | `Int32Array`, `Float32Array`, `Float64Array`, `BigInt64Array` | aliases of `i32[]`, `f32[]`, `f64[]`, `i64[]` | not distinct types; fixed length, so no `push` or `pop` (NL2415): declare `f64[]` to grow one |
294
295
  | `class C`, `interface I` | a struct, fields in declaration order | no header, no vtable |
295
296
  | `enum K` | a **distinct** type represented as `i32` | never interchangeable with `i32` |
297
+ | `enum K { A = "a" }` | a string enum: a distinct type, its member's ordinal as `i32` | never interchangeable with `string`; `String(k)` reads the member's string |
296
298
  | `K.M` | an enum member type: the one member `K.M`, as `i32` | holds only that member; a read is a `K` |
297
299
  | `T \| null` | `T` a class, interface, array, string or function reference | a scalar can never be nullable |
298
300
  | `A \| B` of tagged variants | a pointer to the variant; its first field is the tag | [Discriminated unions](#discriminated-unions); only the tag is read until a test of it narrows |
@@ -918,8 +920,9 @@ export const main = (): i32 => {
918
920
  read `this` (bind `const self = this`), or read a function-typed parameter
919
921
  of its function. An arrow inside another arrow, or given to a method, a
920
922
  constructor, `expose` or `exposeWith`, captures nothing; the callbacks of
921
- the array methods `sort`, `map`, `filter`, `some`, `every` and `findIndex`
922
- are the exception, and capture as an arrow argument does.
923
+ the array methods `sort`, `map`, `filter`, `some`, `every`, `findIndex` and
924
+ `forEach`, and of `Map` and `Set` `forEach`, are the exception, and capture
925
+ as an arrow argument does.
923
926
  - **The argument's type must match exactly**: `(x: i32) => i64` for a
924
927
  `(x: i32) => i32` parameter is refused. A generic function cannot be passed
925
928
  by name — write `(x) => identity(x)`.
@@ -1097,8 +1100,8 @@ export const main = (): i32 => {
1097
1100
  NL9012: each element pays for building it and for the release. Storing an
1098
1101
  allocation into another object (NL2352) and touching `Arena` (NL2351) are
1099
1102
  refused, because either would make that release unsound.
1100
- - **A map's result is a number, a `boolean`, an enum, a `string` or an array
1101
- of numbers, booleans or enums**: a string or a scalar array is copied out of
1103
+ - **A map's result is a number, a `boolean`, an enum (of either kind), a
1104
+ `string` or an array of numbers, booleans or enums**: a string or a scalar array is copied out of
1102
1105
  the worker's arena at the join. An array of strings, a nested array, a class,
1103
1106
  a `Map` or a `Set` is refused (NL2348): answer a string or a number per
1104
1107
  element and build the structure after the call. **A reduce's `T` stays a number, a
@@ -1174,7 +1177,7 @@ export const main = (): i32 => {
1174
1177
  above the scope and `s.spawn(entry, arg, answer, 0)`. Either follows the
1175
1178
  data-parallel rules: it writes nothing anybody else can see but what it
1176
1179
  writes through a `Mutex`'s guard or sends on a `Channel` (below), answers a number,
1177
- a `boolean`, an enum, a `string` or an array of numbers, booleans or enums
1180
+ a `boolean`, an enum of either kind, a `string` or an array of numbers, booleans or enums
1178
1181
  (copied out of its arena at the join), and leaves `Arena` alone. A task cannot open a scope
1179
1182
  of its own or call `parallelMapInto`.
1180
1183
  - **Any argument will do** — an array, an object — because nothing writes
@@ -1241,7 +1244,7 @@ export const main = (): i32 => {
1241
1244
  ```
1242
1245
 
1243
1246
  - **Only `g.value`, and only as the base of a field or element access.** Read
1244
- a number, a `boolean`, an enum or a `string` through it, or store one into a
1247
+ a number, a `boolean`, an enum of either kind or a `string` through it, or store one into a
1245
1248
  field or an element that already exists (a string is copied each way) (for a `Mutex<i32>`, `g.value = g.value + 1`).
1246
1249
  Don't bind, store, return or walk `g` itself (NL2466), nor bind, store, return
1247
1250
  or walk `g.value` or an array it holds (NL2467); store only a scalar or a
@@ -1338,6 +1341,12 @@ export const main = (): i32 => {
1338
1341
  - **Add once per batch**: count into a local array, then one `add` per bin.
1339
1342
  One `add` per value makes the cores wait on each other.
1340
1343
  - **`AtomicI64` takes `i64` values**, exact under Node within ±2^53.
1344
+ - **Many counters — a histogram, a count per route — go in one atomic
1345
+ array**: `new AtomicI32Array(16)` (or `AtomicI64Array`) is 16 counters in
1346
+ one buffer, each `0`; every method takes the index first,
1347
+ `bins.add(b, 1)`, `bins.load(b)`, and checks it as an array index. Prefer it
1348
+ to an `AtomicI32[]`, whose counters are separate objects on separate cache
1349
+ lines. Same rules as above.
1341
1350
 
1342
1351
  ```ts nish:err NL2513
1343
1352
  import { AtomicI32, scope } from "nish/threads";
@@ -1406,7 +1415,7 @@ export const main = (): i32 => {
1406
1415
  };
1407
1416
  ```
1408
1417
 
1409
- - **It carries a number, a `boolean`, an enum or a `string`** (copied in by
1418
+ - **It carries a number, a `boolean`, an enum of either kind or a `string`** (copied in by
1410
1419
  `send`, out by the receive), never an array or an object.
1411
1420
  - **Declare it as a `const` right before its scope** — in the block that holds
1412
1421
  `using s = scope()`, or in the block around the scope's block — and hand it
@@ -1468,7 +1477,9 @@ export const main = (): i32 => {
1468
1477
 
1469
1478
  - **Crosses, by copy:** a number, a `boolean`, an enum, a `string`, an array
1470
1479
  of numbers, booleans or enums — a task's answer, a `parallelMap` element, a
1471
- `Channel<string>` value, a string stored through a guard. Each thread moves
1480
+ `Channel<string>` value, a string stored through a guard. A string enum
1481
+ crosses as its `i32` ordinal, like a numeric one: its strings sit in a
1482
+ constant table every thread reads. Each thread moves
1472
1483
  the `parallelMap` elements it answers into blocks of its own, and the caller
1473
1484
  takes the blocks whole at the join; a task's answer under 64 KB is copied in
1474
1485
  by the joining thread. On one thread every element still pays the move, so
@@ -1618,7 +1629,8 @@ export const main = (): i32 => {
1618
1629
  freed.** `readCString(p: CPtr): string` copies the NUL-terminated bytes at
1619
1630
  `p` into a new string; a dangling or unterminated `p` is undefined
1620
1631
  behaviour, which is why it needs the import. It takes a `CPtr`, so narrow a
1621
- `CPtr | null` with `!== null` first.
1632
+ `CPtr | null` with `!== null` first. A `NULL` `p` panics (`ffi-null`) before
1633
+ the copy, so `--deny-panics` refuses the call.
1622
1634
  - **A struct C owns is copied out with `readStruct` from `nish:unsafe`.**
1623
1635
  `const lc: Lconv = readStruct(p)` copies the bytes at `p` into a new
1624
1636
  instance of the `declare class` the context names; write the annotation,
@@ -2001,6 +2013,43 @@ export const main = (): i32 => {
2001
2013
  point: `Kind` and `i32` never convert in either direction. Members must be
2002
2014
  numeric literals. `===` and `!==` are the **only** operators — no arithmetic,
2003
2015
  no bitwise, so **bit flags stay `i32` module constants**.
2016
+ - A **string enum** gives every member a string literal (`Admin = "admin"`),
2017
+ and is just as distinct: it is stored as its member's `i32` ordinal, `===`,
2018
+ `!==` and `switch` compare ordinals, and `String(r)` is the only way to its
2019
+ string (one load from a constant table, no allocation). `Role` and `string`
2020
+ never convert either way — `r === "admin"` is NL2788,
2021
+ `const s: string = r` and `` `${r}` `` NL2789, `const r: Role = "admin"`
2022
+ NL2790 — because a string compare or a hidden conversion is exactly the cost
2023
+ the ordinal exists to avoid: compare members, or write `String(r)` once.
2024
+ Mixing string and numeric members is NL1043, a member without a value
2025
+ NL1064, a template or computed value NL1065/NL1066, two members of one string
2026
+ NL2786, a value that is not valid UTF-8 NL2787. A `Role | null` is NL2010, as for every enum. There is no
2027
+ `Role.parse` yet: test `s === String(Role.Admin)` per member, or decode it
2028
+ with typed JSON.
2029
+
2030
+ ```ts nish:ok
2031
+ enum Role {
2032
+ Admin = "admin",
2033
+ Guest = "guest",
2034
+ }
2035
+
2036
+ const parse = (s: string): Role => (s === String(Role.Admin) ? Role.Admin : Role.Guest);
2037
+
2038
+ const rank = (r: Role): i32 => {
2039
+ switch (r) {
2040
+ case Role.Admin:
2041
+ return 2;
2042
+ default:
2043
+ return 1;
2044
+ }
2045
+ };
2046
+
2047
+ export const main = (): i32 => {
2048
+ const r = parse("admin");
2049
+ console.log(`${String(r)} ${rank(r)}`);
2050
+ return r === Role.Admin ? 0 : 1;
2051
+ };
2052
+ ```
2004
2053
  - **A member is also a type.** `Kind.While` as an annotation is a slot that
2005
2054
  holds exactly that member — the shape of a tag field that says which case
2006
2055
  its object is. Only the member's own constant (or a value already of that
@@ -2113,10 +2162,14 @@ export const main = (): i32 => {
2113
2162
  other union is still NL1053.
2114
2163
  - A union is a local, parameter, field, return, array element, or nullable
2115
2164
  (`Shape | null`), and a `Map`'s value is any of those (`Map<string, Shape>`,
2116
- `Map<string, Shape[]>`, `Map<string, Shape | null>`). An alias may name another union, which is flattened. A
2165
+ `Map<string, Shape[]>`, `Map<string, Shape | null>`), and a type argument:
2166
+ `Box<Shape>`, `Stack<Shape>`, a generic call binding `T` to a union,
2167
+ `Result<Shape, E>` / `Result<T, Shape>`, and `nish/map`'s `getOrInsert` /
2168
+ `reserve` on a `Map<K, Shape>`. An alias may name another union, which is flattened. A
2117
2169
  variant, or a smaller union, converts into it wherever the union is
2118
2170
  expected — argument, `return`, `push`, an annotated array literal, a
2119
- ternary arm or `??` default whose other side is the union. A class that
2171
+ ternary arm or `??` default whose other side is the union, and a generic's
2172
+ `T` bound to it (`new Box<Shape>(new Circle())`, `Ok(new Square())`). A class that
2120
2173
  implements an interface variant converts to that interface first. A union
2121
2174
  crosses modules but not a sidecar (NL4009).
2122
2175
  - **Test the tag to read a variant.** Before a test, the tag is the only
@@ -2184,12 +2237,13 @@ export const main = (): i32 => {
2184
2237
  falls back to every member the body stored
2185
2238
  anywhere or the whole type, which accepts a few comparisons `tsc` refuses
2186
2239
  (TS2367; LANGUAGE.md, "Accepted here, refused by `tsc`").
2187
- - **Refused by design:** union type arguments (`Box<Shape>`,
2188
- `Result<Shape, E>`, a generic call binding `T` to a union: NL2533; a
2189
- built-in `Map`'s value is the one that may be a union, though `nish/map`'s
2190
- generic `getOrInsert`/`reserve` on such a map is NL2533), unions as `Map`/`Set` keys, covariant arrays (`Circle[]`
2191
- is not `Shape[]`), and inferred unions (an unannotated ternary or array of
2192
- two variants).
2240
+ - **Refused by design:** unions as `Map`/`Set` keys (NL2353), a generic
2241
+ class as a variant (NL2522), covariant arrays (`Circle[]` is not
2242
+ `Shape[]`), inferred unions (an unannotated ternary or array of two
2243
+ variants, or one a generic call would infer: NL2172), a union meeting a
2244
+ constraint `<T extends I>` (NL2328), and a union inside a `Secret`
2245
+ (NL2428), a typed-JSON class (NL2486) or a C header / N-API signature
2246
+ (NL4009), generic instance or not.
2193
2247
  - **Declare what you store.** A store of a value that is only some of the
2194
2248
  variants into a union slot is NL2534, because `tsc` would narrow the slot
2195
2249
  from there on. Declare the slot as the variant, or store a value of the
@@ -2248,7 +2302,9 @@ export const main = (): i32 => {
2248
2302
  - Functions and enums may be renamed on import; classes and interfaces may
2249
2303
  not — the type name is part of the ABI.
2250
2304
  - Import cycles are allowed; a shared dependency is compiled once.
2251
- - **A function name is unique across the whole program**, exported or not.
2305
+ - **A function name is unique across the whole program**, exported or not
2306
+ (a proposal to relax this for private functions is
2307
+ [WP57](https://github.com/amritk/nish/blob/main/docs/wp57-module-scoped-names.md); it has not shipped).
2252
2308
  - An `export`ed function is an external C-ABI symbol; every other function gets
2253
2309
  `internal` linkage so LLVM may inline or drop it.
2254
2310
  - **So an exported function is not named after a C library function**
@@ -2271,7 +2327,16 @@ export const main = (): i32 => {
2271
2327
  - `let` / `const` need an initializer and take their type from it; an
2272
2328
  annotation must match **exactly**. `const` freezes the binding, not the
2273
2329
  contents: `xs[0] = 1` and `xs.push(1)` on a `const xs` are fine.
2274
- - `var` is forbidden. Destructuring is not supported.
2330
+ - `var` is forbidden.
2331
+ - A local or a `for...of` head may destructure: `const { x, y: py } = p`,
2332
+ `let [a, , c] = xs`, `for (const { x, y } of points)`. Each name is one
2333
+ field read, or one bounds-checked element read (past the end panics; it is
2334
+ never `undefined`). No defaults, rests, nested patterns, computed keys or
2335
+ assignment patterns; no pattern over a `Map`, a `string` or a nullable
2336
+ value, and no pattern as a parameter (`const { w, h } = s` over a
2337
+ parameter `s` is fine). A module constant may not destructure either, because a
2338
+ module constant is a compile-time value folded into each use, and a
2339
+ pattern's names are reads of a receiver at run time.
2275
2340
  - **Semicolons are optional**, where TypeScript would insert one: at a line
2276
2341
  break, before `}` and at the end of the file. It is TypeScript's rule, so a
2277
2342
  line starting with `(` or `[` continues the one before it, and `return`
@@ -2723,7 +2788,9 @@ order, SameValueZero keys (`-0` is `+0`, `NaN` finds `NaN`). What they have is
2723
2788
  exactly `size` (a read-only `number`), `get(k)`, `set(k, v)` / `add(x)` (both
2724
2789
  answer the receiver, so they chain), `has(k)`, `delete(k)` (answers whether it
2725
2790
  was there) and `clear()`, and `keys()` / `values()` as the iterable of a
2726
- `for...of` and nowhere else. `entries` and `forEach` are refused by name.
2791
+ `for...of` and nowhere else, and `forEach(f)`: `m.forEach((value, key) => ...)`
2792
+ and `s.forEach((x) => ...)` compile to that `for...of` walk with `f` inlined,
2793
+ and answer `void`. `entries` is refused by name.
2727
2794
 
2728
2795
  ```ts nish:ok-body
2729
2796
  const seen = new Set<string>();
@@ -2799,8 +2866,8 @@ console.log(`${total}`); // 121
2799
2866
 
2800
2867
  - An iterator is not a value: `keys()` / `values()` stored, passed, returned or
2801
2868
  spread are refused. Pass the map itself and walk it where it is used.
2802
- - `for (const e of m)` over a `Map` itself is refused, because it would need
2803
- `[key, value]` destructuring: walk `m.keys()` and call `m.get(k)`.
2869
+ - `for (const e of m)` over a `Map` itself is refused, because its
2870
+ `[key, value]` pairs are two-type tuples: walk `m.keys()` and call `m.get(k)`.
2804
2871
 
2805
2872
  ```ts nish:err-body NL2375
2806
2873
  const m = new Map<string, i32>();
@@ -2843,14 +2910,18 @@ export const main = (): i32 => {
2843
2910
 
2844
2911
  `jsonDecode(d, out)` reads one JSON object into a class and `jsonEncode(w,
2845
2912
  value)` writes one; the compiler writes the code at each call from the class's
2846
- fields. A field is `i32`, `u32`, `i64`, `u64`, `f64`, `boolean`, `string`, a
2847
- numeric enum, a class, an array of one of those, a `Map<string, V>` of any of
2913
+ fields. A field is `i32`, `u32`, `i64`, `u64`, `f64`, `boolean`, `string`, an
2914
+ enum, a class, an array of one of those, a `Map<string, V>` of any of
2848
2915
  those, or a `string`, class, array or map `| null`; anything else is refused at
2849
2916
  the call (NL2485), a `Map` with non-`string` keys and a `Set` included, and so
2850
2917
  is a value that is not a class (NL2486). Decoding is strict: every field
2851
2918
  required, each key once, an unknown key an error unless `d.ignoreUnknown`, and
2852
2919
  every outcome a sticky negative code in `d.failed`, never a panic. An enum is
2853
- its number, and a number that is no member's value is `JSON_DECODE_TYPE`; a
2920
+ read and written as a numeric one's number or a string one's string, and a
2921
+ value that is no member's is `JSON_DECODE_TYPE` (the field keeps its member) —
2922
+ so a string enum field is how a program checks a closed set of strings from
2923
+ input (`role: Role`, `{"role":"admin"}`); a `Role | null` field is NL2010 and a
2924
+ `Map` keyed by an enum NL2485; a
2854
2925
  `u64` is exact to 2^64 - 1, and negative is `JSON_DECODE_RANGE`; a map is
2855
2926
  emptied and filled in the input's key order, a repeated key an error, and
2856
2927
  more keys over all the maps of one decode than `d.maxMapKeys` (4,096 unless
@@ -2868,7 +2939,8 @@ a rename to a non-string (NL2496) or to a key that is not valid UTF-8
2868
2939
  `JsonNumber` field keeps a number's text byte for byte (`text`, `i64`, `u64`,
2869
2940
  `f64`, `setText`). A tagged union of classes is a field, an array element or
2870
2941
  `jsonEncode`'s value too: the object with its tag key first, the tag the
2871
- member's name or the variant's `tag` option. Decode one with
2942
+ member's name (a string enum's member's string) or the variant's `tag`
2943
+ option. Decode one with
2872
2944
  `const u = jsonDecodeUnion(d, prev)` (never `jsonDecode`, NL2719, and no type
2873
2945
  argument): it answers `prev` refilled when the tag matches, else a new variant,
2874
2946
  and `prev` on failure (only at the top: a nested union slot may hold the new
@@ -3010,7 +3082,14 @@ every pass's string, because nothing frees a value a later pass replaced:
3010
3082
  value with `const` inside the loop when only the pass reads it, or keep
3011
3083
  numbers across passes and build the value once after the loop. A server, or
3012
3084
  anything that runs for a long time, should compile with `--deny-retention`,
3013
- which makes this warning and the three like it errors.
3085
+ which makes this warning and the four like it errors.
3086
+
3087
+ **Build a request's temporaries in an arena block.** A pass of a loop with
3088
+ no bound on its passes (`while (true)`, a server's poll loop) that calls
3089
+ `accept`, `respond` or anything else that stores is refused its own scope,
3090
+ so a reply string it builds stays until the loop ends: NL9018. Build it in
3091
+ `{ using a = arena(); ... }` inside the loop body, copy what must outlive the
3092
+ block into a buffer made before the loop, and call what stores after it.
3014
3093
 
3015
3094
  Everything else is bumped from the arena, which is released when `main`
3016
3095
  returns. To give memory back sooner, scope it with `using a = arena()`;
@@ -3059,7 +3138,7 @@ the module (NL4015).
3059
3138
 
3060
3139
  ## Recipes for what is missing
3061
3140
 
3062
- **Iterate and accumulate** — there is no `reduce` or `forEach` (`map`, `filter`, `some`, `every`, `findIndex` and `slice` work); fold in a loop:
3141
+ **Iterate and accumulate** — there is no `reduce` (`map`, `filter`, `forEach`, `some`, `every`, `findIndex` and `slice` work, but a callback may not assign a local of its caller); fold in a loop:
3063
3142
 
3064
3143
  ```ts nish:ok-body
3065
3144
  const xs: i32[] = [1, 2, 3];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/nish-aarch64-linux",
3
- "version": "0.39.0",
3
+ "version": "0.40.1",
4
4
  "description": "The nish native compiler for Linux on ARM64",
5
5
  "license": "MIT",
6
6
  "os": [
package/runtime/nish.d.ts CHANGED
@@ -33,8 +33,8 @@
33
33
  * `lib.es2022`'s**, which a program is checked against: a second declaration
34
34
  * would clash with it, so the interfaces at the foot of this file merge into
35
35
  * lib's, adding Nish's documentation and no signature narrower than lib's.
36
- * `nish`'s surface is lib's less what it defers — no `entries`, no `forEach`,
37
- * no `for...of` over a `Map` itself — with `keys()` and `values()` admitted
36
+ * `nish`'s surface is lib's less what it defers — no `entries`, no `for...of`
37
+ * over a `Map` itself — with `keys()` and `values()` admitted
38
38
  * only as the iterable of a `for...of`, and `get`'s `V | undefined` only as a
39
39
  * `const`'s initialiser, the left of `??` or an operand of `=== undefined`,
40
40
  * none of which `tsc` can know (docs/LANGUAGE.md -> `Map` and `Set`).
@@ -805,20 +805,22 @@ declare function wrappingMul<T extends i32 | i64>(a: T, b: T): T;
805
805
  *
806
806
  * The parameter is `CPtr`, so an unnarrowed `CPtr | null` is refused (``
807
807
  * `readCString` expects an argument of type CPtr, got CPtr | null ``) and `if
808
- * (p !== null)` comes first; a `declare function` whose result is declared
809
- * `CPtr` gets no check, so declare a result that may be `NULL` as `CPtr |
810
- * null`.
808
+ * (p !== null)` comes first. A `declare function` declared to answer `CPtr`
809
+ * may still answer `NULL`, so the call tests `p` first and panics with
810
+ * `ffi-null` on `NULL` (`` `readCString` read a NULL pointer ``, exit 1), as
811
+ * `readStruct` does; declare a result that may be `NULL` as `CPtr | null`.
811
812
  *
812
813
  * The copy is new on every call and is the calling function's allocation, and
813
814
  * it is refused inside a `using a = arena()` block that would release one held
814
815
  * outside it (`` `readCString(p)` may be allocated inside the `using arena()`
815
- * block ``). Under `--deny-panics` it is an allowed `unchecked` site, with the
816
- * copy's `oom` beside it, and the pointer it reads is `ffi`. It lowers the same
816
+ * block ``). Under `--deny-panics` its `NULL` test is an `ffi-null` site no
817
+ * proof removes, so the scope refuses the call (the copy's `oom` beside it is
818
+ * allowed), and the pointer it reads is `ffi`. It lowers the same
817
819
  * on wasm32, where whether the program links is the `declare function`'s
818
820
  * question. It has no Node form, as a `CPtr` comes only from a `declare
819
821
  * function`, which Node cannot call. Capability: unsafe.
820
822
  *
821
- * @param p the address a `declare function` handed back.
823
+ * @param p the address a `declare function` handed back; `NULL` panics.
822
824
  * @returns a copy of the bytes before the first `NUL`.
823
825
  */
824
826
  declare function readCString(p: CPtr): string;
@@ -3571,11 +3573,11 @@ declare module "nish:net" {
3571
3573
  * `i64`. A program that stays in range prints the same as natively.
3572
3574
  *
3573
3575
  * **The no-panic scope.** Under `--deny-panics` or `"nish".noPanic`,
3574
- * `uncheckedGet`, `uncheckedSet` and `readCString` are allowed `unchecked`
3575
- * sites, because the import has already said that an index out of range is
3576
- * the author's to rule out. `readStruct` is not: it tests its pointer and
3576
+ * `uncheckedGet` and `uncheckedSet` are allowed `unchecked` sites, because
3577
+ * the import has already said that an index out of range is the author's to
3578
+ * rule out. `readCString` and `readStruct` are not: each tests its pointer and
3577
3579
  * panics with `ffi-null` on `NULL`, a site no proof removes, so the scope
3578
- * refuses it. The wrapping three are not sites at all: they are defined for
3580
+ * refuses them. The wrapping three are not sites at all: they are defined for
3579
3581
  * every pair.
3580
3582
  *
3581
3583
  * Rules: https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#nishunsafe-unchecked-access-and-defined-wrapping
@@ -3639,10 +3641,11 @@ declare module "nish:unsafe" {
3639
3641
  /**
3640
3642
  * The `NUL`-terminated bytes at `p`, copied into a new string by
3641
3643
  * `@nish.ffi.str`, the scan-and-copy a `string` result of a
3642
- * `declare function` uses. It reads and allocates, and is native only.
3644
+ * `declare function` uses, after a `NULL` test that panics with
3645
+ * `ffi-null`. It reads and allocates, and is native only.
3643
3646
  *
3644
- * @param p A pointer from a `declare function`. Undefined behaviour unless
3645
- * it points at a live C string.
3647
+ * @param p A pointer from a `declare function`; `NULL` panics. Undefined
3648
+ * behaviour unless it points at a live C string.
3646
3649
  * @returns A copy of the bytes before the `NUL`; C keeps its buffer.
3647
3650
  */
3648
3651
  export function readCString(p: CPtr): string;
@@ -6053,8 +6056,9 @@ interface StringConstructor {
6053
6056
  * arguments in this version"); the type arguments are written out, except that
6054
6057
  * a `const` or `let` annotated with the type takes them from the annotation,
6055
6058
  * and a bare `new Map()` is refused: "`Map` is generic: it must be written with
6056
- * its type arguments". The members are JavaScript's, less `entries` and
6057
- * `forEach` (there is no destructuring, and a method cannot take a function);
6059
+ * its type arguments". The members are JavaScript's, less `entries` (there
6060
+ * is no destructuring); `forEach(f)` is the `for...of` walk with `f`, an arrow
6061
+ * or a top-level function of the value and optionally the key, inlined;
6058
6062
  * anything else is refused as if it did not exist. `set` answers the receiver,
6059
6063
  * so calls chain.
6060
6064
  *
package/runtime/nish.h CHANGED
@@ -135,6 +135,16 @@ void nish_arena_release(uint64_t mark);
135
135
  * it) leaves the arena untouched and answers `p`. Compiled callers use it to
136
136
  * reclaim the temporaries a string-returning callee left behind. */
137
137
  void *nish_arena_keep(uint64_t mark, void *p);
138
+ /* Root keep (WP55, wasm only, defined in runtime-wasm.c): after an export call
139
+ * that began at `mark`, keep what the `count` root storages in `roots` reach
140
+ * and compact the kept region when it outgrows them. A page module's
141
+ * `nish_root_keep(mark)` calls it with its `@nish.roots` table; the loader
142
+ * calls that in place of `nish_arena_release(mark)`. */
143
+ struct nish_root;
144
+ void nish_runtime_root_keep(uint64_t mark, const struct nish_root *const *roots, int32_t count);
145
+ /* Root storage's nish_reset_arena and nish_free_arena (wasm only): empty every
146
+ * root in `roots`, then the arena. */
147
+ void nish_runtime_root_reset(const struct nish_root *const *roots, int32_t count);
138
148
  /* Bytes bumped in the current chunk (`Arena.used()`); a steady-state loop keeps it flat. */
139
149
  uint64_t nish_arena_used(void);
140
150
 
@@ -0,0 +1,123 @@
1
+ /**
2
+ * `nish/page/frame`: puts a wasm module's 0xRRGGBB framebuffer on a canvas
3
+ * through WebGPU, WebGL 2 or Canvas 2D, and runs a fixed-step loop that
4
+ * renders on every animation frame (docs/guide/using-nish/interop.md).
5
+ */
6
+
7
+ /** A way of drawing on the canvas, best first: WebGPU, WebGL 2, Canvas 2D. */
8
+ export type Backend = "webgpu" | "webgl2" | "canvas2d";
9
+
10
+ /** A tier given up, and why: refused when it was built, or lost later. */
11
+ export interface Attempt {
12
+ /** The tier given up. */
13
+ readonly backend: Backend;
14
+ /** What refused or lost it, as the browser reported it. */
15
+ readonly reason: string;
16
+ }
17
+
18
+ /** What `createPresenter` takes beyond the canvas. */
19
+ export interface PresenterOptions {
20
+ /** The tier to start from; the tiers above it are not tried. WebGPU by default. */
21
+ readonly prefer?: Backend;
22
+ /**
23
+ * Called each time a tier is given up for the next one, when the presenter
24
+ * is created or later, on a lost device or context. An error it throws is
25
+ * passed to `reportError` and the fallback goes on.
26
+ *
27
+ * @param from - the tier given up
28
+ * @param to - the tier tried next
29
+ * @param reason - why `from` was given up
30
+ * @param canvas - the canvas `to` builds on: a fresh one when `from` had
31
+ * taken a context, the place to add the page's listeners again (during
32
+ * `createPresenter`, before `presenter` exists, the only way to reach it)
33
+ */
34
+ onFallback?(from: Backend, to: Backend, reason: string, canvas: HTMLCanvasElement): void;
35
+ }
36
+
37
+ /** Draws a framebuffer on a canvas, letterboxed to keep its aspect, nearest-neighbour scaled. */
38
+ export interface Presenter {
39
+ /** The tier presenting now; after every tier is lost, the last one tried. */
40
+ readonly backend: Backend;
41
+ /** Every tier refused or lost so far, in order. */
42
+ readonly attempts: readonly Attempt[];
43
+ /**
44
+ * The canvas presented on. A fallback after a tier has taken a context puts
45
+ * a fresh canvas in the old one's place (same attributes, no listeners), so
46
+ * read this again after `onFallback`. A canvas outside the document has no
47
+ * place to give: its fresh canvas is outside the document too, for the page
48
+ * to put where it wants.
49
+ */
50
+ readonly canvas: HTMLCanvasElement;
51
+ /**
52
+ * Draws `width` by `height` pixels of `pixels`, row-major 0xRRGGBB words; the
53
+ * top byte is ignored. Pass the view into the module's memory: it is read,
54
+ * never kept past the call or copied first.
55
+ *
56
+ * @param pixels - the framebuffer, at least `width * height` words
57
+ * @param width - its width in pixels, a whole number of at least 1
58
+ * @param height - its height in pixels, a whole number of at least 1
59
+ */
60
+ present(pixels: Int32Array, width: number, height: number): void;
61
+ /**
62
+ * Sizes the canvas's drawing buffer to its CSS size in device pixels, at
63
+ * least 1 by 1. A size that is not finite or is below 0, or a ratio that is
64
+ * not above 0, is a `RangeError`.
65
+ *
66
+ * @param cssWidth - the canvas's width in CSS pixels
67
+ * @param cssHeight - the canvas's height in CSS pixels
68
+ * @param devicePixelRatio - device pixels per CSS pixel
69
+ */
70
+ resize(cssWidth: number, cssHeight: number, devicePixelRatio: number): void;
71
+ /** Releases the tier's device or context; `present` then draws nothing, and no fallback follows. */
72
+ destroy(): void;
73
+ }
74
+
75
+ /**
76
+ * Makes a presenter on `canvas`, trying WebGPU, then WebGL 2, then Canvas 2D,
77
+ * and keeping the first that builds. A tier lost later is replaced by the next
78
+ * one down, on a fresh canvas element when the old one already holds a context.
79
+ *
80
+ * @param canvas - the canvas to present on
81
+ * @param options - the tier to start from and the fallback callback
82
+ * @returns the presenter; it rejects, naming every tier's reason, when no tier builds
83
+ */
84
+ export declare function createPresenter(
85
+ canvas: HTMLCanvasElement,
86
+ options?: PresenterOptions
87
+ ): Promise<Presenter>;
88
+
89
+ /** What `runFixedStep` takes. */
90
+ export interface FixedStepOptions {
91
+ /** How many times a second `step` runs. */
92
+ readonly stepsPerSecond: number;
93
+ /** The most steps one frame runs; the backlog past it is dropped. 8 by default. */
94
+ readonly maxStepsPerFrame?: number;
95
+ /** Advances the program one fixed step. */
96
+ step(): void;
97
+ /**
98
+ * Draws a frame; called on every animation frame.
99
+ *
100
+ * @param alpha - how far into the next step this frame is, in [0, 1)
101
+ * @param frameMs - the frame's length in milliseconds, at most 250; 0 on the first frame
102
+ */
103
+ render(alpha: number, frameMs: number): void;
104
+ }
105
+
106
+ /** A running loop. */
107
+ export interface FixedStepLoop {
108
+ /** Ends the loop and cancels its next frame. */
109
+ stop(): void;
110
+ /** The display's refresh rate, read from the fastest recent frame intervals; 0 before the second frame. */
111
+ readonly refreshHz: number;
112
+ /** Renders per second over the last half second or so; 0 until one has passed. */
113
+ readonly fps: number;
114
+ }
115
+
116
+ /**
117
+ * Runs `step` at a fixed rate and `render` on every animation frame. A frame
118
+ * longer than a quarter second counts as a quarter second.
119
+ *
120
+ * @param options - the step rate, the per-frame step limit and the callbacks
121
+ * @returns the running loop
122
+ */
123
+ export declare function runFixedStep(options: FixedStepOptions): FixedStepLoop;