@amritk/nish-aarch64-darwin 0.38.0 → 0.39.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 (58) hide show
  1. package/bin/nish +0 -0
  2. package/docs/AI.md +348 -37
  3. package/package.json +1 -1
  4. package/runtime/core/host.d.ts +11 -0
  5. package/runtime/core/host.mjs +35 -0
  6. package/runtime/nish.d.ts +301 -18
  7. package/runtime/nish.h +74 -10
  8. package/runtime/nish.mjs +69 -6
  9. package/runtime/node.mjs +117 -0
  10. package/runtime/runtime-aes.c +12 -4
  11. package/runtime/runtime-async.c +43 -10
  12. package/runtime/runtime-checksum.c +207 -15
  13. package/runtime/runtime-net.c +32 -3
  14. package/runtime/runtime-os.c +174 -27
  15. package/runtime/runtime-region.c +94 -10
  16. package/runtime/runtime-sandbox.c +377 -17
  17. package/runtime/runtime-sha256.c +11 -4
  18. package/runtime/runtime-wasm.c +15 -0
  19. package/runtime/runtime.c +5 -0
  20. package/scripts/build.sh +27 -8
  21. package/std/README.md +5 -4
  22. package/std/compress/checksum.ts +13 -0
  23. package/std/compress/deflate.ts +0 -2
  24. package/std/crypto/p256.ts +247 -74
  25. package/std/crypto/p384.ts +3 -1
  26. package/std/crypto/pki.ts +35 -9
  27. package/std/crypto/x25519.ts +153 -64
  28. package/std/crypto/x509.ts +113 -10
  29. package/std/json-tokenizer.ts +20 -0
  30. package/std/json-typed.ts +217 -8
  31. package/std/net/handler.ts +130 -16
  32. package/std/net/http1-codec.ts +499 -150
  33. package/std/net/http1-server.ts +495 -22
  34. package/std/net/http2-cleartext.ts +526 -0
  35. package/std/net/http2-tls.ts +48 -0
  36. package/std/net/http2.ts +84 -0
  37. package/std/net/postgres-async.ts +1304 -86
  38. package/std/net/postgres-carrier.ts +343 -10
  39. package/std/net/postgres.ts +122 -7
  40. package/std/net/prefork.ts +195 -11
  41. package/std/net/quic-datagram.ts +30 -0
  42. package/std/net/quic-listener.ts +38 -12
  43. package/std/net/quic-packet.ts +19 -6
  44. package/std/net/quic-recovery.ts +134 -19
  45. package/std/net/quic-stream.ts +174 -36
  46. package/std/net/quic.ts +418 -18
  47. package/std/net/router.ts +39 -17
  48. package/std/net/serve.ts +162 -58
  49. package/std/net/tls/codec.ts +110 -32
  50. package/std/net/tls/record-server.ts +37 -7
  51. package/std/net/tls-tcp.ts +56 -1
  52. package/std/net/tls.ts +196 -50
  53. package/std/net/websocket.ts +55 -18
  54. package/std/net/webtransport.ts +179 -1
  55. package/std/regex.ts +69 -47
  56. package/std/region.ts +62 -11
  57. package/std/secret.ts +26 -59
  58. package/std/text.ts +233 -0
package/bin/nish CHANGED
Binary file
package/docs/AI.md CHANGED
@@ -7,6 +7,10 @@ Nish and get it accepted on the first try**. It is a digest, not the authority:
7
7
  This page exists because LANGUAGE.md is 2,300 lines written to be *read*, and
8
8
  what an author needs is the rules in one pass with the traps first.
9
9
 
10
+ > Its short form, published to agents by the docs site, is the
11
+ > [`writing-nish` skill](../skills/writing-nish/SKILL.md): a change here to the
12
+ > loop, the unlearn table or the checklist below moves it too.
13
+
10
14
  > Working **on the compiler** rather than **in the language**? That is a
11
15
  > different document: [`AGENTS.md`](../AGENTS.md) and [`.claude/`](../.claude/).
12
16
 
@@ -92,6 +96,14 @@ what remains. A warning can carry a fix too, and `--fix` applies it only when th
92
96
  compiles and the warning would be printed: `NL9007`'s inserts the guard that
93
97
  proves an index in range (not under `--no-warn-performance`).
94
98
 
99
+ Under `--warn-portability`, a portability warning can carry a **`review`**
100
+ after `fix`, in the same edit shape: a rewrite that makes the line read the
101
+ same under Node and compiles to byte-identical IR, but changes the source's
102
+ words, so `--fix` never applies it. Today that is `NL8006`, an integer
103
+ division, which `review` wraps in its type's conversion (`toI32(a / b)`).
104
+ The loop: run `--fix`, compile with `--warn-portability --json`, apply each
105
+ `review` you agree with, compile again and check the warning is gone.
106
+
95
107
  When it compiles, **check the native build against the program's TypeScript
96
108
  reading**. Run the project's tests natively; where it has none, write the
97
109
  program back out and run both:
@@ -168,6 +180,7 @@ rejects. This table is the highest-value part of the page.
168
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 |
169
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] ... }` |
170
182
  | `s.toUpperCase()`, `s.split()`, `s.trim()`, `s.replace()` | `` Unknown method … on string `` | index bytes with `charCodeAt` / `substring` |
183
+ | `x.toFixed(2)`, `s.split(sep, limit)` | `` Unknown method `toFixed` on f64 `` | `toFixed(x, 2)` and `splitLimit(s, sep, limit)` from `nish/text` |
171
184
  | `a?.b`, `a ?? b` | `?.` only in a chain that ends in `??`; `??` only on a `T \| null`, a chain or `m.get(k)` | `a?.b ?? d`, `a ?? d`, or `if (a !== null)` first |
172
185
  | `x as T`, `<T>x`, `x satisfies T` | `Unsupported expression in Phase 1: AsExpression` (to `any` or `unknown`: `` Type assertion to `any` is forbidden ``); `x!` is a syntax error | there are no casts; `implements` is the only widening |
173
186
  | `typeof x`, `x instanceof C`, `"k" in o`, `delete o.k`, `void 0`, `a, b` | each refused by name (`` `typeof` is forbidden ``, …) | there is no runtime type information: a value's type is its declared one |
@@ -176,7 +189,7 @@ rejects. This table is the highest-value part of the page.
176
189
  | `undefined` | forbidden, except `x === undefined` on a `Map.get` result | `null`, with a `T \| null` type |
177
190
  | `let total = 0` at the top level | `` Top-level `let` is not supported `` | a module `const`, or a local |
178
191
  | `for (const k in o)` | `` `for...in` is forbidden `` | `for (const x of xs)` over an array, or `for (const k of m.keys())` over a `Map` |
179
- | a callback stored or returned: `const cb = (n: i32) => n`, a field `cb: (n: i32) => i32` | `An arrow may only be written as the argument for a function-typed parameter` / `` … is a function type, which may only annotate a parameter of a top-level function `` | there are **no function values**; a callback the call names is a [function parameter](#function-parameters) |
192
+ | a closure stored or returned: `const cb = (n: i32) => n + k` inside a function | `` this arrow captures `k`: a function reference names a top-level function and carries no environment `` / `an arrow in value position is not yet a function reference: declare it as a top-level function and name it` | a [function reference](#function-references) names a capture-free top-level function: declare the function at the top level and store its name, or pass the arrow straight to a [function parameter](#function-parameters) |
180
193
  | `type Pair<T>` (a generic alias) | `Generic type parameters are forbidden on a type alias` | a generic **function**, **class**, **interface** and **method** all work — see below; an alias renames a type that already exists, so it has nothing to specialise |
181
194
  | `constructor<T>(x: T)` | a syntax error: `a constructor cannot have type parameters` | put the parameter on the class (`class Box<T>`), or on a method |
182
195
  | `h.get<i32>(7)` (type argument at a method call) | `Type arguments are not written at a call site in Nish` | `h.get(7)` — a generic method infers like a generic function |
@@ -190,9 +203,10 @@ rejects. This table is the highest-value part of the page.
190
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 |
191
204
  | `function f(): void;` (an overload), `export default function ()` | `Functions must have a body` / `Functions must be named` | one named function, with its body |
192
205
  | a method in an `interface` | `` Interface `I` cannot declare methods (interfaces describe layout only) `` | fields only; a top-level function over the interface |
193
- | `abstract class`, `declare class`, `constructor(public x: i32)`, `interface B extends A`, `[k: string]: T` | `Abstract classes are not supported` / `` `declare class` is not supported `` / `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 |
206
+ | `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 |
194
207
  | `{ m() { … } }`, `{ "a": 1 }`, `const C = class { }` | ``Unsupported object literal member: MethodDeclaration (only `key: value`)`` / `Object literal keys must be plain identifiers` / `Classes must be named` | fields with identifier keys, a top-level function over the interface, a named top-level class |
195
- | `{ ...base, x: 1 }`, `{ [k]: v }`, `[k]: i32` in a class or interface | `Object spread is forbidden in Nish (set each field by name)` / `Computed property names are forbidden in Nish (member names are fixed at compile time)` | every field written by name (`{ x: 1, y: base.y }`); a `Map` for a keyed table |
208
+ | `const o = { ...base }` with no annotation; `{ ...maybe }` for a `T \| null`; `{ ...base }` copying a field the target lacks | ``An object literal with a spread needs a contextual class or interface type…`` / ``Spread of `T \| null` into `T` may spread `null`…`` / ``Spread of `Point3` into `Point` copies field `z`, which `Point` does not declare…`` | annotate the literal's type (`const p: Point = { ...base, x: 1 }`); narrow the source first; spread a value whose fields the target declares, or set the fields by name |
209
+ | `{ [k]: v }`, `[k]: i32` in a class or interface | `Computed property names are forbidden in Nish (member names are fixed at compile time)` | a `Map` for a keyed table |
196
210
  | `type Pair = { a: i32 }` (inline object type) | `` Unsupported type `{ a: i32 }` `` | declare an `interface` |
197
211
  | `A \| B` unions of anything but tagged classes and interfaces | `` Union types other than `T \| null` are forbidden `` | a [discriminated union](#discriminated-unions): a tag field first in each variant |
198
212
  | `String(n)`, `n.toString()` | `` Unknown function `String` `` / `` Unknown method `toString` on i32 `` | `` `${n}` `` |
@@ -224,6 +238,43 @@ if (xs.length !== 0) {
224
238
  }
225
239
  ```
226
240
 
241
+ ### Lines that type-check and are still refused
242
+
243
+ Some mistakes have nothing wrong with their types. rustc warns about them and
244
+ Clippy denies some. Nish refuses all of them, because each is a bug far more
245
+ often than a choice
246
+ ([LANGUAGE.md](LANGUAGE.md#mistakes-every-type-accepts)). They are reported
247
+ only once the program has no other error, so they show up last.
248
+
249
+ | You wrote | Code | Write instead |
250
+ | --- | --- | --- |
251
+ | a local nothing reads, or only stores into (`n++` that nothing reports) | NL2712 | use it, delete it, or name it `_n`; a loop that only counts is `for (const _x of xs)` |
252
+ | a statement with no call, store or `await` in it: `a === b;`, `p.x + 1;` | NL2713 | `a = b`, or delete the line |
253
+ | `x = x`, `p.x = p.x` | NL2714 | the value you meant to store |
254
+ | the same operand on both sides: `a.w === a.w`, `xs[i] - xs[i]`, `ok && ok` | NL2715 | the other operand you meant; to compare a value with itself, copy it to a second `const` first. On a float, `x !== x` (NaN) and `x - x` are allowed |
255
+ | `if (c) … else if (c) …`, the same condition again | NL2716 | the condition you meant for the second branch |
256
+ | `u < 0` or `u >= 0` on a `u8`, `u16`, `u32`, `u64` | NL2717 | test before the subtraction that would wrap, or use a signed type |
257
+
258
+ ```ts nish:err-body NL2712
259
+ const xs = [3, 4];
260
+ let total = 0;
261
+ for (const x of xs) {
262
+ total = total + x;
263
+ }
264
+ const average = total / 2;
265
+ console.log(`${total}`);
266
+ ```
267
+
268
+ ```ts nish:ok-body
269
+ const xs = [3, 4];
270
+ let total = 0;
271
+ for (const x of xs) {
272
+ total = total + x;
273
+ }
274
+ const average = total / 2;
275
+ console.log(`${average}`);
276
+ ```
277
+
227
278
  ## Types
228
279
 
229
280
  Every type is exactly one LLVM first-class type. No boxing, no runtime tag, no
@@ -243,7 +294,7 @@ compatible only when their types are identical.
243
294
  | `class C`, `interface I` | a struct, fields in declaration order | no header, no vtable |
244
295
  | `enum K` | a **distinct** type represented as `i32` | never interchangeable with `i32` |
245
296
  | `K.M` | an enum member type: the one member `K.M`, as `i32` | holds only that member; a read is a `K` |
246
- | `T \| null` | `T` a class, interface, array, or string | a scalar can never be nullable |
297
+ | `T \| null` | `T` a class, interface, array, string or function reference | a scalar can never be nullable |
247
298
  | `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 |
248
299
  | `Result<T, E>` | the only way to report failure | `E` may not be `void` |
249
300
  | `void` | return type only | |
@@ -252,8 +303,9 @@ compatible only when their types are identical.
252
303
  the site: `uncheckedGet(xs, i)` and `uncheckedSet(xs, i, v)` on an array of
253
304
  numbers with an `i32` index (out of range is undefined behaviour), and
254
305
  `wrappingAdd` / `wrappingSub` / `wrappingMul` on two `i32`s or two `i64`s.
255
- The sixth export, `readCString`, copies a C string out of a `CPtr`
256
- ([Calling C](#calling-c)). Calling one without the import is NL2456. No flag turns the checks off for a
306
+ Two more, `readCString` and `readStruct`, copy a C string or a C struct
307
+ out of a `CPtr`, and the eighth, `cErrno()`, reads the errno the last C call
308
+ left ([Calling C](#calling-c)). Calling one without the import is NL2456. No flag turns the checks off for a
257
309
  whole program: `--unchecked-indexing` and `--wrapping` were removed before 1.0
258
310
  and are refused with exit 2.
259
311
 
@@ -419,7 +471,8 @@ export const main = (): i32 => {
419
471
  The surface: `Ok(v)` / `Ok()`, `Err(e)`, `r.isOk()`, `r.isErr()`, `r.ok`,
420
472
  `r.value`, `r.error`, `r.orReturn()`, `r.unwrapOr(d)`, `r.expect(msg)`. There
421
473
  is deliberately no `unwrap()` — `expect` insists on a reason — and no
422
- `map`/`andThen`, which would need function values.
474
+ `map`/`andThen`, whose callbacks are usually closures, which a function
475
+ reference cannot hold.
423
476
 
424
477
  **Three rules, and they are the ones that catch you out:**
425
478
 
@@ -460,9 +513,10 @@ terminates control flow, so a non-`void` function may end with it.
460
513
 
461
514
  ## Absence: nullable types
462
515
 
463
- `T | null` is available for `T` a class, interface, array, or string — never a
464
- scalar, which has no null value. It is the same pointer with `null` as one more
465
- value, so nothing is boxed.
516
+ `T | null` is available for `T` a class, interface, array, string or function
517
+ reference — never a scalar, which has no null value. It is the same pointer
518
+ (or, for a function reference, the same tag) with `null` as one more value, so
519
+ nothing is boxed.
466
520
 
467
521
  ```ts nish:ok
468
522
  class Node {
@@ -578,15 +632,15 @@ const double = (n: i32): i32 => n * 2; // a concise body is that one `return`
578
632
  ```
579
633
 
580
634
  - A function is a **module-level `const` bound to an arrow**. `let` is
581
- rejected; annotating the `const` is rejected (the annotation would be a
582
- function type, which only a parameter may have). The `function` keyword is
635
+ rejected; annotating the `const` is rejected (the signature is written once,
636
+ on the arrow). The `function` keyword is
583
637
  accepted as the legacy spelling and compiles to identical IR.
584
638
  - **Every parameter and the return type must be annotated.**
585
- - **A function is not a value.** `const alias = double` is
586
- `` Unknown identifier `double` ``. A function may be *passed* only for a
587
- function-typed parameter, where it is resolved at compile time — see
588
- [Function parameters](#function-parameters) — and never stored, returned or
589
- held in a field, a local or an array.
639
+ - **A capture-free top-level function is a value** — a
640
+ [function reference](#function-references): `const h: Op = double`, a field
641
+ `op: Op`, an `Op[]`, a returned `Op`, where `type Op = (n: i32) => i32`. An
642
+ arrow written inside a function is not one: declare it at the top level and
643
+ name it.
590
644
  - **Parameters are immutable**: `p = 1`, `p++`, `p += 1` are all rejected. Copy
591
645
  into a `let` first.
592
646
  - A non-`void` function must return on every path.
@@ -750,10 +804,11 @@ export const main = (): i32 => {
750
804
  - **A type parameter takes no type arguments of its own.** `T` is whatever the
751
805
  instantiation bound it to, so `const y: T<i32>` is
752
806
  `` Unsupported type reference `T<i32>` ``.
753
- - **A template obeys every rule a declared class obeys**: `declare class
754
- Box<T>`, `export default class Box<T>`, `abstract class Box<T>` and
755
- `interface Box<T> extends Base` are refused in the words their non-generic
756
- spellings are refused in.
807
+ - **A template obeys every rule a declared class obeys**: `export default
808
+ class Box<T>`, `abstract class Box<T>` and `interface Box<T> extends Base`
809
+ are refused in the words their non-generic spellings are refused in, and
810
+ `declare class Box<T>` (a C struct has one layout) is
811
+ `` A generic `declare class` is not supported ``.
757
812
  - **A template claims its name.** `class Box<T>` is a declaration of `Box`, so
758
813
  a function, constant, alias, enum or second class of that name is refused
759
814
  whichever was written first: `` `Box` is already declared in this module ``,
@@ -871,8 +926,12 @@ export const main = (): i32 => {
871
926
  - **Annotate what cannot be inferred**: an arrow parameter whose type no value
872
927
  argument binds, and the return type of a block-bodied arrow whose result is a
873
928
  type parameter.
874
- - **Only a top-level function** may have one: not a method, a constructor, a
875
- field, a local, a return type or an alias.
929
+ - **Only a top-level function's parameter, written inline**, is one. On a
930
+ method or constructor parameter an inline function type is refused; type it
931
+ through an alias and it is an ordinary [function reference](#function-references)
932
+ parameter. A local holding a reference is a function argument too (a field
933
+ or element is refused, NL2759: read it into a `const`); the runners that check their body (`parallelMap`,
934
+ `parallelReduce`, `spawn`, `expose`, `region`, ...) refuse one (NL2734).
876
935
 
877
936
  ```ts nish:err NL2585
878
937
  const apply = (f: (x: i32) => i32, x: i32): i32 => f(x);
@@ -884,6 +943,65 @@ export const main = (): i32 => {
884
943
  };
885
944
  ```
886
945
 
946
+ ### Function references
947
+
948
+ A **capture-free top-level function** is a value of a function type written
949
+ through an alias. It can sit in a local, a field, an array element or a
950
+ return value, be passed for an alias-typed parameter, called and compared
951
+ with `===` / `!==`:
952
+
953
+ ```ts nish:ok
954
+ type Op = (x: i32) => i32;
955
+
956
+ const inc = (x: i32): i32 => x + 1;
957
+ const square = (x: i32): i32 => x * x;
958
+
959
+ class Stage {
960
+ op: Op;
961
+ constructor(op: Op) { this.op = op; }
962
+ run(x: i32): i32 { return this.op(x); }
963
+ }
964
+
965
+ export const main = (): i32 => {
966
+ const ops: Op[] = [inc, square];
967
+ const s = new Stage(ops[1]);
968
+ console.log(`${s.run(3)}`); // 9
969
+ s.op = inc;
970
+ console.log(`${s.run(3)}`); // 4
971
+ console.log(`${s.op === inc}`); // true
972
+ return 0;
973
+ };
974
+ ```
975
+
976
+ - **Only a top-level function with no captures.** An arrow inside a function
977
+ is refused (NL2731 when it captures, NL2336 when it does not); so are a
978
+ generic (NL2725), `async` (NL2727), `declare` (NL2728) or rest-parameter
979
+ (NL2729) function, one with a function parameter (NL2726), and a method
980
+ (NL2732). A written function type has no rest, optional or defaulted
981
+ parameter either: `(x: i32, y?: i32) => i32` is NL2729. A guard helper,
982
+ a function taking a `MutexGuard`, is only ever called by name (NL2739).
983
+ - **No empty value but `null`.** `new Array<Op>(n)` is refused (NL2730);
984
+ `Op | null` is allowed and `new Array<Op | null>(n)` fills with `null`. A
985
+ call needs a `!== null` test first (NL2758); read a nullable field into a
986
+ `const` and test that. A module `const` cannot hold a reference.
987
+ - **A `Map` value, not a key.** `Map<K, Op>`, `Map<K, Op[]>` and
988
+ `Map<K, Op | null>` work; a call through what `get` returns dispatches over
989
+ the functions stored into any `Map` value or array of that type. A
990
+ function-type key is refused.
991
+ - **Not in a `Result` arm.** `Result<Op, E>`, `Result<Op | null, E>` and
992
+ `Result<T, Op>` are refused (NL2762); `Result<Op[], E>` works, or return a
993
+ class that holds the reference.
994
+ - **Called, compared, stored, passed — nothing else.** Not printed or
995
+ interpolated (NL2737), ordered, joined or encoded as JSON.
996
+ - **A function argument**: a local holding one fills an inline
997
+ function-typed parameter (`const op = ops[0]; apply(op, 3)`); a field or
998
+ element passed directly is refused (NL2759), a nullable local until it is
999
+ narrowed (NL2760); `parallelMap`,
1000
+ `spawn`, `expose`, `region` and the other runners that check their body take
1001
+ only a named function or arrow (NL2734).
1002
+ - **It stays in the program**: a `-o` library cannot export it in a
1003
+ signature or an exported class's field (NL2733); `--link` can.
1004
+
887
1005
  ### Async functions
888
1006
 
889
1007
  `async` compiles natively: a function that awaits becomes a frame and a resume
@@ -987,6 +1105,9 @@ export const main = (): i32 => {
987
1105
  `boolean` or an enum**: map strings to numbers first.
988
1106
  - **`dst` may not be reachable from an element of `src`**: mapping `Row[]` into
989
1107
  `f64[]` is refused when `Row` holds an `f64[]`, because it could be `dst`.
1108
+ A `Map` or `Set` in `Row` reaches only its keys and values, so `f` may
1109
+ `get`, `has` and `size` a `Map<string, i32>` (but not `set`, `delete`,
1110
+ `clear` or iterate it); a `Map<string, f64[]>` is refused.
990
1111
  - **A reduce's `f` is associative and `identity` is its identity** — `0` for
991
1112
  `+`, `1` for `*`. The array is folded in fixed blocks and the blocks combined
992
1113
  in order, so `-` or a wrong identity is refused when `f` is an arrow of one
@@ -1397,10 +1518,49 @@ export const main = (): i32 => {
1397
1518
  };
1398
1519
  ```
1399
1520
 
1400
- - **A parameter is a scalar, a `CPtr`, a borrowed `string` or a `u8[]` buffer
1401
- with its count; a return is a scalar, a `CPtr` or a copied `string`.** The
1402
- scalars are the integer and float widths, `boolean` and `void`. Any other
1403
- array, a class or an interface is rejected, in either position.
1521
+ - **A parameter is a scalar, a `CPtr`, a borrowed `string`, a `u8[]` buffer
1522
+ with its count or a borrowed `declare class`; a return is a scalar, a `CPtr`
1523
+ or a copied `string`.** The scalars are the integer and float widths,
1524
+ `boolean` and `void`. Any other array, a Nish class or an interface is
1525
+ rejected, in either position, and a `declare class` is never a return.
1526
+ - **A `declare class` is a C struct, lent by pointer.** Its fields are laid out
1527
+ in declaration order at C's alignment, and `new Name()` zero-fills it. A
1528
+ field is `i32`, `i64`, `u8`, `u16`, `u32`, `u64`, `f32`, `f64`, `CPtr`,
1529
+ `CPtr | null` or another `declare class`, embedded by value. `number` is
1530
+ refused by any spelling, parentheses or an alias included, because `--number-mode` picks
1531
+ its width; spell `i32` or `f64`. Fields only: no initializer, `readonly`,
1532
+ method or constructor. C borrows it for the call, may write its fields, and
1533
+ may not keep the address. It stays in its module: no exported signature
1534
+ holds one, however deep (NL2746, NL2756), and a page module (freestanding
1535
+ wasm, `--emit-dts`) refuses one (NL2757).
1536
+
1537
+ ```ts nish:ok
1538
+ declare class Timespec {
1539
+ sec: i64;
1540
+ nsec: i64;
1541
+ }
1542
+ declare function clock_gettime(clock: i32, ts: Timespec): i32;
1543
+
1544
+ export const main = (): i32 => {
1545
+ const now = new Timespec();
1546
+ clock_gettime(1, now);
1547
+ console.log(`${now.sec >= 0}`);
1548
+ return 0;
1549
+ };
1550
+ ```
1551
+
1552
+ ```ts nish:err NL2755
1553
+ type Coord = number;
1554
+
1555
+ declare class Point {
1556
+ x: Coord;
1557
+ }
1558
+
1559
+ export const main = (): i32 => {
1560
+ return 0;
1561
+ };
1562
+ ```
1563
+
1404
1564
  - **A run of `u8[]` / `readonly u8[]` parameters is followed by exactly one
1405
1565
  `u64`**, the byte count C may touch in each (`memcpy(dst: u8[], src:
1406
1566
  readonly u8[], n: u64)`). `readonly` is C's `const`. A run without its count
@@ -1459,6 +1619,18 @@ export const main = (): i32 => {
1459
1619
  `p` into a new string; a dangling or unterminated `p` is undefined
1460
1620
  behaviour, which is why it needs the import. It takes a `CPtr`, so narrow a
1461
1621
  `CPtr | null` with `!== null` first.
1622
+ - **A struct C owns is copied out with `readStruct` from `nish:unsafe`.**
1623
+ `const lc: Lconv = readStruct(p)` copies the bytes at `p` into a new
1624
+ instance of the `declare class` the context names; write the annotation,
1625
+ since `readStruct<Lconv>(p)` is refused (NL2763) and a call with no context
1626
+ is NL2764. A `NULL` `p` panics (`ffi-null`) before the copy, so
1627
+ `--deny-panics` refuses the call; a dangling `p`, or a class that does not
1628
+ match C's fields, is undefined behaviour.
1629
+ - **errno is read with `cErrno()` from `nish:unsafe`.** It answers the errno
1630
+ the most recent `declare function` call on this thread left; naming it makes
1631
+ every C call in the program zero errno before and save it after, so read it
1632
+ straight after the call you are checking. It is refused on wasm32 without
1633
+ `--profile wasi`.
1462
1634
  - **A `CPtr | null` parameter takes the literal `null` or a narrowed pointer.**
1463
1635
  `realpath(path, null)` passes `NULL`; a nullable pointer held in a variable
1464
1636
  is NL2539, so C is never handed a `NULL` by accident.
@@ -1649,6 +1821,108 @@ export const main = (): i32 => {
1649
1821
  };
1650
1822
  ```
1651
1823
 
1824
+ ### A tree links first child and next sibling
1825
+
1826
+ A tree node keeps `first` and `next` links, **not a `kids: Node[]` per
1827
+ node**. Every `kids` is a 24-byte header plus a block that doubles as it
1828
+ grows, and the blocks it outgrows stay in the arena; a walk over `kids`
1829
+ follows two pointers per child where the links follow one. On a 4M-node
1830
+ tree the links took 0.52x the memory and 0.68x the time of `kids`.
1831
+
1832
+ ```ts nish:ok
1833
+ class Node {
1834
+ kind: i32;
1835
+ parent: Node | null;
1836
+ first: Node | null = null;
1837
+ next: Node | null = null;
1838
+
1839
+ constructor(kind: i32, parent: Node | null) {
1840
+ this.kind = kind;
1841
+ this.parent = parent;
1842
+ }
1843
+ }
1844
+
1845
+ // `last` is the parent's last child so far, or null before the first.
1846
+ const add = (parent: Node, last: Node | null, kind: i32): Node => {
1847
+ const kid = new Node(kind, parent);
1848
+ if (last === null) {
1849
+ parent.first = kid;
1850
+ } else {
1851
+ last.next = kid;
1852
+ }
1853
+ return kid;
1854
+ };
1855
+
1856
+ const sum = (n: Node): i32 => {
1857
+ let s = n.kind;
1858
+ let kid = n.first;
1859
+ while (kid !== null) {
1860
+ s = s + sum(kid);
1861
+ kid = kid.next;
1862
+ }
1863
+ return s;
1864
+ };
1865
+
1866
+ export const main = (): i32 => {
1867
+ const root = new Node(1, null);
1868
+ const a = add(root, null, 2);
1869
+ add(root, a, 3);
1870
+ add(a, null, 4);
1871
+ console.log(`${sum(root)}`);
1872
+ return 0;
1873
+ };
1874
+ ```
1875
+
1876
+ - Where a pass needs a node's children by index, keep a child count and a
1877
+ `Node[]` filled once, when the node is complete, not pushed to as each child
1878
+ arrives. `new Array<Node>(n)` is refused for a class, so fill it with `push`
1879
+ in one go.
1880
+ - A **hot, closed table** (a token stream, a type or symbol table) uses
1881
+ **columns**: one `i32[]` per field, each `new Array<i32>(n)` at its final
1882
+ length, a row an `i32` index, `-1` for none. Write one out per type; no
1883
+ generic `Pool<T>`. Measured: 0.32x the memory and 0.63x the time of `kids`.
1884
+ - `uncheckedGet` / `uncheckedSet` belong in that table's code only: an index
1885
+ out of range there is undefined behaviour, not a panic.
1886
+
1887
+ ```ts nish:ok
1888
+ import { uncheckedGet, uncheckedSet } from "nish:unsafe";
1889
+
1890
+ // One column per field, each allocated once at its final length.
1891
+ class Tokens {
1892
+ kind: i32[];
1893
+ start: i32[];
1894
+ count: i32 = 0;
1895
+
1896
+ constructor(capacity: i32) {
1897
+ this.kind = new Array<i32>(capacity);
1898
+ this.start = new Array<i32>(capacity);
1899
+ }
1900
+
1901
+ add(kind: i32, start: i32): i32 {
1902
+ if (this.count >= this.kind.length) {
1903
+ return -1;
1904
+ }
1905
+ const id = this.count;
1906
+ uncheckedSet(this.kind, id, kind);
1907
+ uncheckedSet(this.start, id, start);
1908
+ this.count = id + 1;
1909
+ return id;
1910
+ }
1911
+ }
1912
+
1913
+ export const main = (): i32 => {
1914
+ const t = new Tokens(3);
1915
+ t.add(7, 0);
1916
+ t.add(9, 4);
1917
+ let s = 0;
1918
+ for (let i = 0; i < t.count; i++) {
1919
+ s = s + uncheckedGet(t.kind, i) * uncheckedGet(t.start, i);
1920
+ }
1921
+ console.log(`${s}`);
1922
+ return 0;
1923
+ };
1924
+ ```
1925
+
1652
1926
  ### Object literals
1653
1927
 
1654
1928
  An object literal takes its type from context — a variable annotation, the
@@ -1838,7 +2112,8 @@ export const main = (): i32 => {
1838
2112
  NL2535, one typed as the whole enum (`readonly kind: Kind`) NL2559. Any
1839
2113
  other union is still NL1053.
1840
2114
  - A union is a local, parameter, field, return, array element, or nullable
1841
- (`Shape | null`). An alias may name another union, which is flattened. A
2115
+ (`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
1842
2117
  variant, or a smaller union, converts into it wherever the union is
1843
2118
  expected — argument, `return`, `push`, an annotated array literal, a
1844
2119
  ternary arm or `??` default whose other side is the union. A class that
@@ -1910,8 +2185,9 @@ export const main = (): i32 => {
1910
2185
  anywhere or the whole type, which accepts a few comparisons `tsc` refuses
1911
2186
  (TS2367; LANGUAGE.md, "Accepted here, refused by `tsc`").
1912
2187
  - **Refused by design:** union type arguments (`Box<Shape>`,
1913
- `Map<K, Shape>`, `Result<Shape, E>`, a generic call binding `T` to a
1914
- union: NL2533), unions as `Map`/`Set` keys, covariant arrays (`Circle[]`
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[]`
1915
2191
  is not `Shape[]`), and inferred unions (an unannotated ternary or array of
1916
2192
  two variants).
1917
2193
  - **Declare what you store.** A store of a value that is only some of the
@@ -2274,7 +2550,16 @@ a `\u` escape `nish/json` decodes) is one unit per byte, and counts its bytes.
2274
2550
 
2275
2551
  **Files and the system.** `readFileSync(path)` (exits 1 on failure),
2276
2552
  `readFileSyncOrNull(path)` (`string | null`), `readFileBytesSync(path)`
2277
- (`u8[] | null`, the bytes as they are on disk), `writeFileSync(path, data)`,
2553
+ (`u8[] | null`, the bytes as they are on disk), and a file a window at a
2554
+ time: `fileOpen(path)` (an `i32` descriptor for a regular file, or a negative
2555
+ Linux errno: `-2` missing, `-13` denied, `-21` a directory, `-22` not a
2556
+ regular file), `fileReadAt(fd, buf, off, len, pos)` (at most `len` bytes from
2557
+ `i64` byte `pos` into `buf[off, off + len)`, a `u8[]`; the count, `0` at the
2558
+ end, short reads allowed so loop; the window panics like `netRead`'s),
2559
+ `fileSize(fd)` (an `i64`, which can change between calls), `fileClose(fd)`
2560
+ (never call it twice: the number may name another file by then); all four
2561
+ `fs.read`, refused on freestanding `wasm32` (NL2718) but not under
2562
+ `--profile wasi`; `writeFileSync(path, data)`,
2278
2563
  `appendFileSync(path, data)`, `writeFileBytesSync(path, bytes)` (a `u8[]` as
2279
2564
  it is; `i32`: the length, or a negative errno), `renameSync(from, to)` (`0` or
2280
2565
  a negative errno; atomic on one filesystem, `-18` across two, so write the
@@ -2291,6 +2576,9 @@ bytes, no `.`/`..`), `spawnSync(argv)`, `spawnSyncTo(argv, outPath, errPath)`,
2291
2576
  `spawnPiped(argv, stdin, stdout, stderr)` (stdin from a `u8[]`, both outputs
2292
2577
  appended to `u8[]`s, the status; `-2` past 16 MiB; the way to hand a child a
2293
2578
  secret, never argv or the environment),
2579
+ `spawnPipedWithin(argv, stdin, stdout, stderr, timeoutMs)` (the same with a
2580
+ deadline in milliseconds, negative for none: `-3` when it passes, the child
2581
+ killed and its bytes so far kept; only the child's pid is killed),
2294
2582
  `getenv(name)` (`string | null` — unset and empty are different answers),
2295
2583
  `realpathSync(path)` (`string | null`; symbolic links resolved, absolute, and
2296
2584
  `null` when it does not resolve),
@@ -2578,7 +2866,17 @@ literal (NL2493), an unknown option (NL2494), a name that is no field (NL2495),
2578
2866
  a rename to a non-string (NL2496) or to a key that is not valid UTF-8
2579
2867
  (NL2499), two fields with one key (NL2497). A
2580
2868
  `JsonNumber` field keeps a number's text byte for byte (`text`, `i64`, `u64`,
2581
- `f64`, `setText`).
2869
+ `f64`, `setText`). A tagged union of classes is a field, an array element or
2870
+ `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
2872
+ `const u = jsonDecodeUnion(d, prev)` (never `jsonDecode`, NL2719, and no type
2873
+ argument): it answers `prev` refilled when the tag matches, else a new variant,
2874
+ and `prev` on failure (only at the top: a nested union slot may hold the new
2875
+ variant, half read, so check `d.failed`); a bad tag is `JSON_DECODE_TAG`.
2876
+ `tag: ""` is the same as no `tag`. Every variant writes its
2877
+ tag under one key (NL2721) as a different string (NL2720). A `tag` on a class
2878
+ no union holds does nothing, and a JSON call on that class refuses its
2879
+ enum-member field.
2582
2880
 
2583
2881
  ```ts nish:ok
2584
2882
  import { JsonWriter } from "nish/json";
@@ -2816,6 +3114,16 @@ never call it on secret data, because its time says where the match is.
2816
3114
  (No block: a program importing `nish/text` writes two `.ll` files;
2817
3115
  `tests/link/std_text_index_of_any` is its program.)
2818
3116
 
3117
+ **Format a number with fixed digits, or split with a limit** — there are no
3118
+ methods on a number and no optional parameters, so `x.toFixed(n)` is
3119
+ `toFixed(x, n)` and `text.split(sep, limit)` is `splitLimit(text, sep, limit)`,
3120
+ both from `nish/text` and both answering what JavaScript does. `toFixed`
3121
+ rounds the exact binary value (`toFixed(1.005, 2)` is `"1.00"`) and panics
3122
+ outside 0 to 100 digits; `splitLimit` keeps the first `limit` pieces, a
3123
+ negative limit keeps all of them, and an empty separator panics.
3124
+ (No block, as for `nish/text`; `tests/link/std_text_to_fixed` and
3125
+ `tests/link/std_text_split_limit` are its programs.)
3126
+
2819
3127
  **Match a pattern** — there is no `RegExp` and no `/re/` literal:
2820
3128
  `regexCompile(pattern, flags)` from `nish/regex` answers a
2821
3129
  `Result<Regex, string>`, the error text naming the byte. The syntax is
@@ -3131,22 +3439,25 @@ Run it. `nish file.ts --json` is one command and it is the only proof.
3131
3439
  in an object-literal property or a method argument expecting a width?
3132
3440
  6. Is every `Result` read, and is every `.value` behind an `isOk()`?
3133
3441
  7. Is every nullable narrowed with `!== null` before it is touched?
3134
- 8. Did you use `throw`, `try`, `any`, `undefined` or `??` (outside a `T | null`, a chain or `Map.get`), `?.` without a `??`, a cast, a
3135
- stored or returned callback, a generic *alias*, or `extends`?
3136
- 9. Does it reach only what you meant it to? `nish file.ts --emit-capabilities
3442
+ 8. Is every local read, and does every statement do something? An unread
3443
+ local, `x = x`, `a === a` or a repeated `else if` is an error
3444
+ ([Lines that type-check and are still refused](#lines-that-type-check-and-are-still-refused)).
3445
+ 9. Did you use `throw`, `try`, `any`, `undefined` or `??` (outside a `T | null`, a chain or `Map.get`), `?.` without a `??`, a cast, a
3446
+ stored or returned closure, a generic *alias*, or `extends`?
3447
+ 10. Does it reach only what you meant it to? `nish file.ts --emit-capabilities
3137
3448
  caps.json` lists every capability each function can reach — files, processes,
3138
3449
  the network, the environment, the clock, entropy, signals, `exit`, C calls —
3139
3450
  with the call chain that reaches it, and `nish run --capabilities file.ts`
3140
3451
  prints the one-line summary ([LANGUAGE.md](LANGUAGE.md#capabilities)).
3141
3452
  A package that must not touch the network says so in `package.json`
3142
3453
  ([Holding it to its capabilities](#holding-it-to-its-capabilities)).
3143
- 10. Must it never panic? Compile with `--deny-panics` (or list the module in
3454
+ 11. Must it never panic? Compile with `--deny-panics` (or list the module in
3144
3455
  `package.json`'s `"nish": { "noPanic": [...] }`): every index, division,
3145
3456
  signed `+ - *`, `pop`, range entry, `expect` and exiting call it cannot
3146
3457
  prove is an error
3147
3458
  naming the guard ([Proving it cannot panic](#proving-it-cannot-panic)); an
3148
3459
  `uncheckedGet` or `uncheckedSet` behind its `nish:unsafe` import is allowed.
3149
- 11. If you are adding to this repository: `npm run check` and the touched
3460
+ 12. If you are adding to this repository: `npm run check` and the touched
3150
3461
  `node tests/run.js` sections green locally, every CI `test` shard green
3151
3462
  ([CLAUDE.md](../CLAUDE.md#definition-of-done)), and a new construct ships a
3152
3463
  golden `.ll`, an `llvm-as` pass, a native round trip, a negative test, its
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/nish-aarch64-darwin",
3
- "version": "0.38.0",
3
+ "version": "0.39.0",
4
4
  "description": "The nish native compiler for macOS on ARM64",
5
5
  "license": "MIT",
6
6
  "os": [
@@ -42,6 +42,10 @@ export declare function argv(): string[];
42
42
  export declare function readFileSync(path: string): string;
43
43
  export declare function readFileSyncOrNull(path: string): string | null;
44
44
  export declare function readFileBytesSync(path: string): u8[] | null;
45
+ export declare function fileOpen(path: string): i32;
46
+ export declare function fileReadAt(fd: i32, buf: u8[], off: i32, len: i32, pos: i64): i32;
47
+ export declare function fileSize(fd: i32): i64;
48
+ export declare function fileClose(fd: i32): i32;
45
49
  export declare function writeFileSync(path: string, data: string): void;
46
50
  export declare function appendFileSync(path: string, data: string): void;
47
51
  export declare function writeFileBytesSync(path: string, bytes: readonly u8[]): i32;
@@ -60,6 +64,13 @@ export declare function getenv(name: string): string | null;
60
64
  export declare function spawnSync(argv: string[]): number;
61
65
  export declare function spawnSyncTo(argv: string[], stdoutPath: string, stderrPath: string): number;
62
66
  export declare function spawnPiped(argv: string[], stdin: readonly u8[], stdout: u8[], stderr: u8[]): i32;
67
+ export declare function spawnPipedWithin(
68
+ argv: string[],
69
+ stdin: readonly u8[],
70
+ stdout: u8[],
71
+ stderr: u8[],
72
+ timeoutMs: i32
73
+ ): i32;
63
74
  export declare function kill(pid: i32, sig: i32): i32;
64
75
  export declare function availableParallelism(): i32;
65
76
  export declare function totalMemory(): i64;