# The Nish language

This is the normative reference for Nish, the subset of TypeScript that
`nish` compiles to LLVM IR. It describes what the compiler accepts today,
what each construct means, and how every rejection is worded. The design
notes (`docs/wp*.md`) explain *why*; this page says *what*.

**Nish is 0.x, and 1.0 has no date.**
Until then any minor release may change the language: a change that withdraws
or narrows an accepted construct, or changes what one means, is marked breaking
(`type!`) and named in the release notes. From 1.0 the rule tightens: a minor
may add a rule or turn a refusal into an acceptance, and anything else needs a
major. In either case the wording of a refusal may change in any release, but
its diagnostic code may not, because `--json` consumers key on it. Where the
compiler disagrees with this page, the compiler is wrong, and fixing it is not
a change to the language.

Conventions:

- Every rule cites a test case in parentheses, e.g. `(tests/cases/cf_if)`,
  meaning `tests/cases/cf_if.ts` (with its `.ll` golden, `.out` native output,
  or `.err` expected message). A `tests/link/<name>` citation is a whole-program
  link test. Rules marked *(CLI only)* were verified by compiling a snippet
  with `nish` and have no dedicated test case yet.
- Error messages are quoted as the fragment `tests/run.js` matches; the full
  line is `<file>:<line>:<col>: error: <message>` followed by a caret excerpt
  ([wp10-ci.md](wp10-ci.md#diagnostic-format)).
- "i32 mode" is the default; "f64 mode" is `--number-mode f64`. Everything
  else is mode-independent unless stated.
- The exact IR for each construct is in [IR_COOKBOOK.md](IR_COOKBOOK.md).

Contents: [Lexical rules](#lexical-rules) · [Types](#types) ·
[Nullable types](#nullable-types) ·
[Result and error handling](#result-and-error-handling) ·
[Declarations](#declarations) ·
[Statements](#statements) · [Expressions](#expressions) ·
[Builtins](#builtins) · [`Map` and `Set`](#map-and-set) ·
[Capabilities](#capabilities) ·
[Semantics decisions](#semantics-decisions) ·
[Memory model](#memory-model) ·
[Forbidden constructs](#forbidden-constructs-phase-0-validator) ·
[Rejected by the checker](#rejected-by-the-checker) ·
[Known inconsistencies](#known-inconsistencies)

## Lexical rules

Nish source is TypeScript syntax, read by the compiler's own lexer and
parser (`src/lexer.ts`, `src/parser.ts`), which follow TypeScript's rules for
tokens, comments, and ASI; `tests/lexer-oracle.js` and
`tests/parser-oracle.js` hold them to the `typescript` package's scanner and
parser over the test corpus. Syntax errors are reported as `syntax error:` in
the same `file:line:col` shape (`tests/run.js`, WP10 block).

- **Semicolons are optional, by TypeScript's rule.** A statement may end
  without `;` where TypeScript would insert one: at a line break, before a
  `}`, and at the end of the file. A `;` written and a `;` inserted parse to
  the same tree, so the IR is the same byte for byte
  (`tests/cases/asi_statements`). The rule is TypeScript's so that a program
  means what it means under Node, and that includes its three surprises
  (`tests/cases/asi_continuation`):
  - a line that starts with `(` or `[` continues the expression before it
    (`f` then `(x)` on the next line is a call);
  - a `++` or `--` at the start of a line is a prefix operator of a new
    statement, not a postfix one of the line before;
  - `return` followed by a line break returns nothing. The value on the next
    line is then unreachable code, which is an error here
    (`Unreachable code after return`, `tests/cases/reject_asi_return_newline`),
    where TypeScript would run it silently as a separate statement.

  Nothing is inserted between two statements on one line
  (`` expected `;`, found `const` ``, `tests/cases/reject_asi_same_line`) or
  in a `for` header (`reject_asi_for_header`). A template at the start of a
  line is not inserted before either, because TypeScript reads it as a tagged
  template of the line before (`reject_asi_template`).
- **Encoding.** Source is UTF-8. String contents are stored as UTF-8 bytes
  (`tests/cases/str_escape`).
- **A shebang line.** A `#!` line at the very start of a file (byte 0) is
  skipped, as TypeScript and Node skip it, so a program can be made
  executable and run as a script through `#!/usr/bin/env -S nish run`
  (`tests/cases/entry_shebang`). The line's newline is kept, so every line
  and column after it is the file's own (`reject_shebang_keeps_lines`).
  Anywhere else, after a blank line or a comment included, `#!` is
  `` '#!' can only be used at the start of a file ``
  (`tests/cases/reject_shebang_not_first`), as it is to TypeScript and to
  the kernel.
- **A diagnostic column counts UTF-16 code units**, 1-based, from the start of
  the line — so `é` is one column and two bytes, and an emoji is two columns
  and four. That is the unit an editor indexes a line by, and an editor is who
  reads a column: it is what the summary line prints, what the caret under the
  excerpt is placed by, what `--emit-checked` prints, and what `--json`'s
  `column` and `endColumn` carry (`tests/cases/reject_diag_utf8`). A
  `DILocation` column under `-g` is the other answer and counts **bytes**,
  because a debugger reads it back against the file's bytes
  (`tests/cases/dbg_utf8`).
- **Numeric literals.** Decimal, hexadecimal (`0x10`), binary (`0b1`),
  octal (`0o17`), exponent (`1e3`), and separators (`1_000`) are accepted
  *(CLI only)*; a separator goes only between two digits (see
  [Numeric literals](#numeric-literals)). A literal's type comes from its context (see
  [Numeric literals](#numeric-literals)); by default it is `number`. In i32
  mode a literal must have an integral value: `1.5` is rejected with
  `Non-integer literal` (`tests/cases/reject_float_in_i32`); `1e3` is the
  integer 1000 and accepted, but a point spells a float, so `1.0` is refused
  as `1.5` is *(CLI only)*. A literal above `2147483647` is
  rejected with ``Literal `...` does not fit in i32`` *(CLI only)*; the
  directly negated literal `-2147483648` is accepted and is `INT_MIN`
  (`tests/cases/int_min_literal`).
- **String literals.** `"..."`, `'...'`, and `` `...` `` without holes are
  all plain string literals; `` `...${x}...` `` is a template literal
  (`tests/cases/str_literal`, `str_template`). TypeScript escapes (`\n`,
  `\"`, `\\`, `\u...`) are decoded by the parser and re-encoded as UTF-8
  (`tests/cases/str_escape`).
  - **A surrogate pair is the code point it spells.** A high-surrogate escape
    (`\uD800`–`\uDBFF`) written immediately before a low-surrogate escape
    (`\uDC00`–`\uDFFF`) is one code point and encodes as its four UTF-8
    bytes, so `"\uD83D\uDE00"`, `"\u{1F600}"` and `"😀"` are the same string:
    `===` holds, `length` is 4, and a `Map` key set by one spelling is found
    by the others. Either half may be written `\uXXXX` or `\u{...}`, in a
    string or in a template's own text, as in JavaScript
    (`tests/cases/str_surrogate_pair`, `str_surrogate_map_key`).
  - **A lone surrogate keeps its WTF-8 bytes.** A surrogate escape without
    that partner is not refused: it encodes on its own as the three bytes
    UTF-8's pattern gives it (`"\uD83D"` is `ED A0 BD`), which is WTF-8 and
    not valid UTF-8. The pair is joined only inside one literal, so
    `"\uD83D" + "\uDE00" === "\uD83D\uDE00"` is `false` where JavaScript says
    `true` (`tests/cases/str_surrogate_lone`).
  - **A `\u{...}` escape is at most `0x10FFFF`**, the last code point. A
    larger one is refused with TypeScript's words, `` An extended Unicode
    escape value must be between 0x0 and 0x10FFFF inclusive ``
    (`tests/cases/reject_surrogate_escape_too_large`), however many digits it
    has, so that no value can wrap round into a surrogate and join the escape
    after it (`reject_surrogate_escape_wraps`).
- **Boolean literals** `true`, `false` (`tests/cases/cf_logical`).
- **`null`** is a value only where a `T | null` type is expected (see
  [Nullable types](#nullable-types)); with no contextual type it is
  `` `null` needs a contextual `T | null` type `` *(CLI only)*.
  **`undefined`** is forbidden (`` `undefined` is forbidden in Nish; use `null` with a `T | null` type ``,
  `tests/cases/reject_undefined_value`).
- **Bigint** literals (`10n`) and regex literals are forbidden
  (`tests/cases/reject_bigint_literal`, `reject_regex`); a pattern is a
  library instead, `regexCompile` from `nish/regex` (`std/regex.ts`).
- **Reserved prefix.** Function, class, and interface names starting with
  `nish_` are reserved for the runtime: `` Function names starting with `nish_` are reserved for the runtime ``
  *(CLI only; `src/declarations.ts`)*.
- **Identifiers** that may never appear as values: `eval`, `Function`,
  `Proxy`, `Reflect`, `Symbol`, `globalThis`, `arguments`, `undefined`
  (see [Forbidden constructs](#forbidden-constructs-phase-0-validator)).

## Types

Every Nish type maps 1:1 onto one LLVM first-class type. There is no
boxing, no runtime type tag, no structural subtyping (except
`implements`, below), and no implicit conversion of any kind: two values are
compatible only when their types are identical.

Read from the top down as deep as you need: which type to write, what
behaves differently from TypeScript, how each type sits in memory and
crosses to C, then the exact rules.

### Choosing a type

| To hold | Write |
| --- | --- |
| A whole number | `number`, or `i64` beyond ±2³¹ |
| A fraction | `f64`; `f32` for half the memory or twice the SIMD lanes |
| A byte, or bits that wrap | `u8`, `u16`, `u32`, `u64` |
| True or false | `boolean` |
| Text | `string` |
| A list | `T[]`, or `readonly T[]` when nothing writes it |
| A record | `class C`, or `interface I` |
| One of a fixed set of names | `enum K` |
| A value or nothing | `T \| null` |
| One of several kinds of record | `A \| B`, a [tagged union](#discriminated-unions) |
| A value or an error | `Result<T, E>` |
| A function the caller picks | `(x: T) => U` on a parameter |
| No value | `void`, as a return type |

### Coming from TypeScript

- **`number` is one fixed type.** It is `i32` by default and `f64` under
  `--number-mode f64`; nothing else is ever its lowering. `f64` is available
  in both modes.
- **Nothing converts on its own.** Each numeric type is its own type, so
  `u32 + i32` and `f32 + f64` are type errors. Convert with `toI32`, `toU8`,
  `toF64` and the rest ([Type rules](#type-rules)).
- **Signed overflow panics** ([Semantics decisions](#semantics-decisions)),
  in `i32` and `i64` alike; `wrappingAdd`, `wrappingSub` and `wrappingMul`
  from [`nish:unsafe`](#nishunsafe-unchecked-access-and-defined-wrapping)
  wrap instead. [Unsigned integers](#unsigned-integers) always wrap. An
  `i64` takes a literal only by context.
- **Strings are immutable.** Sharing one is always safe, and nothing is ever
  copied.
- **An array has one element type**, and every index is bounds-checked.
  `readonly T[]` refuses every write ([Readonly arrays](#readonly-arrays)).
  `Int32Array`, `Float32Array`, `Float64Array` and `BigInt64Array` are only
  other names for `i32[]`, `f32[]`, `f64[]` and `i64[]` (`sameType` holds,
  and `new Int32Array(n)` is `new Array<i32>(n)`), except that a receiver
  spelled with one has no `push` or `pop`, as in TypeScript
  ([Typed-array names have no `push` or `pop`](#typed-array-names-have-no-push-or-pop)).
- **Only a class, interface, array, string or function reference can be
  `null`.** A nullable value allows only `=== null` / `!== null`, assignment,
  narrowing and a `??` default ([Nullable types](#nullable-types)); a nullable
  function reference is the tag `0` ([Function references](#function-references)).
- **An `enum` is its own type**, not a spelling of `i32`: `sameType` fails
  against every other type ([Enums](#enums)).
- **A record's type has a name.** Its fields are declared once, in an
  `interface` or a `class`; an inline object type, `{ x: i32 }`, is refused
  wherever a type is written, and `type` only renames a type that already
  exists ([Interfaces and object literals](#interfaces-and-object-literals),
  [Type aliases](#type-aliases)).
- **A function reports failure with a `Result`**, the only way it can; the
  payload is unreachable until the discriminant is tested
  ([Result and error handling](#result-and-error-handling)).
- **A function type** written inline on a parameter of a top-level
  function names the callee chosen at each call
  ([Function parameters](#function-parameters)); anywhere else it is the type
  of a reference to a capture-free top-level function, which can be held,
  passed, called and compared, nothing else
  ([Function references](#function-references)).

### In memory and in C

A number, a `boolean` or an `enum` is a plain value. The C column is the
type `--emit-header` writes; a dash means the type cannot cross to C.

| Type | LLVM | Size / align | C |
| --- | --- | --- | --- |
| `i32`, `number` | `i32` | 4 / 4 | `int32_t` |
| `f64`, `number` in f64 mode | `double` | 8 / 8 | `double` |
| `f32` | `float` | 4 / 4 | `float` |
| `i64` | `i64` | 8 / 8 | `int64_t` |
| `u8` | `i8` | 1 / 1 | `uint8_t` |
| `u16` | `i16` | 2 / 2 | `uint16_t` |
| `u32` | `i32` | 4 / 4 | `uint32_t` |
| `u64` | `i64` | 8 / 8 | `uint64_t` |
| `boolean` | `i1` | 1 / 1 | `bool` |
| `enum K` | `i32` | 4 / 4 | — |
| `void` | `void` | — | `void` |

- Signed integers are two's-complement, and floats IEEE-754. An unsigned
  type shares the LLVM type of its signed twin, and its signedness lives in
  the operations ([Unsigned integers](#unsigned-integers)). `i64` and `u64`
  cross to JavaScript as a `bigint`.
- A `boolean` is `zeroext` at the ABI boundary.
- `K.A` is the member's integer (its ordinal, for a string enum), so nothing
  is emitted for a numeric `enum` declaration; a string enum adds one private
  table of its members' strings ([String enums](#string-enums)).

Every other type is a pointer, 8 bytes and 8-aligned, to:

- **`string`**, LLVM `i8*`: `{ i64 len, i8 data[len], i8 0 }`, 8-aligned and
  NUL-terminated, so `data` is a C string, and `len` is the UTF-8 byte
  length. Literals are module constants; every other string lives in the
  arena. In C, a `const nish_str *` parameter and a `nish_str *` result.
- **`T[]`**, LLVM `%struct.nish_array*`: a 24-byte header,
  `{ i64 len, i64 cap, i8* data }`, where `data` holds `cap` elements of
  `sizeof(T)`. In C, a `const nish_array *` parameter the function only
  reads, and a `nish_array *` parameter it writes through or a `nish_array *`
  result.
- **`readonly T[]`**: the same array, a `const nish_array *` parameter in C.
- **`Int32Array`, `Float32Array`, `Float64Array`, `BigInt64Array`**: the
  arrays they name. They name the JS typed array a host passes
  ([wp8-interop.md](wp8-interop.md)). An unsigned array crosses to a host as
  `Uint8Array`, `Uint16Array`, `Uint32Array` or `BigUint64Array`
  ([wp30-bytes-interop.md](wp30-bytes-interop.md)), but those four are
  **not** spellings in the language: a program writes `u8[]`.
- **`class C`, `interface I`**, LLVM `%struct.C*`:
  `%struct.C = type { fields in declaration order }`, laid out as clang lays
  out the same C struct, with no header and no vtable. An object is arena- or
  stack-allocated ([Memory model](#memory-model)). Not in C.
- **`T | null`**: whatever `T` points to; `null` is the constant `null`. Not
  in C.
- **`A | B`**, LLVM `%union.tagged*`: `%union.tagged = type { i32 }`, the tag
  every variant begins with. A variant converts by a `bitcast`, and only the
  tag is read ([Discriminated unions](#discriminated-unions)). Not in C.
- **`Result<T, E>`**, LLVM `%struct.nish_result.<T>.<E>*`:
  `{ i1 ok, T value, E error }`, one struct per pair of payload types, laid
  out as clang lays out the same C struct. It is **passed and returned** as
  one `i64` when both payloads are scalars of at most 4 bytes, and as
  `{ i1, i32, i32 }`, the tag and one slot per arm, between two non-exported
  functions of one module. In C, a `nish_result_<T>_<E>_word` by value, and a
  `struct nish_result_<T>_<E> *` otherwise.

A function type, `(x: T) => U`, written inline on a parameter of a
top-level function is no value at all: it has no LLVM type and no parameter,
and the callee is compiled into the instantiation's body as a direct call.
Anywhere else it is a function reference, LLVM `i32`, 4 / 4: a tag naming
one of the program's functions of that signature, never an address
([Function references](#function-references)). Not in C.

Sources: `src/types.ts` (`TypeTable.llvmType`, `alignOf`; a type is
interned, and two types are the same type exactly when they are the same
`i32`),
`src/interop-abi.ts` (`cType`); `tests/cases/i64_basic`, `f64_mode`,
`str_literal`, `arr_literal`, `cls_point`; the ten-struct layout test
`tests/layout/structs.ts` (offsets and `sizeof` cross-checked against clang,
[wp2-classes.md](wp2-classes.md#layout)).

### Type rules

- **Accepted type syntax**: `number`, `i32`, `i64`, `u8`, `u16`, `u32`, `u64`,
  `f32`, `f64`, `boolean`,
  `string`, `void`, `T[]`, `Array<T>` (exactly one type argument:
  `` `Array` needs exactly one type argument ``), `readonly T[]` and
  `ReadonlyArray<T>` ([Readonly arrays](#readonly-arrays)), `Int32Array`,
  `Float32Array`, `Float64Array`, `BigInt64Array` (no type argument:
  `` `Float64Array` takes no type argument (it is an alias of `f64[]`) ``,
  `tests/cases/reject_arr_typed_view_type_annotation_arg`; a `Float64Array`
  is an `f64[]` wherever one is expected and vice versa,
  `tests/cases/arr_typed_views`, `reject_arr_typed_view_mismatch`), the name of
  a `type` alias or an `enum` (numeric or string) declared or imported in the module
  ([Type aliases](#type-aliases), [Enums](#enums)), one of that enum's
  members as a type, `Kind.If` ([Enums](#enums)), and the
  name of a class or interface declared or imported in the module. Anything else is
  `` Unsupported type `...` `` / `` Unsupported type reference `...` ``
  (`src/annotations.ts`; `tests/cases/reject_union_type`, `reject_function_type`).
  `keyof T` is one of those, `` Unsupported type `keyof T` (Phase 1 supports
  number, i32, i64, u8, u16, u32, u64, f32, f64, boolean, string, void) ``
  (NL2038), and it is refused in a generic declaration nothing instantiates too, because the
  rule is a pass over the whole module rather than a step in resolving an
  annotation (`reject_type_keyof`, `reject_type_keyof_template`). `keyof` is
  the operator only before a type on its own line, so a class a program names
  `keyof` is still a type everywhere else (`tests/parser/names-declarations.ts`).
  `T | null` (or `null | T`) is accepted when `T` is a class, interface,
  array, string or [function reference](#function-references) type; a scalar is
  `` `i32 | null` is not supported: only class, interface, array, and string types can be nullable (a scalar has no null value) ``
  (`tests/cases/reject_nullable_scalar`). A type may be **parenthesised**, and
  `(T | null)[]` is where it matters: `T | null[]` groups the other way and
  means "a `T`, or an array of `null`". The parentheses only group — the type
  inside them is the type — so `(A | B)[]` is held to the union rules as
  `A | B` is (`tests/cases/cls_parenthesized_type`, `reject_paren_union_type`).
  A union of tagged classes and interfaces is a
  [discriminated union](#discriminated-unions).
- **No implicit conversion.** `const y: f64 = x` with `x: number` in i32
  mode is `Cannot initialize f64 variable ... with i32` *(CLI only)*;
  `x + n` with `x: i64`, `n: number` is rejected
  (`tests/cases/reject_i64_mixed`); convert explicitly with `toI32`,
  `toI64`, `toU8`, `toU16`, `toU32`, `toU64`, `toF32`, `toF64`
  (`tests/cases/conversions`, `u_conv_roundtrip`, `f32_conversions`). Width and
  signedness are part of the
  type, so `f32 + f64` is
  `` Operator `+` requires two operands of the same numeric type ... got f32 and f64 ``
  (`tests/cases/reject_f32_mixed`) and, even when the LLVM type is shared, `u32 + i32` is
  `` Operator `+` requires two operands of the same numeric type ... got u32 and i32 ``
  (`tests/cases/reject_u_mixed_signedness`), and so is `u8 * u32`
  (`tests/cases/reject_u_mixed_widths`).
- **Field and element types** may be any type except `void`
  (`Array elements cannot be void`, `... cannot have type void`).
  Arrays of arrays (`tests/cases/arr_nested`), arrays of strings
  (`tests/cases/arr_strings`), arrays of class instances and class fields
  of array type work *(CLI only)*.
- **`integer<Lo, Hi>` is a ranged integer** ([wp31-ranged-integers.md](wp31-ranged-integers.md)):
  an `i32` the compiler knows lies in `[Lo, Hi]`. It is an `i32` in the IR, in
  memory and at the ABI, in both number modes, and `tsc` reads it as a
  `number` alias (`runtime/nish.d.ts`). `integer<0, 0xFF>` and
  `integer<0, 255>` are one type, spelled `integer<0, 255>` in a diagnostic and
  mangled `rng.p0.p255` in a symbol (`rng.m128.p127` for `integer<-128, 127>`),
  so `Box<integer<0, 255>>` is `%struct.Box$rng.p0.p255`
  (`tests/cases/rng_param`, `rng_generic`).
  - **The bounds** are two integer literals, a sign allowed, with
    `Lo <= Hi` and both in `i32`. Each other spelling is refused:
    `` `integer` needs exactly two bounds, e.g. `integer<0, 255>` ``
    (`reject_rng_arity`, `reject_integer_use`);
    ``A bound of `integer<Lo, Hi>` must be an integer literal, got `MAX` ``,
    a constant or a type (`reject_rng_bound_not_literal`,
    `reject_rng_bound_type`);
    ``Non-integer literal `1.5` where a bound of `integer<Lo, Hi>` is expected``
    (`reject_rng_bound_float`);
    `` `integer<10, 0>` is an empty range `` (`reject_rng_empty`); and
    ``Bound `4294967295` of `integer<Lo, Hi>` is outside i32``
    (`reject_rng_bound_i32`, `reject_rng_bound_i32_negative`). A numeric
    literal type is parsed wherever a type is and is legal only as one of
    these bounds: `const x: 5` and `Box<3>` are
    ``A literal type `5` is only allowed as a bound of `integer<Lo, Hi>` ``
    (`reject_rng_literal_type`, `reject_rng_literal_type_argument`).
  - **Entering a range is checked.** An annotated initialiser, an assignment
    (`=`, the compound forms, `++` and `--`), an argument to a function, a
    method or a constructor, a `return`, a field or object-literal field, an
    array-literal element, an element store and `push` are *entries*. The
    source must be an `i32` or another ranged type — a `u8` is not an
    `integer<0, 255>` (`reject_rng_from_u8`), and under `--number-mode f64` a
    `number` is an `f64` that enters through `toI32(x)` (`reject_rng_from_f64`).
    A literal inside the range and a value of a range inside this one cost
    nothing; a literal outside it is
    ``Literal `12` is outside the range of integer<0, 9>``
    (`reject_rng_literal_outside`, `reject_rng_literal_outside_negative`).
    Anything else is compared once and the program panics outside the range,
    printing `value out of range: expected integer<0, 255>` and exiting 1
    (`rng_param`, `rng_entries`, `rng_bitwise`, `rng_entry_panic`,
    `rng_entry_range_panic`, `rng_entry_push_panic`, `rng_entry_bitwise_panic`). The check is the type's
    meaning, so `uncheckedGet` and `uncheckedSet` keep it, and a `wrapping*`
    call changes only the arithmetic before it. Under Node nothing is checked, which
    [RUN_UNDER_NODE.md](RUN_UNDER_NODE.md#what-stays-divergent) records.
  - **An entry the compiler can prove is free** (WP31 §8). The bounds proof of
    [Element access](#element-access) judges each entry where the value is
    computed, and writes no compare where it already places the value inside
    the range. Two sources can be proven. A local is proven one end at a
    time: the lower end when `Lo` is `-2147483648`, or `Lo <= 0` and the local
    is known non-negative; the upper end when `Hi` is `2147483647`, or the
    local is known below `Hi + 1` — by a loop condition, a guard that reaches
    the entry, a literal it was bound to, or its own declared range. And
    `toI32(x)` of a `u8`, a `u16` or a ranged value lands in `x`'s declared
    range, so `const r: integer<0, 255> = toI32(b)` costs nothing for a `u8`
    `b`. `for (let i = 0; i < 256; i++) { const b: integer<0, 255> = i }` is
    the shape §7 recommends, and the loop condition proves it
    (`tests/cases/perf_rng_quiet`); so is a call that hands a loop counter to a
    ranged parameter, which leaves wp31 §12's `getByte` program with no check
    at all (`perf_rng_getbyte`). A lower end above zero is never proven
    from a guard, because the proof records no lower bound but zero, and the
    sum a compound assignment or an increment stores back is never proven at
    all; both keep their check. A check that survives inside a loop is a
    performance warning ([Diagnostics](#diagnostics-and-debugging-flags)), and a counter declared
    with a range is the loop that warns and then panics
    (`perf_rng_counter`).
  - **Leaving a range is free.** Every operator reads a ranged value as `i32`,
    so `r + 1` is an `i32`, `r < 9` compares two `i32`s and `toI64(r)` is a
    `sext`; mixing one with an `i32` is never an error, and nothing computes a
    range. The range survives where nothing is computed: a `const` without an
    annotation keeps it and a `let` widens to `i32` (`rng_widen`); a read of a
    ranged field, element or result keeps it; and a type argument keeps it, so
    `identity(r)` is `identity<integer<0, 9>>` (`rng_generic`). A counter
    declared with a range fails its last `i++`, which is why the range goes on
    the value used rather than on the counter (`rng_entry_panic`).
  - **Where a range may not go.** A `declare function` may not mention one,
    because the C side never promised it (`reject_rng_declare_function`,
    `reject_rng_declare_function_return`), and `new Array<integer<1, 9>>(n)` is
    refused because its zero fill is outside the range
    (`reject_rng_array_zero_fill`). Under `-g` a ranged type is a
    `DW_TAG_typedef` of `int` named `integer<0, 255>` (`dbg_rng`).
  - **The name.** `integer` is on the list of built-in type names, so
    `type integer = …` and `enum integer` are refused the way `type string = …`
    is (`reject_integer_alias`, `reject_integer_enum`). A class, interface or
    function may not take it either, because `integer<0, 255>` would then mean
    two things in the module that declared one:
    `` `integer` is reserved for ranged integers (`integer<Lo, Hi>`) and cannot be declared as a class ``
    (`reject_integer_class`, `reject_integer_interface`,
    `reject_integer_function`). A module constant or a local called `integer`
    is a value, not a type, and is still accepted.

### Numeric literals

**A separator goes between two digits and nowhere else**, as in TypeScript.
`1_000_000`, `0xFF_FF` and `1_234.5_6` are the values their digits spell, and
so is `1e1_0` in an exponent (`tests/cases/math_numeric_separators`). Any
other `_` is refused by the lexer with TypeScript's words, one error for the
whole literal: after a radix prefix (`0x_FF`,
`tests/cases/reject_separator_after_prefix`), at the end (`10_`,
`reject_separator_trailing`), either side of the point (`1_.5`, `1._5`:
`reject_separator_before_dot`, `reject_separator_after_dot`), straight after
the exponent marker or its sign (`1e_5`, `1e+_5`, `reject_separator_exponent`),
before the BigInt suffix (`0xFF_n`, `reject_separator_before_bigint_suffix`)
and after a leading zero (`0_1`, `reject_separator_leading_zero`) are all
`` Numeric separators are not allowed here `` (TS6188), and two in a row
(`1__0`, `0xF__F`, `reject_separator_doubled`) is
`` Multiple consecutive numeric separators are not permitted `` (TS6189). The
parser still reads the literal, so the next token does not cost a second
error, and a bound of a ranged type is refused the same way
(`integer<0, 0x_FF>`, `reject_separator_ranged_bound`).

**A decimal literal does not start with `0` and another digit**, as in
TypeScript, and as in a JavaScript module, where Node refuses one as a
`SyntaxError`. `0`, `0.5` and `0e1` are legal, and so is every radix prefix
(`tests/cases/leading_zero_legal`). A run of octal digits after the zero is a
legacy octal literal: `017`, and `017.5` or `07_1` with it, are
`` Octal literals are not allowed. Use the syntax '0o17' `` (TS1121), naming the
`0o` spelling of those digits (`tests/cases/reject_leading_zero_octal`). Any
other, such as `09`, `08.5` or `09e1`, is
`` Decimals with leading zeros are not allowed `` (TS1489,
`reject_leading_zero_decimal`). The lexer refuses it and it costs one error,
as a misplaced separator does. Before issue #271, `017` compiled as seventeen.
There are two differences from `tsc`. `tsc` reads `017.5` as two tokens and
reports a second error for the `.5`, but the lexer reports one error for the
whole literal. And `-017` suggests `0o17`, not `-0o17`, because the lexer does
not see the sign.

**Every spelling is read at the value it spells, in every numeric type**,
as TypeScript reads it (#267): `0b1010` is 10, `0o17` is 15, `1_000` is 1000
and `1e5` is 100000 as an `i32`, an `i64`, an `f64`, a module constant or a
bound of `integer<Lo, Hi>` (`tests/cases/literal_spellings`). A binary or
octal literal past 2^53 rounds once, to the double TypeScript reads. An
exponent is an integer when its value is one, so `100e-2` is the integer 1 and
`1e-1` in an integer position is `` Non-integer literal `1e-1` where i32 is
expected `` (`reject_literal_exponent_fraction`); a point always spells a
float. The range rules below read the same value, so `1e10` and a 33-bit
`0b` literal are `` Literal `1e10` does not fit in i32 ``
(`reject_literal_exponent_overflow`, `reject_literal_binary_overflow`), and an
`i64` module constant past 2^53 is refused as an `i64` literal is
(`reject_literal_const_precision`).

A numeric literal has the mode's default type (`i32`, or `f64` in f64 mode)
unless its *immediate* context demands another numeric type, in which case it
takes that type (`src/expressions.ts`, `checkNumericLiteral`;
`tests/cases/i64_basic`, `math_i32`, `conversions`):

| Context | Example | Literal type |
| --- | --- | --- |
| annotated initializer | `let x: i64 = 5` | `i64` |
| `return` | `return 5` in a function returning `i64` | `i64` |
| argument to a user function | `square(5)` with `x: i64` | `i64` |
| other operand of a binary operator with a known type | `x * 2`, `2 * x`, `x < 5`, `x = 5` | the other operand's type |
| `Math.min` / `Math.max` | `Math.max(x, 0)` | the other operand's type |
| f64-only `Math.*`, `toF64` | `Math.sqrt(2)`, `toF64(3)` | `f64` |
| `toF32` | `toF32(2.75)` | `f32` |
| `process.exit` | `process.exit(1)` in f64 mode | `i32` |
| `Number` | `Number(2.5)` in i32 mode | `f64` |
| element of an array literal whose own context is a `T[]` | `const bytes: u8[] = [0, 255]` | `u8` |
| a class field's literal initializer | `b: u8 = 255` | `u8` |
| argument to a constructor | `new Pixel(255, 0, 0)` | the parameter's type |
| a field or element assignment target | `p.b = 255`, `bytes[i] = 255` | the field's / element's type |
| a ternary arm, from the conditional's own context | `const x: f64 = c ? 1.5 : 2.5` | `f64` (`tests/cases/f64_ternary_literal`) |

`-5` and `(5)` count as the literal, on **either** side of a binary operator:
`-1 / z` and `(1) / z` with `z: f64` type their literal from `z` exactly as
`1 / z` does, and so do `-1 * big` on an `i64` and `-1 < z`
(`tests/cases/math_literal_operand_forms`). The other operand still has to be
one of the shapes "known type" names below, so `-1 * (cp >> 6)` in f64 mode is
refused for the same reason `0xc0 | (cp >> 6)` is
(`tests/cases/reject_neg_literal_unpeekable`). **The table is the whole list**, so a
position that is not on it leaves the literal at the mode's default however
obvious the intended type looks: an object literal's property value is not on
it, so `const p: Pixel = { b: 255 }` is `` Field `b` of `Pixel` expects a value
of type u8, got i32 `` and has to be written `toU8(255)`
(`tests/cases/reject_struct_field_u8`, and `reject_struct_field_f64` for the
same position in f64 mode); nor is a `Result` payload, so `Ok(3)` for a
`Result<i32, string>` is refused in f64 mode
(`tests/cases/reject_res_ok_f64`), as `unwrapOr`'s fallback is
(`reject_res_unwrap_or_f64`); and nor is a **method's** argument, which is why
the table says a user *function* and a constructor — `b.get(-1)` on a method
whose parameter is an `i32` is an f64 in f64 mode
(`tests/cases/reject_method_arg_literal`).
`xs.push(3)` and `xs.indexOf(3)` are on the list only through a receiver that
is a plain name: `b.xs.push(0)` is not (`reject_push_field_literal`). "Known type" means an already-checked
left operand, a variable, a field or element of one of those, or a call to a
user function or to
`toI32/toI64/toU8/toU16/toU32/toU64/toF64`. Only the literal's *immediate* context counts: in i32
mode `const f: f64 = 0.1 + 0.2` is rejected because `0.1` is an operand of
`+` whose other operand has no known type yet; write `const a: f64 = 0.1;
const f = a + 0.2` *(CLI only)*. The same rule refuses `const b: u8 = 1 + 2`,
which is a sum of two `i32` literals rather than a literal in a `u8` context
(`tests/cases/reject_bin_operand_context`), and `0xc0 | (cp >> 6)` in f64 mode,
because a shift is not one of the shapes "known type" names however plainly it
is an integer: give it a name first, or write `toI32(0xc0)`. A literal in an integer context must be integral
(`` Non-integer literal `1.5` where i64 is expected ``,
`tests/cases/reject_i64_literal_float`); in an `i64` context it must also be
at most 2^53 in magnitude (`` exceeds 2^53 and cannot be written exactly ``,
`tests/cases/reject_i64_literal_precision`; an unsigned context has the same
rule, `reject_u64_literal_precision`) because a numeric literal is read as a
double, as TypeScript reads it, so a larger one is already rounded. Every one of these messages quotes the
literal **as it is written**, not as the parser cooked it: `0x1FF` reads back
as `0x1FF` and a rounded literal as the digits in the file. The one exception
is a separator, which the parser drops, so `1_000_000_000_000` in an `i32`
context reads back as `` Literal `1000000000000` does not fit in i32 ``. In an *unsigned* context it must also be non-negative
and fit the width: `const b: u8 = -1` is
`` Negative literal `-1` where u8 is expected (u8 is unsigned) ``
(`tests/cases/reject_u_negative_literal`) and `const b: u8 = 256` is
`` Literal `256` does not fit in u8 ``
(`tests/cases/reject_u_literal_too_wide`). The largest `u64` values are past
2^53 and cannot be written at all; build them arithmetically
(`toU64(0) - toU64(1)` is 2^64 - 1, `tests/cases/u_print`). The same holds for
the `i64` minimum, -2^63: `-9223372036854775808` is refused like any literal
past 2^53 (NL2055), although 2^63 happens to be an exact double and its
negation fits. The 2^53 bound is what keeps every literal exact in both
readings, and admitting this value would be a one-literal exception to it for
no gain: in the TypeScript reading `i64` is `number`, so the value is a double
there anyway (NL8009). Build it from the widest literal instead:
`const lo: i64 = -9007199254740992; const min: i64 = lo << 10;` is -2^63
(`tests/cases/neg_literal_i64_min`).

### Unsigned integers

`u8`, `u16`, `u32` and `u64` are unsigned integers with wrapping arithmetic.
LLVM has no unsigned types, so they lower to `i8`, `i16`, `i32` and `i64` and
the signedness lives entirely in the *operations*; representing an unsigned
value therefore costs nothing at all, and a `u8` field packs a struct as
tightly as a C `uint8_t` does.

| Operation | On `i32` / `i64` | On `u8` / `u16` / `u32` / `u64` |
| --- | --- | --- |
| `+ - *`, unary `-`, `++`/`--` | `add nsw` `sub nsw` `mul nsw` where proven to fit, else `llvm.s{add,sub,mul}.with.overflow` and a branch to the panic; plain through `wrappingAdd`/`wrappingSub`/`wrappingMul` from `nish:unsafe` | the same instructions, never flagged or checked: unsigned overflow wraps in both modes |
| `/ %` | `sdiv` / `srem` after a two-part divisor check | `udiv` / `urem` after a single compare ([Checked integer division](#checked-integer-division)) |
| `< <= > >=` | `icmp slt sle sgt sge` | `icmp ult ule ugt uge` |
| `>>` | `ashr` | `lshr` |
| `>>>` | `lshr` | `lshr` — the same instruction, so the two are synonyms |
| `=== !==` | `icmp eq` / `icmp ne` | identical (the bits decide) |
| widening conversion | `sext` | `zext` |
| narrowing conversion | `trunc` | `trunc` |
| to / from `f64` | `sitofp` / `llvm.fptosi.sat` | `uitofp` / `llvm.fptoui.sat` |
| `Math.abs` | `llvm.abs` | nothing: the value is already its own magnitude |
| `Math.min` / `Math.max` | `llvm.smin` / `llvm.smax` | `llvm.umin` / `llvm.umax` |
| `console.log(x)`, `` `${x}` `` | `nish_str_from_i32` / `_i64` | `zext` to i64, then `nish_str_from_u64` |
| overflow | a panic, "attempt to add with overflow", exit 1, except a `nish:unsafe` `wrapping*` call | nothing, in either mode: unsigned overflow is defined as wrapping |

The consequences worth knowing:

- **A value above `INT_MAX` behaves.** `const big: u32 = 4000000000` compares,
  divides and prints as four billion, where the same bits in an `i32` are
  -294967296 (`tests/cases/u_compare_above_intmax`, `u_udiv_urem`, `u_print`;
  `tests/differential/corpus/u_div_cmp`).
- **Division is cheaper.** Unsigned division has no overflow case, so its
  check is one compare instead of three plus an `and` and an `or`
  (`tests/cases/u_div_one_check`).
- **Overflow wraps**, and unlike the signed types it wraps in *every* mode:
  `(255: u8) + 1` is `0` and `(0: u8) - 1` is `255` (`tests/cases/u_arith_wrap`,
  `tests/differential/corpus/u_wrap`). No `nuw` is ever emitted, neither is
  `nsw`, and nothing is checked: wrapping is what hashing and bit-packing are
  written against, and it is half the reason the unsigned widths exist.
- **Mixing is an error.** `u32` and `i32` are different types even though both
  are `i32` in the IR, and so are `u8` and `u32`; there is no implicit
  conversion anywhere in this language
  (`tests/cases/reject_u_mixed_signedness`, `reject_u_mixed_widths`).
- **`i32 >>> n` still yields the raw bits read as signed** — `-1 >>> 0` is
  `-1` here where JavaScript gives `4294967295` — because an `i32` is the only
  place the result could go. That is now something to avoid rather than
  something to live with: use `u32` and the answer is `4294967295`
  (`tests/cases/u_shift_logical`, `u_conv_roundtrip`;
  `tests/differential/corpus/u_convert_shift`).

### `f32`

`f32` is 32-bit IEEE-754, LLVM's `float`. Every operation is the instruction
`f64` already uses, one width down — `fadd`/`fsub`/`fmul`/`fdiv`/`frem`,
`fcmp o*`, `fneg` — and float division is never checked, exactly as for `f64`
(`tests/cases/f32_arith`). It exists because a struct of `f32` is half the
footprint of one of `f64` and gives twice the SIMD lane count:
`class Vec3 { x: f32; y: f32; z: f32; hits: u32 }` is 16 bytes where three
doubles alone would be 24 (`tests/cases/f32_struct`).

- **It is not `number`.** `number` is `i32` or `f64` depending on
  `--number-mode`; `f32` is always spelled `f32`, and there is no implicit
  widening: `f32 + f64` is
  `` Operator `+` requires two operands of the same numeric type ... got f32 and f64 ``
  (`tests/cases/reject_f32_mixed`). Convert with `toF32` / `toF64`.
- **A literal takes `f32` from context** the same way it takes `f64`
  (`const tenth: f32 = 0.1`), and is rounded to the nearest float when it is
  emitted. LLVM writes a `float` constant with the 64-bit hex of the double it
  equals and requires that double to be exactly a float, so `0.1` as an `f32`
  is `float 0x3FB99999A0000000` — the double nearest to `(float) 0.1` — and
  not the `f64` spelling `0x3FB999999999999A` (`tests/cases/f32_constant`).
- **Printing gives JavaScript's digits for the float's value.**
  `console.log(x)` and `` `${x}` `` widen with `fpext` and reuse
  `nish_str_from_f64`, so `const tenth: f32 = 0.1` prints
  `0.10000000149011612` where the same literal as an `f64` prints `0.1`
  (`tests/cases/f32_print`; `tests/differential/corpus/f32_round`).
- **The f64-only `Math` functions stay f64-only.** `Math.sqrt(x)` on an `f32`
  is `` `Math.sqrt` requires an f64 argument, got f32 ``
  (`tests/cases/reject_f32_math_sqrt`); `Math.abs`, `Math.min` and `Math.max`
  do work, through `llvm.fabs.f32` and the float compare-and-select `min` and
  `max` lower to, and so does `Math.sign`.
- **`Float32Array` is `f32[]`**, one more typed-array alias with no second
  layout, so a Node host's `Float32Array` crosses the boundary the way an
  `Int32Array` already does.

### Shifts

`<<`, `>>` and `>>>` take two operands of one *integer* type and produce that
type. There is no implicit conversion, so the shift amount has the same type as
the value (`` Operator `>>` requires two operands of the same integer type, got
u32 and i32 ``, `tests/cases/reject_u_shift_mixed`), and `f64` has no shift at
all.

`>>` is an arithmetic shift on a signed type (`ashr`, sign bit replicated) and
a logical one on an unsigned type (`lshr`, zeros in); `>>>` is always `lshr`,
so on an unsigned type the two operators are synonyms and code that is generic
over a width may spell either (`tests/cases/u_shift_logical`).

The count is **masked to the operand width** rather than left undefined, which
is what makes `x << 33` mean `x << 1` instead of the poison LLVM produces for a
shift at or beyond the width. The mask is `31` at 32 bits and `63` at 64,
matching JavaScript; `u8` and `u16` mask to `7` and `15`, their own widths,
since JavaScript has no narrow unsigned type to be compatible with
(`tests/cases/bit_shift_narrow`). A literal count is masked in the emitter and
written out already masked, so `x << 3` is one instruction and no `and` reaches
the IR; only a computed count costs the mask
([Semantics decisions](#semantics-decisions)).

### Nullable types

`T | null` is available for `T` a class, interface, array, string, or
function reference (`tests/cases/mem_nullable`;
[wp6-memory.md](wp6-memory.md#4-t--null)). For a pointer type it is the same
LLVM pointer type as `T` with the constant `null` as one more
value, so nothing is boxed; `null` takes its type from context. A
[function reference](#function-references) may be nullable too: it is an
`i32` tag, and `null` is tag 0, which names no function
(`tests/cases/fnref_nullable`).

- **Where `null` may appear**: an annotated initializer
  (`let p: Node | null = null`), a field initializer (`next: Node | null = null`),
  `return` in a function returning `T | null`, an argument, a field or
  element store, an object literal property, `push`, and a ternary arm
  (`c ? p : null` is `T | null`). A `T` is accepted wherever `T | null` is
  expected; the reverse is `` `null` is not a Node; declare the type as `Node | null` ``
  (`tests/cases/reject_null_to_nonnull`).
- **`new Array<T | null>(n)`** is allowed: the zero fill *is* `null`
  (`tests/cases/mem_nullable`).
- **Comparison**: `p === null`, `p !== null`, `null === p` are pointer
  compares (`icmp eq ... null`). Two nullable values cannot be compared with
  each other (`` Cannot compare two `string | null` values; compare each with `null` ``,
  `tests/cases/reject_null_compare_two`), and neither can a nullable and a
  plain `T` *(CLI only)*: narrow first.
- **Narrowing** (`src/expressions.ts`): inside the region a condition
  guards, a nullable *variable* (a local or parameter, never a property
  path) reads as `T`:

  | Form | Where `p` is `T` |
  | --- | --- |
  | `if (p !== null) A else B` | in `A`; and after the `if` when `B` cannot fall through |
  | `if (p === null) A else B` | in `B`; and after the `if` when `A` cannot fall through (`return`, `break`, `continue`, `process.exit`, `panic`) |
  | `while (p !== null) A`, `for (...; p !== null; ...) A` | in `A`, on every iteration |
  | `p !== null && e`, `p === null \|\| e` | in `e` |
  | `p !== null ? a : b` | in `a` (and in `b` for `=== null`) |
  | `!cond`, `(cond)`, `a && b`, `a \|\| b` | composed as expected |

  A narrowing ends at any assignment to the variable (`cur = cur.next` reads
  the narrowed `cur` on the right and then drops it) and before a loop whose
  body, condition, or update assigns the variable, because the second
  iteration sees the assigned value (`tests/cases/reject_null_narrowing_assigned`;
  `reject_null_narrowing_leaks` for a use after the guarded block). Inside an
  `&&` or `||` chain the same holds operand by operand: an operand that
  assigns the variable ends its narrowing for every operand after it and for
  the region the chain guards, so `p !== null && g((p = null) === null) && p.v`
  is refused, and a test after the assignment narrows again
  (`tests/cases/reject_null_narrowing_assigned_in_chain`, `res_proof_consumers`).
  Constants and parameters keep their narrowing for the whole region.
  Property paths are not narrowed: `if (n.next !== null) n.next.v` is
  rejected; copy into a local first *(CLI only)*.
- **`undefined`** is not a value of `T | null`, but the same narrowing rules
  hold for a `const` bound to `Map.get`, with `undefined` in place of `null`
  (WP32, [`Map` and `Set`](#map-and-set)).
- **Access** to a field, method, element, or `.length` on an un-narrowed
  nullable is `` Cannot read property `value` of `Node | null`; check for null first ``
  (`tests/cases/reject_null_field_access`).
- **A default**: `a ?? d` on a `T | null` answers `a` where it is not `null`
  and `d` where it is, and runs `d` only then, as TypeScript does: `null` is
  nullish, so no `undefined` is involved. Its type is `T` when `d` is a `T`,
  as `tsc` types it, so the result needs no narrowing; a `d` that may itself
  be `null` keeps the `T | null` (`nullish_nullable`,
  `nullish_nullable_default_null`). `d` takes its context from `T`, so
  `xs ?? []` and an object literal need no annotation; a bare `null`, or a
  ternary that may answer one, is checked into `T | null`
  (`nullish_nullable_default_context`). The left operand is read once, so a
  property path works here although it never narrows: `cur = cur.next ?? cur`
  (`nullish_nullable_field`). A default that cannot have an effect, a literal
  or a name, is one `select`; any other is a branch to `nullish.default` and
  a `phi`. A `new` in the default goes wherever the `??` goes, as a ternary's
  arm does (`nullish_nullable_escapes`), and an arena block is held to both
  operands (`reject_using_arena_nullish`). `d` must be a `T` or a `T | null`:
  `` The right operand of `??` stands in for a missing value, so it must be `string`, the type of the value on its left; got `i32` ``
  (`reject_nullish_nullable_default_type`). The left operand may not be an
  element read, because past the end of the array Node reads `undefined` and
  answers `d` while the bounds check panics:
  `` `??` cannot default an element read: past the end of the array, JavaScript answers the default and Nish panics (test the index against `length`, or read the element into a `const` first) ``
  (`reject_nullish_element`). A left operand that cannot be `null` (a scalar,
  or a nullable already narrowed to `T`) keeps Phase 0's refusal,
  `` Nullish coalescing `??` is forbidden in Nish (narrow with `!== null` instead) ``
  (`reject_nullish`, `reject_nullish_nullable`); the `nullish` feature of
  [the compatibility dialect](#the-compatibility-dialect) admits it.
- **An optional chain**: `a?.b?.c ?? d` reads each link only where the
  receiver before its `?.` is not `null`, and answers `d` where one is, as
  TypeScript does. A `?.` is allowed only in a chain whose value is the left
  operand of a `??`, so `undefined`, which `a?.b` answers on its own, is never
  a value: anywhere else, a `const`, an argument, a template hole, an
  assignment target or behind a parenthesis that ends the chain, it is
  `` `?.` is allowed only in a chain that ends in `??`, whose default stands in when a link is `null`: write `a?.b ?? d`, or narrow with `!== null` ``
  (`reject_optional_chain`, `reject_optional_chain_paren`,
  `reject_optional_chain_argument`, `reject_optional_chain_assign`,
  `reject_optional_chain_template`); the `optional-chaining` feature of
  [the compatibility dialect](#the-compatibility-dialect) admits a chain that
  is a statement of its own. A link reads a field, a string's or an
  array's `length`, or calls a method, and its receiver is read as `T`
  (`optional_chain_field`, `optional_chain_order`,
  `optional_chain_generic`, `tests/link/optional_chain_modules`). The chain's value is its last link's, typed with
  the default as a `T | null` is above, so a number at the end works:
  `o?.next?.id ?? -1` is an `i32`. Only a `?.` link skips a `null`: a plain
  link after one reads what it is given, so `a?.next.value` with a nullable
  `next` is `` Cannot read property `value` of `Node | null`; a link of a `?.` chain that may be `null` needs a `?.` of its own: `a?.next?.value` ``
  (`reject_optional_chain_link_nullable`). `?.` on a receiver that cannot
  be `null`, `this`, a narrowed local or a builtin namespace, is
  `` `a` is never `null` here, so `?.` has nothing to skip: write `.` ``
  (`reject_optional_chain_never_null`, `reject_optional_chain_narrowed`,
  `reject_optional_chain_this`, `reject_optional_chain_namespace`). `?.[i]`
  and `f?.()` stay refused: an element read inside a chain is
  `` Optional chaining `?.` is forbidden in Nish (narrow with `!== null` instead) ``
  (`reject_optional_chain_element_inner`, which `optional-chaining` admits),
  one that ends the chain is
  `` An element read cannot end a `?.` chain or be what a `?.` tests: past the end of the array JavaScript answers `undefined` and carries on, and the bounds check panics (test the index against `length`, or narrow the array with `!== null` and read the element into a `const`) ``
  (NL1067, `reject_optional_chain_element`), and an optional call is
  `` An optional call `f?.()` is not supported, with or without `--compat`: call `f()` directly, or narrow `f` with `!== null` first ``
  (NL1068, `reject_optional_call`), in both dialects. A chain that ends in an element read is the
  element-read refusal above (`reject_optional_chain_element_last`), and one
  that ends in `get` is
  `` `h?.counts.get("a")` ends a `?.` chain in `get`: give the map a default first, then default what `get` answers ``
  (`reject_optional_chain_map_get`). Each `?.` lowers to an `icmp eq` against
  `null` and a branch to `nullish.default`, which every link shares, and runs
  nothing after a `null` link, an argument included. What a chain proves about
  an index holds only where its links ran, so a read after the `??` keeps its
  check (`optional_chain_bounds`). A call in a chain is held to every rule a
  call is (`reject_optional_chain_lock`, `reject_optional_chain_channel`), and
  a `Secret` either operand of the `??` makes is refused as one nobody owns
  (`reject_optional_chain_secret`).
- **Attributes**: a nullable parameter or return loses `nonnull` and
  `dereferenceable`; `align 8`, `readonly` and `nocapture` follow the usual
  rules ([ARCHITECTURE.md](ARCHITECTURE.md#attribute-soundness-rules)).

### Discriminated unions

A union of two or more **variants**, `type Shape = Circle | Square | Tri`, is a
pointer to whichever variant it holds, and its first field says which. A
variant is a class or an interface whose first field is its **tag**: a field
of an [enum member type](#enums), conventionally
`readonly kind: Kind.Circle = Kind.Circle` (`tests/cases/union_types`,
`tests/link/union_export` across modules). The enum may be numeric or a
[string enum](#string-enums), whose member is the tag in memory as its
ordinal (`tests/cases/enum_string_union_tag`).

```ts
enum Kind {
  Circle,
  Square,
}
class Circle {
  readonly kind: Kind.Circle = Kind.Circle;
  r: i32 = 1;
}
class Square {
  readonly kind: Kind.Square = Kind.Square;
  side: i32 = 2;
}
type Shape = Circle | Square;
const label = (s: Shape): string => (s.kind === Kind.Circle ? "circle" : "square");
```

Typed JSON reads and writes a union of classes by its tag ([Typed JSON](#typed-json-nishjson-typed)),
whose value on the wire is the tag member's name, or a string enum member's
string, unless the variant's `tag` option names another
(`tests/link/json_enum_string`).

**Layout.** Every union is the one LLVM type `%union.tagged = type { i32 }`,
behind a pointer. Every variant begins with its `i32` tag, so a variant
pointer is a union pointer by a `bitcast`, and reading the tag is a
`getelementptr` to field 0 and a load, whichever variant is there:

```llvm
%4 = bitcast %struct.Circle* %3 to %union.tagged*
...
%0 = getelementptr inbounds %union.tagged, %union.tagged* %s, i32 0, i32 0
%1 = load i32, i32* %0, align 4
```

`Shape | null` is the same pointer with `null` allowed, as
[Nullable types](#nullable-types) are.

**What makes a variant.** Each rule is checked where the union is spelled,
and each has its own code:

- A variant is a class or an interface that is not generic, so
  `type R = Ring<i32>` named in a union is
  `` `Ring<i32>` cannot be a union variant: a variant is a class or an interface that is not generic, because its tag is a field it declares itself ``
  (NL2522, `reject_union_generic_variant`). A generic type spelled with its
  arguments inside the union, `Circle | Ring<i32>`, and a member that is a
  scalar, an enum or an alias of one get the general refusal,
  `` Union types other than `T | null` are forbidden in Nish (values have one fixed layout) ``
  (NL1053, `reject_union_inline_generic`, `reject_union_untagged_scalar`,
  `reject_union_enum_alias_member`, `reject_union_scalar_alias_member`,
  `reject_union_type`).
- Its first field is of one enum member type: otherwise
  `` `Point` cannot be a union variant: its first field must be its tag, a field whose type is one member of an enum, such as `readonly kind: Kind.Circle = Kind.Circle` ``
  (NL2523, `reject_union_untagged`, `reject_paren_union_type`). A first
  field typed with its whole enum, `readonly kind: Kind = Kind.A`, holds a tag
  but types it as every variant's, so the union could not tell its variants
  apart by it; that is NL2559, which names the member to write:
  `` `First` cannot be a union variant: its tag `kind` has the whole enum `Kind` as its type, which every variant shares, so give it the one member it holds instead: `readonly kind: Kind.A = Kind.A` ``
  (`reject_union_tag_whole_enum`).
- The tag is `readonly`: otherwise
  `` `Circle` cannot be a union variant: its tag `kind` must be `readonly`, because the union tells its variants apart by it ``
  (NL2535, `reject_union_mutable_tag`).
- All the tags come from one enum (NL2524, `reject_union_mixed_enums`), the
  tag field has one name in every variant (NL2525, `reject_union_tag_names`),
  and no two variants share a tag (NL2526, `reject_union_duplicate_tag`).
- A union names at least two different variants, after aliases and nested
  unions are flattened: `Circle | Circle` is NL2527
  (`reject_union_one_variant`).

**Where a union goes.** A union is the type of a local, a parameter, a
field, a return, an array element (`Shape[]`, `Shape[][]`, or the members
spelled in place, `(Circle | Square)[]`), or of any of those made nullable,
and a `Map`'s value is any of those: `Map<string, Shape>`,
`Map<string, Shape[]>`, `Map<string, Shape | null>` (`union_map_value`).
A union is also a type argument: a generic class's (`Box<Shape>`,
`Box<Box<Shape>>`, `Stack<Shape>`, `union_generic_class`), a generic
function's or method's type parameter bound to one by its arguments
(`union_generic_call`), either side of a `Result`, `Result<Shape, E>` and
`Result<T, Shape>` (`union_result`), and `nish/map`'s `getOrInsert` and
`reserve` on a `Map<K, Shape>` (`union_map_helpers`). The instance is
monomorphised as for any other type argument, so `Box<Shape>` is laid out as
a class with a `Shape` field would be, and a `T` slot holds the union's one
pointer.
An alias may name another union, which is flattened: with `type Round =
Circle | Square`, `type Shape = Round | Tri` is the three variants. A value
of a variant, or of a union whose variants are all the wider union's,
converts to the union wherever the union is expected: an argument, a
`return`, an array literal under a `Shape[]` annotation, a `push`, a ternary
arm or a `??` default whose other side is the union
(`tests/cases/union_forms`), and the same places where a generic's `T` is
the union: a constructor's or a generic call's argument, `Ok(new Circle())`
in a function that returns `Result<Shape, E>` (`union_generic_class`,
`union_generic_call`, `union_result`). Equality on two unions compares the pointers, as
on any object.

**Reading.** The tag is the one member a union has until a test of the tag
narrows it (below): any other field or method is
`` `r` cannot be used on the union `Circle | Square`: a union has only its tag `kind` until a test of the tag narrows it to one variant ``
(NL2528, `reject_union_member_field`, `reject_union_method_call`, even when
every variant has it). It reads as the enum, `Kind`, so it compares, switches
and is passed as one. A union is read-only: a write through it is NL2529, even
to a field every variant has (`reject_union_assign_tag`).

**Comparisons that cannot be true.** As in `tsc`, comparing the tag with a
member no variant has is an error: `s.kind === Kind.Tri` when no variant is
tagged `Kind.Tri` is NL2531 (`reject_union_disjoint_compare`), and
`case Kind.Tri:` in a `switch (s.kind)` is NL2532
(`reject_union_disjoint_case`).

**Narrowing.** A test of a variable's tag narrows the variable, as in `tsc`.
Where `s.kind === Kind.Circle` holds, `s` reads as a `Circle`, so its fields
and methods are there; where it fails, `s` is the union of the variants left,
and when one variant is left it reads as that one
(`tests/cases/union_narrowing`):

```ts
const area = (s: Shape): i32 => {
  if (s.kind === Kind.Circle) {
    return 3 * s.r * s.r;
  }
  return s.side * s.side;
};
```

- The test narrows the branch it guards: the `then` and `else` of an `if`,
  the arms of a ternary, the right side of `&&` (where it held) and of `||`
  (where it failed), and the statements after an `if` whose branch always
  leaves (`return`, `break`, `continue`, a `panic(...)`). `!==` narrows the other way
  round, and the operands may be either way round, `Kind.Square === s.kind`.
- Each `case Kind.X:` of a `switch (s.kind)` narrows `s` to its variant, and
  `default` to the variants no `case` named. A `case` that a previous one falls
  through into narrows nothing.
- A null test composes with it: on `s: Shape | null`,
  `s !== null && s.kind === Kind.Circle && s.r > 0` reads `s.r`.
- Where an `||` held, either side may have made it hold, so the variable is
  what either side proved: past `s.kind === Kind.Circle || s.kind ===
  Kind.Square`, `s` is a `Circle | Square`, which has only its tag and whose
  tag is not `Kind.Tri`. The same goes for the side of an `&&` where it
  failed, for an enum variable, for any number of arms and for `===` mixed
  with `!==`; an arm that tests something else leaves the variable as
  declared (`tests/cases/union_narrowing_join`; `reject_union_narrow_or_if`,
  `reject_union_narrow_or_ternary`, `reject_union_narrow_and_false`,
  `reject_enum_narrow_or_if`, `reject_enum_narrow_or_ternary`,
  `reject_enum_narrow_or_three`, `reject_enum_narrow_or_mixed`,
  `reject_enum_narrow_and_false`).
- The test may read the variable through an assignment, which answers the
  value it stored: `(t = next()).kind === Kind.Square` narrows `t`, as
  `(k = next()) === Kind.A` narrows an enum `k`
  (`reject_union_narrow_test_assign`, `reject_union_narrow_or_assign`,
  `reject_enum_narrow_assign`).
- The variable is a parameter or a `let` or `const` local; a narrowed `const`
  stays narrowed in a data-parallel arrow that reads it
  (`tests/link/union_narrowing_capture`). An
  assignment to it drops what the tests proved, as for a nullable
  and a loop that assigns it drops it before its body
  (`reject_union_narrow_dropped`, `reject_union_narrow_else_assign`,
  `reject_union_narrow_loop_assign`).
- What a test proved holds past the statement that made it as far as every
  way out of it agrees, as in `tsc`. After an `if` with an `else`, the
  variable is what the arms that fall through left it, joined; after an
  `if` whose one arm falls through, what that arm left, so a chain of `else
  if`s whose branches all return leaves the variant no test named and an arm
  that assigns the variable leaves what it assigned
  (`reject_union_narrow_else_if_chain`, `reject_union_narrow_arm_assign`,
  `reject_nullable_arm_assign`). A block's early return narrows what follows
  the block. An enum local that an `if`, a ternary, a loop or a `switch`
  stores a member into holds, after it, what it held before or any member
  stored (`reject_enum_held_if_join`, `reject_enum_held_else_join`,
  `reject_enum_held_ternary`, `reject_enum_held_ternary_assign`,
  `reject_enum_held_loop_join`, `reject_enum_held_switch_join`). The join
  after an `if` covers every local and path either arm assigns, one first
  assigned in the `else` included (`reject_union_narrow_path_if_join`,
  `reject_union_narrow_path_if_test`), and every one a test inside either arm
  narrowed, whether or not an arm assigns it: two arms that each leave when
  `k === Kind.A` leave `k` not `Kind.A` past the `if`, joined with what held
  before it (`tests/cases/union_narrowing_tested_join`;
  `reject_enum_if_tested_join`, `reject_union_narrow_if_tested_join`,
  `reject_union_narrow_path_tested_join`, `reject_union_narrow_nullable_tested_join`,
  `reject_enum_else_if_tested_join`, `reject_enum_if_tested_outer`). A `switch` joins what each of its
  exits leaves: every `break` out of it, the fall off its last clause and,
  when no `default` covers every member, the case no clause matches; a
  clause that returns is no exit (`tests/cases/union_narrowing_switch_join`;
  `reject_union_narrow_path_switch`, `reject_union_narrow_path_switch_late`,
  `reject_enum_switch_join`, `reject_enum_switch_unmatched`), a variable only
  its clauses' tests narrowed included (`reject_enum_switch_tested_join`,
  `reject_enum_switch_tag_tested_join`). What held
  before the `switch` holds again at the start of each clause and in the
  case no label matches, whatever an earlier clause stored
  (`reject_union_narrow_switch_kept`, `reject_enum_switch_kept`). A loop is
  followed to a fixpoint, as `tsc` follows it: the head of a `while`, `for`
  or `do` holds what reaches it before the loop, at the end of an iteration
  and at a `continue` (through its update, for a `for`), joined until it no
  longer changes; after a `while` or `for` comes the head with its condition
  false, joined with every `break`,
  after a `do` the end of the body and its `continue`s with the condition
  false, and after a `for...of` the head and the `break`s. A loop inside the
  body and a `switch` inside it are followed the same way, an `if` or a
  `switch` narrowing its arms and clauses inside the loop as it does outside
  one (`tests/cases/union_narrowing_loop_flow`,
  `tests/cases/union_narrowing_loop_reads`; `reject_union_loop_while_join`,
  `reject_union_loop_do_join`, `reject_union_loop_condition_reassigned`,
  `reject_enum_loop_for_join`, `reject_enum_loop_do_join`,
  `reject_enum_loop_top_of_body`, `reject_enum_loop_do_continue`,
  `reject_enum_loop_break`, `reject_enum_loop_for_of`,
  `reject_enum_loop_nested`, `reject_enum_loop_switch`,
  `reject_enum_loop_switch_store`, `reject_enum_loop_switch_while`,
  `reject_union_loop_switch`). A variable the loop only tests, never
  writes, is followed too (`reject_enum_loop_tested_while`,
  `reject_enum_loop_tested_do`, `reject_enum_loop_tested_break`,
  `reject_enum_loop_tested_inner`, `reject_enum_loop_switch_tested`,
  `reject_union_loop_tested_while`, `reject_union_loop_null_tested`). A
  store holds what its value holds where the value is one of: a member; a
  local of a member type, `const m: Kind.B`; a call of a function that
  returns a member type; a field of a member type, or a call of a method
  that returns one, read through `this`, a local or parameter or a field of
  one, nullable or not; a `const` the loop declares once, read by its
  initializer; another
  enum variable; a union's tag; or a ternary of two of these, each arm read
  on its side of the condition
  (`reject_enum_loop_ternary_store`, `reject_enum_loop_copy_store`,
  `reject_union_loop_tag_copy`, `reject_enum_loop_member_local`,
  `reject_enum_loop_member_call`, `reject_enum_loop_field_store`,
  `reject_enum_loop_method_store`, `reject_enum_loop_nullable_receiver`,
  `reject_enum_loop_body_const`,
  `reject_enum_loop_ternary_narrowed`, `reject_enum_loop_ternary_tracked`,
  `reject_enum_loop_ternary_self`). A test against a member, a local of a
  member type or such a call narrows as outside a loop, and so does a test
  against another enum variable, by the members it holds there
  (`reject_enum_loop_const_test`, `reject_union_loop_const_test`,
  `reject_enum_loop_held_operand`, `reject_enum_loop_held_single`,
  `reject_enum_loop_held_ternary`, `reject_union_loop_held_operand`;
  `tests/cases/enum_loop_held_several`). A `for`
  update runs after the body and before the next test, and is followed
  there (`tests/cases/enum_loop_for_update`;
  `reject_enum_loop_for_update_store`, `reject_enum_loop_for_update_cond`),
  and is checked when the body is one refused statement, so both errors are
  reported (`reject_for_update_after_body`). A store of any other value holds
  the whole declared type. Where the loop holds a shape the fixpoint does not
  follow, a local or path holds, after it and throughout it, every member
  stored anywhere in it, which may be more than `tsc` knows ("Accepted here,
  refused by `tsc`", below).
- A tag compared with an enum variable narrows on the side where they are
  equal: `s.kind === k`, with `k` holding `Kind.Circle | Kind.Square`, makes
  `s` a `Circle | Square` there, and `j === k` leaves the enum `j` one of
  `k`'s members. Where they differ, nothing is known, since `k` may hold
  either, unless `k` holds one member, which is then left out
  (`tests/cases/union_narrowing_arms`;
  `reject_union_narrow_tag_variable`, `reject_enum_compare_variable`).
- A tag tested through a path — a field `h.k`, `this.k`, a field of a field
  `h.s.kind`, a literal index `xs[0].kind` — stays narrowed for the
  comparisons after it, so a repeat test of a member already excluded is
  NL2531, as `tsc`'s TS2367 is. A store to the path, to a prefix of it
  (`h.s = t`, `xs[0] = t`) or to its root drops what it held, and the joins
  above follow a path as they follow a variable; a call does not, as in
  `tsc` (`tests/cases/union_narrowing_paths`;
  `reject_union_narrow_path_field`, `reject_union_narrow_path_this`,
  `reject_union_narrow_path_nested`, `reject_union_narrow_path_index`,
  `reject_union_narrow_path_join`, `reject_union_narrow_path_loop`). An
  index is part of the path when it names one element, as TypeScript 5.5
  reads it: a number literal, a parameter, a `const` (`const i = 0` makes
  `xs[i]` the path `xs[0]`, annotated or not, and so does `const j = i`
  after an unannotated `const i = 0`, whose type is the literal `0`), a module
  constant (`const IDX: i32 = 0` makes `xs[IDX]` the path `xs[0]` too, and
  `const A: i32 = -1` and `const B: i32 = -1` make `xs[A]` and `xs[B]` one
  path), or a `let` nothing in its block assigns, a closure's body included. A
  `let` that is assigned or stepped (`i = 1`, `i++`), a parenthesised name or any
  other expression keys no path, so `xs[i]` is not narrowed through it, and a
  store through such an index (`xs[j] = t`) drops nothing, as in `tsc`
  (`tests/cases/union_narrowing_index`, `union_narrowing_index_const`;
  `reject_union_narrow_path_ident`, `reject_union_narrow_path_steady`,
  `reject_union_narrow_path_const_index`,
  `reject_union_narrow_path_index_store`,
  `reject_union_narrow_path_const_chain`,
  `reject_union_narrow_path_negative_index`,
  `reject_union_narrow_path_negative_zero`,
  `reject_union_narrow_path_module_index`,
  `reject_union_narrow_path_module_literal`,
  `reject_union_narrow_path_module_ident`,
  `reject_union_narrow_path_module_negative`). The union read through the path is
  not narrowed (below).
- A union of two or more variants left still has only its tag
  (`reject_union_narrow_none_if`, `reject_union_narrow_none_ternary`,
  `reject_union_narrow_none_and`, `reject_union_narrow_none_or`,
  `reject_union_narrow_none_fallthrough`), and a narrowed variant has only its
  own fields (`reject_union_narrow_none_case`, `reject_union_narrow_none_null`,
  `reject_union_narrow_none_reversed`).

What a test excluded stays excluded, so a second test of a tag already ruled
out is always false and NL2531, in an `if`, a ternary or an `&&`
(`reject_union_narrow_second_if`, `reject_union_narrow_second_ternary`,
`reject_union_narrow_second_and`), and so is its `case`, NL2532
(`reject_union_narrow_dead_case`). An enum local holds what it was given: the
tag stored in a local, `const k: Kind = s.kind`, holds only the variants'
members, and a local given `Kind.Circle` holds only that member until it is
assigned again, so `k === Kind.Tri` against a member it cannot hold is NL2531
and `case Kind.Tri:` of a `switch (k)` NL2532, as `tsc`'s TS2367 and TS2678 are
(`reject_union_tag_local_compare`, `reject_union_tag_local_case`,
`reject_enum_held_const`, `reject_enum_held_let`, `reject_enum_held_reassign`,
`reject_union_tag_held_capture`).

A test of an enum variable against a member narrows what it holds in the same
forms, as `tsc` narrows it: `k === Kind.A` and `k !== Kind.A`, either way
round, in an `if` and its `else`, a ternary, `&&` and `||`, after an `if` whose
branch always leaves, and each `case` and the `default` of a `switch (k)`. This
holds for a parameter `k: Kind` as for the tag local `const k: Kind = s.kind`,
and an assignment drops it as it drops a union's. So after
`if (k === Kind.A) return`, `k === Kind.A` is NL2531 and `case Kind.A:` NL2532,
as `tsc`'s TS2367 and TS2678 are (`tests/cases/enum_narrowing`;
`reject_enum_narrow_else`, `reject_enum_narrow_early`,
`reject_enum_narrow_ternary`, `reject_enum_narrow_and`,
`reject_enum_narrow_or`, `reject_enum_narrow_switch`,
`reject_enum_narrow_tag_local`). Narrowed to one member, the variable is that
member's type, so `let j = k` is a `Kind.A` that `j = Kind.B` does not fit
(`reject_enum_narrow_let_member`), as in `tsc`.

A `switch` whose subject reads a union variant's tag field, with no
`default` and labels that name every variant the tag can hold, is
**complete**: no value reaches the case no label
names, so when no `break` targets the `switch` and its last clause leaves, the
`switch` terminates (see Termination) and can end a function that returns a
value, as in `tsc`. Its unmatched case compiles to LLVM's `unreachable`. The
tag may be read through a union variable, a field, an element or a call's
result, `s.kind`, `h.shape.kind`, `shapes[i].kind`, and a variable that a test
before the `switch` left fewer variants needs labels for those only
(`tests/cases/union_switch`). With a variant unnamed, the `switch` does not
terminate, and a function that returns a value and ends in it is the
missing-return error, as `tsc --strict --noImplicitReturns`'s TS2366 is
(`reject_union_switch_missing_case`, `reject_union_switch_missing_case_field`).
Complete means the tag can hold nothing else: a variant's tag is `readonly`,
written only with its own member, and a union never crosses the interop
boundary, so no other `i32` reaches it.

**Stricter than TypeScript.** Each of these programs is accepted by
`tsc --strict` and refused here; each refusal is pinned:

- **No narrowing by assignment.** `tsc` narrows a union-typed slot to the
  type of the value last stored in it, so after `let s: Shape = new Circle()`
  it treats `s` as a `Circle`. This version does not track that, so a store
  of a value that is only some of the variants into a union local, field,
  element or nullable union is NL2534, and asks for the variant's own type or
  a value of the whole union (`reject_union_narrow_const`,
  `reject_union_narrow_assign`, `reject_union_narrow_field`,
  `reject_union_narrow_element`, `reject_union_narrow_ternary`,
  `reject_union_narrow_nullable`). A call that returns `Shape` is a value of
  the whole union, and is stored freely. Passing and returning a variant
  narrows nothing, and is accepted. A test of the tag does narrow (above).
- **A union is a type argument, but not a key.** `Box<Shape>`, a generic
  function or method whose type parameter binds to a union, `Result<Shape, E>`
  / `Result<T, Shape>` and `nish/map`'s helpers on a `Map<K, Shape>` are
  accepted (above), as in `tsc`. Three things stay refused, each under its own
  rule: a union is not a `Map` or `Set` key, which is the key rule's refusal
  (NL2353, `reject_union_map_key`, `reject_union_set`); a generic class is
  not a variant (NL2522, `reject_union_generic_variant`); and a store of a
  bare variant into a generic instance's union field, `b.value = new
  Square()` on a `Box<Shape>`, is NL2534 as into any union field
  (`reject_union_generic_field_store`). A union does not meet a constraint
  (`<T extends HasKind>`, NL2328, `reject_union_generic_constraint`), and an instance
  over a union is not key material for `nish:secret`
  (NL2428, `reject_union_generic_secret`), nor a class typed JSON writes
  (NL2486, `reject_union_generic_json`), nor something a C header or N-API bridge
  spells (`reject_union_generic_export`, `reject_union_result_export`).
- **No inferred unions.** A union is never inferred: an unannotated ternary
  or array literal of two variants is the existing same-type refusal
  (`reject_union_ternary_inferred`, `reject_union_array_inferred`; so is
  one a generic call would bind `T` to, `first([new Square(), new Circle()])`,
  `reject_union_generic_inferred`), an arrow
  returning one needs its annotation (`reject_union_arrow_result`), and a
  local initialised from the tag without an annotation, `const k = s.kind`
  or the tag in a `for…of`, is NL2530, because `tsc` would infer the union
  of the tags' member types, which this version does not have
  (`reject_union_inferred_tag`, `reject_union_forof_tag`). So is the tag as
  an element of an unannotated array literal, an arm of an unannotated
  ternary, or the result of an arrow that binds a type parameter
  (`reject_union_tag_array`, `reject_union_tag_ternary`,
  `reject_union_tag_arrow`). An annotation as the enum, `const k: Kind =
  s.kind`, is accepted, and the local holds the variants' members (above).
  An enum variable narrowed to two or more members is the same: `const j = k`
  after `if (k === Kind.A) return` is NL2530, since `tsc` would infer
  `Kind.B | Kind.C` (`reject_enum_narrow_inferred_set`); annotate it as `Kind`.
- **No narrowing of a union through a path.** `tsc` narrows a property
  path, `h.s.kind === Kind.Circle` then `h.s.r`; this version narrows the
  tag read through the path (above) but the union only in a variable, so a
  read of a variant's member through the path is
  `` `r` cannot be used on the union `Circle | Square | Tri` read through a property path: a test of the tag narrows a variable, not a path, so copy the union into a local first and test that ``
  (NL2558, `reject_union_narrow_path`).
- **A complete `switch` reads the union's tag.** `tsc` treats a `switch`
  whose labels name every member of an enum as complete, and so ends a
  function in it; this version does so for a union's tag only (above). A
  plain enum, `switch (k)` for `k: Kind`, can arrive from C holding any
  `i32`, so a `switch` on a plain `Kind` local or field is never complete
  (`reject_union_switch_enum`), nor is one on the tag copied into an enum
  local, `const k: Kind = s.kind`, or a `let` one reassigned on another path
  (`reject_union_switch_tag_local`, `reject_union_switch_tag_local_reassigned`).
  A narrowed path needs every tag of the whole union: `switch (h.s.kind)`
  after `if (h.s.kind === Kind.A) return` is complete only with `Kind.A`
  labelled too, since a call between the test and the `switch` could have
  reassigned `h.s` (`reject_union_switch_path_narrowed`); a narrowed union
  local, which nothing reassigns unseen, is complete with the labels of the
  variants left to it (`tests/cases/union_switch_narrowed`). Nor is a `switch`
  complete on an enum field assigned from
  a tag, `b.k = s.kind`, which a call, an alias, a method or `this` can
  overwrite with any member (`reject_union_switch_enum_field_call` and its
  siblings): what decides is the subject's static type, a union's tag field,
  never what a path was assigned or narrowed to hold. End such a function
  after the `switch`, or give it a `default` (`tests/cases/union_switch_flow`).
- **No `never`.** Where the tests have excluded every variant, `tsc` types the
  variable `never` and accepts a read of it; this version has no such type, so
  the read is
  `` `s` has no variant left here: the tests before this read excluded every variant of its union, which TypeScript types `never` and this version has no type for ``
  (NL2557, `reject_union_narrow_exhausted`).
- **No narrowing through a stored condition.** `tsc` narrows `s` where a
  `const` holding a test of its tag is true, `const round = s.kind ===
  Kind.Circle; if (round) { s.r }`; this version narrows on the test
  itself only, so `s.r` there reads the union (NL2528,
  `reject_union_narrow_aliased`). Test the tag in the condition.
- **No field shared by every variant.** `tsc` reads a field every variant
  declares through the union; this version reads only the tag before a test
  narrows it (NL2528, `reject_union_member_field`).
- **A tag of one member.** `tsc` accepts a variant whose tag is typed with its
  whole enum, `readonly kind: Kind = Kind.A`, which then discriminates
  nothing; this version asks for the member type (NL2559,
  `reject_union_tag_whole_enum`).
- **No covariant arrays.** A `Circle[]` is not a `Shape[]`, since a push
  through the wider type would put a `Square` among the circles; build the
  array as a `Shape[]` (`reject_union_covariant_array`).
- **No object literal of a union.** An object literal where a union is
  wanted, `area({ kind: Kind.Tri, base: 2 })` for a `Circle | Tri`
  parameter, has no one class to build (`reject_union_object_literal`):
  build it into a local annotated as the interface, `const t: Tri = { ... }`,
  and pass that.
- **No `new Array<Shape>(n)`**, which would fill the array with a zero no
  variant is (`reject_union_new_array`).
- **No class for its interface variant.** A class that implements an
  interface variant is not itself a variant, so `tsc` accepts a `Band
  implements Ring` where `Circle | Ring` is wanted and this version does not
  (`reject_union_implements_variant`): convert it to the interface first,
  `const r: Ring = new Band()`.
- **A readonly tag.** `tsc` accepts a variant whose tag can be reassigned;
  this version asks for `readonly` (NL2535, `reject_union_mutable_tag`).
- **No write through the union.** `tsc` accepts `s.x = 1` when every variant
  has `x`; this version refuses every write through a union (NL2529,
  `reject_union_assign_tag`).

A union is not a class either, so `new Shape()` names no constructor, as in
`tsc` (`reject_union_new`). A value of any other type where a union is
wanted is the existing refusal of its position (`reject_union_into_init`,
`reject_union_into_assign`, `reject_union_into_arg`,
`reject_union_into_push`, `reject_union_into_index`,
`reject_union_into_nullable`, `reject_union_field_other`,
`reject_union_return_other`, `reject_union_method_arg`,
`reject_union_ctor_arg`, `reject_union_array_other`,
`reject_union_ternary_other`, `reject_union_nullish_other`). A smaller union
stored where a larger one is declared narrows it in `tsc`, as a variant
does, and is NL2534 too (`reject_union_narrow_subunion`).

**Accepted here, refused by `tsc`.** The loop pass (above) reads less than
`tsc` in the shapes below, and these are all of them: a variable holds every
member stored anywhere in the loop, or its whole declared type, so a
comparison `tsc` refuses as TS2367 may compile here. Each is pinned as it
stands, with the expected `tsc` error written at the comparison, so the case
fails on either side once the gap closes (`tests/cases/enum_loop_join_gap`):

- **A path.** A tag or enum held by a field, `h.k`, is joined over the whole
  loop, not followed through it.
- **A store inside an expression.** An assignment that is an argument,
  `keep((j = Kind.C))`, an initializer, `const t = (j = Kind.C)`, or the
  inner store of a chain, `k = j = Kind.C`, rather than a statement of its
  own.
- **A value the pass cannot read.** A store of a field or a method call
  read through anything but `this`, a local or parameter the loop does not
  declare, or a field of one — an element, `j = gs[0].b` or
  `j = gs[0].pick()`, a call's result, `j = makeG().b`, a receiver the loop
  declares, `const g = new G(); j = g.b` — holds the whole declared type,
  though the field or method is typed with one member. So does a store of a
  `let` the loop declares, or of a `const` it declares from a tracked
  variable, as the swap `const t: Kind = a; a = b; b = t;` does.
- **An arm that holds nothing.** A ternary arm that reads the stored
  variable where the condition leaves it no member, the `k` of
  `k = k === Kind.A ? Kind.B : k` while `k` holds only `Kind.A`, reads as
  the whole type, as the checker reads a variable narrowed to `never`, so
  the store holds every member from then on.
- **A wide type.** A union of more than 29 variants or an enum of more than
  29 members.

`try` is refused by Nish on its own, a destructuring pattern only ever
declares fresh names rather than storing to a variable (a destructuring
assignment is NL2773, [Destructuring declarations](#destructuring-declarations)),
and an arrow may read a local it captures but never
assign it (NL2586, [Function parameters](#function-parameters)), so no loop
that compiles stores through any of them. A loop that holds a
labelled statement or a labelled `break` or `continue` anywhere in its body,
or whose `switch` has a clause that falls into the next, is one the pass
gives up on: it keeps the checker's widened state.

**Across a sidecar.** A union has no C spelling yet, so a function exported
through `--emit-header` or `--emit-napi` whose parameter or return holds a
union is refused, and so is a union-holding field of any class or interface
the compilation declares, exported or not, under a flag that lays the classes
out as C structs (`--emit-header`, `--emit-napi`, `--emit-napi-async`): a
header lays out every class and interface of the program, a private one too
(`reject_union_private_field`). A build with `--emit-dts` alone describes no
class, so there a union field of a class only the module reads — root
storage's graph among them — is accepted; a union in an exported function's
parameter or result is still refused under every sidecar flag. The message is
`` `tagOf`'s parameter `s` is `Circle | Square`, which holds a union no sidecar can describe: a union has no C spelling in this version ``
(NL4009, `reject_union_export_param`, `reject_union_export_return`,
`reject_union_export_field`, `reject_union_export_array_field`). Unions
cross Nish modules freely (`tests/link/union_export`). A string enum in an
exported function's signature is refused under the same flags for a reason
of its own (NL4019, [String enums](#string-enums)).

## Result and error handling

A function that can fail says so in its return type, hands back a
`Result<T, E>`, and the caller cannot get at the success value without first
deciding what happens to the failure. There is no `throw`, no `try`, and no
unwinding anywhere in the language (WP16;
[wp16-results.md](wp16-results.md)).

```ts
const half = (n: i32): Result<i32, string> => {
  if (n % 2 !== 0) {
    return Err("odd");
  }
  return Ok(n / 2);
};

const quarter = (n: i32): Result<i32, string> => {
  const h = half(n).orReturn();   // Rust's `?`: propagate the error
  return half(h);
};

export const main = (): i32 => {
  const outcome = quarter(8);
  if (outcome.isErr()) {
    console.log(outcome.error);
    return 1;
  }
  console.log(outcome.value);
  return 0;
};
```

### The type

`Result<T, E>` is a built-in type constructor with exactly two arguments — the
same kind of thing `Array<T>` is, built in rather than a user
[generic class](#generic-classes-and-interfaces) (`` `Result` needs exactly two type arguments, e.g. `Result<number, string>` ``,
`tests/cases/reject_result_type_args`).

- `T` may be `void`: `Result<void, E>` is the fallible operation with nothing
  to hand back, and it carries no `value` at all
  (`tests/cases/res_void`).
- `E` may not be `void` (`` `Result<T, void>` is not supported ``): a failure
  that says nothing is what `panic` is for.
- `Result<T, E> | null` is refused (`tests/cases/reject_result_nullable`): the
  error arm already models absence.
- A `Result` is **immutable**. `r.ok = false` is
  `` Cannot assign to `ok` of Result<i32, string>: a `Result` is immutable once built ``
  (`tests/cases/reject_result_immutable`), which is what keeps a narrowing from
  being falsified under it.

Each distinct pair of payload types gets one monomorphised struct,
`%struct.nish_result.<T>.<E> = type { i1, <T>, <E> }`, held by pointer and
allocated exactly as a class is — so a `Result` costs what a small object
costs, and one that does not outlive its function becomes an entry-block
`alloca` with no allocator call at all (`tests/cases/res_stack`).

A `Result` **crossing a call boundary** is different, and this is the one
place its representation is not a pointer. When both payload types are
scalars of at most four bytes — `void`, `boolean`, `u8`, `u16`, `i32`/`number`,
`u32`, `f32` — it is returned *and* passed as one `i64` instead:

```
bits  0..31   the discriminant: 1 for Ok, 0 for Err
bits 32..63   the live arm's payload, zero-extended (f32 through a bitcast)
```

so `return Ok(v)` is a shift and an `or` with no allocation at all
(`tests/cases/res_by_value`, and `res_by_value_payloads` for each payload
width), and the receiving side unpacks the word into an object of its own,
which every construct below reads exactly as before. Only the value in transit
changes: a `Result` in a field or an array element, and a `Result` whose
payloads do not fit, stay the WP16 pointer.

The word is what a **host** sees. Between two functions of one module it is
`{ i1, i32, i32 }` — the discriminant and one slot per arm, the arm that is
not live left `undef` — because a non-exported function's calling convention
is nobody else's business and the word costs two folds this shape does not
(WP15 §7b, which took `bench/result` from 2.59x behind Rust `-O3` to parity in
two steps). The condition is exactly the one that gives a function
`internal` linkage, so `--no-strict-exports` returns every function to the
word, and an exported function is packed whoever calls it — which is what
keeps `--emit-header` honest (`tests/cases/res_export`). Nothing about the
language changes either way: the two spellings compute the same value and only
the register they arrive in differs.

Where that object lives is the ordinary WP6 decision. A callee's unpacked
parameter is an entry-block `alloca` unless a use of the parameter stores the
pointer somewhere that outlives the frame — an object literal, `push` — in
which case it is an arena bump like any other escaping allocation
(`tests/cases/res_by_value_param` shows both in one golden).

Eight bytes is where the six supported targets agree about a register rather
than a number worth tuning; the measurements, and the one place the packing
still costs something against C and Rust, are in
[wp17-result-abi.md](wp17-result-abi.md).

### The surface

| Spelling | Meaning | Test |
| --- | --- | --- |
| `Ok(v)`, `Ok()` | the success value; takes its `Result` type from the context, as `null` does. `Ok()` is the `Result<void, E>` form | `res_basic`, `res_void`; `reject_result_no_context` |
| `Err(e)` | the failure value, likewise | `res_basic` |
| `r.isOk()`, `r.isErr()` | the discriminant test, and what narrows `r` | `res_basic` |
| `r.ok` | the same bit as a plain `boolean`; `if (r.ok)` narrows too, because a tagged union is how TypeScript itself would spell this | `res_basic` |
| `r.value` | `T`, only where the checker proved `isOk()` | `res_basic`, `res_by_value_param`; `reject_result_value_unchecked`, `reject_result_by_value_unchecked`, `reject_result_let_keeps_proof`, `reject_result_narrowing_assigned_in_chain` |
| `r.error` | `E`, only where it proved `isErr()` | `res_basic`; `reject_result_error_in_ok_arm` |
| `r.orReturn()` | `T` when ok; otherwise `return Err(r.error)` from the enclosing function — Rust's `?` | `res_propagate`, `res_by_value_propagate`; `reject_result_propagate_plain`, `reject_result_propagate_error_type` |
| `r.unwrapOr(d)` | `T` when ok, `d` otherwise | `res_unwrap` |
| `r.expect(message)` | `T` when ok; otherwise `message` on stderr and exit 1, the same ending `panic` has | `res_unwrap`, `res_void` |

There is deliberately no `unwrap()`: `expect(message)` says the same thing and
insists on a reason. There is no `map` / `andThen` / `orElse` either — they
need a callback written at the call, often a closure, which a
[function reference](#function-references) cannot hold, and through an
unknown callee the whole-program pass cannot prove purity, termination or
escape.
Narrowing plus `orReturn()` covers what those combinators are for.

### The three rules

**1. A `Result` cannot be dropped.** A call that answers one may not stand as
an expression statement (`` `Result<i32, string>` must be handled, not
discarded ``, `tests/cases/reject_result_discarded`), and a local that holds
one must be read at least once (`` `outcome` holds a `Result<i32, string>`
that is never inspected ``, `reject_result_unhandled`). Handing the value on —
an argument, a `return` — counts as reading it: the responsibility moves with
the value, and the receiving signature carries the same rules.

Storing one is handing it on too. An assignment statement — `rs[0] = rs[1]`,
`r2 = r1` — moves the `Result` into its target and is not a
discard; `r2 = r1` reads `r1`, and `r2`, a local, must still be inspected
(`tests/cases/res_result_store`, `reject_result_store_unread`). The value an
assignment replaces is dropped, though, so a `Result` local may not be
assigned again while the value it holds has not been read since it was
written (`` `r` is assigned again before its `Result<i32, string>` is
inspected ``, `reject_result_overwrite_unread`). The check reads the function
in source order, with an assignment's right-hand side before its target, so
`r = retry(r)` is accepted, and a read in either branch of an `if` counts for
an assignment after it. An element or a field is not tracked slot by slot, so
`rs[0] = rs[1]` overwrites `rs[0]` unchecked. In a generic
body a discarded value is judged by the type its template declares, as Rust's
`#[must_use]` is: `items.pop()` on `items: T[]` drops a `T`, which is not a
`Result` to the template's author even where `T` is one, while a template
that drops a `Result<T, E>` it declared, or a concrete `Result`, is refused at
every instantiation (`res_result_store`, `reject_result_generic_discarded`).
That is what lets a `Map` hold a `Result` value
(`tests/cases/map_value_result`, and `map_value_result_by_value` for one that
travels packed).

**2. The error arm comes first.** `r.value` is legal only where the checker
proved `isOk()`, `r.error` only where it proved `isErr()`. There is no
spelling that reaches the success payload without deciding what happens to the
failure, so the success path cannot be written before the error path is
handled.

Narrowing is the same engine as `T | null` (`src/expressions.ts`) and
obeys the same rules: it applies to a **variable**, not a property path; it
ends at any assignment to that variable; and it is dropped before a loop that
assigns it. All three spellings compose with `!`, `&&`, `||` and the ternary,
and hold after an `if` whose other branch cannot fall through:

| Form | Where `r` reads as its ok arm |
| --- | --- |
| `if (r.isOk()) A else B` | in `A`; and after the `if` when `B` cannot fall through |
| `if (r.isErr()) A else B` | in `B`; and after the `if` when `A` cannot fall through |
| `if (r.ok) A else B` | as `isOk()` |
| `r.isOk() && e`, `r.isErr() \|\| e` | in `e` |
| `r.isOk() ? a : b` | in `a` (and in `b` for `isErr()`) |

A field or element holding a `Result` is not narrowed; bind it to a local
first, exactly as for a nullable. An assignment inside an `&&` or `||` chain
ends the narrowing for the operands after it, as for a nullable
(`tests/cases/reject_result_narrowing_assigned_in_chain`).

**A proof stays with its variable.** What a test proved is seen only by a
*proof consumer*: the receiver of `.ok`, `.value`, `.error`, `isOk()`,
`isErr()`, `unwrapOr`, `expect` or `orReturn`, or another narrowing test.
Wherever a type is instead inferred from the narrowed variable's value, it is
the plain `Result<T, E>`: a `let` or `const` initialiser, a ternary, and an
array literal's elements. Arguments, `return`s and stores already take the
declared type they flow into. So inside `if (r.ok)`, `const y = r` needs its
own test before `y.value`, `c ? r : q` does too whatever `q` was narrowed to,
and `[r]` is a `Result<T, E>[]` that an `Err` may be pushed onto
(`tests/cases/reject_result_let_keeps_proof`, `reject_result_ternary_keeps_proof`,
`reject_result_array_keeps_proof`; `res_proof_consumers` for the tests that
make each of them compile). `tsc` narrows `const y = r` along with `r`, so this
refuses programs `tsc` accepts; that is the safe direction, and the rule a
reassignment, a pushed element or the other arm of a ternary would otherwise
break.

**3. Propagation is contagious.** `r.orReturn()` is legal only inside a
function that itself returns a `Result` whose error arm accepts `E`
(`` `orReturn()` propagates the error, so `main` must return a `Result<T, E>`
(it returns i32) ``, and `` `orReturn()` would propagate IoError but `read`
returns Result<i32, string> ``). A function that propagates a callee's failure
therefore has to admit it in its own signature. There is no implicit error
conversion — Rust's `From<E>` needs a trait and Nish has none — so a
mismatch is named rather than papered over; convert it by hand with
`if (r.isErr()) { return Err(...); }`.

### It is still TypeScript

Every line above parses as TypeScript, and with
[`runtime/nish.d.ts`](../runtime/nish.d.ts) on the include path it
type-checks under plain `tsc --strict` and in an editor too. The declarations
model `Result` as the tagged union TypeScript would use anyway, intersected
with the method surface, so `if (r.ok)` and `if (r.isOk())` narrow `r` in
`tsc` for the same reason and in the same places they narrow here — and `tsc`
refuses `r.value` before the test just as this compiler does (`tests/run.js`,
"WP16: the ambient declarations").

`nish` remains the authority: `tsc` cannot see that a `Result` may not be
dropped, that `orReturn()` returns early, or that the enclosing function has
to return a `Result` for it to be legal at all. A program `tsc` accepts may
still be rejected here; the reverse is a bug in the declarations.

### Interop

A `Result` crosses the host boundary. `--emit-header` writes two C types per
`Result` and a signature uses whichever its position calls for:

```c
/* Result<number, number> */

/* the arena object: a `Result` too large to pack, and what a field holds */
struct nish_result_i32_i32 {
  bool ok; /* 1 = value, 0 = error */
  int32_t value;
  int32_t error;
};

/* the by-value form, in either direction: one 64-bit word */
typedef struct nish_result_i32_i32_word {
  int32_t ok; /* 1 = value, 0 = error */
  union { int32_t value; int32_t error; } as;
} nish_result_i32_i32_word;
NISH_RESULT_ASSERT(sizeof(nish_result_i32_i32_word) == 8, "...");
```

The word is not a description of the ABI, it is the ABI: clang lowers a
function returning *or taking* that type to `i64` on every supported native
target, which is the same declaration the module already defines
([wp17-result-abi.md](wp17-result-abi.md) §3). A C host includes the header
and calls across with no glue, in both directions (`tests/run.js`, the WP17
interop block).

`--emit-napi` bridges a by-value `Result` whose payloads are numbers or
booleans, in both positions, as the object JS already models —
`{ ok: true, value }` or `{ ok: false, error }`. `--emit-dts` declares the
same union for the wasm build, and the generated loader packs an argument and
unpacks a result. A `Result` held by pointer still does not cross either JS
boundary: it is arena memory the next call may recycle.

**A wasm export's `string` result is a JS string; a `string` parameter is
not bridged** (`docs/wp50-wasm-host.md` §7). The loader decodes the result's
UTF-8 bytes with `TextDecoder` straight out of the arena, before it releases
the call's mark, so the page never holds module memory; an invalid sequence
becomes U+FFFD. An export that takes a `string` is left out of the `.d.ts`
and the loader with
`` argument 1 (s) is `string`, which the wasm bridge carries only as a result: have the page `encodeInto` module storage and pass the byte count (`nish/host/text`) ``:
the page writes the text into a `u8[]` module storage and the module reads
it back with `textRead` (`tests/run.js`, section `host-import-text`).
Going the other way, `textRead(buf, n)` answers `null` for an `n` that is
negative or past the buffer, and each writer (`textWrite`, `textWriteInt`,
`textWriteF64`) takes the offset to write at and answers the offset after
what it wrote, so writes chain. **Text that does not fit writes nothing and
answers -1, and a writer handed a -1 offset answers -1 without writing**, so
a chain that overflowed once stays -1 to its end.

A **ranged parameter** (`integer<Lo, Hi>`, [Types](#types)) crosses as the
`i32` it is, and is checked where every call passes through
([wp31-ranged-integers.md](wp31-ranged-integers.md) §9):

- **Where the check lives is the linkage condition.** A function that
  `--strict-exports` makes `internal` has every caller in view, so each call
  site checks its argument, where the facts that can prove it free are. Any
  other function (exported, or every function under `--no-strict-exports`)
  can be called by a host with any `int32_t`, so it checks its ranged
  parameters in its own prologue, before anything else it does, and its
  callers in the program pass theirs unchecked (`tests/cases/interop_rng_param`),
  so a loop that passes one is given no performance warning for it: no guard
  at the call would remove the callee's check (`interop_rng_loop`).
  Leaving the range there is the same panic as at any other entry, which is
  what a C host sees (`interop_rng_host`, driven by `interop_rng_host.c`).
- **The bridges throw first.** The N-API shim reads a ranged argument with
  `napi_get_value_double`, and the wasm loader judges the number it was
  given, so a value that is not an integer in `[Lo, Hi]` throws
  ``RangeError: pick: argument 2 (day) must be an integer in [1, 7]`` before the
  call, rather than ending the process. The value is read as a double because
  ToInt32 would wrap `4294967301` to `5`, which is in range; `RangeError` is
  what JavaScript throws for `new Uint8Array(-1)`. `--emit-napi-async`
  rejects with the same error.
- **The sidecars say the range.** `--emit-header` spells the parameter
  `int32_t` and gives the source signature above the prototype, with
  `day: panics outside [1, 7]`; `--emit-dts` spells it `number` and adds
  `Throws a RangeError unless day is an integer in [1, 7].` A ranged result
  and a ranged field are `int32_t` / `number` with the range in the comment,
  since a value the program produced is already inside it.
- **A range inside data is not described.** An `integer<0, 9>[]` parameter, a
  record with a ranged field, or a `Result` over a range is memory a host
  writes and nothing checks on entry, so the header gives the function its
  existing line, `not declared; no C spelling for one of its types`, and the
  `.d.ts`, the loader and the N-API shim leave it out with their own
  (`tests/run.js`, the `interop_rng` block, which builds every sidecar of
  `interop_rng_host.ts`, compiles the header under `-pedantic` and calls the
  addon and the wasm build from Node).

## Declarations

### Program structure

A module (one `.ts` file) may contain, at the top level, only function
declarations (a `const` bound to an arrow, or the legacy `function` keyword),
`class` and `interface` declarations, `const` declarations
([Module constants](#module-constants)), `type` aliases
([Type aliases](#type-aliases)), numeric `enum` declarations
([Enums](#enums)), `declare function` declarations
([Calling C](#calling-c)), `import` statements, and `export` modifiers on
those declarations. The entry module may instead hold
[top-level code](#top-level-code), which runs as its `main`. In any other
module, and in an entry that declares `main`, any other top-level statement
is rejected with
`Only top-level function declarations are supported in Phase 1 (found <Kind>)`,
where `<Kind>` is TypeScript's name for the statement, `ExpressionStatement`
or `IfStatement` (`tests/cases/reject_top_level_stmt`); a top-level `let`
names the reason instead (`` Top-level `let` is not supported; a module has no
top-level code, so only `const` is available ``,
`reject_const_top_level_let`), and `var` is refused wherever it is written
([Forbidden constructs](#forbidden-constructs-phase-0-validator)). Modules have no top-level code, so there is no
initialisation order to worry about — which is exactly why a top-level `const`
must be a value the compiler can compute for itself. The one piece of state a
module keeps is [module storage](#module-storage), a `const` array laid out
and zero-filled at compile time, which is a declaration, not code.

### Top-level code

An entry module that declares no `main` may hold statements at the top level,
the way a script does. They run as the program's `main`: the compiler moves
them, in order, into an exported `main(): void` before anything else reads
the tree, so the native program is the one a hand-written `main` gives and
exits 0 unless the code calls `process.exit` (`tests/cases/script_basic`,
`script_exit`).

```ts
const LIMIT: i32 = 4

const capped = (n: i32): i32 => (n > LIMIT ? LIMIT : n)

const start = 1
let total = start
for (let i = 0; i < 3; i++) {
  total += capped(i + 2)
}
console.log(total)              // 10
```

- **What moves:** every top-level statement (an expression, `if`, a loop,
  `switch`, a block, a labelled statement, `throw`, `try`), every top-level
  `let`, and every top-level `const` that is not exported and that no
  declaration names. `return`, `break` and `continue` stay refused.
- **What stays:** functions, classes, interfaces, enums, types, imports, and
  a `const` that a function, a class or another staying constant names. That
  `const` is a [module constant](#module-constants) with all its rules, since a
  function cannot read a local of `main`; `LIMIT` above is one. A variable of
  the code that a function names is refused with
  `` `count` is a variable of the entry module's top-level code, which runs as `main`, so a function cannot read it ``
  (`reject_script_local_in_function`).
- **Declare before the code reaches it.** Under Node a top-level statement runs
  where it stands, before the declarations below it exist; natively they all
  exist first. So a statement that reaches a function, class, enum or
  constant, by naming it or through a function that does, must stand below
  it: `` `twice` is declared below the top-level code on line 5 that reaches it ``
  (`reject_script_declared_below`).
- **One scope.** Under Node the code's variables share the module scope with
  its declarations, so a variable may not take a name the module declares or
  imports: `` `go` is a variable of the top-level code and also a name the module declares or imports ``
  (`reject_script_name_collision`).
- **Only the entry, and only without `main`.** An imported module has no
  top-level code, and neither has an entry that declares `main` in either
  spelling (`reject_top_level_stmt`, `reject_const_top_level_let`). An entry
  of nothing but constants is a module, not a script.
- There is no top-level `await`: `await` is written only inside an `async`
  function (NL2641, [Async functions](#async-functions-async-and-await)), so a
  script that waits declares `export async function main` instead.
- `--emit-ts` writes the code back where it stands, and its `entry.ts`
  imports the module rather than calling `main`.

### Functions

A function is declared as an arrow bound to a module-level `const`
([wp22-arrow-functions.md](wp22-arrow-functions.md)):

```ts
const add = (a: number, b: number): number => {
  return a + b;
};

const double = (n: i32): i32 => n * 2; // a concise body is that one `return`
```

The `function` keyword declares the same thing and is accepted as the legacy
spelling; the two compile to identical IR, instruction for instruction
(`tests/cases/fn_arrow`).

- **The arrow form** is a `const` — `let` is
  `` Function `f` must be declared `const`, not `let` ``
  (`tests/cases/reject_arrow_let`) — binding one name
  (`const f = (): i32 => 1, g = 2` is `A function declaration binds one name`,
  `reject_fn_two_names`), with the signature on the arrow itself. Annotating
  the `const` is
  `` Function `f` takes its signature from the arrow; drop the annotation on `f` ``
  (`reject_arrow_annotated`): the signature is written once, on the arrow. A
  function returning `void` uses a block.
- A **concise body** (`=> n * 2`) means exactly what a block with one `return`
  means, everywhere the difference could show. It takes the return type as its
  contextual type, so an object literal gets its struct, a class value converts
  to an interface it implements, a numeric literal takes the declared width and
  `[]` takes its element type; and a value it allocates is returned rather than
  local, so the caller brackets the call with the arena reclaim
  ([Memory model](#memory-model)). `tests/cases/fn_arrow_concise` pins all five,
  each of which the block form has always had.
- **A capture-free top-level function is a value** in either spelling: a
  name bound to a non-generic, non-async function this program defines, with
  no rest parameter, is a value of its function type, so
  `const alias = double` is a [function reference](#function-references). It
  can be held in a local, a field, an array element, a return value or a type
  alias, passed, called and compared with `===` and `!==`, and nothing else
  (`tests/cases/fnref_field`, `fnref_array`, `fnref_eq`, `fnref_stores`). An
  arrow that is not a top-level `const` is no reference: one that captures is
  `` this arrow captures `k`: a function reference names a top-level function and carries no environment ``
  (`tests/cases/reject_arrow_as_value`), and one that does not is
  `` an arrow in value position is not yet a function reference: declare it as a top-level function and name it ``
  (`reject_fnarg_arrow_value`).
- Every parameter and the return type must be annotated
  (`` Parameter `x` needs a type annotation ``;
  `` Function `f` needs an explicit return type annotation ``,
  `tests/cases/reject_missing_return_type`, `reject_arrow_return_type`). The
  return type is asked of every function and method as the module is read, a
  generic one nothing instantiates included
  (`reject_method_return_template`, `reject_method_return_generic`).
- Functions may call each other in any order; signatures are collected
  before bodies are checked (`tests/cases/locals`, `cf_fib`). **This holds for
  the arrow form too**, which is not what a reader who knows that a `const` is
  not hoisted in JavaScript would expect: a module-level `const` bound to an
  arrow *is* a function declaration, so it is in scope for the whole module and
  not only below its own line, and two of them may call each other
  (`tests/cases/fn_arrow_hoisting`). Nothing else would let a file be converted
  from one spelling to the other without reordering it
  ([wp22-arrow-functions.md](wp22-arrow-functions.md) §8b).
- Calls take exactly the declared number of arguments (`expects 1 argument`,
  `tests/cases/reject_arity`), each of exactly the declared type
  (`` Argument 1 of `area`: expected Shape, got Rect ``,
  `tests/cases/reject_cls_not_implements`).
- Parameters are immutable: `p = 1`, `p++`, `p += 1` are
  `` Cannot assign to `p` because it is a parameter ``
  (`tests/cases/reject_assign_param`, `reject_cf_incdec_param`).
- Parameters and the body's top-level block share one scope: `let x` in
  the body of `f(x)` is `` Duplicate declaration of `x` `` *(CLI only)*.
- **A function's name shares one declaration namespace** with classes,
  interfaces, type aliases, enums and module constants, whichever declaration
  came first. A class or interface of the same name is
  `` `Point` is already declared as a class or interface ``
  (`tests/cases/reject_cls_name_is_function`); everything else is
  `` `value` is already declared in this module ``
  (`tests/cases/reject_fn_after_const`).
- **A function may be generic**, and each instantiation is compiled on its
  own; see [Generic functions](#generic-functions). Rejected forms:
  generators (`reject_generator`), an `async` function without its
  `Promise<T>` ([Async functions](#async-functions-async-and-await),
  `reject_async_function`),
  destructured parameters (`Destructured parameters are not supported`,
  `reject_param_destructured`), optional parameters (`x?: T`,
  `Optional parameters are not supported`, `reject_param_optional`, which names
  `x: T = <default>` instead; the compatibility dialect's `optional-params`
  feature accepts one read through `??`, [The compatibility
  dialect](#the-compatibility-dialect)), a default or rest parameter anywhere but the
  declarations [Default and rest parameters](#default-and-rest-parameters)
  lists (`reject_param_default`, `reject_param_rest`), overloads
  (`` Duplicate function `f` ``, `tests/cases/reject_fn_duplicate`; a
  signature with no body, `function f(): void;`, is
  `Functions must have a body`; the compatibility dialect's `overloads`
  feature accepts signatures before the implementation), an anonymous `export default function ()`
  (`Functions must be named`, `reject_fn_anonymous`),
  function expressions, an arrow anywhere but as a top-level `const` or a
  function argument (`reject_fnarg_arrow_value`, `reject_arrow_as_value`),
  and nested function declarations (`Unsupported statement in Phase 1:
  FunctionDeclaration`, `reject_fn_nested`, in a template nothing
  instantiates too, `reject_fn_nested_template`; an `import` in a body is
  `Unsupported statement in Phase 1: ImportDeclaration`).
- A non-`void` function must return on every path
  (`` Function `f` must return a value of type i32 on every path ``,
  `tests/cases/reject_missing_return`, `reject_cf_missing_return_loop`); see
  [Termination](#termination-definite-return-and-unreachable-code).

#### Default and rest parameters

```ts
const scale = (x: number, by: number = 2): number => { return x * by }
const area = (w: number, h: number = w): number => { return w * h }
const total = (...xs: i64[]): i64 => { let s: i64 = 0; for (const x of xs) { s = s + x } return s }

scale(3)        // scale(3, 2)
area(4)         // area(4, 4)
total()         // total([])
total(1, 2, 3)  // total([1, 2, 3])
```

A function, a method with a body, a constructor, and an arrow bound to a
module `const` may give trailing parameters a **default** or end in one **rest
parameter**. Both are filled in **at the call site**: the callee is compiled as
if every argument were always passed, with no branch on a missing one, so a call
that passes every argument compiles to the same IR it did before the function
had a default (`tests/cases/param_default`, `param_rest`, `param_method`,
`param_generic`, across modules `tests/link/param_modules`).

- **A default is a constant or an earlier parameter**: a numeric literal (a
  negative one too), `true`/`false`, a string literal, an enum member, or the
  name of a parameter written before it, or `null` for a `T | null`
  parameter (next rule). Anything else is refused
  (`reject_param_default_expression`, `reject_param_default_later`,
  `reject_param_default_array`, `reject_param_default_fraction`).
- **A `T | null` parameter defaults to `null`, and only to `null`**:
  `opts: Options | null = null` makes a call that leaves `opts` out pass a
  typed null pointer, the same IR as passing `null` itself
  (`tests/cases/param_default_null`, across modules
  `tests/link/param_modules`). This is how an options argument is written
  without `undefined`: `fetch(url)` and `fetch(url, init)` are one function.
  `null` is refused as the default of a type with no `null`
  (`reject_param_default_null_not_nullable`), any other default of a
  `T | null` is refused, since every call that omits it would build the value
  (`reject_param_default_object`), and `T | null` of a type parameter takes no
  default (`reject_param_default_null_generic`).
- **A default's parameter is annotated**, `n: i32 = 1`, never `n = 1`
  (`reject_param_default_untyped`), and its type is a number, `boolean`,
  `string`, enum or a `T | null` defaulting to `null`
  (`reject_param_default_parameter_type`), not a type
  parameter (`reject_param_default_generic`). Every parameter after one with a
  default has one too (`reject_param_default_order`).
- **A rest parameter is last, has an array type and no default**
  (`reject_param_rest_not_last`, `reject_param_rest_not_array`,
  `reject_param_rest_default`), and a function has a default or a rest, not
  both (`reject_param_rest_and_default`). The call gathers its trailing
  arguments into one array of exactly that many elements, on the stack unless
  the callee lets it escape — the same array an explicit literal
  `total([1, 2, 3])` builds.
- **A rest of records takes only fresh object literals.** The array copies each
  inline record (an interface no class implements) into its slot, so a named
  record passed through a rest would be a copy the callee's write never
  reaches, where TypeScript would write the caller's own: `bumpAll(p)` is
  `` A rest parameter copies each `Cell` record it gathers, ... ``
  (`reject_param_rest_record`). Pass `[p]` to a `Cell[]` parameter, where the
  copy is written out. A class instance is a reference, so a rest of class
  instances gathers the caller's objects.
- **Not on a function-typed parameter**, which a call names by value
  (`reject_param_function_default`, `reject_param_function_type`), and a
  function with a rest parameter is never passed for a function parameter
  (`reject_param_rest_function_value`) nor held in a function reference
  (NL2729, `reject_fnref_rest`): called through either, Node would gather
  differently.
- **No spread argument**: `total(...xs)` is
  `Spread arguments are not supported` (`reject_param_spread_call`); pass `xs`
  to a parameter of array type.
- Too few or too many arguments name the range the function takes
  (`reject_param_arity`).
- **A host sees neither.** Defaults and rest are filled in by a Nish call
  site, so an exported function's symbol takes every parameter: the
  `--emit-dts` typings, the `--emit-header` prototype and the `--emit-napi`
  shim require each argument, and take a rest parameter as one plain array
  ([wp8-interop.md](wp8-interop.md#the-c-abi)).
- What a call evaluates is what TypeScript evaluates: each argument once, left
  to right, whether it fills a default's place or gathers into a rest
  (`tests/cases/param_eval_order`). A rest array the callee returns, stores in
  a field or lets a caller keep is allocated in the arena, not on the stack
  (`param_rest_escape`); a default on an imported class's constructor or method
  is filled in by the importing module (`tests/link/param_default_import`).

### Module constants

```ts
const TOKEN_NAME: i32 = 1;
const TOKEN_END: i32 = TOKEN_NAME + 1;
export const PROMPT: string = "> ";
```

A top-level `const` names a value the compiler already knows. It is **not a
global variable**: no symbol is emitted, no initialiser runs, and every use of
the name lowers to the value itself — `AREA` below is the literal `64` in the
IR, not a load (`tests/cases/const_basic`, `const_fold`, `dump_checked_const`).
That is what lets a module keep its table of kinds and limits while still
having no top-level code and therefore no initialisation order.

- **The type annotation is required**, as on every other top-level declaration
  (`` Module constant `answer` needs a type annotation ``,
  `tests/cases/reject_const_no_annotation`), and so is an initialiser.
- **The type must be `i32`, `i64`, `f64`, `number`, `boolean`, or `string`.**
  A class or interface constant would need an allocation, and there is
  no code to run it (`` must be a number, boolean, string, or a `readonly`
  array of numbers ``, `tests/cases/reject_ffi_handle_module_binding`). There
  are two exceptions with rules of their own: a `readonly` array of numbers
  written out as a literal, which is a [constant table](#constant-tables), and
  a `new Array<T>(n)` or typed-array `new` of a compile-time length, which is
  [module storage](#module-storage).
- **The initialiser is an ordinary Nish expression restricted to literals
  and other constants**: the operators of [Operators](#operators) over numeric,
  boolean, and string literals, other module constants (declared anywhere in
  the module, or imported), and parentheses. Anything else — a call, a `new` (other than
  [module storage](#module-storage)'s), a local, a parameter — is
  `` A module constant's initialiser must be a literal, another constant, or arithmetic over them ``
  (`tests/cases/reject_const_not_constant`, `reject_const_unknown_name`).
  There is deliberately no second, larger language inside `const`: a constant
  can compute exactly what a runtime expression can.
- **Folding follows the language's own arithmetic**, whichever mode the
  compiler is in, because a constant must compute what the instruction it
  replaces computes. By default that instruction is checked, so a fold that
  overflows is
  `` attempt to compute with overflow in a constant `` — the run-time
  operation would panic, and a constant has no run time to panic at
  (`tests/cases/reject_const_overflow_arith`). A wrap the program means is
  written `wrappingAdd`, `wrappingSub` or `wrappingMul` from `nish:unsafe`, the
  one call a constant's initialiser may make, and that fold wraps:
  `const WRAPPED: i32 = wrappingAdd(2147483647, 1)` is `-2147483648`
  (`tests/cases/unsafe_wrapping`). Negation is arithmetic too, so `-2147483648` is fine
  (its result fits) while `-(-2147483648)` is refused. A bare
  integer literal takes the width of the constant it initialises, so `const BIG: i64 = 1000000000 * 10` is computed in
  64 bits (`const_i64`). Mixing widths is an error, as it is anywhere else
  (`reject_const_mixed_widths`). `f64` folds in IEEE-754 (`const_f64`), and
  `+` on two strings concatenates at compile time, interning the result once
  (`const_string`).
- **The two failures the divisor check catches at run time are refused at
  compile time** instead: `1 / 0` and `MIN / -1` in a constant are
  `attempt to divide by zero in a constant` and
  `attempt to divide with overflow in a constant`
  (`tests/cases/reject_const_div_zero`; see
  [Checked integer division](#checked-integer-division)).
- **A value that does not fit its annotation is an error, not a wrap**:
  `const TOO_BIG: i32 = 3000000000` is `` Constant `TOO_BIG` does not fit in i32 ``
  (`tests/cases/reject_const_overflow`), and a folded value of the wrong type is
  `` declared i32 but its value is string `` (`reject_const_type_mismatch`).
- **A constant cannot be assigned**: `` Cannot assign to `LIMIT` because it is a
  module constant `` covers `=`, `op=`, `++` and `--`
  (`tests/cases/reject_const_assign`, `reject_const_incdec`).
- **A local shadows a constant of the same name**, as it would in TypeScript:
  the scope chain is consulted first (`tests/cases/const_shadow`).
- **A constant may name a constant declared later**, in the same module or in
  an imported one, because folding is by need rather than in source order. A
  cycle is `` Module constant `A` is defined in terms of itself ``
  (`tests/cases/reject_const_cycle`).
- **A string constant is a value**, so it is a receiver like any other string:
  `NAME.length` is the folded literal's byte length
  (`tests/cases/const_string_member`).

### Constant tables

```ts
const CLASS: readonly u8[] = [0, 0, 1, 1, 2, 3]
const STEPS: readonly i32[] = [-1, 0, 1, LIMIT]
```

**A top-level `const` of type `readonly T[]` whose initialiser is an array
literal is a constant table**: its elements are folded at compile time and laid
out as one read-only data global, with a constant array header over it, so no
code runs to build it and nothing can write it (`tests/cases/const_array_u8`,
`const_array_numeric`). A use of the name is the header's address — the same
`readonly T[]` value any other read-only array is — so `CLASS[c]`,
`CLASS.length`, `for (const v of CLASS)` and passing it to a `readonly T[]`
parameter all work, and `CLASS[c]` with `c: u8` into a 256-entry table is one
load the bounds prover has already discharged.

- **The element type is `u8`, `u16`, `u32`, `i32`, `i64` or `f64`** — the
  numbers whose bytes are their value. Anything else is
  `` Constant table `XS` cannot hold string ``
  (`tests/cases/reject_const_array_element_type`).
- **The annotation must be `readonly T[]`** (or `ReadonlyArray<T>`): the data
  is constant, and a plain `T[]` could be written through. `const XS: i32[] =
  [1, 2, 3]` is `` must be declared `readonly i32[]` ``
  (`tests/cases/reject_const_array`).
- **Each element is a constant expression** under the rule above — literals,
  other module constants and arithmetic over them
  (`tests/cases/reject_const_array_nonconst`) — and must fit the element type:
  `256` in a `readonly u8[]` is `` Element 2 of constant table `XS` does not fit
  in u8 `` (`tests/cases/reject_const_array_element`). An empty literal is
  refused (`` has no elements ``, `reject_const_array_empty`).
- **Writing is refused like any write to a `readonly` array**: an element
  store, `push`, `pop` or any other mutating method
  (`tests/cases/reject_const_array_write`, `reject_const_array_push`), and
  handing the table to a mutable `T[]` — a parameter or a local
  (`reject_const_array_mutable`, `reject_const_array_alias`).
- **The symbols are `@nish_const_<module>_<name>.data`** (`private unnamed_addr
  constant`) **and `@nish_const_<module>_<name>`** (the header, `internal
  constant`), `<module>` the module's index. An exported table follows module
  storage's rule: the header in its own module is not `internal`, and an
  importer declares it `external constant`.

### Module storage

**A top-level `const` whose initialiser is `new Array<T>(n)`, or `new` of one
of the typed-array names, is module storage**: a fixed array the module keeps
between calls, laid out by the compiler and zero-filled before the first call,
so no code runs to build it and the module still has no top-level code
(`tests/cases/storage_module`, `docs/wp50-wasm-host.md` §5). It is the one
place a module keeps state, and the place a page reads and writes a wasm
module's memory in place ([Host modules](#host-modules-the-functions-a-page-supplies)).
It is legal in every build, native included.

```ts
interface Body { x: f32; vx: f32; hits: u32; alive: boolean }

export const SLOTS: i32 = 8
export const bodies = new Array<Body>(SLOTS)
export const scale = new Float64Array(2)

export const step = (): void => {
  for (let i = 0; i < bodies.length; i++) {
    if (bodies[i].alive) bodies[i].x = bodies[i].x + bodies[i].vx
  }
}
```

```llvm
@nish_storage_0_bodies.data = global [8 x %struct.Body] zeroinitializer, align 16
@nish_storage_0_bodies = global %struct.nish_array { i64 8, i64 8, i8* bitcast ([8 x %struct.Body]* @nish_storage_0_bodies.data to i8*) }, align 8
```

- **Two globals.** `<symbol>.data` holds the elements and `<symbol>` is an
  ordinary array header over them, so every read and write is the indexing an
  array already lowers to. The symbol is `nish_storage_<module>_<name>`, with
  `<module>` the module's place in the program, so two modules may each keep
  a private storage of one name, and none takes a C symbol such as `write`.
  The data has external linkage: the `--profile wasm-host` link exports it,
  and the loader reads its address from that export. The header is
  `internal` unless the storage is exported; another module reaches an
  exported one as `@<symbol> = external global %struct.nish_array`
  ([cookbook](IR_COOKBOOK.md#module-storage-two-globals-a-page-can-find)).
- **The length is known at compile time**: a literal, a module constant, or
  arithmetic over them (`wrappingAdd` and the other `nish:unsafe` folds
  included), from 1 to 16,777,216 elements and at most 256 MiB
  (268,435,456 bytes). Anything else is
  `` Module storage `X` needs a length known at compile time: a literal, a module constant, or arithmetic over them, because the page reads its layout from the type ``
  (NL2676, `reject_storage_dynamic_length`), and a length outside the range is
  `` Module storage `X` has length 0; a storage holds from 1 to 16777216 elements ``
  (NL2680, `reject_storage_length_zero`; past 256 MiB the message names the
  element's size, `reject_storage_too_many_bytes`).
- **The element is pointer-free, and zero is one of its values**: a number, a
  `boolean`, an enum or a ranged integer whose zero is a member, a
  `HostHandle`, or an interface no class implements whose fields are all of
  these. A string, an array, a class, a `Map` or a `| null` (but `C | null`
  for a class `C`, which is [root storage](#root-storage-an-object-graph-kept-between-calls)) is
  `` Module storage `X` cannot hold T: its bytes are zero-filled where a page can read them, … ``
  (NL2686, `reject_storage_string_element`, `_array_element`,
  `_class_element`, `_map_element`, `_nullable_element`,
  `_record_string_field`). An interface a class implements, generic classes
  included, is a class's shape and is refused the same way
  (`reject_storage_implemented_interface`, `_generic_implementer`). A field
  may not be another record, since a record field is a pointer to it:
  `` Module storage `X` cannot hold Out.p (In): a record field that is itself a record is a pointer to it, and storage holds no pointer; spell the inner fields on the outer record ``
  (NL2685, `reject_storage_nested_record`). An enum or range without a zero is
  `` Module storage `X` is zero-filled, and 0 is not a value of T; give the type a zero member, or store the number and convert it where it is read ``
  (NL2687, `reject_storage_enum_no_zero`, `_range_no_zero`).
- **An annotation must say what the `new` makes**: `const xs: f64[] = new
  Int32Array(4)` is NL2679 (`reject_storage_annotation`). The annotation may
  be left off.
- **It never moves and never resizes.** `push`, `pop`, `sort`, any other
  method and `X.length =` are
  `` Module storage `X` has a fixed length and a fixed place, so `X.m` is not available: index it, and keep a count beside it for the slots in use ``
  (NL2688, `reject_storage_push`, `_pop`, `_sort`, `_length_assign`).
  `X[i]` and `X.length` are what remain.
- **Its name is a place, not a value.** Binding, returning, storing or
  passing `X` itself is
  `` Module storage `X` is a place, not a value: index it (`X[i]`) or read `X.length`, lend it only to a parameter declared `u8[]`, `Int32Array`, `Float32Array`, `Float64Array` or `BigInt64Array` or to a host function's buffer window, and never alias, return or store the array itself ``
  (NL2677, `reject_storage_pass_whole`). The two exceptions are lendings:
  a **scalar** storage passed to a parameter spelled with a typed-array name
  (which has no `push`, `pop` or `length =`), as in
  `const total = (xs: Int32Array): i32 => …; total(SCORES)`
  (`tests/cases/storage_lend`), or a byte storage passed to a `u8[]` or
  `readonly u8[]` parameter, the spelling a byte buffer has
  (`tests/cases/storage_lend_bytes`, which `nish/host/text` writes through),
  and to a host function's buffer window
  ([Host modules](#host-modules-the-functions-a-page-supplies)). A record
  storage is never lent. A lending to a function of the same module holds
  only while that function keeps the parameter in place: it may index it,
  read `.length` (never assign it or `++` it), loop over it with `for of`,
  call a method that reads it (`at`, `indexOf`, `slice`, `map`, …), call
  `fill`, `sort`, `reverse` or `copyWithin` as a statement, copy it with
  `String.fromBytes`, and lend it on to another such parameter or a buffer
  window. Anything else (binding it under another name, returning it,
  passing it to an `i32[]` parameter, which could `push`) is
  `` Module storage `X` cannot be lent to `f`, which lets its parameter `a` go further than indexing: … ``
  (NL2684, `reject_storage_lend_respell_arg`, `_const`, `_return`). The
  rule holds wherever the callee is declared: a function another module
  declares is judged by its own body, read in its own module, so a lending
  on from there resolves the next callee by that module's names — its
  imports and import aliases (`import { good as sum }`) included — and is
  judged the same way, for as many hops as it lends on
  (`tests/link/storage_lend_import`, `reject_storage_lend_import`). A
  callee name the calling function binds itself (a parameter, a local, a
  pattern) is not a declared function and is refused.
- **A record element is a place too.** `X[i].x` reads and writes a field,
  and `X[i] = X[j]` or `X[i] = v` copies a whole element, field by field.
  Binding, returning or storing `X[i]` is NL2674
  (`reject_storage_bind_element`); passing it is
  `` An element of module storage `X` cannot be passed as an argument: it is a place, not a value; pass the index, or the fields the callee needs ``
  (NL2675, `reject_storage_pass_element`), except `out.push(X[i])` onto an
  array of the same record, which copies; and `for (const p of X)` over a
  record storage is NL2678 (`reject_storage_for_of`): loop over the index. A
  `for-of` over a scalar storage binds numbers and is allowed.
- **It is memory every function reaches**, so it moves the inferred
  attributes: a function that reads storage is at most `readonly`, one that
  writes it is neither `readonly` nor `readnone`
  (`tests/cases/storage_attributes`), and a `parallelMap` body that writes it
  is refused as any shared write is (`reject_storage_parallel_write`).
- **Under `--emit-ts` it is a typed view, and only it.** The reading writes
  one more file, `nish-storage.ts`, holding one `ArrayBuffer` laid out as the
  wasm build's `layout` says, `memory` (`{ buffer, grow }`, whose `grow`
  throws: the buffer never moves), `layout` itself, `views()`, `loadSync` and
  `load` as the wasm loader has them (they take the module's exports where the
  wasm loader takes its bytes), and each storage as a view of the buffer; the
  module's `new` is written as that
  view (`src/emit-ts-storage.ts`, `docs/wp50-wasm-host.md` §5.4). A scalar
  storage is the typed array its element reads as (`Int32Array`,
  `Float32Array`, …; a `boolean` one is a byte array behind a proxy that reads
  `!== 0`). A record storage is an array of objects whose fields are getters
  and setters over the buffer, so `X[i].x = v` writes the bytes a page reads,
  and a whole-element copy is `Object.assign`. Each storage starts on an
  8-byte boundary from 0, so the reading's offsets differ from the wasm
  build's; a page reads them from `layout` and never spells one. A local
  `f32[]` is still a plain JavaScript array there: only module storage is a
  view.

#### Root storage: an object graph kept between calls

**Module storage whose element is `C | null` for a class `C` is root
storage**: each slot holds one object, and everything that object reaches —
its fields, their arrays and strings, the objects they hold — outlives the
call that built it (`tests/cases/root_storage`,
`docs/wp55-persistent-root.md`). It is how a wasm module keeps a game, a
document or any class instance across `init`, `step` and `draw`.

```ts
class World {
  balls: Ball[]
  tick: i32 = 0
  constructor() {
    this.balls = []
  }
}

const world = new Array<World | null>(1)

export const init = (): void => {
  world[0] = new World()
}

export const step = (): void => {
  const w = world[0]
  if (w !== null) {
    w.tick = w.tick + 1
  }
}
```

On a page module each root is a record of its data, its length and the
descriptor of its class, gathered into one table the keep walks
(`tests/cases/root_storage_page`, whose root is `head`, a list of `Node`):

```llvm
%nish.root = type { i8*, i32, i8* }
@nish_storage_0_head.root = constant %nish.root { i8* bitcast ([1 x %struct.Node*]* @nish_storage_0_head.data to i8*), i32 1, i8* bitcast (%nish.trace* @nish.trace.0 to i8*) }
@nish.roots = internal constant [1 x %nish.root*] [%nish.root* @nish_storage_0_head.root]

define void @nish_root_keep(i64 %mark) {
  call void @nish_runtime_root_keep(i64 %mark, i8* bitcast ([1 x %nish.root*]* @nish.roots to i8*), i32 1)
  ret void
}
```

- **Natively it is module storage and nothing more.** A native program never
  hands its arena back between calls, so the graph simply stays.
- **On a page module the loader keeps the graph and releases the rest.**
  Where the loader of a program without root storage releases each export
  call's arena, this one calls `nish_root_keep`. The runtime traces what the
  roots reach from descriptors the compiler writes (`%nish.trace`, one per
  class, string and array type the roots reach;
  `tests/cases/root_storage_page`), slides it down over the garbage, rewrites
  every pointer to it, and frees what is left. It does so only once the kept
  region passes twice the live bytes and 64 KiB, so a call that changes a
  little copies nothing, and memory stays bounded however long the page runs
  (`node tests/run.js persist`: 100,000 steps with memory flat).
- **What a root reaches is traceable.** A number, a `boolean`, an enum, a
  string, an array, a class or a discriminated union of classes. Anything
  else — a `Map`, a `Set`, an interface a class implements, a `Region`, a
  `Secret`, a `CPtr`, a handle class or a C struct layout — is
  `` Root storage `X` cannot keep C.f (T): the runtime moves what a root reaches between calls, … ``
  (NL2766, `tests/wordings/nl2766_root_storage_map`).
- **It is not exported**: the objects move, so a page has no layout to read.
  `export const world = new Array<World | null>(1)` is
  `` Root storage `X` cannot be exported: the runtime moves the objects its elements point to between calls, so a page has no layout it could read; export a function that reads it instead ``
  (NL2767, `tests/wordings/nl2767_root_storage_export`), and `layout` leaves
  root storage out.
- **No threads, no regions.** Each allocates from an arena of its own, which
  a root could be left pointing into, so root storage in a program that
  loads `nish/threads` or `nish:region` is
  `` Root storage `X` cannot be kept in a program that loads `nish/threads` or `nish:region`: … ``
  (NL2768, `tests/wordings/nl2768_root_storage_threads`).
- **No native shim.** A build that writes `--emit-napi`, `--emit-napi-async`
  or `--emit-header` gets a shim that releases the arena after a call that
  passes a string or an array, which would free what a root reaches, so root
  storage there is
  `` Root storage `X` cannot be kept in a build that writes a native shim (`--emit-napi`, `--emit-napi-async` or `--emit-header`): … ``
  (NL2769, `tests/wordings/nl2769_root_storage_napi`). A plain native
  program keeps it.
- **No WASI loader.** A `--profile wasi` build with `--emit-dts` writes a
  loader that releases the arena after every call, and only a page module
  emits the `nish_root_keep` a loader calls instead, so root storage there is
  `` Root storage `X` cannot be kept in a WASI build that writes a loader (`--emit-dts`): … ``
  (NL2770, `tests/wordings/nl2770_root_storage_wasi_dts`).
- **A freestanding module without a loader** (`--target wasm32` and no
  `--emit-dts`) still emits `nish_root_keep(mark)`; the host that calls its
  exports writes its own loader, and must call `nish_root_keep(mark)` where it
  would call `nish_arena_release(mark)`, or what a root reaches is freed.
- **Every function may store through a root**, so a program with root
  storage does not prove a parameter-only allocation stays in its caller's
  scope from the signature alone; the compiler's other proofs are unchanged.

### Type aliases

```ts
type Byte = u8;
type Bytes = Byte[];
type Reading = Sample | null;
```

A `type` alias is a second name for a type that already exists. **It is not a
type of its own**: `type Byte = u8` says that `Byte` and `u8` are two spellings
of one type, exactly as `Int32Array` is a spelling of `i32[]` (see
[Types](#types)). So `sameType` never sees the alias's name, there is no new
LLVM type, and an alias emits nothing at all — the same program written with
and without its aliases produces byte-identical IR, which is what
`tests/cases/type_alias_ir` and `tests/cases/type_alias_expanded` are: one
program twice, with one golden between them.

- **The right-hand side may be any type the language accepts**: a scalar,
  `string`, `void`, `T[]`, `readonly T[]`, `T | null`, `Result<T, E>`, a
  declared class or interface, or another alias
  (`tests/cases/type_alias_ir`). Everything is refused exactly where it would
  be in an annotation, so `type Bad = any` is `` `any` is forbidden `` and not
  a rule of its own, and an object type, `type Point = { x: i32; y: i32 }`,
  is the syntax error an inline object type is anywhere else
  (`tests/cases/reject_type_object_literal_alias`): declare
  `interface Point` instead.
- **Order does not matter.** An alias may name a class, an interface or an
  alias declared further down the file, because resolution is by need rather
  than in source order — the rule module constants follow. A cycle is
  `` Type alias `Feet` is defined in terms of itself ``
  (`tests/cases/reject_type_alias_cycle`), the wording the constant cycle uses,
  because it is the same mistake.
- **An alias is resolved even when nothing uses it**, so a broken right-hand
  side is reported where it is written rather than never.
- **Generic aliases are forbidden**, unlike a generic *function*: an alias
  only renames a type that already exists, so there is nothing for a type
  argument to apply to. `type Box<T> = T[]` is
  `` Generic type parameters are forbidden on a type alias in Nish; a generic function, class or interface is monomorphised, and an alias only renames a type that already exists ``
  (NL1054, `tests/cases/reject_type_alias_generic`).
- **A built-in type name may not be aliased.** `type string = i32` is
  `` `string` is a built-in type name and cannot be used for a type alias ``
  (`tests/cases/reject_type_alias_builtin`). A keyword like `string` is
  resolved from the syntax, and `i32`, `Array`, `ReadonlyArray`, `Result` and
  the typed-array names before any declared name, so such an alias would
  otherwise sit there meaning nothing.
- **The name shares one declaration namespace** with functions, classes,
  interfaces and module constants: a clash is
  `` `Point` is already declared in this module `` whichever came first
  (`tests/cases/reject_type_alias_duplicate`).
- **An exported alias is imported, and in the importer it is the type it
  names.** `export type Pt = Point` in `shapes.ts` and
  `import { Pt } from "./shapes"` elsewhere make `Pt` a second spelling of
  `Point` there too: a field, parameter or return type, a local, an array
  element, and a `Point` from `new` passes where a `Pt` is declared
  (`tests/link/alias_export_class`). The right-hand side is resolved **in the
  module that wrote it**, whichever module asks first, so
  `export type Conn = Socket | null` works when `Socket` is a class the
  exporter itself imported, and the importer never has to import `Socket`
  (`alias_export_imported_class`). An array, a `T | null` and a `Result`
  alias are the types they name (`alias_export_array`,
  `alias_export_nullable`, `alias_export_result`), so is an alias of a
  generic class's instantiation, which the exporter instantiates even when an
  importer asks first (`alias_export_generic`), a chain of aliases across
  modules resolves by need (`alias_export_chain`: `Table` is `Line[]`, `Line`
  is an imported `Row`, `Row` is `Cell[]`, `Cell` is `i32`), and unlike a
  class an alias may be renamed on import — `import { Conn as Handle }` —
  because it has no symbol for its name to be part of (`alias_export_rename`).
  Nothing is emitted in either module, so the importer's IR is
  byte-identical to the same program with every alias written out
  (`alias_export_ir` and `alias_export_ir_local`, whose `.ll` goldens are the
  same files).
  - **A mistake on the right-hand side is the exporter's.** It is reported
    against the module that wrote the alias, even when another module asked
    for the alias first (`tests/link/alias_export_broken`), and a cycle that
    runs through two modules' aliases is
    `` Type alias `B` is defined in terms of itself ``, at the first alias of
    the cycle the report reaches (`alias_export_cycle`).
  - **The import errors are the ones every import has.** An alias declared
    without `export` is
    `` `Conn` is declared in `./conn` but not exported (add `export`) ``
    (`tests/link/alias_import_not_exported`); a declaration of the imported
    name is `` `Conn` is already declared in this module ``
    (`alias_import_clash`); a second import of it is
    `` `Conn` is already imported from `./conn` `` (`alias_import_duplicate`);
    and an alias is a type, not a value: `new Conn()` is
    `` Unknown class `Conn` ``, as it is for a local alias
    (`alias_import_as_value`). A module does not re-export an alias it
    imported. An imported alias is bound before the signatures, for the
    reason an imported [enum](#enums) is.
- **Aliases are top-level only.** `type X = i32` inside a function body is
  `Unsupported statement in Phase 1: TypeAliasDeclaration` *(CLI only)*.

### Enums

```ts
enum Kind {
  If = 1,
  While = 2,
  Return = 3,
}

enum Level {
  Low,   // 0
  Mid,   // 1
  High,  // 2
}

enum Role {
  Admin = "admin",
  Guest = "guest",
}
```

An `enum` is of one of two kinds. A **numeric** enum's members are integers;
a **string** enum's members are each given a string literal, and its rules
past the ones below are in [String enums](#string-enums). Either kind
declares a **distinct type whose representation is `i32`**: a numeric
member's integer, or a string member's ordinal. Distinct is the point, and it
is stricter than TypeScript, where a numeric enum member is assignable to
`number` and a string one to `string`: the rule this language is built on is that
two values are compatible only when their types are identical
([Types](#types)), and an enum that were silently `i32` would be the one type
compatible with something it is not spelled as. So `Kind` and `i32` are two
types, in both directions, as `Role` and `string` are, and the only values of
`Kind` are the members it declares.

Nothing is emitted for a numeric enum (a string enum adds its one table of
strings, [String enums](#string-enums)). A member is folded to its integer the way a module
constant is folded to its value, so `Kind.While` lowers to the literal `2`, a
`Kind` parameter is an `i32` parameter, and there is no symbol, no table and no
`%struct` anywhere. `tests/cases/enum_ir` and `tests/cases/enum_expanded` are
one program written twice — with the enum, and with `i32` module constants —
and their `.ll` goldens are byte-identical files.

- **A member's value is a numeric literal, or the one before it plus one.**
  Auto-numbering is TypeScript's: the first member without an initialiser is
  `0`. An enum any of whose members is given a string literal is a
  [string enum](#string-enums) instead. A member that is neither — a computed
  value in a numeric enum, or a numeric member beside a string one — is
  `` Enum members must be numeric literals in Nish, or every member a string literal (an enum lowers to a plain integer, and one numbering cannot mix with strings) ``
  (NL1043, `tests/cases/reject_enum_computed`, `reject_enum_string_mixed`); a numeric literal
  that is not an integer is `` Enum member `Kind.Half` must be an integer literal ``
  (`reject_enum_float`), and one outside the width is
  `` Enum member `Kind.Big` does not fit in i32 `` (`reject_enum_overflow`).
- **An enum must declare at least one member**, because an empty one is a type
  no value can inhabit: `` Enum `Kind` must declare at least one member ``
  (`tests/cases/reject_enum_empty`). Two members of one name are
  `` Duplicate member `If` in enum `Kind` `` (`reject_enum_duplicate_member`).
- **A value is spelled `Kind.If` and nothing else.** A name that is not a
  member is `` Enum `Kind` has no member `Nope` ``
  (`tests/cases/reject_enum_unknown_member`), and there is no conversion in
  either direction: `const n: i32 = k` is
  `` Cannot initialize i32 variable `n` with Kind ``
  (`reject_enum_not_i32`) and `const k: Kind = 1` is
  `` Cannot initialize Kind variable `k` with i32 `` (`reject_enum_from_i32`).
- **`===` and `!==` are the only operators.** Two values of one enum compare;
  everything else is refused because an enum is not numeric — `+` is
  `` Operator `+` requires two operands of the same numeric type or two strings, got Kind and Kind ``
  (`tests/cases/reject_enum_arith`), `<` is
  `` Operator `<` requires two numeric operands, got Kind and Kind ``
  *(CLI only)*, and the bitwise operators are
  `` Operator `|` requires two operands of the same integer type, got Flag and Flag ``
  (`reject_enum_bitwise`). **Bit flags therefore stay `i32` module constants**:
  `A | B` on an enum would produce a value that is no declared member, which is
  the one thing the type exists to prevent
  ([wp23-language-surface.md](wp23-language-surface.md) §10 question 1 leaves
  the wider form open).
- **A `switch` takes an enum discriminant and enum-member labels**
  (`tests/cases/enum_ir`), which is what an enum is for: the statement lowers
  to LLVM's `switch` exactly as an integer discriminant does. A label of any
  other type is `` `case` label is i32 but the discriminant is Kind ``
  (`reject_enum_case_label`), so the integer a member stands for is not a
  label. See [`switch`](#switch).
- **A member is also a type: `Kind.While` names the type whose one value is
  that member.** A slot of a member type — a field, a parameter, a return, a
  local, an element, an object-literal field or a `Result` arm — holds that
  member and nothing else, which is what lets a `readonly` field record which
  of an enum's cases its object is, as the tag a later discriminated union
  reads:

  ```ts
  class ArrayNode {
    readonly kind: Kind.While = Kind.While;
  }
  ```

  The slot is entered by the member's own constant, or by a value already of
  that member type; the enum's other members, and any `Kind` value that is not
  a constant, are
  `` Type `Kind.Array` holds only the member `Kind.Array`, got `Kind.Scalar` ``
  (NL2519, `tests/cases/reject_enum_member_type_other`) and
  `` …, got a value of type `Kind` `` (`reject_enum_member_type_widened`),
  because a `Kind` could be any member. Every way into a slot is held to it:
  a call argument, an assignment to a `let` or a field, a `push`, an element
  write, an array literal, an object-literal field, `Ok`, `unwrapOr`'s
  default, a ternary arm and a `return` (`reject_enum_member_type_argument`,
  `_assign`, `_field_assign`, `_push`, `_element_write`, `_array_literal`,
  `_object_field`, `_result_ok`, `_unwrap_or`, `_ternary`, `_return`), and so is an
  argument of a generic call, whether the member type binds a type parameter
  (`fold(xs, Kind.Array)` with `xs: Kind.Array[]`), sits in a concrete
  parameter beside one, or is `getOrInsert`'s value
  (`tests/cases/enum_member_type_generic`, `reject_enum_member_type_generic`,
  `_fold`, `_get_or_insert`, `_generic_variable`, `_generic_method`,
  `_class_param`); a parenthesised constant, `(Kind.Array)`, is the constant.
  Two generic calls `tsc` accepts are refused, because the language binds a
  type parameter only from the arguments, and binds it from the constant
  before it reads a function argument: `const y: Kind.Array = id(Kind.Array)`
  binds `T` to `Kind`, since the slot the call returns into binds nothing
  (`reject_enum_member_type_generic_return`), and `apply(take, Kind.Array)`
  binds `T` to `Kind` before `take: (x: Kind.Array) => Kind.Array` is read
  (`reject_enum_member_type_generic_function_arg`). Pass a value already of
  the member type, `id(a)` and `apply(take, a)`, and both bind `Kind.Array`.
  An unannotated `let` keeps the member type of a value already of it, as
  `tsc`'s does, and widens a member constant to its enum: `let w = keep(a)`
  holds only `Kind.Array`, `let w = Kind.Array` any `Kind`
  (`reject_enum_member_type_inferred_let`). So does every place whose type is
  inferred from what is written: a ternary whose arms are both `Kind.Array`,
  an array literal of them (`[a]` is a `Kind.Array[]`), `??` between two
  `Kind.Array[]`, each of those passed to a generic function, and an arrow's
  result, which binds the type parameter it returns: `map([a], (k) => k)` is a
  `Kind.Array[]` and `apply(a, (k) => k)` a `Kind.Array`, while an arrow that
  answers the constant, `(k) => Kind.Array`, answers `Kind`, as `tsc` widens
  it (`tests/cases/enum_member_type_inferred`, `enum_member_type_arrow`,
  `reject_enum_member_type_ternary_let`, `_ternary_const`, `_ternary_generic`,
  `_array_inferred`, `_array_let`, `_array_generic`, `_nullish`, `_arrow_map`,
  `_arrow_apply`). Two arms or two elements that differ where one is a member
  type, or an array of one — `c ? a : b` over `Kind.Array` and `Kind.Scalar`,
  `c ? a : k` over a `Kind`, `c ? a : Kind.Array`, `[a, Kind.Array]`, or
  `[[a], [Kind.Array]]` — are refused, `` Ternary branches must have the same type, got Kind.Array and Kind.Scalar: an enum member type is not widened to its enum, so annotate the type it holds, e.g. `Kind` ``,
  and the array literal's message reads the same way, naming `Kind[]` for the
  nested case: `tsc` types them as a union of the members (the enum itself
  when they are all of its members), or as the member, or as the enum, by
  whether the constant is fresh, so the variable is annotated instead
  (`reject_enum_member_type_ternary_mixed`, `_ternary_enum`,
  `_ternary_constant`, `_ternary_nested`, `_array_mixed`, `_array_constant`,
  `_array_nested_mixed`). An object literal is always annotated,
  so its fields always have a type to enter. Two member types of one enum are two
  types (`reject_enum_member_type_between`), and a field initializer of a
  member type is held to the same rule (`reject_enum_member_type_field_init`).
  The other direction is free: a member type converts to its enum, and a read
  of a member-typed slot is the enum wherever a value is computed with, so it
  compares with `===`, switches and passes as a `Kind`, and converts to `i32`
  no more than a `Kind` does (`reject_enum_member_type_read`). In IR a member
  type is its enum's `i32`: `tests/cases/enum_member_type` lowers to the same
  bytes as the program with every member type written `Kind`
  (`enum_member_type_widened`, whose golden is byte for byte the same).
  - **The qualifier is an enum, local or imported, and the name one of its
    members.** `import { Kind as K }` spells the exporter's member types
    `K.Array` (`tests/link/enum_member_type_import`). Anything else before the
    dot is `` `Point.x` is not a type: only a member of an enum may be named with a dot in a type, and `Point` is not an enum ``
    (NL2517, `reject_enum_member_type_not_enum`), a missing member is
    `` Enum `Kind` has no member `Missing` to name as a type ``
    (NL2518, `reject_enum_member_type_unknown`), and type arguments are
    `` Unsupported type reference `Kind.Array<i32>` `` (`reject_enum_member_type_args`).
    One dot is read; `A.B.C` is a syntax error (`reject_enum_member_type_nested`).
  - **Two members of one value are one type**, as `tsc` reads them, spelled
    by the member declared first (a string enum has no two such members,
    [String enums](#string-enums)): with `List = 1` beside `Array`, a
    `Kind.List` slot is reported as `` `Kind.Array` ``
    (`reject_enum_member_type_same_value`), and `Kind.List` enters a
    `Kind.Array[]` (`tests/cases/enum_member_type_slots`).
  - **A member type is a type wherever one is written**: a `type` alias's
    right-hand side (`type ArrayTag = Kind.Array`), a type argument
    (`Box<Kind.Array>`, `Map<Kind.Array, i32>`, `Set<Kind.Array>`), an
    element type and an arrow argument's return type, and a `-g` build
    describes it as its enum (`enum_member_type_slots`).
  - **A zero-filled array of a member type holds 0**, so
    `new Array<Kind.Array>(n)` is
    `` `new Array<Kind.Array>(n)` would zero-fill with 0, which is not the member `Kind.Array`; build it with `[]` and `push` instead ``
    (NL2520, `reject_enum_member_type_zero_fill`), and a member whose value
    is 0, `Kind.Scalar` here, is allowed (`enum_member_type_slots`). The
    `parallelMap`, `parallelFrom` and `parallelReduce` templates zero-fill the
    array their workers write, so a body answering such a member type is
    refused at the call, `` … answers the member type `Kind.Array`, and `parallelMap` zero-fills the array its workers write, which a `Kind.Array` cannot hold; declare the body to answer `Kind` ``
    (NL2521, `reject_enum_member_type_parallel`, `_parallel_from`,
    `_parallel_reduce`); a body answering the member at 0 runs in all three
    (`tests/link/enum_member_type_parallel`).
  - **A field initializer may be a member's constant** when the field is the
    enum or one of its member types: `readonly kind: Kind = Kind.If` stores the
    integer before the constructor runs, as a numeric literal would
    (`enum_member_type_slots`). Another enum's member, a member the enum does
    not declare, a member given to a number field and any other dotted
    initializer are refused (`reject_enum_member_type_field_init_enum`,
    `_field_init_level`, `_field_init_unknown`, `_field_init_i32`,
    `_field_init_dotted`).
  - **Typed JSON refuses a member-typed field** (`tests/cases/json_reject_enum_member`):
    it reads an enum as any of its members, which a member type cannot hold.
    The one exception is a union's tag: a member that tags a variant of a
    union is written as its name, or a string enum's member as its string,
    the union's [typed JSON](#typed-json-nishjson-typed)
    tag (`tests/link/json_tagged_union`, `tests/link/json_enum_string`). A member type crosses to C and JavaScript exactly where its enum does, which
    is nowhere.
- **A built-in type name may not be taken**: `enum i32 { ... }` is
  `` `i32` is a built-in type name and cannot be used for an enum ``
  (`tests/cases/reject_enum_builtin_name`), for the reason the same rule exists
  for a `type` alias — the name would never be looked at. The name shares the
  one declaration namespace with functions, classes, interfaces, type aliases
  and module constants: a clash is `` `Kind` is already declared in this module ``
  whichever came first (`reject_enum_duplicate`).
- **An exported enum is imported, and in the importer it is the exporter's
  enum.** `export enum Kind { ... }` in `kinds.ts` and
  `import { Kind } from "./kinds"` elsewhere bind one type, not a copy: the
  importer may use `Kind` as a field, parameter or return type, a local, a
  `Map` key and a `switch` discriminant, `Kind.If` folds to the integer
  `kinds.ts` gave it, and a `Kind` crosses a call between the two modules as
  itself (`tests/link/enum_export_uses`). One enum reached along two import
  paths is one type (`enum_export_diamond`), two modules may import each
  other's enums (`enum_export_cycle`), and unlike a class an enum may be
  renamed on import — `import { Kind as Level }` — because it has no symbol
  for its name to be part of (`enum_export_rename`). Nothing is emitted in
  either module, so the importer's IR is byte-identical to the same program
  with the enum declared in it (`enum_export_ir` and `enum_export_ir_local`,
  whose `.ll` goldens are the same files).
  - **Every enum declaration is a type of its own.** A `Kind` a module
    declares and the `Kind` it could have imported are two types, so a member
    of one is not an argument where the other is declared:
    `` Argument 1 of `weight`: expected Kind, got Kind `` (`tests/link/enum_import_distinct`).
    An imported enum converts to and from `i32` no more than a local one does
    (`enum_import_i32`, `enum_import_from_i32`).
  - **The import errors are the ones every import has.** An enum declared
    without `export` is
    `` `Kind` is declared in `./kinds` but not exported (add `export`) ``
    (`tests/link/enum_import_not_exported`); a declaration of the imported
    name is `` `Kind` is already declared in this module ``
    (`enum_import_clash`, `enum_import_clash_function`); a second import of
    it is `` `Kind` is already imported from `./kinds` ``
    (`enum_import_duplicate`, `enum_import_duplicate_function`); and an
    enum is not a function, imported or not: `Kind(2)` is
    `` Unknown function `Kind` `` (`enum_import_as_call`). A module does not
    re-export an enum it imported.
  - **Why it is bound before the signatures.** An enum is a type with no
    layout, so a signature that names an imported one has to find it
    declared, where an imported class can be resolved provisionally and bound
    later. Every module of the program therefore declares its names and binds
    its imported enums before any module collects a signature (`load` in
    `src/compilation.ts`).
- **`const enum` and `declare enum` are refused.** `const enum` asks for the
  inlining every member already gets —
  `` `const enum` is not supported: an enum member is already folded to its integer, so `const` would ask for nothing ``
  (`tests/cases/reject_enum_const_enum`) — and `` `declare enum` is not supported ``
  is the ambient form, which has nothing to declare against
  (`tests/cases/reject_enum_declare`; `declare const enum` too, since `declare`
  is written first).
- **An enum does not cross to C or JavaScript.** `--emit-header`, `--emit-dts`
  and `--emit-napi` have no spelling for one, so a function whose signature
  mentions a numeric enum is skipped with the note those generators write for
  every type they cannot carry (`weight(k: Kind): number: not declared; no C
  spelling for one of its types.`), and one whose signature holds a string
  enum is refused (NL4019, [String enums](#string-enums)). An enum is a type
  inside one module, as it is across a module boundary: give a host an `i32`
  or a `string` and keep the enum behind it.
- **Enums are top-level only.** `enum K { A = 1 }` inside a function body is
  `Unsupported statement in Phase 1: EnumDeclaration` *(CLI only)*.

#### String enums

An enum whose members are each given a string literal is a **string enum**.
It is the spelling Nish takes for a closed set of strings: a union of string
literals, `"admin" | "guest"`, is refused (NL1053, and a lone string literal
type is NL2668), because a value has one fixed layout and a string enum's is
an `i32`.

```ts
enum Role {
  Admin = "admin",
  Guest = "guest",
  Nobody = "",
}

const rank = (r: Role): i32 => {
  switch (r) {
    case Role.Admin:
      return 3;
    case Role.Guest:
      return 1;
    default:
      return 0;
  }
};

const name = (r: Role): string => String(r); // name(Role.Admin) is "admin"
```

- **A value is its member's ordinal.** A string enum is a distinct type, as a
  numeric one is, stored as an `i32`: the member's position in declaration
  order, `0`, `1`, `2`, and never the bytes of its string. Every rule of
  [Enums](#enums) above holds for it as it does for a numeric enum: `===` and
  `!==` between two of its values are the only operators, and they compare
  ordinals; a `switch` over one lowers to LLVM's `switch` on the ordinal; a
  member is also a type (`kind: Role.Admin`), and so tags a variant of a
  [discriminated union](#discriminated-unions)
  (`tests/cases/enum_string_union_tag`); a value is a `Map` or `Set` key, an
  element, a field and a `Result` arm; it crosses a thread, a channel and a
  task as the `i32` it is; and it is exported and imported as a numeric enum
  is (`tests/cases/enum_string`, `tests/link/enum_string_export`). It is never
  `| null` (NL2010), as no enum is.
- **Its strings are one table per module.** Each module that names the enum's
  strings holds them as `@.enumstr.<Name>`, an array of the module's string
  constants indexed by ordinal; an importer gets its own copy of the table, so
  nothing is looked up across a module boundary
  (`tests/link/enum_string_export`). Nothing else is emitted: `Role.Guest`
  folds to `1` as `Kind.While` folds to `2`.

  ```llvm
  @.enumstr.Role = private unnamed_addr constant [3 x i8*] [i8* bitcast ({ i64, [6 x i8] }* @.str.0 to i8*), i8* bitcast ({ i64, [6 x i8] }* @.str.1 to i8*), i8* bitcast ({ i64, [1 x i8] }* @.str.2 to i8*)], align 8

  define internal noundef i32 @rank(i32 noundef %r) #0 {
  entry:
    switch i32 %r, label %sw.default [
      i32 0, label %sw.case
      i32 1, label %sw.case.1
    ]
  ```
- **`String(r)` is the member's string.** It loads the table's entry at the
  ordinal, so it allocates nothing and its answer is the module's constant:

  ```llvm
  %19 = sext i32 %18 to i64
  %20 = getelementptr inbounds [3 x i8*], [3 x i8*]* @.enumstr.Role, i64 0, i64 %19
  %21 = load i8*, i8** %20, align 8
  call void @nish_print(i8* %21)
  ```

  `String` takes a string enum's value and nothing else; on any other
  argument it is `` Unknown function `String` `` (NL2247,
  `reject_string_call_non_enum`).
- **A member's value is a string literal, written once.** Every member of a
  string enum has an initializer:
  `` String enum member `Role.Guest` has no initializer: every member of an enum whose members are strings is given its own string literal ``
  (NL1064, `tests/cases/reject_enum_string_missing`). A numeric member beside
  a string one is NL1043 (`reject_enum_string_mixed`, and in typed JSON
  `json_reject_enum_mixed`), and a template literal is
  `` An enum member's value cannot be a template literal: write it as a plain string literal, which is fixed when the enum is declared ``
  (NL1065, `reject_enum_string_template`); a computed value, `"gu" + "est"`,
  is
  `` A string enum member's value must be a string literal: a computed value is not supported, because the enum's strings are a table fixed when it is declared ``
  (NL1066, `reject_enum_string_computed`). The value is valid UTF-8, since it
  is written to and matched against JSON: a lone surrogate, `"\uD800"`, is
  `` Enum member `Role.Bad` is not valid UTF-8: a string enum's values are written to and matched against JSON, which is UTF-8 ``
  (NL2787, `reject_enum_string_utf8`). The empty string is a value like any
  other (`tests/cases/enum_string`).
- **Two members do not share a string.**
  `` Enum member `Role.Root` repeats the string of `Role.Admin`: each member of a string enum has its own string, because the string is how JSON and `String` name the member ``
  (NL2786, `tests/cases/reject_enum_string_same_value`). A numeric enum
  allows two members of one value, which are one type; a string enum does
  not, because its string is how the member is named outside the program: a
  decoded `"admin"` must name one member, and `String` must answer one
  string per member. `tsc` would also read two members of one string as one
  value, where Nish's ordinals would make them two.
- **A `Role` is not a `string`, in either direction.** A string is never
  compared with one:
  `` Cannot compare a `Role` with a string using `===`: an enum value is not its string, so compare it with a member, such as `Role.Admin` ``
  (NL2788, `tests/cases/reject_enum_string_compare_literal`). A `Role` where
  a string is wanted, `const s: string = r` or `${r}` in a template, is
  `` A `Role` is not a string: write `String(r)` for the member's string ``
  (NL2789, `reject_enum_string_to_string`, `reject_enum_string_template_use`),
  and a string where a `Role` is wanted, `const r: Role = "admin"`, is
  `` `"admin"` is a string, and a `Role` is not one: write the member itself, such as `Role.Admin` ``
  (NL2790, `reject_enum_string_from_string`). Arithmetic is refused as on any
  enum, `r + 1` being
  `` Operator `+` requires two operands of the same numeric type or two strings, got Role and i32 ``
  (NL2231, `reject_enum_string_arith`), and `const enum` is NL2285 as above.
- **Typed JSON reads and writes its string.** A string-enum field, array,
  `| null` array or `Map` value is the member's string on the wire, and a
  union tagged by a string enum's member writes that string as its tag
  ([Typed JSON](#typed-json-nishjson-typed)).
- **Under `--emit-ts` it is a `const` object.** `enum Role { Admin = "admin" }`
  is written as

  ```ts
  export const Role = { Admin: "admin", Guest: "guest" } as const;
  export type Role = (typeof Role)[keyof typeof Role];
  ```

  so each member is the string `tsc` gives it, `String(r)` is the identity
  and prints what the native program reads from its table, and a member type
  is `typeof Role.Admin` (`tests/emit-ts/control/string-enums`). `tsc` would
  accept `r === "admin"`, `const s: string = r` and `const r: Role = "admin"`
  on that output; Nish refuses all three, so it is the stricter of the two,
  and every program it accepts is one `tsc` accepts too.
- **A string enum does not cross to C, N-API or wasm yet.** An exported
  function whose parameter or result is a string enum, or an array, `| null`
  or `Result` that holds one, is refused under `--emit-header`, `--emit-dts`,
  `--emit-napi` and `--emit-napi-async`:
  `` `rank`'s parameter `r` is `Role`, which holds a string enum: a string enum has no C, N-API or wasm spelling in this version, so take or return a `string` and convert with `String(r)` and a `switch` ``
  (NL4019, `tests/cases/reject_enum_string_export`,
  `reject_enum_string_export_napi`). It is an ordinal natively and a string in
  TypeScript, and a sidecar cannot yet say which a host passes.
- **Open questions.** A `Role.parse(s)` that answers the member a string
  names is not built: today a program tests `s === String(Role.Admin)` for
  each member, or decodes the string with typed JSON; the C, N-API and wasm spelling of a string enum is open
  (NL4019); and a union of string literals stays refused, string enums being
  the spelling Nish takes instead.

### `export` and `import`

- `export` is accepted on `function`, `class`, `interface`, `enum`, `type`
  and `const` declarations (`tests/cases/export_fn`, `tests/link/class_export`,
  `tests/link/enum_export_uses`, `tests/link/alias_export_class`,
  `tests/link/const_export`). Every other export form is refused by its rule,
  once: `export { a }`, with or without `from`, `export * from`,
  `export * as ns from` and `export type { A }` are
  `` `export { ... }` / `export * from` are not supported; put `export` on the function declaration itself ``
  (`tests/cases/reject_export_list`); `export default <value>` and `export =`
  are `` `export default` / `export =` are not supported; use a named `export function` ``
  (`reject_export_assignment`); `export default function f` is
  `` `export default` is not supported; use a named `export function` ``
  (`reject_export_default`), and `export default class C` or
  `export default interface I` `` `export default` is not supported; use a named `export` ``
  (`reject_cls_export_default`, `reject_generic_export_default`); an
  anonymous one is `Functions must be named` or `Classes must be named`.
  `export import` is
  `` Only functions can be exported for now, plus classes and interfaces (found `export` on ImportEqualsDeclaration) ``
  (or `ImportDeclaration`; `reject_export_import_equals`), and
  `export as namespace X` is
  `Only top-level function declarations are supported in Phase 1 (found NamespaceExportDeclaration)`.
  Several in one module report one each (`reject_module_sweep_together`),
  unless one is a Phase 0 form below, which is then reported alone.
- **What `export` promises depends on the build.** In every build it makes a
  declaration importable by another module of the program. A build whose
  output something else links or loads — `-o` alone (IR for a C host to link),
  `--emit-header`, `--emit-dts`, `--emit-napi`, `--emit-napi-async`,
  `--profile wasi` or a wasm `--target` — also makes an exported function, and
  every method of an exported class, callable by that host with any arguments,
  so the compiler assumes nothing about them from the program's own calls
  (`tests/cases/arr_range_call_exported`, where a C host's `pick(7)` panics).
  A **`--link` build with none of those flags and no `declare function`** is
  its own final link: the executable holds the program's modules and the
  runtime and nothing else, so every call to an exported function is one the
  compiler sees, and it may, for example, prove an exported method's index in
  range from what every caller passes (`tests/link/range_export`, AWFY Permute
  as an exported class, whose `swap` carries no bounds check;
  `tests/link/range_export_unproven`, where one caller proves nothing, so the
  check stays and panics). The `.ll` such a build writes beside the executable
  is that executable's, not an object for another link; build with `-o` alone,
  or with a sidecar, to hand a host the program. `main` is the one exception:
  the runtime calls it, and it is never assumed anything about. The rule is
  `hostVisible` in `src/visibility.ts`, and `docs/ARCHITECTURE.md` (the
  call-site ranges row of the attribute soundness rules) is why it is sound.
- **An exported function is not named after a C library function.** A module of
  the program's own package has no symbol prefix, so an exported function's
  symbol is its name, in the entry module and in every other module of the
  package, and under `--no-strict-exports` every function's is. Named `write`,
  `read`, `free`, `exit`, `sin` or another function the C library defines for
  the runtime or for the program's own arithmetic, it would be the definition
  those references reach in the linked program (`console.log` printing nothing,
  a crash at the first file read, `Math.sin` answering what the program's `sin`
  returns), so it is `` `write` is the C library's `write`: an exported function
  of the program's own package keeps its name as its symbol, so the references
  the C library and the runtime make to that name would reach this function
  instead; rename it `` (`tests/cases/reject_export_c_symbol_const`,
  `reject_export_c_symbol_function`, `reject_export_c_symbol_libm`,
  `reject_export_c_symbol_libm_f32`, `tests/link/export_c_symbol_sibling`,
  `export_c_symbol_sibling_function`; with `--no-strict-exports`,
  `reject_export_c_symbol_no_strict` and
  `reject_export_c_symbol_no_strict_exported`). A name that begins with `_`,
  which C reserves for its library and start-up code (C11 7.1.3), or with
  `napi_` or `node_api_`, which Node-API reserves, is refused the same way with
  `` begins with `_`, which C reserves for its library and start-up code `` or
  `` begins with `napi_`, which Node-API reserves for its functions `` (or
  `node_api_`) (`reject_export_c_symbol_reserved_prefix`, which pins
  `__libc_start_main` and `__register_atfork`, each of which crashed;
  `reject_export_c_symbol_napi_prefix`). The rule is the same in a wasm or an
  N-API build, where the exported name is the one JavaScript calls: rename the
  function there too. The names are reserved on every target, whichever target
  each one binds on: a name only wasi-libc defines (`strdup`, `unlink`) is
  refused in a native build as well, and no flag lifts the rule. The names and
  where each comes from are in `src/c-symbols.ts`: the symbols the runtime
  leaves undefined on every platform it builds for, the libm calls behind every
  `Math` builtin and `%` on a float in `double` and in `float`, with the ones
  LLVM rewrites them into, the `memcpy` family, the rest of the C allocator,
  and, because `--profile wasi` links wasi-libc statically, every name a
  wasi-libc member that link pulls in defines or references (an exported `sbrk`
  trapped at start), and every name LLVM's TargetLibraryInfo recognises as a
  library function on the targets the compiler emits for (`abs`, `atan`,
  `rename`, `qsort`: LLVM folds or rewrites a call to one of them whatever its
  definition, so `abs(-3)` answered 3; `reject_export_c_symbol_tli`), and every
  function C23's `<math.h>` and C99's `<complex.h>` declare, in `double`,
  `float` and `long double` (`tgamma`, `erff`, `ilogbl`, `cexp`), whether or not
  the LLVM in use knows it, because a later LLVM than CI's recognises more of
  them (#651). `tests/run.js` reads them back with `llvm-nm` from the runtime's
  objects, `runtime-wasm.c`, the N-API shim, and two programs — one that calls
  every `Math` builtin, one that multiplies `i64`s, copies arrays and prints
  strings — linked at three optimisation levels and compiled for wasm32, the
  wasi-libc members a traced `--profile wasi` link of each pulls in, and fails
  on a name the file does not reserve ("c-symbols: ..."); it reads the
  TargetLibraryInfo names with `llvm-tli-checker` for five target triples. A
  function whose symbol is not its ABI is spelled apart instead of refused: an
  `internal` one whose name is reserved takes a `$` at the end of its symbol
  (`@floor$`), because LLVM folds a call to a function it knows by name as the C
  library's, and a private `floor` called as `floor(1.5)` answered 1
  (`tests/link/c_symbol_private_libm`), and a `hidden` one, which another
  module's instantiation calls, takes it whatever its name (#610, under
  [function parameters](#function-parameters);
  `tests/link/thread_no_strict_hidden_task`, under `--no-strict-exports`). A
  method, whose symbol carries its class, and a function of another package,
  whose symbol carries the package, may have any of these names
  (`tests/link/export_c_symbol_allowed`). `main` is the entry's alone
  (`tests/link/main_in_import`), and emitted as `@nish_main`.
- **A wasm module's function is not named `memory`.** `wasm-ld` exports the
  module's linear memory as `memory`, and `scripts/build.sh --profile wasm`
  links with `--export-all` (`--profile wasm-host` with an export list of the
  module's exported functions and `memory`), so in that module an exported
  function of that name, or any function under `--no-strict-exports`, is a
  second export of it, and Node refuses the module ("Duplicate export name 'memory'"). The
  `wasi` command module exports only `memory` and `_start`, so the function
  does not collide there; the name is reserved there too, so that a program
  that builds for wasi also builds as a freestanding wasm module. On a wasm
  `--target`, under `--profile wasi`, and in an `--emit-dts` compile, whose
  loader is for the module `scripts/build.sh --profile wasm` or `wasm-host`
  links its IR into, it is
  `` `memory` is the name a wasm module exports its linear memory under: an exported function of the program's own package keeps its name as its symbol, so the module would export two things named `memory` and no host could load it; rename it ``
  (NL3038; `tests/cases/reject_export_wasm_memory`,
  `reject_export_wasm_memory_wasi`, `reject_export_wasm_memory_dts`,
  `tests/link/export_wasm_memory_sibling`; with `--no-strict-exports`,
  `reject_export_wasm_memory_no_strict`; without the flag a `memory` nobody
  exported stays internal and compiles, "wasm memory: a --target wasm32
  compile keeps a `memory` nobody exported" in `tests/run.js`). IR compiled for the host with `-o`
  alone reaches build.sh without the compiler knowing the build is wasm, so
  `build.sh --profile wasm`, `wasm-host` and `wasi` refuse IR that defines an
  exported `@memory` with exit 2 ("wasm memory: ..." in `tests/run.js`). A
  native build has no linear memory to collide with and keeps the name
  (`export_memory_native`, `tests/link/export_memory_native_sibling`). The
  linker's other names, `_start`, `__heap_base`, `__data_end` and
  `__indirect_function_table`, are already refused by the rule above.
  A wasm program with module storage reserves two more: its loader answers
  the storage as `layout` and `views` beside the exports (§5.2 of
  `docs/wp50-wasm-host.md`), so in such a program an exported function of
  either name is
  `` `views` is the name the wasm loader answers the program's module storage under: an exported function of the program's own package keeps its name as its symbol, so the loader would answer two things named `views` and the page could not reach this function; rename it ``
  (NL3051, `tests/cases/reject_storage_loader_name`). A program without
  module storage keeps both names (`export_loader_names_no_storage`).
- The only import form is a named import: `import { square, cube as pow3 } from
  "./math"` (`tests/link/two_file`). The specifier must start with `./` or
  `../`, name one of the three builtin modules below, name a standard-library
  module as `nish/<module>`, or be a **package name** — `hash` or
  `@scope/hash`, each of which may be followed by a subpath
  (`@scope/hash/blake3`), resolved through `node_modules` and the `nish` export
  condition (`tests/link/package_bare`; a package that is not installed is
  `` Cannot find package `hash` ``, `tests/cases/reject_bare_package`). Anything
  else is `Import specifier ... must be relative`
  (`tests/cases/reject_bare_import`). `.ts` is optional and `./x.js` maps to
  `./x.ts`; a relative path resolves relative to the importing file. Every
  other import form is refused by its rule, once, before anything is loaded:
  a default import, `import d from "./m"`, `import d, { a } from "./m"` or
  `import { default as d } from "./m"`, is
  `` Default imports are not supported; use `import { d } from "./m"` ``
  (`reject_default_import`); a namespace import is
  `` Namespace imports (`import * as ns`) are not supported; import functions by name ``
  (`reject_namespace_import`); a side-effect import is
  `` Side-effect imports (`import "./m"`) are not supported; modules have no top-level code ``
  (`reject_side_effect_import`); `import type`, and `type` in front of one
  name, is `Type-only imports are not supported` (`reject_import_type_only`);
  a specifier that is not a string literal is
  `Import specifier must be a string literal`
  (`reject_import_template_specifier`); and `import x = require("./m")` or
  `import x = A.B` is
  `Only top-level function declarations are supported in Phase 1 (found ImportEqualsDeclaration)`.
  Three are refused by Phase 0, because no later release could give them a
  meaning: import attributes (`with { type: "json" }`, `assert { ... }`,
  `reject_import_attributes`), a module export name written as a string
  (`import { "a-b" as b }`, `reject_import_string_name`) and `import defer`
  (`reject_import_defer`) — see
  [Forbidden constructs](#forbidden-constructs-phase-0-validator). `type`,
  `as`, `from`, `defer`, `require` and `assert` are not reserved, and are the
  modifier only where TypeScript reads one: `import type from "./m"` is a
  default import of a binding called `type`, and `{ type }`, `{ type as t }`
  and `{ type as as }` each import a function called `type`
  (`tests/parser/names-modules.ts`). A missing file is
  `` Cannot find module `./does_not_exist` `` (`reject_missing_module`).
- **A file is one module however it is named.** The command line and the
  imports may spell one file differently — `./types.ts`, its absolute path,
  a path through a linked directory, and the `types.ts` an
  `import from "./types"` resolves to — and it is loaded once, under the first
  spelling that reached it, so its declarations never clash with themselves
  and its `.ll` is written once (`tests/link/root_named_twice`,
  `tests/link/identity_symlink_cwd`). **A module's identity is its real
  path**: the file the operating system opens under a spelling, with every
  symbolic link resolved, as Node and `tsc` (`preserveSymlinks: false`)
  identify one. A command-line path is taken as the operating system reads
  it, so `far/../types.ts` with `far` a link into `other/` is
  `other/types.ts`, a second module beside `./types.ts`
  (`tests/link/identity_symlink_dotdot`); an import specifier is joined to its
  importer's name, as a relative URL is. What a module is *called* — its IR
  header, its diagnostics, its output file — is still the first spelling,
  so no emitted byte depends on where the links point.
- **Two modules never share an output file.** `-o <dir>/` names each `.ll`
  after its module's basename, after its path relative to the entry when two
  modules share a basename, and — when those still meet, as `types.ts` and
  `far/../types.ts` do — a later module takes `<stem>_2.ll`, `<stem>_3.ll`
  and on, in load order (`tests/nish/cli.ts`).
- **The standard library is imported as `nish/<module>`**
  (`tests/link/std_bare_specifier`). It resolves to `std/<module>.ts` beside
  the running compiler rather than relative to the importing file, so the same
  specifier works at any depth. A module the library does not have is
  `` Module `nish/toml` is not part of the standard library (it has:
  collections, compress/checksum, compress/deflate, compress/gzip, compress/zlib, crypto/aes, crypto/base64url, crypto/chacha20poly1305,
  crypto/ct, crypto/ed25519, crypto/hkdf, crypto/hmac, crypto/p256,
  crypto/pki, crypto/pki-roots, crypto/rsa, crypto/sha256, crypto/sha512, crypto/x25519, crypto/x509, json, map, pair,
  testing, text, threads) ``
  (`reject_std_unknown_module`), and one that would leave the
  library — an empty segment, or a segment beginning with a `.` — is refused
  rather than resolved: `` Module `nish/../../escape/lib` climbs out of the
  standard library; a `nish/` specifier names a module inside it, so no segment
  may be empty or begin with a `.` `` (`reject_std_escaping_module`).
  **The module is named by that specifier**, not by where the library is
  installed: `nish/text` carries `std/text.ts` in its `; ModuleID`, its
  `source_filename`, its `DIFile` and — with no `-o` — the path its `.ll` is
  written to, whichever directory the compiler sits in and however the compiler
  was invoked (`tests/link/std_bare_specifier`). Two installs of one compiler
  therefore emit the same bytes for the same program, which is the reason the
  specifier is refused when it could not be a name. Unlike a `nish:` builtin this is
  ordinary Nish source: it is compiled into the program that imports it and is
  subject to every rule in this document. What it costs is what you call —
  `speed` and `size` link with `--gc-sections`, and a module imported but never
  called is byte-for-byte free (`std/README.md`). Its symbols are scoped to
  package `nish`, so a program may declare a function a `std/` module also
  exports (`tests/link/std_package_scope`); the package is decided by the
  specifier rather than by where the file sits, because reading it off the path
  would answer differently for an installed compiler and a checkout of the same
  version.
- **`nish/pair` is `Pair<A, B>`, two values answered by one call.** It is
  `interface Pair<A, B> { first: A; second: B; }` and nothing else: a generic
  interface, so an object literal takes its type from the annotation and must
  set both fields, and there is no tuple syntax and no constructor behind it.
  It crosses a module boundary like any exported interface, over scalars
  (`tests/link/std_pair_scalar`), a string and an `f64` under
  `--number-mode f64` (`std_pair_f64`), an array (`std_pair_array`), another
  `Pair` (`std_pair_nested`), and held in a class field and an array
  (`std_pair_held`).
  The instantiations are ordered — a `Pair<i32, string>` returned where a
  `Pair<string, i32>` is declared is `` Return type mismatch: function returns
  Pair<string, i32> but expression is Pair<i32, string> ``
  (`reject_std_pair_swapped`) — and a literal that leaves a field out is
  `` Object literal for `Pair<i32, boolean>` is missing field `second` ``
  (`reject_std_pair_missing`). It lowers as any generic interface does
  (`gen_interface`): one struct per instantiation, `%struct.Pair$i32$bool`,
  returned by pointer. Use it to return two values, not to store them side by
  side; `docs/wp23-language-surface.md` §5 is the reasoning.
- **`nish/crypto/<primitive>` is a module in a subdirectory of the library**,
  one per primitive: `sha256`, `sha512` (SHA-512 and SHA-384), `hmac`, `hkdf`,
  `ct` (constant-time compare), `base64url`, `x25519`, `ed25519` (Ed25519
  signatures), `chacha20poly1305` (ChaCha20-Poly1305), `aes` (AES-128 and
  AES-256 with GCM), `p256` (P-256 ECDSA), `p384` (P-384 ECDSA
  verification), `rsa` (RSA signature verification), `x509` (DER, PEM and
  self-signed P-256 certificates), `pki-roots` (the trust anchors from
  `SSL_CERT_FILE`, `SSL_CERT_DIR` or the system bundle; native only) and
  `pki` (RFC 5280 path validation and RFC 6125 hostname matching of a TLS
  server's chain) (`tests/link/crypto_base64url` is the case
  that resolves a nested specifier). Each is ordinary Nish source under the
  rules above, and a byte string is a `u8[]`. They are written branch-free on
  secret data, and WP34 N6's disassembly check (`tests/ct-asm.js`) verifies
  that of the functions its `ct_asm_*` fixtures hold, on x86-64 and aarch64;
  the rest is discipline. `std/README.md` lists what each module exports, the
  specification it reproduces, which of its functions are verified, and the
  rules they share.
- **A package is imported by name, and what is resolved is its source.**
  `import { scale } from "pkg_bare"` looks for `node_modules/pkg_bare` in the
  importing file's directory and in every directory above it — above the
  directory the compiler was run in included, which is the ordinary npm layout
  (`tests/link/package_above`) — stepping over an ancestor already called
  `node_modules` wherever the module's own name spells one, as Node does
  (`tests/link/package_doubled`) — reads that package's `package.json`, and
  compiles the file its `exports` map offers for the **`nish` condition**
  (`tests/link/package_bare`, `docs/wp21-packages.md` §2):

  ```jsonc
  { "exports": { ".": { "nish": "./src/index.ts" }, "./util": { "nish": "./src/util.ts" } } }
  ```

  Source, not a built artifact, and that is the decision rather than a stage:
  the whole-program fact fixpoint, monomorphisation, and `--number-mode` being
  a compile-time ABI each make a prebuilt library strictly worse than the
  source that is already there (`docs/wp21-packages.md` §3). The consequence a
  reader should carry away is that a dependency is compiled, checked and
  optimised as if it were your own code, and its non-exported functions are
  `internal` and dead-stripped like your own.
  - **The number mode rides in the condition.** `nish-i32` and `nish-f64` are
    the mode-qualified spellings, and the compiler asks for its own mode first
    and then plain `nish` — so a package correct under either declares `nish`,
    a package that needs different source per mode declares both, and a
    mismatch is a *resolution* failure at the package boundary rather than a
    wrong answer at run time. "First" is the compiler's order and not the
    manifest's: the mode-qualified condition wins wherever the package
    declares it, unlike Node, which would take whichever of the two the
    manifest names first (`tests/link/package_mode_order`,
    `tests/link/package_mode_order_f64`). Node's order is right for rival
    conditions and wrong for these two, because `nish-f64` is not a rival of
    `nish` but `nish` refined by the mode: honouring the order would let a
    package write `nish` above `nish-f64` and never have its f64 source
    compiled, with nothing said about it — the silent mismatch this spelling
    exists to make loud.
  - **Presence of the condition is the claim, and every failure to find it
    names its cause** (`docs/wp21-packages.md` §6, §11). Each is refused at
    the import, before a byte of the package is checked, with its own `--json`
    code:
    - A package whose entry offers no Nish condition in any spelling — an
      ordinary npm package, with `import` and `require` rows or a bare
      `".": "./index.js"` — is `` Package `plainjs` has no Nish entry point:
      its `exports` gave this compiler no file to compile for `.`, because that
      entry declares none of the conditions this compiler compiles source from
      (`nish`, `nish-i32`, `nish-f64`) `` (`NL3020`,
      `tests/link/package_not_nish`, `tests/link/package_no_condition`).
    - A package that offers only the *other* mode's condition is
      `` Package `pkg_f64` supports Nish in f64 mode only: its `exports` offers
      `nish-f64` for `.` and neither `nish-i32` nor `nish`, and this program is
      compiling in i32 (`--number-mode i32`) `` (`NL3017`,
      `tests/link/package_other_mode`, and the reverse in
      `tests/link/package_other_mode_f64`).
    - A `package.json` that is not well-formed JSON, when no entry point could
      be read out of it, names the manifest and the line and column where it
      breaks: `` Package `pkg_broken` has a malformed manifest:
      …/package.json:4:3 is not well-formed JSON `` (`NL3021`,
      `tests/link/package_malformed`). One the reader got a file out of before
      the break compiles, as it always has.
    - Anything else — no `exports` at all, no key for the subpath asked for, or
      a value the reader does not follow — is `` Package `pkg_one` has no Nish
      entry point: its `exports` gave this compiler no file to compile for
      `./extra` `` (`NL3014`, `tests/link/package_no_subpath`). The sentence
      reports what the compiler came away with rather than what the manifest
      declares, because a `nish-f64` that names something other than a file
      outranks a `nish` that is there and correct, and is what the message is
      about.

    A package that is not installed at all is `` Cannot find package `@x/y` ``
    (`tests/cases/reject_bare_package`).
  - **A compiler floor goes in `engines.nish`**, npm's slot for it, and it is
    checked whether or not the entry point resolves. The one range read is a
    floor, `>=X.Y.Z` or `>=X.Y`, blanks allowed around the version; a package
    whose floor is above this compiler is `` Package `pkg_future` needs a
    newer compiler: its `engines.nish` asks for `>=999.0.0` and this is nish
    0.8.0 `` (`NL3018`, `tests/link/package_engines_floor`), and one met
    compiles (`tests/link/package_engines_met`). Any other shape — a caret, a
    tilde, an upper bound, a bare version, a value that is not a string — is
    refused rather than taken as met, because a floor the compiler cannot read
    is one it cannot claim to meet: `` declares `engines.nish` as `^0.1.0`,
    which is not a range this compiler reads `` (`NL3019`,
    `tests/link/package_engines_range`).
  - **A package is its real directory, and a program compiles one copy of
    it.** One package reached both directly and through a symlink — pnpm's
    layout, and npm's whenever it cannot hoist — is one package, as it is to
    Node's resolver, and its own dependencies are looked for beside where it
    really is (`tests/link/package_symlink`). One package *name* at two real
    directories — npm's duplicate copies, or two versions of it under two
    dependencies — is refused at the import that reached the second, naming
    both directories and both versions: `` Package `hash` is at two places,
    …/node_modules/hash (1.0.0) and …/node_modules/user/node_modules/hash
    (2.0.0): Nish compiles one copy of a package per program, so every import
    of it has to reach the same directory `` (`NL3029`,
    `tests/link/package_two_dirs`, `docs/wp21-packages.md` §7; a copy whose
    manifest declares no `version` is said to have `no version`,
    `tests/link/package_two_dirs_unversioned`). A directory no link leads
    through keeps the spelling the search found it by. One a link leads
    through is named by its real directory, spelled relative to the working
    directory when the program was named relatively, and every module under
    it is in that package — so a workspace link to a directory outside any
    `node_modules` (`node_modules/foo -> ../packages/foo`) keeps `foo`'s own
    relative imports in `foo` (`tests/link/package_workspace`).
  - **Only the `nish` conditions are honoured**, and a subpath is an exact key:
    `default`, `import` and `node` are skipped rather than matched, and the
    `"./*"` pattern form is not read. A target is a string beginning with `./`
    and naming a file inside the package.
  - A package's symbols carry its prefix (`@pkg_bare.scale`), so two packages
    may each keep a private `helper()`; the root package — the program being
    compiled — has no prefix and its IR is unchanged (`docs/wp21-packages.md`
    §9).
  - **A diagnostic in a dependency says it is the dependency's.** An error or
    warning spanned in a package's own source keeps its code and wording, adds
    `` = note: this is in the dependency `pkg_broken` 0.3.1, not in this
    program's own source `` under the excerpt (the version as its manifest
    gives it, left out when it gives none), and under `--json` carries
    `"package":"pkg_broken"` (`tests/link/package_dependency_error`). What
    decides is where the module was resolved, so a dependency that calls
    itself `nish` is still one, and the standard library never is.
  - **A builtin with no runtime on the target is refused by what the program
    reaches**, once every module is checked. A freestanding `--target wasm32`
    build has no file, clock, environment, process, signal, terminal or
    entropy call (`runtime/runtime-wasm.c`), so a program whose `main` or
    any exported function of its own modules reaches one — `readFileSync`,
    `getenv`, `spawnSync`, `monotonicNanos` among the ones no call-site rule
    refuses — is refused with the N3 rule's words (NL2404), one error per
    capability, spanned at the first call of the witness chain, which names
    every hop; when the chain passes through a dependency the message names
    the one nearest the builtin: `` `getenv` reaches the operating system,
    and a wasm32 build has none to reach; the dependency `pkg_conf` calls it
    in `load` `` (`tests/link/package_wasm_hostless`,
    `tests/link/wasm_hostless_own`, `reject_read_file_wasm`). A module that
    calls one in a function the program never reaches is not refused: a
    wasm32 program may import `nish/cli` for `Style` (`npm test` "wasm
    hostless"). `--target wasm32-wasi` and `--profile wasi` have the calls,
    and refuse none of them.
- An imported constant contributes no `declare` and no relocation: it is
  folded into every use site in the importing module exactly as it is in the
  exporting one (`tests/link/const_export`,
  `tests/differential/corpus/const_modules`).
- Functions may be renamed on import (`as`); classes and interfaces may not,
  because the type name is part of the ABI (`%struct.Point`,
  `@Point.constructor`): `` Classes cannot be renamed on import ``
  (`tests/link/class_import_rename`).
- Importing a name the module declares but does not export, or does not
  declare at all, is an error with distinct messages
  (`tests/link/not_exported`, `tests/link/unknown_export`); importing the
  same local name twice, or a name also declared locally, is an error
  (`tests/link/duplicate_import`).
- An imported class or interface brings the **layouts** of the classes and
  interfaces its own members mention — field types, and the parameter and
  return types of its methods and constructor, through arrays and nullables —
  so a module that imports `Registry` may hold, call and read the `Entry`
  values `Registry.all(): Entry[]` hands it without importing `Entry`
  (`tests/link/reachable_struct`). Only the layout travels, not the name: a
  type *annotation* still needs the import, and `const e: Entry` in that
  module is `` Unsupported type reference `Entry` ``
  (`tests/link/reachable_struct_annotation`). An imported *function* brings its own
  signature's layouts the same way — `import { lex }` where `lex(): Token`
  gives this module `Token` values it never names
  (`tests/link/reachable_struct_return`) — and the layouts travel however many
  modules apart the declaration is (`tests/link/reachable_struct_chain`).
- Import cycles are allowed (`tests/link/cycle`); a shared dependency is
  compiled once (`tests/link/diamond`).
- **Linkage.** An `export`ed function is an external C-ABI symbol; every other
  function gets `internal` linkage by default, so LLVM may inline, specialise
  or drop it (`tests/cases/export_fn`, `tests/link/strict`).
  `--no-strict-exports` makes every function external again, which is what a C
  driver calling a non-exported function needs (`tests/cases/export_no_strict`).
  - **A method another module calls is in the link.** The layouts an import
    brings (above) include a class its module does not export — `Conn.space():
    Space` hands an importer of `Conn` a `Space` whether or not `Space` is
    exported — and the importer may call that value's methods, generic ones
    included. Such a method (or instantiation of one) is `hidden` rather than
    `internal`: one the final link resolves and the
    output exports to nothing, with the `Result` ABI an exported one has. A
    method only its own module calls stays `internal`
    (`tests/link/package_hidden_method`, #442). The class's name stays its
    module's: importing it is
    `` `Space` is declared in `pkg_q` but not exported (add `export`) ``
    (`tests/link/package_hidden_class_import`), and naming it in an annotation
    is `` Unsupported type reference `Space` ``
    (`tests/link/package_hidden_class_annotation`).
- **A function name is unique across the whole program**, exported or not, in
  either mode (`tests/link/duplicate_export`, `duplicate_internal`).
  `internal` linkage keeps a name out of the linker's way but it does not buy a
  second namespace: the whole-program attribute analysis is keyed by symbol
  name, so two functions sharing one would be emitted with each other's
  attributes — a miscompile rather than a link error, which is why the rule
  does not depend on the flag. A proposal to qualify a private function's
  symbol by its module when it would clash is
  [WP57](wp57-module-scoped-names.md); the rule above holds until it ships.

### `main`

```ts
export const main = (): number => {   // or `: void`; `: i32` in f64 mode
  console.log("hello");
  return 0;                             // the process exit code
};
```

- Only the entry module (the first file on the command line) may declare
  `export const main` (`Only the entry module may declare`,
  `tests/link/main_in_import`); `--link` requires it (`tests/link/no_main`),
  unless the entry holds [top-level code](#top-level-code), which becomes it.
- It takes no parameters (`` `main` cannot take parameters ``,
  `tests/cases/reject_main_params`; the command line is
  [`process.argv`](#process)) and
  returns `void` (exit code 0, `tests/cases/entry_main_void`) or an
  `i32`-lowered `number` (`tests/cases/entry_main`, `tests/link/two_file`).
  In f64 mode declare `main(): i32`; `main(): number` is rejected with
  `` `main` must return void or an i32 number ... under --number-mode f64 declare `main(): i32` ``
  *(CLI only)*.
- The user's function is emitted as `@nish_main`; the compiler adds a C
  `@main(i32 %argc, i8** %argv)` wrapper that builds `process.argv` when the
  program reads it (`call void @nish_argv_init(i32 %argc, i8** %argv)`,
  `tests/cases/argv_echo`, `tests/link/argv_import`), calls it, frees the
  arena, and returns the code. A non-exported `function main` is an ordinary
  function named `@main` (for C drivers such as `tests/driver.c`).

### Classes

```ts
class Point {
  x: number;
  y: number;
  label: string = "p";          // literal initializer

  constructor(x: number, y: number) {
    this.x = x;
    this.y = y;
  }

  manhattan(): number {
    return this.x + this.y;
  }
}
```

- **Fields** need a type annotation (`` Field `x` of class `Point` needs a type annotation ``,
  `tests/cases/reject_cls_field_no_type`). An initializer must be a literal
  (a number, a negated number, a string, or a boolean) of the field's type
  (`initializers must be literals` *(CLI only)*; `tests/cases/cls_initializers`).
  Layout is declaration order with natural alignment and padding, exactly
  as clang lays out the same C struct (`tests/layout/structs.ts`).
- **Constructor**: at most one, with a body
  (`` Constructor of class `Point` must have a body (no overload signatures) ``,
  `tests/cases/reject_cls_ctor_no_body`), no return type annotation
  (`Constructors cannot declare a return type`, `reject_cls_ctor_return_type`),
  and no parameter properties
  (``Parameter properties (`constructor(public x: number)`) are not supported; declare the field and assign it``,
  `reject_cls_param_property`; `public`, `private`, `protected`, `readonly`
  and `override` are a parameter's modifier only before its name on their
  line, so `constructor(public: i32)` is a parameter called `public`,
  `tests/parser/names-classes.ts`).
  `new C(args)` takes exactly the constructor's arity
  (`` `new Point` expects 2 argument(s), got 1 ``, `tests/cases/reject_cls_ctor_arity`).
  A class without a constructor may be `new`ed with zero arguments and gets
  its initializers stored inline (`tests/cases/cls_initializers`).
- **Definite assignment** (`tests/cases/reject_cls_uninitialised`,
  `reject_cls_uninitialised_no_ctor`, `reject_cls_read_before_assign`):
  after the constructor returns every field holds a value. The check is
  syntactic, top to bottom: `this.f = e;` statements (and chains) mark `f`;
  an `if` marks what both arms mark; assignments inside loops, nested
  expressions, ternaries or calls do not count; every `return` must see
  every field assigned; reading `this.f`, calling `this.m()`, or using
  `this` as a value before every field is assigned is an error. A class
  with no constructor must initialise every field
  (`` has no initializer and no constructor assigns it ``).
- **Methods** need a body (`` Method `scale` of class `Point` must have a body ``,
  `tests/cases/reject_cls_method_no_body`: a signature without one is an
  overload, and there are none) and an explicit return type; they are ordinary
  functions `@Class.method` with `this` first. `this` is valid only inside
  a method or constructor (`` `this` is only valid inside a method or constructor ``,
  `tests/cases/reject_cls_this_outside`) and may be aliased or passed on
  (`const self = this` *(CLI only)*; `tests/cases/cls_this_method_call`).
  Methods may call each other and free functions, recursively.
- **Field access**: `p.x` reads, `p.x = v` and `p.x op= v` write, for the
  arithmetic and the bitwise compound operators alike
  (`tests/cases/cls_field_write`, `cls_compound_field`,
  `cls_field_bitwise_assign`); `++`/`--` on fields is not supported
  (`Only simple variables can be assigned`).
  Unknown fields: `` Unknown field `z` on class `Point` ``
  (`tests/cases/reject_cls_unknown_field`, `reject_cls_assign_unknown_field`).
- **`readonly`** fields may be assigned only as `this.f = v` in their own
  class's constructor (`tests/cases/cls_readonly_ok`;
  `` Cannot assign to readonly field `value` of `Id` outside its constructor ``,
  `reject_cls_readonly_write`). A compound assignment is a write like any
  other, so `this.f |= bit` is refused too, in the declaring class's own
  constructor as much as anywhere else
  (`reject_cls_field_bitwise_readonly`). `public`, `private`, `protected`
  are accepted and ignored.
- **Equality**: `===` / `!==` on two values of the same class compare
  identity (pointer equality) (`tests/cases/cls_this_method_call`, `Account.same`);
  `<` and friends are rejected (`tests/cases/reject_cls_ordering`). Both
  operands must have the same declared type.
- **No inheritance** (WP25). `extends` on a class is
  `` `extends` is not supported: Nish has no inheritance ``
  (`tests/cases/reject_cls_extends`), and `super` in every spelling —
  `super(...)`, `super.m()`, a bare `super` — is
  `` `super` is not supported: Nish has no inheritance ``
  (`reject_cls_super`). A class is never a subtype of another class, so
  every method call in a program names exactly one symbol and there is
  nothing for a vtable to decide. The widening `extends` used to provide is
  `implements`, below: repeat the fields you were going to inherit as the
  class's first fields and name an interface that declares them. Shared
  behaviour is a free function over that interface.
- **Rejected**: `static` on a field, a method or the constructor
  (`tests/cases/reject_cls_static`, `reject_cls_method_static`,
  `reject_cls_ctor_static`) — the word is still a legal member *name*, and
  `static?: i32` is an optional field called `static`
  (`reject_cls_field_named_static`), and on an interface field too, where the
  message says which kind it is (`reject_cls_static_interface`), with one
  exception: a class's typed JSON options, `static readonly json = { ... }`,
  which is not a field and is written without a type ([Typed
  JSON](#typed-json-nishjson-typed)) — `readonly` on
  a method or the constructor, which has no storage to be read-only
  (`reject_cls_method_readonly`, `reject_cls_ctor_readonly`),
  getters/setters
  (`` Getters and setters are not supported in class `Box` (use a method) ``,
  `reject_cls_accessor`; `get` and `set` are still member names,
  `tests/parser/names-bindings.ts`), optional fields
  (`cannot be optional`), index signatures
  (`` Index signatures are not supported in class `Point` (object layout is fixed) ``,
  `reject_cls_index_signature`), `!` assertions, `abstract` on the class or a
  member (`Abstract classes are not supported`, `reject_generic_abstract`),
  a `declare class` that is not a C struct layout (a method, accessor,
  constructor or initializer in one is refused as the
  [`declare class` section](#a-declare-class-a-c-struct-lent-by-pointer) lists,
  `reject_cls_declare`, `reject_ffi_struct_*`),
  a class with no name — `export default class { }` or a class expression —
  (`Classes must be named`, `reject_cls_anonymous`; a named class expression is
  `Unsupported expression in Phase 1: ClassExpression`), a member named by a
  string or a number (`` Members of `Point` must have plain identifier names ``,
  `reject_cls_field_string_name`), a `static { }` block
  (`` Unsupported class member in `Point`: ClassStaticBlockDeclaration ``,
  `reject_cls_static_block`), type parameters on the constructor
  (`reject_generic_method_constructor`; a *method* may declare its own — see
  [Generic methods](#generic-methods)),
  decorators
  (`reject_decorator`), computed member names
  (`Computed property names are forbidden in Nish (member names are fixed at compile time)`,
  `reject_cls_computed_field`, `reject_cls_computed_method`; `[Symbol.dispose]`
  is the one bracketed name read, see [Scoped tasks](#scoped-tasks-using-s--scope)),
  overloaded constructors.

### Generic functions

A function may declare type parameters, and **every instantiation is compiled
to its own specialised function**: one `define` per (template, type-argument
tuple), named by appending `$` and each argument's mangled type to the
template's name. There is no boxing, no type dictionary and no runtime type
information, and the IR of an instantiation is the IR of the monomorphic
function somebody would have written by hand, with the symbol renamed
(`tests/cases/gen_identity`).

```typescript
const identity = <T>(x: T): T => x;

export const main = (): i32 => {
  console.log(identity(7));      // @identity$i32
  console.log(identity("hi"));   // @identity$str
  return 0;
};
```

- **Both spellings take type parameters.** `function identity<T>(x: T): T` and
  `const identity = <T>(x: T): T => x` declare the same thing, as they do
  without them (`tests/cases/gen_identity`).
- **A type argument is inferred from the arguments, and is never written at a
  call site.** `identity<i32>(7)` is
  `` Type arguments are not written at a call site in Nish: `T` is inferred from the arguments, so write `identity(...)` ``
  (`tests/cases/reject_generic_call_type_args`). One token of lookahead cannot
  tell `f<i32>(x)` from `(f < i32) > (x)`, and inference already covers the
  spelling. Inference matches the *shape* of each declared parameter against
  its argument's type — `T` against `i32`, `T[]` against `i32[]`,
  `Result<T, string>` against `Result<i32, string>` — left to right, first
  binding wins (`tests/cases/gen_infer_two`, `gen_result_payload`).
- **A type parameter that appears in no parameter is an error at the
  declaration**, because it could never be inferred and the function could
  never be called:
  `` Cannot infer `T` for `empty`: a type parameter is inferred from the arguments, and `T` appears in none of them; give `empty` a parameter that mentions `T` ``
  (`tests/cases/reject_generic_function`).
- **Every other type rule applies to a type argument unchanged.** A type
  parameter is not a hole through which something the language refuses can be
  smuggled in: `Result<T, void>` is still refused at an instantiation whose `E`
  is `void`, `T | null` is still only over a pointer type, and each
  instantiation's body is checked with `T` bound to a concrete type.
- **Each instantiation gets its own facts.** The attribute fixpoint and the
  escape analysis are keyed by symbol, so `eq<T>` is `readnone` at `T = i32`
  and `readonly` at `T = string` — one source line, two sets of attributes
  (`tests/cases/gen_eq_purity`).
- **Recursion terminates or is refused by name.** A recursive call whose type
  argument is the parameter itself, or a type that does not mention it, is
  accepted: `countDown<string>` asking for `countDown<i32>` is two
  instantiations and no more (`tests/cases/gen_recursive_ground`). A call that
  puts the parameter *under a type constructor* has no end and is refused:
  `` Monomorphising `grow` would not terminate: `grow<i32>` asks for `grow<i32[]>`, which puts `i32` under a type constructor instead of passing it on, so the chain has no end; pass `T` itself, or a type that does not mention it ``
  (`tests/cases/reject_generic_polymorphic_recursion`). Behind the rule are two
  compiler limits — 256 instantiations of one template, 4096 in one module —
  whose message says it is a limit rather than a rule of the language.
- **`$` may not appear in a declared name.** It separates a generic's name from
  its type arguments in every symbol the compiler emits, so a function called
  `identity$i32` would be the symbol `identity<i32>` already has:
  `` `identity$i32` cannot be the name of a function in Nish: `$` separates a generic's name from its type arguments in the symbols the compiler emits ``
  (`tests/cases/reject_generic_dollar_name`). A class or interface, generic or
  not, is held to it too: a `class Box$i32` would be the struct `Box<i32>`
  already is, and one type with it wherever either is declared (#193;
  `tests/link/class_dollar_name`, `…_imported`). Locals, parameters and fields
  are unaffected — only names that become symbols are restricted.
- **An instantiation is spelled as written wherever a person reads it, and
  mangled wherever a machine does.** Every diagnostic, the `--emit-checked`
  dump and the `-g` DWARF `name` say `identity<i32>`, `identity<Box<i32>>`,
  `Box<i32>` and `Box<i32>.get`; the symbol, the `%struct` name, the DWARF
  `linkageName` and a header's `NISH_SYMBOL` binding keep `identity$i32`,
  `identity$$Box$i32` and `Box$i32`. Every instantiation's `DISubprogram` carries
  the template's `line`, so a breakpoint in a generic body has one address per
  instantiation, as a C++ template's does (`tests/cases/dbg_generic`). A
  polymorphic-recursion chain through a class reads
  `` `grow<i32>` asks for `grow<Box<i32>>` ``
  (`tests/cases/reject_generic_recursion_through_class`).
- **An exported instantiation reaches a host as `nish_gen_<name>`.** Its symbol
  holds a `$`, and a `.` when an argument is an array, a nullable or a `Result`
  (`identity$arr.i32`), so neither C nor JavaScript can spell it. `--emit-header`
  declares `nish_gen_identity_i32` and `nish_gen_identity_arr_i32`, bound to the
  symbols with `NISH_SYMBOL`, and `--emit-dts`, the wasm loader and `--emit-napi`
  export the same names; the comment above each says which instantiation it is.
  An instantiated class is `struct nish_gen_Box_i32` with methods such as
  `nish_gen_Box_i32_get`. A user name cannot start with `nish_`, so no
  declaration of the program can take one of these names — a user
  `identity_i32` beside `identity<i32>` is two C functions
  (`tests/cases/interop_generic_fn`, `interop_generic_collision`). The sidecars
  declare instantiations only: `identity<T>` itself has no symbol, so nothing
  declares it.
- **An exported generic that nothing instantiates is refused when a sidecar is
  asked for.** It has no symbol, so a header, a `.d.ts` or an N-API shim would
  leave it out without a word. With any of `--emit-header`, `--emit-dts`,
  `--emit-napi` or `--emit-napi-async` it is
  `` `identity` is generic, so it has no single C signature: a generic function becomes a symbol only where it is instantiated, and this program instantiates none ``
  (NL4007), and for a class
  `` `Box` is generic, so it has no single C layout: a generic class becomes a struct only where it is instantiated, and this program instantiates none ``
  (`tests/cases/reject_interop_generic_unused`); without a sidecar flag the same
  program compiles. The same flags refuse two functions whose C names collapse
  to one, which only a method's `.`-joined name can still cause —
  `Point.shifted` beside a function `Point_shifted`:
  `` `Point.shifted` and `Point_shifted` are both `Point_shifted` in C, so a header that declared both would not compile: rename one of them ``
  (NL4008, `tests/cases/reject_interop_generic_clash`). They also refuse a
  signature or an exported struct field that holds a
  [discriminated union](#discriminated-unions), which has no C spelling yet
  (NL4009, `tests/cases/reject_union_export_param`), and a signature that
  holds a [string enum](#string-enums), alone or in an array, a `| null` or
  a `Result`:
  `` `rank`'s parameter `r` is `Role`, which holds a string enum: a string enum has no C, N-API or wasm spelling in this version, so take or return a `string` and convert with `String(r)` and a `switch` ``
  (NL4019, `tests/cases/reject_enum_string_export`,
  `reject_enum_string_export_napi`).
- **A template may be exported and instantiated from another module, and each
  instantiation is defined exactly once**, in the module that declares the
  template. Everywhere else it is a `declare` carrying that definition's
  attributes, which is what an imported plain function gets — the difference is
  that one imported name becomes one symbol per distinct type-argument tuple
  rather than one symbol (`tests/link/generic_import`). Two modules asking for
  the same tuple share the one definition (`tests/link/generic_two_importers`),
  and the symbol carries the **declaring** package's prefix, so a package that
  exports `pick<T>` owns `@pkg_lib.pick$i32` however many packages call it
  (`tests/link/package_generic_import`). A type argument may be a class the
  declaring module has never heard of: the layout travels with the request, and
  the instantiation is emitted where the template is (`identity<Point>` in
  `tests/link/generic_import`). A template that is not exported cannot be
  imported, in the words every other private declaration is refused in
  (`tests/link/generic_import_private`), and an imported generic may be renamed
  — `import { Box as B }` — without moving the symbol, because the instantiation
  is named after the template rather than after whatever the caller called it.
- **A type-argument list belongs to a template and to nothing else.** An
  imported name that is not one is refused when the import binds, rather than
  where the annotation is written, because a module's signatures are resolved
  as soon as it is parsed and before any import is bound:
  `` `Point` in `./lib` takes no type arguments: only a generic class or interface is written with them ``
  (`tests/link/generic_import_plain`).
- **A type parameter has no members until a constraint names them.** A
  template may pass a `T` on, return it, store it, compare it and hand it to an
  operator that works at the concrete type, but it may not read, write or call
  a member through one, even when every instantiation it has would have that
  member:
  `` Cannot read `x` of `T`: an unconstrained type parameter has no members; say which ones it has with `<T extends Point>` ``
  (`tests/cases/reject_generic_member_unconstrained`), and the call form
  `` Cannot call `bump` of `T`: ... `` (`reject_generic_member_unconstrained_method`).
  A value is `T`-typed however it reached the receiver: a local inferred from a
  `T`, an element of a `T[]`, a `T | null` narrowed to `T`, a field of type `T`
  read through `this`, and the result of a generic call that returns its
  argument (`reject_generic_member_through_local`); a field of `new Box<T>(t)`,
  an element of `[t]` (`reject_generic_member_through_expression`); and a
  `Result<T, E>`'s `value`, `pop()` on a `T[]`, an assignment's value and `this`
  copied into a local (`reject_generic_member_through_payload`). What decides it is where
  the value came from, never its type — at `T = Point` a `T` and a `Point` are
  one type, and only the `T` is refused
  (`reject_generic_member_same_type_local`).
- **`<T extends Shape>` constrains a type parameter**, and then a `T` has
  exactly `Shape`'s members: its fields, and its methods when `Shape` is a
  class. Each instantiation still reads its own struct directly — `T` at
  `Circle` reads field 0 of `%struct.Circle` and calls `@Circle.bump`, with no
  `bitcast` and no vtable (`tests/cases/gen_constraint`,
  `gen_constraint_method`). A field may be written through a `T` on the same
  terms (`gen_constraint_write`), and each parameter answers from its own
  constraint, so `<T extends Shape, U extends Counter>` reads `area` through a
  `T` and calls `bump` through a `U` (`gen_constraint_two`). A member the concrete type has and the constraint
  does not is refused, once for the template however many instantiations it
  has, or the constraint would be decoration:
  `` Unknown field `radius` on interface `Shape`, the constraint of `T`: a constrained type parameter has only the members its constraint declares ``
  (`tests/cases/reject_generic_member_not_in_constraint`).
- **A constraint is a declared class or interface**, or an instantiation of a
  generic one written with concrete type arguments
  (`T extends Container<i32>`, `tests/cases/gen_constraint_generic_bound`). It
  is resolved once, in the template's own module, so a template imported from
  another module carries its constraint with it
  (`tests/link/generic_constraint_import`). Anything else is refused at the
  constraint — a scalar, `string`, an array or a `Result`:
  `` `T extends i32` is not supported: a constraint must be a declared class or interface, because the members a type parameter has are its constraint's ``
  — and so is one that mentions a type parameter, which would mean something
  different at every instantiation:
  `` `U extends T` is not supported: a constraint cannot mention a type parameter, ... ``
  (`tests/cases/reject_generic_constraint`).
- **A type argument must satisfy its constraint**: it is the constraint
  itself, or a class that `implements` it. Having fields of the same names is
  not enough, because satisfying a constraint is a declaration, and a class
  constraint is satisfied by that class alone because a class can only
  `implements` an interface. It is checked at each request, where the argument
  was inferred or written, and reported in that module:
  `` `T` of `areaOf` requires `T extends Shape`, and `i32` does not implement it; pass a class or interface that declares `implements Shape` ``
  (`tests/cases/reject_generic_unsatisfied_constraint`,
  `tests/link/generic_constraint_import_unsatisfied`). **The constraint is a
  declaration, not a name**: a module that declares a `Shape` of its own has not
  satisfied another module's `<T extends Shape>`, whatever fields the two
  share — neither with that `Shape` itself nor with a class that implements it —
  and a same-named class does not satisfy a class constraint either. The
  request is refused in those words at the call in the asking module
  (`tests/link/generic_constraint_same_name`, `…_same_name_fields`,
  `…_same_name_itself`, `…_same_name_class`). The constraint may still be the
  asking module's own declaration when the template's module imports that very
  declaration (`tests/link/generic_constraint_import_back`).
  Two modules can no longer declare a `Shape` each at all (*A class or
  interface name is program-wide*, under
  [Generic classes and interfaces](#generic-classes-and-interfaces)), so the
  four programs above are refused at the second declaration now, before any
  call is checked; this rule is still what decides a constraint.
  Every position a type
  argument can be written in is a request of its own — a field, an array
  element, a `Result` arm, inside another instantiation, an `implements`
  clause (`reject_generic_unsatisfied_constraint_positions`).
- **A type parameter list names each parameter once**, on a function, an
  arrow, a method, a class and an interface alike:
  `` Duplicate type parameter `T` `` (NL2302). The second `T` could never be
  bound to anything the first was not, so the list is refused on the first
  name that repeats, and only there: `<T, T, T>` is one diagnostic, on the
  second `T`, because a declaration reports one. The rule needs no type, so a
  template nothing instantiates is refused too
  (`tests/cases/reject_generic_duplicate_type_parameter`, `…_arrow`,
  `…_method`, `…_class`, `…_interface`, `…_template`, `…_triple`). A type
  alias's list is refused before it is read, by NL1054.
- **Not supported yet**: a default type argument (`<T = string>`,
  `` a default type argument (`T = ...`) is not supported: a type argument is inferred from the arguments ``,
  NL2292, refused on a template nothing instantiates too,
  `tests/cases/reject_decl_sweep_together`) and type parameters on a
  constructor, each with its own message. Type parameters on a type alias are
  forbidden rather than unsupported (NL1054, [Type aliases](#type-aliases)).
  A generic `main` is refused too, in words of its own: the entry point is
  called by the C runtime, which has no type arguments to give it. Multiple bounds (`T extends A & B`), a bound
  that mentions the parameter it constrains, and a bound that is "any type with
  a method `compare`" are not planned on this path. The design and the
  milestones are in [wp18-generics.md](wp18-generics.md).

### Generic classes and interfaces

A `class` or an `interface` may declare type parameters too, and an
instantiation is **an ordinary struct**: `Box<i32>` is `%struct.Box$i32` with
`Box`'s fields at `T = i32`, its methods are `@Box$i32.get` and
`@Box$i32.constructor`, and everything the language already does to a struct —
the layout, `implements`, `new`, field access, the C header, the debug info —
works on it unchanged (`tests/cases/gen_box_i32`, `gen_box_string`).

```typescript
class Box<T> {
  value: T;
  constructor(v: T) { this.value = v; }
  get(): T { return this.value; }
}

interface Pair<A, B> { first: A; second: B; }

export const main = (): i32 => {
  const b = new Box<i32>(7);                            // %struct.Box$i32
  const p: Pair<i32, string> = { first: 1, second: "" }; // %struct.Pair$i32$str
  return b.get();
};
```

- **The type arguments are written out, never inferred.** `Box` on its own is
  not a type, because there is no layout until `T` is bound:
  `` `Holder` is generic: it must be written with its type arguments, e.g. `Holder<number>` ``
  (`tests/cases/reject_generic_class`). The two positions that take them are an
  annotation (`const b: Box<i32>`) and `new` (`new Box<i32>(7)`) — the two a
  one-token parser can read a type-argument list in, which is the same reason a
  *call* infers instead (§2a of [wp18-generics.md](wp18-generics.md)). A class
  that is not generic takes none:
  `` `Point` is not generic, so `new Point` takes no type arguments ``
  (`tests/cases/reject_cls_new_generic`).
- **A type argument may be anything a type may be**, including another
  instantiation: `Box<Point>` is `%struct.Box$$Point` and `Box<Box<i32>>` is
  `%struct.Box$$Box$i32`, the `>>` split back into two by the parser
  (`tests/cases/gen_box_struct`, `gen_nested`). A *type parameter* takes none,
  though: `T` is whatever the instantiation bound it to, so `const y: T<i32>`
  is `` Unsupported type reference `T<i32>` ``
  (`tests/cases/reject_generic_type_param_args`).
- **A template obeys every rule a declared class obeys.** Type parameters
  change what a declaration *means*, not what it may be written with, so
  `export default class Box<T>`, `abstract class Box<T>` and `interface
  Box<T> extends Base` are refused in the same words as their non-generic
  spellings, and `declare class Box<T>` is
  `` A generic `declare class` is not supported `` (a C struct has one layout;
  `tests/cases/reject_generic_declare_class`,
  `reject_generic_export_default`, `reject_generic_abstract`,
  `reject_generic_interface_extends`).
- **A template claims its name in the one declaration namespace.** `class
  Box<T>` is a declaration of `Box`, so a function, a constant, an alias, an
  enum or a second class of that name is refused whichever was written first —
  the structs pass runs before the functions pass, so the template is always
  the one already there (`tests/cases/reject_generic_class_fn_clash`,
  `reject_generic_class_after_fn`, `reject_generic_class_redeclared`).
- **A class or interface name is program-wide**, because a struct type is
  identified by its name alone: `%struct.Base`, and a type id interned by that
  name. So two modules may not both declare a class or interface of one name,
  whether or not either is exported, whether it has fields only, and however
  different the two field lists are. The later declaration in load order is
  refused, once per name per module, naming the module that declared it first:
  `` Class `Base` is also declared in main.ts; a class or interface name must be unique across the program whether or not it is exported, because a struct type is identified by its name alone ``
  (`tests/link/class_clash_fields`, `tests/link/iface_clash_private`; NL3028).
  Left alone, a value of one was accepted where the other was expected and its
  fields were read at the other's offsets, with no diagnostic (#193). Two
  classes that share a name and a constructor or method are refused in the
  same words, once (`tests/link/class_clash_constructor`, `…_method`,
  `…_package`), and across two packages the wording is the one
  `tests/link/two_packages_struct` pins. A declaration is compared with the
  first of its name in its own package before any other, so when a third
  package declared the name first, the first of the two is refused across
  packages and the second in these words
  (`tests/link/class_clash_after_package`, `…_package_after_root`). Importing
  the one declaration is how two modules share a struct
  (`tests/link/iface_same_name_imported`).
- **An instantiation's name is program-wide**, because `%struct.Box$i32` and
  `@Box$i32.constructor` are. So two modules may not both declare a generic
  class or interface of one name once both instantiate it:
  `` Generic class `Holder` is also declared in helper.ts; a class or interface name must be unique across the program, and an instantiation is named after its template ``
  (`tests/link/generic_class_clash`), once per template even when signatures
  have made both instantiations, constructor and methods included, before any
  body is checked (`tests/link/generic_class_clash_signature`), and across two
  packages the wording is the one `tests/link/package_generic_class_clash` pins.
  As for a declared name, a template is compared with the first of its
  instantiation's name in its own package before any other, so when a third
  package instantiated the name first, the second module of the package is
  refused in these words (`tests/link/generic_class_clash_after_package`). Nothing about the two
  declarations is visible at a call, so left unreported the second layout would
  simply replace the first and a field read would land on the wrong offset.
- **`implements` may name an instantiation.** `class Box<T> implements
  Container<T>` is checked once per instantiation, against `Container$i32`, by
  the ordinary field-prefix rule — the interface's fields are the class's first
  fields, so the conversion is one `bitcast` (`tests/cases/gen_implements`).
- **Each instantiation gets its own facts**, exactly as a generic function's
  do: one `new Box<T>(v)` in a body that does not escape is an entry-block
  `alloca` at `T = i32` and an arena bump at `T = string` when the box is
  returned — one source line, two memory behaviours (`tests/cases/gen_stack`).
- **It is named as written, and linked as mangled.** A diagnostic says
  `` Unknown field `nope` on class `Box<i32>` `` and
  `` Argument 1 of `Box<i32>.set`: expected i32, got string ``
  (`tests/cases/reject_generic_member_display`, `reject_generic_implements_display`,
  `reject_generic_ctor_display`), and `-g` names the composite type `Box<i32>`
  and its methods `Box<i32>.get`, with `Box$i32.get` as the `linkageName`
  (`tests/cases/dbg_generic`). In a header it is `struct nish_gen_Box_i32`; the
  rule for both is the generic function's
  ([Generic functions](#generic-functions)).
- **A class or interface may constrain its parameters** with the rules a
  generic function's follow. Its own methods read the constraint's members
  through a field of that type — `this.item.area` in `class Holder<T extends
  Shape>` is two loads, `item` and then `area` of `%struct.Circle`
  (`tests/cases/gen_constraint_class`) — and every instantiation is checked
  against the constraint where its type arguments are written, after `new` and
  in an annotation
  (`tests/cases/reject_generic_unsatisfied_constraint_class`,
  `reject_generic_unsatisfied_constraint_annotation`).
- **A field may not grow its own type argument.** `class Nest<T> { inner:
  Nest<T[]> | null }` asks for a strictly larger instantiation every time it is
  laid out:
  `` Monomorphising `Nest` would not terminate: `Nest<i32>` names `Nest<i32[]>`, which puts `i32` under a type constructor instead of passing it on, so the chain has no end; name `T` itself, or a type that does not mention it ``
  (`tests/cases/reject_generic_expanding_field`). `Nest<T>` and a type that
  mentions no parameter are both fine — it is the same rule a generic
  function's recursive call is held to, stated over fields.
- **A generic class or interface may be imported**, and the whole-program rule
  is the one a generic function's is: `%struct.Box$i32` and every
  `@Box$i32.*` symbol are defined once, by the module that declares `Box<T>`,
  and `declare`d by every module that holds one (`tests/link/generic_import`,
  `tests/link/package_generic_import`). Unlike a declared class it may be
  renamed on import, because the name that crosses the ABI is the template's
  and not the caller's. Named without its type arguments it is refused in the
  same words a locally declared template is
  (`tests/link/generic_import_no_args`).

### Generic methods

A method of a class — generic or not — may declare type parameters of its own,
and it is compiled the way a generic function is: **one `define` per (receiver
struct, method type-argument tuple)**, named by appending `$` and each of the
method's mangled type arguments to the receiver's method symbol. The IR of an
instantiation is the IR of the method somebody would have written for that type,
with `this` first and the symbol renamed (`tests/cases/gen_method`).

```typescript
class Chooser {
  flip: boolean = false;
  pick<T>(a: T, b: T): T { return this.flip ? b : a; }
}

class Box<T> {
  value: T;
  constructor(value: T) { this.value = value; }
  keep<U>(other: U): T { return this.value; }
}

const c = new Chooser();
c.pick(1, 2);                    // @Chooser.pick$i32
c.pick("a", "b");                // @Chooser.pick$str
new Box<i32>(7).keep("seven");   // @Box$i32.keep$str
```

- **The type arguments are inferred from the arguments**, exactly as a generic
  function's are, and never written at the call: `h.get<i32>(7)` is
  `` Type arguments are not written at a call site in Nish: `T` is inferred from the arguments, so write `h.get(...)` ``
  (`tests/cases/reject_generic_method`, and through a field path,
  `reject_generic_method_path_type_args`). A method type parameter no parameter
  mentions is refused at the declaration:
  `` Cannot infer `U` for `Holder.make`: a type parameter is inferred from the arguments, and `U` appears in none of them; give `Holder.make` a parameter that mentions `U` ``
  (`reject_generic_method_uninferable`).
- **The receiver is part of the key.** On a generic class, `Box<i32>.pair<string>`
  and `Box<string>.pair<string>` are two instantiations, and a tuple asked for
  twice is one: two receivers times two method tuples are four `define`s and no
  more (`tests/cases/gen_method_generic_class`). Inside the body the class's
  parameters and the method's are both bound.
- **A method's type parameter may not reuse a name of its class's**, because
  both are in scope in its body and every `T` there would have two meanings:
  `` Type parameter `T` of `Box.map` shadows `Box`'s own `T`: a class's type parameters are in scope in its methods, and a diagnostic that names `T` has to mean one of them; give the method's another name ``
  (`reject_generic_method_shadow`, once per class however many times it is
  instantiated).
- **A method type parameter may be constrained**, with a generic function's
  rules: a `U extends Shape` has exactly `Shape`'s members, read straight out of
  the concrete struct (`tests/cases/gen_method_constraint`); an unconstrained
  one has none, through a local, a field or another generic call alike
  (`reject_generic_method_member`, `reject_generic_method_member_through_call`);
  a type argument is held to the constraint at each call
  (`reject_generic_method_unsatisfied`); and the constraint may mention no type
  parameter, the class's included, because it is resolved once for every
  receiver (`reject_generic_method_constraint_class_param`).
- **Recursion terminates or is refused by name**, with a generic function's
  rule and sentence: `` Monomorphising `Walker.walk` would not terminate: `Walker.walk<i32>` asks for `Walker.walk<i32[]>`, ... ``
  (`reject_generic_method_recursion`).
- **`-g` names an instantiation as written** — `Box<i32>.pair<string>` — and
  links it as mangled, `Box$i32.pair$str` (`tests/cases/dbg_generic_method`).
- **The whole-program rule holds**: a generic method of an exported class is
  instantiated, and defined once, in the class's module, and every other module
  that calls it `declare`s it (`tests/link/generic_method_import`).
- **In the C header** an instantiation is declared under the `nish_gen_`
  spelling a generic function's takes, bound to its symbol, with the object
  first: `int32_t nish_gen_Holder_pick_i32(struct Holder *this_, int32_t a, int32_t b) NISH_SYMBOL("Holder.pick$i32");`
  (`tests/cases/gen_method_export`). The wasm and N-API sidecars bridge no method.
  An exported class's generic method that nothing calls has no symbol, so with a
  sidecar flag it is refused:
  `` `Holder.pick` is generic, so it has no single C signature: a generic method becomes a symbol only where it is instantiated, and this program instantiates none ``
  (`reject_generic_method_unused`).
- **A constructor has no type parameters of its own**: it takes its class's,
  written after `new`. `constructor<T>()` is a syntax error
  (`reject_generic_method_constructor`), as it is in TypeScript.
- **A generic method is a member like any other**, so a field or another method
  of the same name is `` Duplicate member `pick` in class `Chooser` ``
  (`reject_generic_method_field_clash`).
- **`$` is refused in a method name where it could spell an instantiation**:
  in any generic method's own name, which every instantiation's symbol is built
  on (`pick$i32<V>` at `i32` would be `pick<U1, U2>` at `i32, i32`;
  `reject_generic_method_dollar_generic`, `…_generic_first`,
  `…_generic_class`), and in a plain method's name when the part before the `$`
  is a generic sibling's — `pick$i32` beside a generic `pick` would be
  `pick<i32>`'s symbol (`reject_generic_method_dollar`).

### Function parameters

A parameter of a top-level function may have a **function type** written
inline in its annotation, and its argument is then a function the checker can
name at the call: a top-level
function written by name, an arrow written right there, or a local holding a
function reference, which the call wraps in an arrow that calls it
([Function references](#function-references)). Such a function is
a template, with or without type parameters, and **each callee it is given is
an instantiation of its own**, exactly as each type-argument tuple is: one
`define` per (template, type arguments, function arguments), whose body calls
its callee directly (`tests/cases/fnarg_named`). There is no function pointer
and no indirect call; the parameter has no LLVM parameter at all, and the whole-program fixpoint sees an ordinary direct call
it can prove things through ([wp23-language-surface.md](wp23-language-surface.md)
§6, and [wp28-compatibility-mode.md](wp28-compatibility-mode.md) §7.4 for what
the other kind of callee would cost). A parameter whose function type comes
through an alias (`type F = (x: i32) => i32`, then `f: F`) is not a function
parameter but an ordinary parameter holding a
[function reference](#function-references).

```typescript
const apply = (f: (x: i32) => i32, x: i32): i32 => f(x) + 1;
const square = (x: i32): i32 => x * x;

export const main = (): i32 => {
  const a = apply(square, 3);        // @apply$fn.6.square, calling @square
  const b = apply((x) => x - 1, 3);  // @apply$fn.16.nish_main$arrow0
  return a + b;
};
```

- **The callee is part of the symbol.** An instantiation's name is the
  template's, then its type arguments, then `$fn.<length>.<symbol>` for each
  function argument, which is self-delimiting however many `$` the callee's
  own symbol holds; a person reads it as `apply<square>` or
  `map<i32, str, (x) => ...>` in every diagnostic, the `--emit-checked` dump
  and the `-g` DWARF `name`. Two callees are two `define`s; the same callee
  twice is one (`tests/cases/fnarg_named`).
- **An arrow argument is lifted into a function of its own**, named after the
  function it is written in (`nish_main$arrow0`) — a symbol no declaration can
  spell, because a declared name may not hold a `$`. It may be written
  `x => ...`, `(x) => ...` or with annotations, with a concise or a block body
  (`tests/cases/fnarg_arrow`), and under `-g` it has a `DISubprogram` of its
  own, placed where the arrow starts (`tests/cases/dbg_fnarg_arrow`).
- **Inference runs in two phases.** The value arguments bind what they can
  first; then each function argument is resolved against its parameter's
  function type. An arrow's unannotated parameters take the types the value
  arguments bound, a named function's signature binds any type parameter it
  mentions, and an arrow with a concise body binds the result type from its
  body, so `map(xs, (n) => n > 1)` over an `i32[]` is
  `map<i32, boolean, (n) => ...>`. A numeric
  literal argument is checked after the others, against what they bound, so a
  fold's identity `0.0` over an `f64[]` is an `f64` in either number mode
  (`tests/cases/fnarg_generic`).
- **A function parameter may be called and passed on, and nothing else.**
  Passing it to another function-typed parameter forwards the callee as part
  of the key, so the innermost call is still direct
  (`tests/cases/fnarg_forward`). Storing, returning, comparing or putting it
  in an array is
  `` `f` is a function parameter and can only be called or passed on as a function argument: it names the callee each call is compiled for, not a value, so it cannot be stored, returned, compared or put in an array ``
  (`tests/cases/reject_fnarg_store`, `reject_fnarg_return`).
- **An arrow may read the `const` locals and the parameters of the function
  it is written in** (WP29 capture). Each name it reads is handed to it as an
  extra argument when the call is made: the lifted arrow gains a parameter per
  capture, the instantiation that runs it gains one too and forwards it, and
  every call stays direct — no environment object, no indirect call. The
  captures are not part of the instantiation's key, so one arrow is one
  `define` however many values it reads. A narrowing in force at the call holds
  in the body (`if (name !== null) { each(xs, (x) => use(name)) }` reads `name`
  as a `string`). The arrow may write through what it captured —
  `infos.push(x)`, `box.n = v` — because the call runs before the function goes
  on (`tests/cases/fnarg_capture`, `fnarg_capture_narrow`,
  `fnarg_capture_local`, `fnarg_capture_escape`). What it may not do:
  - read `this` (NL2590, `reject_fnarg_capture_this`): bind it, or what the
    arrow needs of it, to a `const` before the call;
  - read a `let` (NL2585, `reject_fnarg_capture_let`), whose value could
    change after the arrow is handed it; `nish --fix` copies it into a
    `const` just before the call (`tests/fix/fnarg-capture-let`);
  - assign to a name it captured (NL2586, `reject_fnarg_capture_write`):
    the assignment would change only its own copy;
  - name a function parameter of the function it is written in (NL2587,
    `reject_fnarg_capture_function_param`), which is bound at instantiation
    and is no value;
  - capture a `Secret`, a scope, a lock, a guard, a channel, a foreign handle
    or a `CPtr` (NL2588, `reject_fnarg_capture_secret`,
    `reject_mutex_guard_capture`, `reject_ffi_handle_closure_capture`,
    `reject_ffi_handle_field_capture`), which their own rules keep in the
    block that made them;
  - read anything from outside it when it is written inside another arrow
    (NL2501, `reject_fnarg_capture_nested`).

  An arrow given to `expose` or `exposeWith` still captures nothing (NL2335,
  NL2589; `reject_secret_expose_capture`, `_forwarded`), an arrow handed on to
  a parallel form or `spawn` meets their rules where it runs
  (`reject_fnarg_capture_parallel_write`, `_spawn_write`,
  `tests/link/fnarg_capture_forward`), and a recursive function that passes
  itself a new arrow on every call meets the instantiation limit
  (`reject_fnarg_capture_recursion`). Escape analysis and the parameter
  attributes read a capture as an argument to the arrow, at the arrow's own
  parameter for it: what it names escapes only when the arrow keeps it, or
  hands it to something that does, so an object an arrow only reads may be an
  alloca and a parameter it only reads `readonly nocapture`
  (`mem_capture_read_stack`, `fnarg_capture_readonly`; the negatives are
  `mem_capture_forward_keep`, `mem_capture_callee_keep`). An element of a
  captured array is kept unless the arrow proved it keeps none, and a
  captured array is never one whose strings go to the caller with it
  (`mem_capture_element_keep`). The capture stays an escape, as it was before,
  when anything but an ordinary function stands between the call and the
  arrow (a data-parallel form, `spawn`, a task, an async function:
  `tests/link/mem_capture_parallel_forward`, `mem_capture_async`), and a
  captured `parts` array is not released by `join`, whose release depends on
  order rather than escape (`mem_join_parts_captured`). An arrow anywhere but
  as such an argument or as a top-level `const` is
  `` an arrow in value position is not yet a function reference: declare it as a top-level function and name it ``
  (`tests/cases/reject_fnarg_arrow_value`), or NL2731 when it captures
  ([Function references](#function-references)).
- **A function argument has exactly its parameter's type**, once the type
  parameters are bound, because the body calls it with those types and reads
  that result:
  `` Argument 1 of `apply`: `widen` is `(x: i32) => i64`, and `f` is `(x: i32) => i32`; a function argument must have exactly its parameter's type ``
  (`tests/cases/reject_fnarg_mismatch`). The argument must be the name of a
  top-level function, an arrow, or a local that holds a
  [function reference](#function-references) (`tests/cases/fnref_arg`): the
  call passes an arrow that captures the local by value, so the callee calls
  the function that was passed even if it reassigns where that came from
  (`fnref_arg_reassign`). An arrow passed there may call a reference it
  captures, narrowed first if it is nullable (`fnref_arg_capture`,
  `fnref_arg_capture_param`). A field or element would be read again at
  each call the callee makes, where JavaScript reads it once, so it is
  refused, `ops[next(b)]` and `b.op` alike:
  `` `ops[next(b)]` is read again at each call `twice` makes, where JavaScript reads it once at the call: read it into a `const` first and pass the `const` ``
  (NL2759, `reject_fnref_arg_effect`, `reject_fnref_arg_field`,
  `reject_fnref_arg_element_nullable`). A nullable local is passed once a
  test has narrowed it:
  `` `h` may be `null`, and `apply` calls it: pass it once a test such as `h !== null` has narrowed it ``
  (NL2760, `tests/wordings/nl2760_fnarg_nullable_reference`). A local that a
  later argument of the same call assigns is refused, since the call reads it
  after its arguments where JavaScript reads it before them:
  `` `h` is assigned by a later argument of `apply`, and the call reads it after its arguments where JavaScript reads it before them: read it into a `const` first and pass the `const` ``
  (NL2761, `reject_fnarg_ref_assigned_later`). A reference of
  another signature is refused as any other function argument is (NL2340,
  `tests/wordings/nl2340_fnarg_reference_arity`); any
  other value is refused and named by its type,
  `` `n` is `i32`, which is not a function `` (`reject_fnarg_not_name`). The
  builtins that check the body they are handed — `parallelMap`,
  `parallelMapInto`, `parallelReduce`, a scope's `spawn`, `expose`,
  `exposeWith`, `region` and `enterWith` — take only a function or an arrow
  named at the call, so a reference there is
  `` `h` is a function reference: `parallelMap` takes a top-level function or an arrow named at the call ``
  (NL2734, `tests/wordings/nl2734_fnref_to_function_parameter`). A generic function names no one function
  and is refused with the arrow to write instead (`reject_fnarg_generic_name`),
  and an arrow takes exactly its type's parameters (`reject_fnarg_arity`). An
  unannotated arrow parameter whose type no value argument binds
  (`reject_fnarg_infer`) and a block-bodied arrow whose result only it could
  bind (`reject_fnarg_block_return`) must be annotated.
- **Only a top-level function's parameter makes a function type a function
  parameter.** Written inline on a parameter of a method or a constructor, or
  of a function type that is itself a function parameter's, it is
  `` `f` cannot have a function type here: a function type may only annotate a parameter of a top-level function, which is monomorphised for each function it is given, and this is a parameter of a method or a constructor ``,
  with `a parameter of a function type` for the second
  (`tests/cases/reject_fnarg_method`, `reject_fnarg_nested`); a method or a
  constructor takes a reference through an alias instead. Anywhere else — a
  field, a local, an array element, a return type, an alias — a function type
  is the type of a [function reference](#function-references), and what is
  stored there is checked against it:
  `` Field `run` of class `Handler` is (i32) => i32 but its initializer is i32 ``
  (`reject_fnarg_field`),
  `` Return type mismatch: function returns (i32) => i32 but expression is i32 ``
  (`reject_fnarg_return_type`), and a reference local is initialised where it
  is declared, `` Variable `g` must be initialized `` (`reject_fnarg_local`).
- **Across modules**, an instantiation is made in the template's module
  (WP18 G7), so it may call a private function, or an arrow, of the module that
  asked. That callee is `hidden` rather than `internal` — in the final link,
  exported from nothing — and the template's module `declare`s it with the
  attributes of its `define` (`tests/link/fnarg_private`). A hidden symbol is
  still global in the executable, so one the program's own package declared,
  which carries no prefix, ends with a `$` (`@square$`): C cannot spell it,
  so a task called `read`, `write` or `free` is never the definition the
  runtime's calls into the C library reach
  (`tests/link/thread_scope_libc_named_tasks`, #610). The interop sidecars
  describe no instantiation that was given a function, and no lifted arrow:
  neither has a name a host could call.

### Function references

A name bound to a top-level function, in either spelling, written anywhere but
a call's callee or a function argument is a **function reference**
(a local holding one may itself be passed as a function argument, below): a value
of the function's type, `(x: i32) => i32`. A function type names a reference
everywhere but inline on a parameter of a top-level function
([Function parameters](#function-parameters)): on a local, a field, an array
element, a return type, a type alias, and a parameter typed through an alias.

```typescript
type Op = (x: i32) => i32;

const double = (x: i32): i32 => x * 2;
const negate = (x: i32): i32 => 0 - x;

class Stage {
  op: Op;
  constructor(op: Op) {
    this.op = op;
  }
  run(x: i32): i32 {
    return this.op(x);   // a direct call of the dispatcher for `Op`
  }
}

export const main = (): void => {
  const s = new Stage(double);
  console.log(`${s.run(5)}`);  // 10
  s.op = negate;
  console.log(`${s.run(5)}`);  // -5
};
```

- **What a reference can hold.** A function this program defines, at the top
  level of a module, that is not generic, not `async`, has no rest parameter
  and takes no function parameter, and whose arrow, if it is one, captures
  nothing. Each other kind is refused where it is named:
  - `` `id` is generic: a function reference names one non-generic top-level function ``
    (NL2725, `tests/cases/reject_fnref_generic`);
  - `` `later` is async: a function reference cannot hold it, because its call is a promise ``
    (NL2727, `reject_fnref_async`);
  - `` `abs` is declared in C: a function reference names a function this program defines ``
    (NL2728, `reject_fnref_ffi`);
  - `` `sum` has a rest parameter: a function reference names a function whose every parameter the caller passes ``
    (NL2729, `reject_fnref_rest`; a defaulted parameter the same, `nl2729_fnref_default`), and a written function type with a rest,
    optional or defaulted parameter,
    `` `(x: i32, y?: i32) => i32` has an optional parameter: a function reference names a function whose every parameter the caller passes ``
    (NL2729, `reject_fnref_type_optional`, `reject_fnref_type_rest`);
  - `` `bump` takes a `MutexGuard`: a guard is handed only to a function named at the call, so a function reference cannot name it; call the helper by name ``
    (NL2739, `tests/wordings/nl2739_fnref_guard`);
  - `` `apply` takes a function parameter, so it has no single body to refer to ``
    (NL2726, `tests/wordings/nl2726_fnref_template`), and a function type
    whose own parameter is written as a function type,
    `` `(g: (x: i32) => i32) => i32` takes a function parameter, so no function it could name has a single body to refer to ``
    (NL2735, `tests/wordings/nl2735_fnref_type_function_param`);
  - a method, `` `c.step` is a method: a function reference names a top-level function, and a method needs its receiver ``
    (NL2732, `tests/cases/reject_fnarg_alias`);
  - an arrow that captures,
    `` this arrow captures `k`: a function reference names a top-level function and carries no environment ``
    (NL2731, `reject_arrow_as_value`, `reject_fnref_capture`), and one that
    does not but is not a top-level `const`,
    `` an arrow in value position is not yet a function reference: declare it as a top-level function and name it ``
    (NL2336, `reject_fnarg_arrow_value`).
- **Where a reference goes.** It is held in a local, a field (of a class or an
  interface), an array element, a `Map` value or a return value, and passed as
  an argument to a parameter typed through an alias, of a function, a method
  or a constructor (`tests/cases/fnref_field`, `fnref_array`, `fnref_stores`,
  `fnref_generic`, `fnref_map`), or to an inline function-typed parameter
  ([Function parameters](#function-parameters), `fnref_arg`): that call
  passes an arrow that calls the reference, so the callee is instantiated for
  the call and calls through the dispatcher of the argument's place. A `Map`
  may hold an array of references or a nullable of either as its value
  (`fnref_map_array`, `fnref_map_nullable`); `??` on a nullable reference
  tests it against `null`, tag 0 (`fnref_nullable_coalesce`); a `Map` key may not be a reference,
  `` `(i32) => i32` cannot be the key type of `Map<(i32) => i32, i32>` ``
  (`reject_fnref_map_key`). A reference has no zero value: a local is initialised
  where it is declared (`reject_fnarg_local`), and
  `new Array<(i32) => i32>(n)` is
  `` `new Array<(i32) => i32>(n)` would zero-fill with 0, which names no function; build it with `[]` and `push` instead ``
  (NL2730, `reject_fnref_zero_fill`); `new Array<F | null>(n)` fills with
  `null` and is allowed, except as module storage, which holds no `| null`
  (NL2686, `reject_fnref_storage_nullable`). For the same reason an array of
  references has no `fill`, `unshift` or `splice`: `fill` is refused as a
  byte copy (`reject_fnref_row_fill`), the other two as an unknown method
  (`reject_fnref_row_unshift`, `reject_fnref_row_splice`). A module constant may not hold one
  (`` Module constant `alias` must be a number, boolean, string, or a `readonly` array of numbers written out as a literal, not (i32) => i32; there is no top-level code to build anything else ``).
  An arrow argument may capture a `const` reference local like any other
  value (`fnref_capture`).
- **What a reference does.** It is called — `h(3)`, `this.op(4)`, or
  an element called in place — and compared with `===` and `!==`, which are true when the two
  name the same function (`fnref_eq`). Nothing else: printing it, putting it in
  a template string or any other use is
  `` `f` is a function reference: it can be called, compared, stored and passed, nothing else ``
  (NL2737, `reject_fnref_print`, and as `JSON.stringify`'s argument,
  `reject_fnref_stringify`; a field, an element or a nullable reference
  alike, `reject_fnref_stringify_place`); `jsonEncode` refuses a type that holds one
  (`` `jsonEncode` cannot handle `Stage.op`, which is `(i32) => i32` ``,
  `reject_fnref_json`); `<` and the other orderings take numbers only (`reject_fnref_order`,
  `reject_fnref_order_gt`), as `+` and the other arithmetic does
  (`reject_fnref_arith`); and a
  function type inside another type prints in parentheses,
  `((i32) => i32)[]` (`reject_fnref_type_name`).
- **A reference may be `null`.** `F | null` holds a function or nothing: a
  field of that type starts `null`, `new Array<F | null>(n)` holds `n`
  `null`s, and in memory `null` is tag 0, a tag no function has. A call goes
  through it only once a test proves it holds a function, `h !== null` or an
  early `return` on `h === null`; a call before one is
  `` `h` may be `null`: a nullable function reference is called only after a test such as `h !== null` proves it holds a function ``
  (NL2758, `reject_fnref_nullable_call`). A field is not narrowed: read it
  into a `const` and test that (`reject_fnref_nullable_field_call`). A
  number is no reference, so a nullable field initialised with one is
  refused as a non-null one is (NL2013, `reject_fnref_nullable_field_literal`,
  `reject_fnref_nullable_field_negative`). The
  rules otherwise follow [Nullable types](#nullable-types)
  (`tests/cases/fnref_nullable`).
- **In memory a reference is an `i32` tag**, the function's position, from 1,
  among the program's functions of that signature: never an address. A call
  through it is a direct call of an internal **dispatcher**,
  `@$ref.<module>.<signature>.<n>`, that takes the tag and the arguments,
  switches on the tag and tail-calls each function directly, the last one as
  the `default` arm; there is no function pointer and no indirect call
  (`tests/cases/fnref_field`). Each place — a local or a parameter, a
  function's return, a field, and the elements of every array of one reference
  type (a `Map`'s values are such elements) — has a set, the functions that can flow into it, and a call dispatches
  over its place's set only: a set of one's dispatcher is one tail call with
  no `switch`, and an empty set's dispatcher traps (`fnref_empty_set`,
  `fnref_place_set`).
  The dispatcher carries the attributes its members share, so a call through a
  set whose members all leave an argument alone leaves it on the stack. A set
  that mixes members that keep a pointer argument with members that do not is
  refused,
  `` this call through `h` can reach `u3`, which keeps `p`, and `u0`, which does not, so every call here would allocate `p` in the arena; ... ``
  (NL2736, `reject_fnref_escape_join`, `fnref_escape_join`). `Map.get`
  reads the place a `Map`'s values share with the arrays of that type, so a
  call through what it returns dispatches over the functions stored into any
  of them (`fnref_map`, `fnref_place_set_map`); where one of those keeps a
  pointer argument the others leave alone, that call is the mixed set above
  and refused (`reject_fnref_place_set_map`). A `Result` arm is not a place,
  so a reference directly in one — `Result<F, E>`, `Result<F | null, E>`,
  `Result<T, F>`, including through a generic's type parameter — is refused,
  `` `Result<(i32) => i32, string>` cannot hold a function reference in an arm: ... ``
  (NL2762, `reject_fnref_result`, `reject_fnref_result_generic`); an array of references in an arm holds the
  element place and compiles (`fnref_result_array`). An assignment used as a value,
  `k((r = inc))`, stores into its target and hands the same function on
  (`fnref_assign_value`). A set past
  eight members is warning NL9017, a `switch` where a direct call would not
  branch (`tests/wordings/nl9017_fnref_wide_set`). Under `--profile debug` the
  dispatcher first checks that the tag is in its set and panics with
  `function reference holds a function outside its place's set` if it is not;
  the speed build checks nothing (`fnref_debug_check`). The IR is in
  [IR_COOKBOOK.md](IR_COOKBOOK.md#a-function-reference-in-a-field).
- **A reference does not cross to a host.** A tag means something only to this
  program's dispatchers, so in an open-world build (`-o`) an exported function
  whose parameter or return type holds a reference, or a class an exported
  signature reaches with such a field, is
  `` Parameter `f` of `apply` holds a function reference that code outside this program can reach: a reference is a tag this program's dispatcher reads, not an address, and a host could hand back one no dispatcher knows ``
  (NL2733, `reject_fnref_host`, `reject_fnref_host_field`,
  `reject_fnref_no_strict`, `tests/wordings/nl2733_fnref_host_return`). A
  closed-world `--link` build exports such a function between its own modules
  (`tests/link/fnref_cross_module`).

Still refused: a closure (an arrow that captures), a reference to a method, a
generic or an `async` function, and a reference as a `Map` key
(`reject_fnref_map_key`).

### Async functions: `async` and `await`

An `async` function is a task the compiler can size: it may wait, and every
wait is written `await` on a direct call
([wp49-async-server.md](wp49-async-server.md) §2). No expression ever has a
promise type, so there is no promise to store, pass or chain, and an awaited
call's frame nests in its caller's. **An `async` function compiles to a frame
and a resume switch** (`async_lowered`, `async_await_single`,
`async_await_chain`, `async_await_all`, `async_spawn`, `async_main`,
`async_result`): one that awaits becomes `i1 @f.resume(i8*)`, which picks up
at the state its frame records and answers whether it finished; one that
awaits nothing is a plain function, and awaiting it is a plain call. The
frames of a program are sized when it is linked, and `export async function
main` is resumed from the process entry until it finishes and its spawned
tasks are done (`async_main`). A task waits on the outside world with
`await sleep(ms)`, `await readable(fd)` or `await writable(fd)`: it is parked
on the executor's kernel wait (epoll, kqueue on Darwin) and the others run
until it is ready ([below](#waiting-on-a-timer-or-a-descriptor-sleep-readable-and-writable);
[wp49-async-server.md](wp49-async-server.md), "Stage 5, part 1"). A
program with no `async` function compiles byte for byte as before, and links
no executor; one
whose `async` functions are never called keeps them `internal`, as it would a
plain function (`async_unused`). A function that awaits loses `willreturn`
and `readonly`; one that does not keeps its attributes (`async_attributes`).
A failure is the answer's `Result`, `Promise<Result<T, E>>`, read after the
`await` as any other `Result` (`async_result`).

```ts
import { awaitAll, spawn } from "nish:async"

const double = async (x: i32): Promise<i32> => {
  return x * 2
}

const log = async (x: i32): Promise<void> => {
  console.log(x)
}

const run = async (): Promise<void> => {
  const a = await double(3)
  let b: i32 = 0
  b = await double(a)
  await log(b)
  const [c, d] = await awaitAll(double(1), double(2))
  spawn(log(c + d))
}
```

- **Who may be `async`.** A top-level `function` or an arrow, top-level or
  passed to a function-typed parameter. A method, a field or a constructor
  is `` Only a top-level function or an arrow may be `async` `` (NL1063,
  `reject_async_method`), because a task never keeps a `this`.
- **`Promise<T>` is only an `async` function's return type.** An `async`
  function without it is
  `` An `async` function's return type is `Promise<T>` `` (NL2655,
  `reject_async_function`, `reject_async_arrow_declaration`,
  `reject_async_return_missing`); `T` is written inside it, `Promise<void>` for none. Anywhere else — a parameter, a field,
  a local, a type alias, an interface member — `Promise<T>` is
  `` `Promise<T>` is only an `async` function's return type `` (NL2654,
  `reject_async_promise_parameter`, `_field`, `_local`, `_alias`,
  `_interface_member`).
- **`await` is written inside an `async` function**
  (`` `await` is only written inside an `async` function ``, NL2641,
  `reject_await`, `reject_await_constant`), **on a direct call to one**: `await x` on a value is NL2643
  (`reject_async_await_value`), `await` on a plain function's call NL2644
  (`reject_async_await_plain_call`). Inside an `async` function `await (f(x))`
  is the operator, as TypeScript reads it; outside one `await(f(x))` is a call
  to a function named `await`, NL2651 (`reject_async_await_parenthesised`).
- **`await` stands at the top of a statement**: an expression statement, a
  declaration's initializer, a `return` or the right side of a plain `=`.
  Inside another expression — an argument, a condition, an operand, a
  compound assignment — it would hold a value across the wait, and is NL2642
  (`reject_async_await_nested`, `_condition`, `_compound`); a `for`
  initializer is not a declaration statement, for `awaitAll` too
  (`reject_async_await_all_for`). Bind the answer to a `const` first.
- **A call to an `async` function is awaited where it is made**, or handed to
  `spawn` or `awaitAll`. Anything else would make a promise a value:
  `` `load` is `async`: a call to it is awaited where it is made `` (NL2645,
  `reject_async_unawaited_call`, `reject_async_unawaited_argument`).
  `.then` is NL2650 (`reject_async_then`), `Promise.all` NL2649 (`reject_async_promise_all`), and `for await` is
  `` `for await` is not supported here `` (NL2133,
  `reject_for_await_template`, `tests/wordings/nl2133_for_await`).
- **`nish:async` exports `spawn` and `awaitAll`**, reached only through the
  import. `spawn(f(x))` starts `f` as a task of its own and does not wait for
  it; it takes a direct call to an `async` function (NL2644), and since
  nothing reads its answer, `f` answers `void` or a `Result` it reports
  itself (NL2646, `reject_async_spawn_answer`). `awaitAll(f(x), g(y))` waits
  for two to eight calls at once and is awaited into one name per call,
  `const [a, b] = await awaitAll(f(x), g(y))`; one call, or an `awaitAll` not
  so destructured, is NL2647 (`reject_async_await_all_one`,
  `reject_async_await_all_bare`). So is a pattern over it that is not one
  plain name per call, each with the reason: an object pattern (the answers
  are read by position), a hole (it would drop an answer; name it `_b`), or
  a default, rest or nested slot (`reject_async_await_all_object`,
  `reject_async_await_all_hole`, `reject_async_await_all_default`).
- **An `async` arrow is passed only where it is awaited.** The parameter's
  function type answers `Promise<T>`, and the callee awaits each call to it.
  An `async` arrow where the type answers a plain `T` is NL2639
  (`reject_async_arrow`); a plain function where it answers `Promise<T>` is
  NL2640 (`reject_async_plain_to_promise_parameter`).
- **No recursion through `await`.** An awaited call's frame is nested in its
  caller's, so a cycle in the call graph that runs through an `await` has no
  size: `` recursion through `await` `` is refused at the `await` that closes
  the cycle, direct or mutual (NL2648,
  `reject_async_await_self`, `reject_async_await_mutual`). Write it as a loop.
- **A spawned task's arguments outlive the spawner.** `spawn(f(x))` may
  return, and its caller with it, while `f` still waits. A number, a
  `boolean` or an enum is copied by value, and a `string` is copied into the
  task's own region before the task first runs (`async_sleep_spawn_string`,
  `tests/link/async_spawn_args`). An object, an array, a `Map` or a `Set` is
  shared: the task holds the spawner's own, and sees and updates its numbers
  (`async_spawn_shared`). A function that feeds a task a shared argument,
  itself or through a callee, releases no arena scope over what it allocated,
  so the object outlives every task that holds it
  (`tests/link/async_spawn_shared_outlives`). An argument of any other type —
  `T | null`, a `Region`, a `Secret` — is
  `` `spawn` hands `f` an argument of type `T`, which lives in the spawner's
  region and is freed when the spawner returns `` (NL2673,
  `reject_async_spawn_array_arg`). A shared object or array that holds, in
  any field or element, a `Region`, a `Secret`, a handle class a `using`
  block closes, or a scope, lock, guard or channel of `nish/threads` is
  refused too, with what it holds named: its spawner may free, wipe or close
  that part while the task still waits (NL2691,
  `reject_async_spawn_region_field`, `reject_async_spawn_secret_field`,
  `reject_async_spawn_handle`, `reject_async_spawn_threads_field`).
- **A spawned task keeps its own memory out of what it shares.** The task's
  region is freed when the task ends, so the region rules hold it to a
  shared argument, and everything reachable from it, as memory outside its
  region ([Regions](#regions-nishregion)): storing an object or a `string`
  it made into a field or an element is NL2609, directly, through an alias,
  a method or a callee (`reject_async_spawn_store_region`, `reject_async_spawn_store_string`,
  `reject_async_spawn_store_alias`, `reject_async_spawn_store_method`,
  `reject_async_spawn_store_callee`, `reject_async_spawn_store_reachable`,
  `reject_async_spawn_store_element`, `reject_async_spawn_store_bound`,
  `reject_async_spawn_await_all`). A call that hands a function or method
  both a shared object it writes into and a `string` or object of the
  task's is NL2609 as well, since nothing says the one is not kept in the
  other (`reject_async_spawn_store_string_callee`,
  `reject_async_spawn_store_string_method`,
  `reject_async_spawn_store_copied`), and growing a shared array, `Map` or
  `Set` — `push`, `set`, `add`, `spawnPiped` or `spawnPipedWithin`
  appending to its output arrays, on the argument or on what a method answers out of it — is NL2615
  (`reject_async_spawn_grow`, `reject_async_spawn_grow_method`,
  `reject_async_spawn_grow_map`, `reject_async_spawn_grow_piped`), and so
  is a builtin with no body of its own that does either, `reserve` on a
  shared `Map` (`reject_async_spawn_grow_reserve`) or `jsonDecode` into a
  shared object (`reject_async_spawn_store_json`). Copy
  numbers into it instead. The task keeps none of what it shares in memory
  of its own: a shared object, or anything reachable from it, put into a
  constructor argument, an array or object literal, a field or element
  store, `push`, a `Map`'s `set` or a `Set`'s `add`, a method that may keep
  its argument in its receiver, or a callee that stores one argument into
  another is NL2610, as in a `region(...)` body
  (`reject_async_spawn_keep_holder`, `reject_async_spawn_keep_literal`), and
  so is an element read out of a shared array (`for (const t of shared)`,
  `reject_async_spawn_keep_element`). An object a helper makes may hold
  what the helper was handed, so in a task a fresh helper's answer other
  than a string, awaited or not, carries its arguments' origins too, and a
  store through a holder a helper built from the shared object is NL2609
  (`reject_async_spawn_keep_returned`). An argument is left out of that
  join only when the answer's type cannot reach it: no class, array or
  string type the answer may hold (through fields, elements, a nullable or a
  union) is one the argument may hold, and neither side holds a class that
  implements an interface. So a `PgAsyncResult` awaited from a query on a
  shared `PgAsyncPool` is the task's own, while a `Holder` of a shared
  `Tally` or a `Badge` of an interface `Tally` implements is still the
  shared object's (`reject_async_spawn_answer_reach`). Read and update the
  shared object in place instead. Three refusals are conservative, and known to refuse
  sound programs: a call that hands a callee both a shared object it writes
  into and any string or object of the task's, even when the callee writes
  only numbers; a store into the shared object of what an `await` answers
  (`const x = await helper(tally); tally.child = x`), since an awaited
  answer is unknown to the walk; and a store of the task's memory into a
  holder a helper answered from the shared object (`wrap(tally).note = s`),
  which may be the task's alone. A task may not itself spawn a task with an
  object or an array, directly or through a callee, since what it hands on may be its own region's (NL2689,
  `reject_async_spawn_nested`); a task with only copied arguments may.
- **A spawned task's function argument captures only what the task may
  share.** A top-level function, or an arrow written at the call, is a
  compile-time argument: the call is an instance with the function in its
  body (`async_spawn_fn_arg`). The arrow may read locals of the function it
  is written in when each is a number, a `boolean` or an enum, copied into
  the task's frame, or an object or array that holds, through any field or
  element, no `Region`, no `Secret`, no handle class and no `nish/threads`
  scope, lock, guard or channel. Its strings and nested objects are fine (a
  `PgAsyncPool` holds both). Any other capture is NL2690: a `string`, a
  nullable value or a union itself, or an object holding a `Region`
  (`reject_async_spawn_block_arg`, `reject_async_spawn_handler_holds_region`).
  A capture of a handle, or of an object holding a `Secret`, is refused
  sooner, by the rule for any arrow argument (NL2588,
  `reject_async_spawn_handler_holds_handle`,
  `reject_async_spawn_handler_holds_secret`); the capture rule refuses them
  as well, a check behind that one. A captured object is shared with
  the task as if handed to it: the spawner releases no arena scope over it,
  and the arrow's body is walked with the task's rules, the capture as memory
  the task does not own, so the arrow may update its numbers and call its
  methods (a serve handler awaiting a query on a captured `PgAsyncPool`) but
  may not store the task's memory into it or grow it (NL2609, NL2615,
  `async_spawn_handler_reach`, `reject_async_spawn_handler_*`). The arrow's
  parameters carry what the task passes at each direct call; one it reaches
  through a further function parameter is unknown, so storing it into a
  capture is refused. Each arrow is an instance of its own, so a refused
  arrow at one call site is not hidden by an admitted one at another.
- **Each spawned task has a region of its own**, entered whenever the task
  runs and freed when it finishes, so what a task allocates is given back
  when it ends, not when `main` does (`tests/link/async_region_per_task`).
- **Each `awaitAll` call has a region of its own**, made before it first
  runs and entered whenever it runs. When the call finishes, what it allocated joins the
  caller's memory, so an answer that points into it (a `string`, an array, a
  class) stays readable, and is given back when the caller's would be. So two
  calls that each hold memory across an `await` never free or overwrite each
  other's, whatever its size or whichever finishes first
  (`async_await_all_lanes_large`, `tests/link/async_await_all_lanes`). What a
  call allocates and does not answer is given back when it finishes, so its
  temporaries never reach the caller's memory
  (`tests/link/async_await_all_retain`). What the caller does keep is the
  answer and about 1.3 KB more per call, the unused end of the region's
  first block, until the caller's own memory is given back (ASYNC-17 in
  `docs/security/async.md`).
- **A `main` that never waits runs the loop too.** An `async` `main` that
  awaits nothing compiles to a plain call, as any such function does; one
  that spawns tasks returns first, then the executor runs every task it
  spawned, and the program exits with `main`'s answer once they are done
  (`tests/link/async_sync_main_loop`).
- **No `async` in a wasm build.** A task is resumed by the native event loop,
  which a wasm module does not have: under a `wasm32` target or
  `--profile wasi` an `async` function is NL2652 (`reject_async_wasm`,
  `reject_async_wasi_profile`).

#### Waiting on a timer or a descriptor: `sleep`, `readable` and `writable`

`nish:async` exports three waits on the executor. Each takes one `i32` and
answers a `boolean`, and each is written only where it is awaited:

| Call | Waits until | Answers `false` at once when |
| --- | --- | --- |
| `await sleep(ms)` | `ms` milliseconds have passed | `ms` is negative |
| `await readable(fd)` | `fd` has bytes to read, or its peer closed it | `fd` is not an open descriptor |
| `await writable(fd)` | `fd` can take bytes | `fd` is not an open descriptor |

A wait that is answered at once does not suspend the task. A regular file
never blocks, so `readable` and `writable` answer `true` for one at once.
While a task waits, the others run; when none can run, the executor blocks
in the kernel until a descriptor is ready or the first timer is due, and
resumes the tasks it woke: the descriptors in the order the kernel reported
them, then the expired timers, earliest deadline first, ties in the order
they were made (`async_sleep`, `tests/link/async_timer_order`,
`tests/link/async_readable`). A wait holds a duplicate of its descriptor, so
closing the descriptor while a task waits on it does not end the wait, and
the number's reuse cannot answer it ([`docs/security/async.md`](security/async.md),
ASYNC-4).

```ts
import { readable, sleep, spawn } from "nish:async"
import { netRead } from "nish:net"

const echo = async (fd: i32): Promise<void> => {
  const ready = await readable(fd)
  if (!ready) {
    return
  }
  const buf: u8[] = new Array<u8>(4)
  console.log(netRead(fd, buf, 0, 4))
}

const tick = async (): Promise<void> => {
  await sleep(10)
  console.log("tick")
}

export const main = async (): Promise<i32> => {
  spawn(echo(0))
  spawn(tick())
  return 0
}
```

- **A wait is awaited where it is written.** `sleep(10)` as a statement, as
  `spawn`'s argument or anywhere else a value would be kept is
  `` `sleep` is a wait on the executor, written only where it is awaited ``
  (NL2671, `reject_async_sleep_bare`, `reject_async_sleep_spawned`), and so
  are `readable` and `writable`.
- **It takes one `i32`**: `` `readable` takes one `i32` `` (NL2672,
  `reject_async_wait_argument`).
- **`readable` and `writable` have no deadline of their own.** A descriptor
  that never becomes ready parks its task until it does, or until the task
  is cancelled; `readableWithin` and `writableWithin`, below, take one
  ([`docs/security/async.md`](security/async.md), ASYNC-6).

#### Bounding a wait and cancelling a task

`nish:async` bounds a descriptor wait, and cancels a task, with six more
calls:

| Call | Answers |
| --- | --- |
| `await readableWithin(fd, ms)`, `await writableWithin(fd, ms)` | `true` once `fd` is ready; `false` when `ms` milliseconds passed first, when the wait could not be made, or when the task is cancelled. A negative `ms` waits without a limit |
| `taskId()` | the running task's handle, an `i64`; `main`'s is 0 |
| `cancel(task)` | `true` when the task was still running, so it is now cancelled; `false` for a finished task or `main` |
| `cancelled()` | whether the running task has been cancelled |
| `cancelAfter(task, ms)` | as `cancel`, `ms` milliseconds from now unless the task finishes first; a later call replaces the deadline, a negative `ms` removes it |

A cancel is cooperative: it never stops a task in the middle of its code.
Every `sleep`, `readable`, `writable` or bounded wait the task has parked
answers `false` at once, and every one it makes later answers `false`
without parking, so the task runs on to its end, its `using` bindings
dispose and its region is freed. A task that does not await is not reached
until it does. A handle names its task and no later one: a handle kept past
its task's end, once the executor reuses the task's slot, cancels nothing
([`docs/security/async.md`](security/async.md), ASYNC-18).

```ts
import { cancelAfter, cancelled, readableWithin, taskId } from "nish:async"

const serveOne = async (fd: i32): Promise<void> => {
  // The whole task gets two seconds; this one read gets half of one.
  cancelAfter(taskId(), 2000)
  const ready = await readableWithin(fd, 500)
  if (!ready) {
    console.log(cancelled() ? "cancelled" : "timed out")
    return
  }
}
```

- **The bounded waits are waits.** Each is written only where it is
  awaited (NL2671, `reject_async_within_bare`) and takes two `i32`s:
  `` `readableWithin` takes two `i32`s: the descriptor it waits on, and the
  milliseconds it waits at most before it answers false `` (NL2692,
  `reject_async_within_argument`).
- **The cancellation calls are plain calls**, written anywhere, the task's
  handle an `i64`: `` `cancel` from `nish:async` takes one `i64`, a task's
  handle from `taskId()` `` (NL2693, `reject_async_cancel_argument`).
- **`spawn` runs its task to its first wait** before it returns, so a cancel
  written after `spawn(f(x))` lands after `f` has run that far.
- `std/net/serve` cancels a handler's task when its client hangs up, when
  its `deadline` passes and when the server stops; the async `fetch` and the
  async Postgres pool answer a cancelled wait as a failure of their own
  (`tests/link/async_cancel`, `tests/link/net_serve_hangup`,
  `tests/link/std_postgres_async_cancel`).

**Where it is not Node.** The source is TypeScript and runs under Node, but
the resume order is not Node's, and these are declared differences:

| Node | Nish |
| --- | --- |
| Every `await` yields to the microtask queue, even on a value that is already there | An `await` on a call that finishes without waiting returns at once; nothing else runs in between |
| Microtasks run before I/O callbacks, in a defined order | Tasks resume in the order the kernel reports readiness, then by timer deadline |
| A rejected promise throws at the `await` | There is no `throw`: a failure is the call's `Result` or `null`, as every Nish call reports it |
| `spawn(f(x))` runs `f` to its first `await`, and the rest of `f` after the current task yields | `spawn(f(x))` runs `f` at once until it first waits on the outside world, then returns; a task that never waits has finished, its output printed, before `spawn` returns (`async_spawn`) |
| `setTimeout` and socket callbacks run on libuv's loop, which keeps the process alive while anything is registered | `sleep`, `readable` and `writable` park a task on the executor; the program exits once `main` has returned and no task waits, a synchronous `main` included |
| A `string` passed to a spawned call is a shared reference | It is copied into the task's region; an object, array, `Map` or `Set` is shared, and the task may store only numbers into it (NL2609, NL2615) and keep none of it in memory of its own (NL2610); one holding a `Region`, `Secret`, handle or `nish/threads` value is refused (NL2691), as is any other argument (NL2673) |
| A task that never awaits holds the thread, as here | The same: the executor is cooperative and does not preempt a task |

A program whose output does not depend on how its tasks interleave prints the
same under both.

**Under `--emit-ts`.** An `async` function, `Promise<T>`, `await`, an `async`
`main`, `spawn(f(x))` and `const [a, b] = await awaitAll(f(), g())` are
written as the TypeScript they already are, so the output runs on Node's own
async/await and resumes in Node's order, the left column above
(`tests/emit-ts/async/`). `nish:async` is `nish/runtime/async.mjs`: `awaitAll`
is `Promise.all` over its two to eight calls, and `spawn` starts its task
without awaiting it and keeps it. The launcher of a program that declares an
`async` function awaits `main`, then `settleTasks()`, which waits for every
task `spawn` started, those tasks' own included, before it exits, as the
native driver drains its queue. `await sleep(ms)` is a `setTimeout` that
answers `true`, or `false` at once for a negative `ms`
(`tests/emit-ts/async/sleep`); `readable` and `writable` have no Node
counterpart a task can await, so a program that calls either is
`--emit-ts cannot write readable or writable from nish:async` (NL4017,
`tests/emit-ts/async/refused-readable`), and so is one that calls
`readableWithin`, `writableWithin`, `taskId`, `cancel`, `cancelled` or
`cancelAfter`, since a Node promise is not a task the executor can cancel
(NL4018, `tests/emit-ts/async/refused-cancel`). A program whose spawned tasks print in an
interleaving prints the same lines in another order (`async_spawn`, the
`order` row of `tests/differential/emit-ts-known.txt`).

### Data parallelism: `nish/threads`

`parallelMapInto`, `parallelMap`, `parallelFrom` and `parallelReduce` run a
function over every element of an array, or every index of a new one, on as
many threads as the machine has and the length is worth
([wp29-thread-surface.md](wp29-thread-surface.md) §4.1). They are imported from
the standard library, and the function is a [function parameter](#function-parameters):
a top-level function by name, or an arrow written at the call — which may read
the `const` locals of the function it is written in
([below](#a-data-parallel-arrow-reads-its-functions-const-locals)).

```typescript
import { parallelFrom, parallelMap, parallelMapInto, parallelReduce } from "nish/threads";

const square = (x: f64): f64 => x * x;

export const main = (): i32 => {
  const src: f64[] = [1.0, 2.0, 3.0];
  const dst: f64[] = [0.0, 0.0, 0.0];
  parallelMapInto(src, dst, square);                         // dst[i] = square(src[i])
  parallelMapInto(dst, dst, (x) => x + 1.0);                 // in place
  const k: f64 = 2.0;
  const scaled = parallelMap(src, (x) => x * k);             // a new array: 2, 4, 6
  const halves = parallelFrom(3, (i) => toF64(i) / k);       // a new array: 0, 0.5, 1
  const total = parallelReduce(dst, (a, b) => a + b, 0.0);   // 17
  return toI32(total + scaled[2] + halves[2]);
};
```

- **The module is ordinary Nish, and its bodies are the meaning.**
  `std/threads.ts` writes each function as the sequential loop, which is what
  runs under Node and what `npm run check` type-checks. The compiler recognises
  the two templates by module and name and lowers one call in each instance —
  the loop over the whole range — onto `nish_parallel_range`
  (`runtime/runtime-parallel.c`), which cuts the range into contiguous pieces,
  up to eight per thread, that the threads claim one at a time as they finish
  the last, and joins them all before it returns. Everything else in the instance is
  emitted as written (`tests/link/par_map`, whose `threads.ll` is the whole
  lowering).
- **`parallelMapInto(src, dst, f)`** writes `f(src[i])` into `dst[i]` for every
  index of `src`. `dst` must be at least as long, which is checked once, before
  any element is written or any thread started: a shorter one panics with
  `parallelMapInto: dst has 2 elements and src has 3` and exits 1
  (`tests/link/par_dst_short`). `src` and `dst` may be the same array
  (`tests/link/par_map`).
- **`parallelMap(src, f)`** answers a new array of `f(src[i])` for every
  index of `src`, and **`parallelFrom(n, f)`** a new array of `n` elements,
  `f(i)` at index `i` — `Array.from({ length: n }, (_, i) => f(i))`. Each
  allocates its result on the calling thread before any element is computed,
  so nothing but the region can hold it while the threads write it, and then
  runs the map: `parallelMap` is `parallelMapInto` into that array, and
  `parallelFrom` the same region over the indices (`tests/link/par_map_new`,
  `tests/link/par_from`). `parallelFrom(0, f)` answers an empty array. The
  rules below hold of their `f` as they hold of `parallelMapInto`'s, except
  the one about `dst`, which nothing else can reach.
- **A short array is the loop it would have been.** A map is divided only
  once every thread's share carries enough work to pay for handing it to
  another thread ([wp20-threads.md](wp20-threads.md) §8e). How many elements
  that is — the *grain* — is sized per call from a static estimate of what
  `f` costs: 2^21 over the estimate, which counts one per operation, 32 per
  allocation, 4 per call, and a loop's body as many times as its literal
  bound says or 64 times when the bound is not a literal. A map longer than
  the grain is divided into `ceil(length / grain)` chunks, at most eight per
  thread with one thread per core, so the first division is two chunks of
  half the grain: 2^20 units each. That is where a measured body, `(x) => x + 1` at an estimate of 3,
  beat its loop by 1.31x on the minimum and 1.19x on the median, more than
  any difference between the loop and a byte-identical copy of it (at most
  3.3% and 9.1%); at two chunks of 2^19 units the minimum won by 1.16x and
  the median by only 1.04x, within that 9.1%
  ([wp29-thread-surface.md](wp29-thread-surface.md) §8a). So a body estimated
  at 3, such as `(x) => x + 1` or `(x) => x * x`, is divided past 699,050
  elements (`tests/link/par_map`), `(x * 31 + 7) % 1000` past 262,144
  (`tests/link/par_map_large`), a body with a loop far sooner, and a cheaper
  body later: `(x) => x`, estimated at 1, past 2,097,152. Up to the grain the
  map calls its loop directly on the calling thread, where it inlines; there
  is no hand-off and no indirect call. The estimate counts a call as a call
  and not as the callee's body, so a body that hides its work behind a call
  is divided too little rather than too much. There is no knob for the grain
  ([wp29-thread-surface.md](wp29-thread-surface.md) §9).
- **The threads are a pool, as many as the cores the process may use.** The
  first region or scope join that divides starts one worker per core but the
  caller's, which is the last of them, and at most 63 workers; they park
  between calls ([wp20-threads.md](wp20-threads.md) §8e). The core count is
  the smallest of the CPUs online, the process's affinity mask (`taskset`, a
  container's cpuset) and the cgroup v2 `cpu.max` quota rounded up, so a
  program in a container limited to two cores divides two ways, not as many
  as the host has. **`NISH_NUM_THREADS`**, when it is set to a positive
  number, lowers that count and never raises it: `NISH_NUM_THREADS=1` runs
  every region and every scope's tasks on the calling thread, in spawn order,
  and anything that is not a positive number is ignored. It is read once, by
  the first region or join that asks, and it decides only how the work is
  divided: a map's answer and a reduce's bits are the same at any count
  (`tests/run.js` runs every `tests/link/thread_*` and `par_*` program under
  `NISH_NUM_THREADS=1` and `=2` and requires the output it gave without). A
  Node addon (`--emit-napi`) keeps a thread per chunk or task for each call
  instead of a pool, because Node can unload it and a parked worker would
  outlive its code, and on WASI every region and task runs on the one thread
  there is.
- **`parallelReduce(src, f, identity)` is deterministic.** `src` is split into
  `min(64, ceil(n / 2^20))` blocks, each block is folded from `identity`, and
  the block results are combined left to right. `std/threads.ts` does the same
  blocking on one thread, so an `f64` sum is the same bits on one core or
  sixty-four, compiled or under Node — which is not the bits of a plain left
  fold over the array (`tests/link/par_reduce`). The blocks are part of the
  answer, so where block `k` starts, `floor(n * k / blocks)`, is computed
  exactly even where `n * k` passes 2^31 (`tests/link/par_reduce_blocks`, 64
  blocks over 70,000,001 elements). An empty `src` answers
  `identity`. For that to be the fold it looks like, `f` has to be associative
  and `identity` its identity. An arrow whose whole body is one operator on its
  two parameters is held to both: a non-associative one is
  `` `(a, b) => ...` combines with `-`, which is not associative: `parallelReduce` folds each block from the identity and then combines the blocks, which is a left fold only for an associative operator ``
  (`-`, `/`, `%`, `**` and the shifts; `tests/cases/reject_par_reduce_operator`),
  and a recognised one given anything but its identity — `0` for `+`, `|` and
  `^`, `1` for `*`, `true` for `&&`, `false` for `||`, written as a literal — is
  `` `parallelReduce` folds every block from its identity, and the identity of `+` is `0`, not `1`: any other value would be counted once per block ``
  (`tests/cases/reject_par_reduce_identity`). **A named function is opaque**:
  its associativity, and the identity it is given, are its author's promise,
  and a wrong one gives a deterministic answer that is not the fold.
- **Importing `nish/threads` compiles the program with `--threads`**, because
  every worker bumps an arena of its own: `@nish_arena` is declared
  `thread_local` in every module and the runtime is built with
  `-DNISH_THREADS` (`tests/link/par_map`). A program that does not import it is
  compiled exactly as before.

What makes a region safe to run on several threads is checked at the call,
from the whole-program facts, and each rule is reported there:

- **The function writes nothing its caller can see.** A store through a
  parameter, a call that makes one, or a runtime call that writes — `console.log`
  included — is
  `` `bump` writes memory its caller can see at main.ts:10:3, and `parallelMapInto` runs it on several threads at once: a parallel body may read what its caller owns and write nothing but its result ``,
  naming the write, or the callee that makes it (`tests/cases/reject_par_shared_write`,
  `reject_par_shared_write_via`, and `reject_par_console_log`, which names the
  runtime's `nish_print`). A method of an
  [atomic](#atomics-atomici32-and-atomici64) — `add`, `max` and the rest — is
  the one shared write a body may make (`tests/link/par_atomic`). A bounds
  check, an integer division, the length
  check of `new Array(n)` and `panic` are not writes: each prints and exits,
  and nothing runs again to see memory. When several threads panic at once,
  the first claims the program: it prints its whole message and exits 1, and
  every later one waits for that exit without printing, so a failing run
  prints one message, never two or a mix of them
  (`tests/link/par_panic_once`, `thread_panic_once`). Output is a write —
  `console.error` and `process.exit` as much as `console.log`
  (`reject_par_console_error`, `reject_par_process_exit`). Reading a shared
  `Map` or `Set` that an element or a capture reaches, with `get`, `has` or
  `size`, is a read (`tests/link/par_map_table_reads`); `set`, `delete`,
  `clear` and iterating one, whose walk counts itself on the table, are writes
  (`tests/cases/reject_par_map_set`, `_delete`, `_clear`, `_values`). Handing a helper a number, a
  `boolean`, an enum or a `string` — a `string` element of the caller's array
  included, `verify(hashes[k])` — gives it no slot to store into, so it is a
  read (`tests/link/thread_bcrypt_batch`, whose task verifies against the
  parent's hashes). The instance performs every store itself, into slots the
  partitioner has made disjoint, so a function that writes nothing cannot race.
- **A store into an array only this call reaches is not a shared write.** A
  `const` the function binds to its own array literal or `new Array(n)` —
  one whose elements are not stored inline — is *private* while every use of
  it is an element, a store into a slot, `.length`, an array method, a
  `for...of`, or an argument of a function that keeps nothing of it. Such a
  function may fill it, `push` onto it, or hand it to a helper that writes
  through its parameter, and still write nothing its caller can see: the
  helper's writes through that parameter land in the private array
  (`tests/link/thread_task_private`, whose body takes its element apart into a
  scratch array). Returned, stored, pushed, bound to a second name (in any
  declarator), named in an arrow, or handed to a function or a constructor that
  keeps it, the array is shared, and so is every store into it
  (`tests/cases/reject_par_private_kept`; the scoped-task twins below). What a
  private array's slots hold is not private: a store into `rows[0][0]`, or a
  helper that makes one, writes what `rows[0]` reaches
  (`reject_par_private_helper_deep`).
- **Nor is a write into an object's own slots, when the object is one this
  call made.** A `const` bound to the function's own `new` or object literal
  is memory no caller, thread or task can see while the call runs, so a method
  or a function that writes only that object's own fields — scalar state such
  as an `Rng`'s — writes nothing shared: `const r = new Rng(seed);
  r.nextI32()` is a body's own business (`tests/link/std_random`). That is
  the whole of what is admitted. A write below the object's own slots, into a
  field or an element of it, counts as a write into whatever it may hold, and
  once a constructor, a store, a `push`, a `Map` or a `Set` has put the
  caller's memory there, or memory of unknown origin, that write is refused
  as any shared write is: `hs.push(box); hs[0].bump()`, `h.b = box;
  h.b.bump()`, a constructor that keeps `box`, a method that forwards to a
  field's method, `o.a.b = box`, and the same with a captured `Rng`
  (`tests/cases/reject_thread_task_private_object_element`, `_field`,
  `_ctor_alias`, `_capture`, `_map`, `_set`, `_nested`, `_array_own`,
  `_forward`, `_forward_store`, `_array_rng`, and
  `reject_par_private_object_field_rng`, `_array_rng`, `_for_of`, `_held`,
  `_kept`). Freshness is not followed through a call: an object a helper made
  and returned is not one this call made.
- **What the function allocates dies with its element.** A function may build
  strings, arrays and objects on the way to its result. They are given back
  after every element: the function gets an arena scope of its own, so each
  call marks the arena of the thread it runs on and releases it before it
  returns, and a map over a million elements holds one element's temporaries
  at a time (`tests/link/par_alloc`). Under glibc, a program that has divided
  a region or joined a scope on other threads keeps the memory a release
  gives back rather than returning it to the kernel, so an element or a task
  that builds a 1 MB temporary does not fault it in again on every call: 200
  tasks that each build one took 48 ms on 1 thread, against 314 ms when every
  release trimmed the heap. A worker that then finds no work for a second
  gives the memory back to the kernel before it parks, its own heap included:
  after ten rounds of 8 tasks that each build a 16 MB temporary, an idle
  program holds 2.3 MB rather than 68 MB, and after four maps of 1.2 million
  strings on four threads, 2.3 MB rather than 82 MB
  (`tests/link/par_map_idle`). With no worker (one CPU, or `NISH_NUM_THREADS=1`) nothing
  parks, so nothing gives memory back early: what a join freed is kept up to
  the 64 MB at which glibc returns the top of the heap by itself. A region below its grain runs as the loop it would
  have been, on the calling thread, and keeps that loop's costs: 200 elements
  that each build a 1 MB temporary take some 320 ms, as the loop does. It
  compiles with a performance warning,
  NL9012, because every element pays for the allocation and the release:
  `` the body of this `parallelMapInto` allocates per element: `label` answers `i32` but allocates on every call, so each thread marks and releases its arena around every element. Compute the answer without building a string, an array or an object to save both ``.
  Two things make that release unsound, and each is refused. An allocation
  stored into memory, which the escape analysis stops following, is
  `` `width` allocates at main.ts:21:21 and stores the allocation into memory, and `parallelMapInto` releases what a body allocates after every element: a parallel body may allocate only temporaries it drops before it returns, and this analysis stops following a value once it is stored ``
  (`tests/cases/reject_par_alloc_escapes`). And a function that reads or moves
  the arena would see the arena of whichever thread ran the element:
  `` `used` reads or moves the arena, and `parallelMapInto` runs it on several threads that each have an arena of their own: a parallel body may not call `Arena.mark` or `Arena.used`, nor open a `using a = arena()` block, nor call `region`, `regionWith`, `child`, `childWith`, `enter`, `enterWith` or `free` (`nish:region`) ``
  (`tests/cases/reject_par_arena`).
- **A map's result `U` is a number, a `boolean`, an enum, a `string`, or an
  array of numbers, booleans or enums**, because the element's memory is
  released before the next element runs and a worker's arena is freed when
  its thread exits. A string or a scalar array crosses by copy-at-join, and
  the caller then adopts it: as the chunk loop rewinds its arena after each
  element, it moves the answer to the end of the chunk's transfer block, a
  `malloc`'d block of 4 KB doubling to 64 KB, or of the answer's size when
  that is larger (`nish_cross_keep`). Once every chunk has finished, blocks
  holding 64 KB or more in all are linked into the caller's arena's chunk
  list (`nish_cross_adopt`), so the answers stay where they are and the join
  costs one link per block rather than a copy per element; less than that is
  copied into the caller's arena and the blocks freed, so a small map run in
  a loop does not leave a chunk behind on every run
  (`tests/link/par_map_join_small`). Adopted blocks are then the
  caller's arena memory like any other, given back when the caller's scope
  releases what the result was made in, exactly when a copied value would
  have been (`tests/link/thread_adopt_lifetime`); a result the body did not
  allocate — a literal, a string it was handed — is not moved at all
  (`tests/link/par_map_string`: `parallelMap`, `parallelFrom` and
  `parallelMapInto` into a `string[]`, under `churn()`). Anything else — an
  array of strings, of arrays or of objects, a `Map`, a `Set`, a class — is
  `` `name` answers `string[]`, and `parallelMapInto` hands back only a number, a `boolean`, an enum, a `string` or an array of numbers, booleans or enums, which the join copies out of the worker's arena: anything else would point into memory the worker frees or reuses ``
  (NL2348, `tests/cases/reject_par_result_type`; `reject_par_map_result_strings`
  for `parallelMap`), because its copy would have to follow every element.
  `parallelMap` and `parallelFrom` allocate their result before the region, so
  theirs is refused there, before `std/threads.ts` is instantiated
  (`reject_par_map_new_result_class`, `reject_par_from_result_type`).
  A map of 1M short strings, `` `s${x % 100000}` ``, took a median of 23 ms
  on 4 threads and 24 ms on 8, against 38 ms for the same loop written
  sequentially, and peaked at 32 MB against the loop's 55 MB. On 1 thread it
  is the loop's time: 54.9 ms against the loop's 57.6 ms and its copy's
  56.4 ms, minima of 9 interleaved rounds on one machine. It used to take
  72.8 ms there, because the mark sat at the end of the full chunk the result
  had filled, so every element's body allocated a fresh 64 KB chunk and the
  rewind freed it; the rewind now keeps that chunk, emptied
  (`tests/runtime-test.c`'s `test_cross_keep_rewind`). Before adoption, when the
  caller copied every string into its arena one at a time, the map took
  56 ms on 4 threads and peaked at 67 MB; two byte-identical copies of that
  binary differed by 5 ms in the same 7 interleaved rounds. What
  the body allocates for an element is released with that element, also when
  the body stores what it builds into an array literal on the way, which the
  arena scope above does not cover: the chunk loop marks the arena before each
  call and keeps only the answer
  (`nish_cross_keep` moves it to the transfer block and rewinds to the mark;
  on the sequential path, below a map's grain, it copies it out and back).
  A body that builds a 2 KB string, stores it in an array literal and answers
  a 4-byte slice of it, over 1M elements, peaks at 32 MB on 1 thread and on
  8 (63 and 67 MB before adoption), where it used to hold every element's
  temporaries until its chunk ended and peaked at 2.1 GB
  (`tests/link/par_map_release`).
- **A frame that runs a map gives its result back when it returns.** A
  function that calls `parallelMap`, `parallelFrom` or `parallelMapInto` and
  lets nothing the map made outlive it frees the result array, and the blocks
  a string map adopted from its workers, when it returns, as the same loop
  written sequentially does. A result that is returned, stored into a field
  or an outer array, captured by a later task, or nested in an array of arrays
  is kept with whatever holds it (`tests/link/par_map_reclaim_escapes`). A
  function that maps 2^22 elements and answers one of them, called 40 times
  on 4 threads, takes 140.3 ms and peaks at 33.8 MB, where it took 493.3 ms
  and peaked at 658 MB: 1.87x its sequential loop (262.3 ms) instead of 0.56x
  (main against a byte-identical copy of itself: about 2%). One call over
  2^25 elements is unchanged, 251.3 against 252.5 ms, inside that band
  (`tests/link/par_map_reclaim`).
  A string map's result handed to a function whose `string[]` parameter keeps
  none of it, reading it or handing it on only to another such parameter, is
  still freed with the frame: 72 string maps over 2^17 whose frames each pass
  the array to such a callee peak at 20 MB on 1 thread and 22 MB on 8, where
  they peaked at 237 MB. The parameter keeps it, and the frame keeps the
  strings, when the callee stores the array or one of its strings into a
  field, an outer array or a `Map`, returns either, passes it to `new` or to a
  constructor that hands `this` out, stores it through any declarator of a
  statement or through a local alias, or hands it to a callee that keeps it,
  and whenever the callee holds an arrow, such as a map's body; the proof
  covers a parameter typed `string[]` exactly, so one typed `string[][]` keeps
  the strings it reaches (`tests/link/par_map_reclaim_strings`).
- **A reduce's `T` stays a number, a `boolean` or an enum.** It is the
  element, the identity and every partial as well as the answer, folded on
  several threads, so a string would be copied at every combine; a reduce over
  strings or objects is refused at the call:
  `` `(a, b) => ...` answers `string`, and `parallelReduce` hands back only a number, a `boolean` or an enum: a worker's arena is freed when its thread exits, so anything else would point into freed memory; answer a number and fold those, or run it on the thread that called it, `let joined: string = ""; for (const b of words) { const a = joined; joined = a + b }` ``
  (NL2348, `tests/cases/reject_par_reduce_result_type`, and
  `reject_par_reduce_result_class` for a class). Map the strings to numbers
  first — `parallelReduce(parallelMap(names, (s) => s.length), ...)`.
- **`dst` is not reachable from an element of `src`.** A function that only
  reads can still read `dst` through its argument while another thread writes
  it, so an array of `dst`'s element type reachable from `T`, through fields,
  elements and `| null`, is
  `` `(r) => ...` can reach a `f64[]` through `r.cells`, which could be the array `parallelMapInto` is writing: another thread would be writing it while this one reads, so `dst` may not be reachable from an element of `src` ``
  (`tests/cases/reject_par_reaches_dst`). It is judged by type, so such an
  array is refused whether or not it is `dst` at run time. A global `Map` or
  `Set` reaches only what it stores: its own arrays are private to it, so a
  `Map<string, i32>` beside a `dst: i32[]` is not refused
  (`tests/link/par_map_read_into`, `par_map_read_into_keys`,
  `par_map_read_capture`), while a `Map<string, i32[]>` is, through
  `x.index.get(k)` (`tests/cases/reject_par_map_value_dst`). A program's own
  class named `Map` is walked like any class
  (`tests/cases/reject_par_map_user_class`). A reduce writes no
  array of its caller's and has no such rule.

#### A data-parallel arrow reads its function's `const` locals

An arrow passed to one of the four forms may read the `const` locals and the
parameters of the function it is written in, and so may an arrow given to a
scope's `spawn`, by the rules of [scoped tasks](#scoped-tasks-using-s--scope).
An arrow given to any other function-typed parameter of a top-level function
captures too, by the sequential rules of
[function parameters](#function-parameters) (`tests/cases/fnarg_capture_local`);
the rules below are the stricter ones a body that runs on other threads keeps.

```typescript
import { parallelMapInto } from "nish/threads";

export const main = (): i32 => {
  const k: i32 = 3;
  const table: i32[] = [10, 20, 30, 40];
  const xs: i32[] = [1, 2, 3, 4];
  const dst: i32[] = [0, 0, 0, 0];
  parallelMapInto(xs, dst, (x) => table[x % 4] * k);   // 60 90 120 30
  return dst[0];
};
```

- **Each name the body reads is a parameter of the body.** The checker
  appends it to the arrow's parameters after the ones it wrote, and the call
  passes the local's value through every instance on the way to the body and
  through the region's context with the other arguments, so a scalar is
  copied and a reference is passed as the pointer it is
  (`tests/link/par_capture`, and `tests/link/par_capture_large`, whose regions
  divide). A narrowing in force at the call holds in the body, because a
  `const` cannot change: `if (w !== null)` around the call lets the body read
  `w.scale`. No closure is made: the arrow is still a function of its own, with
  a direct call to it.
- **A captured reference is read-only.** A store through it — an element, a
  field, `push`, `pop`, `fill` or `set`, through a second name the body binds
  to it, or through an object or an array of the body's own that holds it — is
  a store into memory the caller owns, and is refused as any shared write is
  (`reject_par_capture_element_write`, `_field_write`, `_push`, `_pop`,
  `_fill`, `_set`, `_map_set`, `_alias`, `_alias_object`, `_alias_literal`,
  `_nested_array`, `_param_write`, and
  `_reduce_write` and `_into_write` for the other forms). So is handing it to a
  function or a method that writes it (`_helper`, `_method`). Assigning to the
  name itself is
  `` The arrow assigns to `k`, which belongs to the function it is written in: a data-parallel body reads a captured value and never writes it, because every thread reads the same one; answer the value from the body instead, and read the answers from the array the call gives back, `const kValues = parallelMap([1, 2], (x): i32 => x)` ``
  (`reject_par_capture_assign`, and `reject_par_capture_update` for a `k++`
  after a read). A reducer that assigns to one is shown the same
  `parallelReduce` without the write,
  `` answer the value from the reducer instead, and let `parallelReduce` fold it, `const callsTotal = parallelReduce([1, 2, 3], (a, b): i32 => a + b, 0)` ``.
- **A `let` is not captured**, since it could change between the call and a
  thread's read of it:
  `` The arrow reads `m`, a `let` of the function it is written in: a data-parallel body may read only a `const` or a parameter of that function, whose value no thread can change while the body runs; bind the value to a `const` before the call, `const mNow = m`, and read `mNow` in the arrow ``
  (`reject_par_capture_let`).
- **Only an arrow written directly in a function's body captures.** An arrow
  inside another arrow reads nothing from outside itself, neither the
  function's locals nor the outer arrow's parameters:
  `` The arrow reads `k` from outside the arrow it is written in: only an arrow written directly in a function's body may read that function's `const` locals and parameters, and an arrow inside another arrow reads only its own parameters and the module's top-level names; move the inner call into a top-level function that takes the value as a parameter ``
  (`reject_par_capture_nested_arrow`, `reject_par_capture_nested_param`).
- **`this` is not captured by that name**, nor a field through it; bind it,
  or what the body needs of it, to a `const` first:
  `` The arrow reads `this`: a data-parallel body may read the `const` locals and the parameters of the function it is written in, and `this` is neither; bind it, or what the body needs of it, to a `const` before the call (`const self = this`, `const k = this.k`) ``
  (`reject_par_capture_this`). This is a matter of spelling, not of safety: a
  capture becomes a parameter of the arrow, and a parameter named `this` is
  what makes a function a method to every analysis that reads one. A `const`
  bound to `this` is captured as the object reference it is, read-only like
  any other (`const self = this`, in `tests/link/par_capture`).
- **A captured name is read at the call.** The body runs where the call is,
  so the rules that follow a local of the function through its reads count a
  capture as a read of that local there. Three refuse: a destination of a
  scope's task read through a capture before the scope joins, by any of the
  four forms and on a loop's later pass (`reject_par_capture_scope_dst_index`,
  `_indexof`, `_for_of`, `_large`, `_map`, `_map_into`, `_reduce`, `_loop`), an
  element reference read through a capture after a `push` or a `pop` may have
  moved its storage (`reject_par_capture_stale_record`, `_into`, `_loop`,
  `_pop`, `_for_of`, `_helper`), and an array read through a capture after
  `secret(raw)` took it (`reject_par_capture_secret_moved`), each with the
  rule's own message. Two warn under `--warn-portability`, at the read inside
  the arrow as at a direct one: a record copied into an array and written
  through one copy (NL8003, `tests/link/port_rec_capture_copy`, and
  `port_rec_capture_quiet` for a read before the write), and a byte offset
  compared with a count or answered by the arrow, which stores it in the
  form's array (NL8001, `tests/link/port_str_capture_offset`,
  `port_str_capture_result`). A captured name is not a parameter of the
  arrow to NL8009, which reports it where its function declares it
  (`tests/link/port_num_capture_wide`).
- **Some values are never captured**: a `Mutex`, its guard, a `Channel` or a
  scope, which are shared only by their own block's rules, a `Result`, a value
  that may be absent, a `Secret`, or anything that reaches one of them:
  `` The arrow reads `m`, which is `Mutex<i32>`, and a data-parallel body cannot capture it: a scope, a lock, a guard or a channel is shared only by the rules of its own block ``
  (`reject_par_capture_mutex`, `_guard`, `_channel`, `_scope`, `_result`,
  `_maybe`, `_secret`; `_mutex_field` for a lock in a field of a captured
  object, `_mutex_map` for one in a `Map`'s values). A body that runs a data-parallel form of its own is
  refused as a shared write, captures or not (`reject_par_capture_nested_parallel`).
- **`dst` is not reachable from a capture either.** A captured array of `dst`'s
  element type, or a captured value that reaches one, could be `dst`, which
  other threads are writing while the body reads it:
  `` `(x) => ...` reads `dst`, and can reach a `i32[]` through `dst`, which could be the array `parallelMapInto` is writing: another thread would be writing it while this one reads; a captured array is known not to be `dst` only when one of the two is a `const` bound to an array of its own, such as a literal or a `new Array`, and the other is another such `const` or a parameter ``
  (`reject_par_capture_dst`, `_dst_alias`, `_dst_field`, `_dst_param`;
  `_self_field_dst` for `self.out` while `this.out` is `dst`, and
  `_generic_same_dst`, refused in each of two instantiations). A
  capture is a binding the call can name, so one case is admitted by
  identity: a captured array and a `dst` that are two different bindings, one
  of them a `const` bound to an array of its own and the other another such
  `const` or a parameter of the function, as `table` and `dst` are above. A
  fresh array is memory no binding held before it was made, and a parameter's
  value was fixed before the function ran (`tests/link/par_capture`, where a
  parameter table, and two fresh `const`s in a generic function, are
  admitted). Two parameters may be one array and are refused. `parallelMap`
  and `parallelFrom` allocate their own `dst`, which no capture can reach.
- **A fresh `dst` nothing was handed is apart from every capture** (#612).
  When `dst` is a `const` bound to an array of its own, and nothing before the
  call — or in a loop around the call that does not also declare it, or in a
  function written inside — names it except to index it or read a member, then
  no capture can reach it: the only way into a value is through a binding, and
  none was given this one. So the body may read a `parallelMap` result, a
  config object or a `const self = this` beside it
  (`tests/link/par_into_fresh_pipeline`, `par_into_fresh_object`); indexing
  it, reading `d.length`, calling `d.fill(0)` or walking it with `for...of`
  first hands it to no one (`par_into_fresh_reads`). Anything that hands
  `dst` on first is refused with the message above: a store `p.arr = d` or
  `this.tab = d` (`reject_par_into_store_field`, `_this_field`), an argument
  `keep(h, d)` or `ts.push(d)` (`_helper`, `_push`), an alias `const e = d`
  (`_alias`), a branch `c ? d : w` (`_ternary`), a holder `new Holder(d)`
  (`_holder`), a store after the call inside a loop around it
  (`_loop_store`, and `_loop_store_while`, `_do`, `_for_of` for the other
  loops) — the outermost such loop, so a store after an inner loop
  inside an outer one counts (`_nested_loop`) — a hand-on on one branch of
  an `if` (`_if_branch`), an
  earlier call writing the same `dst` (`_twice`), `dst` passed as the call's
  own `src` (`_as_src`), and the arrow reading `dst` itself (`_captured`). A
  `dst` bound to a captured array is no fresh `const` (`_from_capture`). The
  rule asks for the one binding of that name in its function, so a `dst`
  whose name is declared twice there keeps the stricter rule above
  (`_shadow`).

### Scoped tasks: `using s = scope()`

A scope runs a handful of different functions at once, each on a thread of its
own, and joins them all when the block that declares it ends
([wp29-thread-surface.md](wp29-thread-surface.md) §4.2). It is the shape
`parallelMapInto` cannot take: work that is not one function over one array.

```typescript
import { scope } from "nish/threads";

const sumOf = (xs: f64[]): f64 => { /* ... */ return 7.0; };
const primesBelow = (n: i32): i32 => { /* ... */ return 168; };

export const main = (): i32 => {
  const xs: f64[] = [1.5, 2.5, 3.0];
  const sums: f64[] = [0.0];
  const counts: i32[] = [0];
  {
    using s = scope();
    s.spawn(sumOf, xs, sums, 0);           // sums[0] = sumOf(xs)
    s.spawn(primesBelow, 1000, counts, 0); // counts[0] = primesBelow(1000)
  }                                        // both have run, and both answers are stored
  console.log(`${sums[0]} ${counts[0]}`);  // 7 168
  return 0;
};
```

- **`s.spawn(entry, arg, dst, at)`** runs `entry(arg)` on a thread of its own
  and stores the answer in `dst[at]` (`tests/link/thread_scope_basic`). `entry`
  is a [function parameter](#function-parameters): a top-level function named
  at the call, or an arrow written there, which may read its function's
  `const` locals (below). `at` is checked at the spawn and
  again when the answer is stored; out of range is
  `spawn: destination index 3 is out of range for an array of 1 elements` and exit 1.
- **`s.spawn(entry, arg)` and `s.spawn(() => ...)` have no destination.** The
  task runs as any other does and its scope stores nothing when it joins, so
  `entry` answers `void`: it is seen through the guard of a
  [`Mutex`](#a-lock-that-owns-its-data-mutext) its argument or a capture
  reaches, or through a [`Channel`](#channels-channelt) it sends on
  (`tests/link/thread_task_void`, `thread_task_arrow`). A block body is `void`
  without an annotation. An entry that answers a value is
  `` `sumOf` answers `i32`, and a `spawn` without a destination stores nothing: a task's answer is kept only by `s.spawn(entry, arg, dst, at)`, which stores it in `dst[at]` when the scope joins, so make the task answer `void` or give it a destination, `const answer2 = new Array<i32>(1)` above the scope's block and `s.spawn(sumOf, xs, answer2, 0)` ``
  (NL2511, `tests/cases/reject_thread_task_void_result`, and `_arrow` for
  `() => sumOf(xs)`). TypeScript would spell the three forms as overloads;
  the checker picks `ThreadScope`'s method by the number of arguments,
  `spawnWith` for two and `spawnThunk` for one, and under Node every form
  reaches `spawn`, which runs a task without a slot at once
  ([RUN_UNDER_NODE.md](RUN_UNDER_NODE.md)).
- **An arrow task reads its function's `const` locals and parameters**, which
  is the whole spelling of a task that needs more than one value:

  ```typescript
  {
    using s = scope();
    s.spawn(() => binInto(xs0, hist));   // xs0: a `const` array; hist: a `Mutex`
    s.spawn(() => binInto(xs1, hist));
  }
  ```

  Each name the arrow reads is appended to its parameters, as a
  [data-parallel arrow](#a-data-parallel-arrow-reads-its-functions-const-locals)'s
  is, and copied into the task's payload at the spawn beside its argument; the
  task reads it on its own thread when the scope joins. A capture **is the
  task's argument to every rule of this section**: the parent may not write
  what it reaches before the join, however it does so — a store, a second name
  for it, a helper, a `new` whose constructor writes it or keeps `this` in it,
  in a scope bound by any declarator of its `using`
  (`tests/cases/reject_thread_task_capture_parent_write`, `_alias`, `_helper`,
  `_new`, `_this_escape`, `_declarator`); a destination is never captured
  (`_dst`); the task writes nothing its caller can see except through a guard,
  a constructor it runs included (`_task_write`, `_task_new`,
  `_task_this_escape`); a `Mutex` it captures is one the parent may not lock
  before the join (R7, `_mutex_lock`) and that it may reach only as a capture
  or a field of one (R8,
  `` The task's arrow reads `o`, which is `Outer` and reaches a `Mutex` through `o.inner.m`: a captured value is the task's argument, … ``,
  NL2510, `_mutex_deep`); the parent's `orReturn` before the join is refused
  (NL2394, `_or_return`); a captured element reference is read at the join,
  so a `push` that may move its storage before the end of the block is
  NL2290 (`_stale_record`, `_stale_join`, and
  `reject_thread_task_arg_stale_join` for a task's argument, read at the join
  the same way); and an array moved into a `Secret` is not read again
  (NL2445, `_secret_moved`). A `let` is not captured, since it could change
  before the task runs (NL2506, `_let`), nor `this` (NL2507, `_this`; a `const
  self = this` is captured as the reference it is,
  `tests/link/thread_task_arrow`), and a captured name is never assigned
  (NL2508, `_assign`). A guard, a channel, a scope, a `Result`, a value that
  may be absent and a `Secret` are never captured:
  `` The arrow reads `ch`, which is `Channel<i32>`, and a task cannot capture it: a guard, a channel or a scope is shared only by the rules of its own block; a task reaches a channel through its argument, `s.spawn(entry, arg)`, where the scope counts its senders ``
  (NL2509, `_guard`, `_channel`, `_secret`). An arrow inside a task's arrow
  reads only its own parameters and the module's top-level names (NL2501, `_nested`). The arrow is lifted into a function
  named after the one it is written in and a counter (`main$arrow0`), which
  is the name a debugger or a profiler shows for the task's thread.
- **A task runs when its scope joins, not when it is spawned.** Joining a
  scope runs every task it was given at once — the first on the thread that
  opened the scope and each other on a thread of its own, so `N` tasks start
  `N - 1` threads — waits for all of them, and then stores each answer in the
  order the tasks were spawned, on the thread that opened the scope. That is
  what makes a scope free of races: while the tasks run, the thread that opened the scope is
  waiting for them, the tasks write nothing another can see (below), and every
  store into the program's memory is made after the last task has finished. So
  a task may be handed any argument — an array, an object.
- **`scopeWithStack(bytes)` is a scope whose tasks have a stack of at least
  `bytes` bytes**, for a task that recurses deeper than a thread's default
  stack allows (8 MiB on Linux): `using s = scopeWithStack(64 * 1024 * 1024)`
  (`tests/link/thread_stack_deep`, a million calls deep on 256 MiB; under an
  8 MiB `ulimit -s` the same program faults with `scope()`, and with
  `scopeWithStack(131072)` on its guard page, `tests/link/thread_stack_fixtures`).
  It covers a scope's tasks only: `parallelMap`, `parallelFrom` and the other
  data-parallel calls run on the pool's workers, whose stack is the platform's
  default. It is a scope in every other rule. Its tasks all run on new
  threads, a thread each, none on the thread that opened it; each thread's
  stack is `bytes` rounded up to the page, with a guard page below it, so a task that still overflows faults rather than
  writing past it. If one cannot be started the program ends with exit 1 and
  `nish: cannot start a thread for scopeWithStack: out of threads or of memory for its stack`
  when the system is out of either, or
  `nish: cannot start a thread with the stack scopeWithStack asked for` when
  it refuses the size. The
  smallest size is 131072 (128 KiB, the largest `PTHREAD_STACK_MIN` among the
  targets): a number written at the call below it is refused,
  `` `scopeWithStack(4096)` asks for a stack below the minimum of 131072 bytes: no target can start a thread on less, and a task that ran on it would overflow before it did any work; ask for at least 131072, `scopeWithStack(131072)` ``
  (NL2584, `tests/cases/reject_thread_stack_small`, `_negative`), and a
  computed one panics when the scope is made,
  `scopeWithStack: a stack of 65536 bytes is below the minimum of 131072`
  and exit 1 (`tests/link/thread_stack_computed_small`). Under Node, on WASI
  and wasm32 (no threads: every task runs on the one thread, in spawn order)
  and in a build without `--threads`, the size is checked the same way and has
  no other effect, so a program that needs the stack needs it from Node too
  (`node --stack-size`).
- **A destination is a fresh `const` array that is never handed on, and until
  the block ends the scope's thread neither reads a destination nor writes
  what a task may read.** Natively a task runs, and its answer is stored, when
  the scope joins; under Node each runs and stores where it is spawned. Two
  rules keep the program's meaning the same either way:
  - A `spawn`'s destination is a `const` local bound to a literal array or
    `new Array(...)` in the same function, used only by index, `.length`, its
    methods, a `for...of` and as a destination — never an argument, a task's
    argument, a stored value or a returned one — so nothing else can reach it.
    Anything else is
    `` The destination of this `spawn` must be a `const` local bound to a fresh array (a literal or `new Array`), used only by index, `.length`, its methods and as a destination: a scope's tasks run, and store their answers, when its block ends, and under Node each runs and stores where it is spawned, so a destination is a fresh `const` array that is never handed on, and between a scope's first `spawn` and the end of its block its thread neither reads a destination nor writes memory a task may read ``
    (`tests/cases/reject_thread_region_dst_not_fresh`, and
    `reject_thread_region_dst_as_arg` for one handed to a later task).
  - From the first statement of the block that holds a `spawn` on the scope
    to the block's end — a `return`'s value aside, computed after the join —
    the program may not read a destination a task of the scope has been given
    by then (`` This reads `sums`, a destination of a task of `s`, before the scope joins: … ``,
    `tests/cases/reject_thread_region_read`), and may not write memory a task
    could read. A task reads only what its argument reaches, so a store is
    fine into the own slots of a `const` bound to a fresh array or object
    literal that is never handed on, and a call is fine unless it writes
    through a pointer it is handed; a function that only fills an array it
    allocates, such as one that builds and returns a row, writes nothing a task
    can see. Every other write is refused, whatever alias it goes through —
    a store, `push` or `pop`, `Arena`, a call that writes through its
    argument, a task of another scope, whose join stores
    (`reject_thread_region_write`, `reject_thread_region_alias_write`,
    `reject_thread_region_call_write`). A constructor is a call: a `new`
    whose constructor writes through an argument, directly or through a
    constructor it calls, is
    `` `new Bump` writes memory a task of `s` may read, before the scope joins: … ``
    (`tests/cases/reject_thread_region_new_write`, and `_declarator` for the
    second declarator of a statement, `_nested` for a constructor that calls
    one, `_this` for one that hands `this` to its argument, which is a store
    through that argument). A write counts however deep it lands in what the
    argument reaches: a field of a field, a field of an element, through a
    `const` that names one, a `for...of` variable over one, a helper, or a
    method of what a field holds (`reject_thread_region_new_deep`,
    `_new_element`, `_new_helper`, `_new_method`, `_call_deep`,
    `_call_element`, `_call_alias`, `_call_loop`). Its stores into
    the fresh object itself are not counted, so `new Point(3, 4)` is fine
    there (`tests/link/thread_task_private`). An object a function or a
    constructor made itself is its own memory, and a write into it counts
    against nothing, until memory an argument reaches may have got into it:
    stored into a field or an element at any depth, pushed, put there by a
    method or a function it was handed to, kept by its constructor from an
    argument, or any non-number value rooted at it — the object, a field or
    an element of it at any depth, a constructor's `this` or `this.f` — used
    as a value anywhere but a read, a comparison or an argument the checker
    follows into its callee: the right side of an assignment, a `const`'s
    initialiser, an element of an array literal, a property of an object
    literal, `{ k: v }` or `{ k }`, an argument of `push`, of a `Map` or `Set`
    method or of a call, an arm of a `?:`. Each position is refused for each
    form of the value, a local, a field, an element and `this.f`
    (`reject_thread_region_escape_<position>_<form>`, with positions
    `assign`, `alias`, `array`, `object`, `shorthand`, `push`, `call`,
    `ternary` and `element`, forms `local`, `member`, `index` and
    `this_field`, and `_this` for the bare `this` in every position but
    `shorthand`, which cannot name it). A `Map` or a `Set` keeps exactly what
    its methods are handed — `set`'s key and value, `add`'s element,
    `getOrInsert`'s from `nish/map` — so each is a store into the table, as a
    `push` is (`reject_thread_region_map_value_param`, `_map_fused_value_param`,
    `_map_own_subpath`, `_map_route_subpath`, `_map_route_value_param`,
    `_set_own_subpath`), and its methods write only the table's own storage,
    never what it holds. What a container gives back is its element: what
    `get` or `getOrInsert` answers, and the `const` variable of a `for...of`
    over an array, a `Set`, or a `Map`'s `keys()` or `values()`, is memory
    below that container, so a write through it counts against what was
    stored into the container, and a store through it is a store into the
    container (`_readback_get`, `_readback_get_or_insert`,
    `_readback_nested`, `_readback_store_alias`, `_table_param_store`,
    `_walk_array_param`, `_walk_array_twice`, `_walk_values`, `_walk_keys`,
    `_walk_set_param`, `_walk_array_store`, `_walk_set_store`). So a call
    that answers a table or what one holds — `getOrInsert(m, …)`, `m.set(…)`,
    `s.add(…)` — is a value rooted at that table, and escapes it wherever a
    name would (`reject_thread_region_call_escape_<position>_<form>`, with
    positions `push`, `field`, `index`, `array` and `object`, forms `goi`,
    `set_chain` and `add_chain`, and `_ternary_goi`, `_nullish_get`,
    `_let_init_goi`, `_let_assign_goi`, `_table_arg_set_chain`). Only a call
    that keeps what it is handed stores it — `set` its key and value, `add`
    its element, `getOrInsert` its key and default — so a lookup, `has`,
    `get` or `delete`, keeps nothing (`reject_thread_region_table_key_set`,
    `_table_key_get_or_insert`); and a number, a string or a `boolean` read
    back through `| undefined`, as `m.get(k) ?? 0`, names no memory. A
    lookup in an argument's table, `has` or `get`, reads it and writes
    nothing (`tests/link/thread_scope_region_param_lookup`). A `?:`
    or a `??` stored somewhere may be either of its sides. Two values may
    be anything where they are written through: an `x ?? y`, and the
    variable of a walk of anything else —
    a `Channel`'s messages are another task's. An object literal
    whose property is an argument's memory carries it however it is written
    (`reject_thread_region_literal_object_param`, `_shorthand_param`,
    `_array_object_param`, `_field_object_param`, `_push_object_param`,
    `_new_object_param`, `_object_const_param`, `_object_method_param`). A
    write below such a slot counts against the arguments
    whose memory may be there, or against all of them when that cannot be
    told (`reject_thread_region_new_alias_field`, `_alias_push`,
    `_alias_element`, `_alias_const`, `_alias_helper`, `_alias_method`,
    `_alias_item`, `_call_wrap`, `_fresh_field`, `_fresh_method_bind`,
    `_fresh_attach`, `_fresh_push`, `_fresh_element`, `_fresh_array_field`,
    `_fresh_nested`, `_fresh_bump_method`, `_fresh_const`, `_fresh_ctor_field`,
    `_fresh_literal`, `_fresh_escape`, `_fresh_held`, `_fresh_held_temp`,
    `_fresh_captured`, `_this_local`, `_this_ternary`,
    `_this_literal`, `_this_object`). A constructor that keeps what it is
    handed keeps it per argument, so one that keeps the caller's own array, or
    pushes an argument's object onto an array it made, writes nothing of the
    task's (`tests/link/thread_scope_region_fresh_object`,
    `thread_scope_region_kept_own`), and a call that only writes its argument,
    or returns an object of its own, keeps nothing of the caller's in it:
    `w = build(h)` on a function that returns a fresh object, and
    `c.reset(h.nums[0])` on a fresh counter followed by writes into `c`
    (`thread_scope_region_own_handoff`). So a `Map` or a `Set` a function
    makes and fills itself writes nothing of the task's
    (`thread_scope_region_map_set`, `thread_scope_region_map_get_or_insert`,
    `thread_scope_region_set_add`), and so does one that walks, memoises
    or indexes a table of its own, or writes through what it reads back out
    of a container of fresh objects it made
    (`thread_scope_region_own_tables`, `thread_scope_region_read_back`). A
    map handed to `set` as a named `const` escapes, as any own object handed
    to a table does, so a write into it counts against every argument: build
    a nested table from what `get` reads back instead. A task argument read out of a
    variable — `s.spawn(f, ps[0], out, 0)`, or either arm of a `?:` or `??` —
    hands that variable on, so a store into its elements or fields before the
    join is refused too: a record element is the address of its slot, and the
    task reads it at the join (`tests/cases/cg_sec_scope_record_arg`). And
    `r.orReturn()` on a `Result` is refused in the same stretch, between the
    first `spawn` and the end of the block, because its early return would
    leave the scope unjoined (NL2394, `tests/cases/cg_sec_scope_or_return`).

  The rules are local because memory is reached only through parameters and
  what a function allocates: a module constant is a number, a `boolean` or a
  string, and nothing is `static`. N tasks over N arrays of the destination's
  own type, built before the scope, in the spawning loop or after the first
  spawn, all compile (`tests/link/thread_scope_many_arrays`).
- **The join is emitted at every exit of the block**: its end, a `return` —
  before the returned value is computed, so the value can read what the tasks
  stored — and a `break` or `continue` that leaves the block
  (`tests/link/thread_scope_exit_paths`). It sits inside every arena scope
  around it, which releases only after the join, and an argument a task is
  handed is never given back by a loop's pass before the join reads it
  (`tests/link/thread_scope_nested_arena`, which also nests one scope inside
  another). Since the join comes first, spawning gives up no memory: a
  function, a loop's pass or a `using a = arena()` block that hands a task an
  array it made still gives that array back when it ends, after the join,
  unless the task keeps it — answers it, or stores it where it outlives the
  task — or the frame keeps it past its end by any other route
  (`tests/link/thread_scope_reclaim`, whose peak resident memory
  `tests/run.js` bounds at every thread count, and
  `thread_scope_reclaim_escapes`, which reads each route after the memory is
  reused). A panic ends the process and joins nothing (`throw` is refused by
  Phase 0, `reject_throw`).
- **A scope is introduced by `using`, and `using` takes only a scope, a
  [`Mutex`'s lock](#a-lock-that-owns-its-data-mutext) or an
  [`arena()`](#using-a--arena).** A scope bound any other way is
  `` `scope()` must be the initialiser of a `using` declaration: a scope joins its tasks when the block that declares it ends, so a scope bound any other way would be one nobody joins; declare it as `using s = scope()` ``
  (`tests/cases/reject_thread_scope_not_using`), and a `using` of anything else is
  `` `using` takes only `scope()` or a `Mutex`'s `lock()` from `nish/threads`, or the builtin `arena()`, in this version: they are the values whose disposal the language defines — a scope joins its tasks, a guard releases its lock, an arena releases what its block allocated — so a `using` of anything else would promise a disposal nothing performs ``
  (`tests/cases/reject_thread_using_not_scope`). A `using` declaration is a
  statement of a block; as the body of an `if` or a loop it is
  `` A `using` declaration must be a statement of a block, `{ ... }`: its scope joins when that block ends, and a single-statement body is not a block ``
  (`tests/cases/reject_thread_using_placement`), and in a `case` clause it is
  refused as every declaration there is. Outside a declaration `using` is an
  ordinary identifier, as in TypeScript (`tests/parser/using.ts`).
- **A scope never leaves its block.** It is only ever the receiver of a `spawn`
  statement; passed, stored, returned or copied it is
  `` A `ThreadScope` can only be the receiver of a `spawn` statement: passed, stored, returned or copied, it could be given a task after its block has joined it ``
  (`tests/cases/reject_thread_scope_escapes`). That, and the join at every exit,
  is the whole proof that every task is joined: there is no handle to forget.
- **`[Symbol.dispose]` is `nish/threads`'s alone.** `ThreadScope` and
  `MutexGuard` declare one, so TypeScript and Node accept `using s = scope()`
  and `using g = m.lock()`; the compiler emits the join and the release itself
  and never calls it. `Channel`'s `[Symbol.iterator]`, Node's way into a
  `for...of`, is the one other computed name, and is `nish/threads`'s alone
  too: anywhere else it is refused as every computed name is (NL1041). Any other class's is
  `` `Handle` cannot declare `[Symbol.dispose]`: in this version `using` takes only `scope()` or a `Mutex`'s `lock()` from `nish/threads`, or the builtin `arena()`, whose disposal the compiler emits itself, so a disposal method of any other class would never be called ``
  (`tests/cases/reject_thread_dispose_elsewhere`).
- **There is no thread count.** Each spawn is one task and each task one
  thread; a scope with more tasks than cores leaves the scheduler to share them
  ([wp29-thread-surface.md](wp29-thread-surface.md) §9 declines the knob until
  a measurement asks for it).

What a task may do is what a data-parallel body may, less the rules about an
element's arena, which a task does not share, and each rule is reported at the
`spawn`:

- **The task writes nothing another can see**, except through the guard of a
  [`Mutex`](#a-lock-that-owns-its-data-mutext), the one shared write a task may
  make, by a method of an [atomic](#atomics-atomici32-and-atomici64)
  (`tests/link/thread_atomic_tasks`), or by a `send` or a receive on a
  [`Channel`](#channels-channelt), neither of which is a write the rule counts:
  `` `bump` writes memory its caller can see at main.ts:10:3, and `spawn` runs it beside the scope's other tasks: make scratch only this task uses inside it, because an object handed in as the argument is shared memory even when the `spawn` made it, since where an argument was made is not tracked. Write memory the tasks share only through the guard of a `Mutex`; hand a value the parent needs back as the task's answer, or run it on the thread that called it, `out[0] = bump(c)` ``
  (NL2471; `tests/cases/reject_thread_task_shared_write`, and
  `reject_mutex_task_unguarded` for a task that also writes through a guard).
  A `wipe` is a write through its argument like any other, so it is shared
  exactly when its target is: an array the task, or a function it calls,
  allocated itself is private, and wiping it is allowed
  (`tests/link/thread_task_wipe`). So is a `Secret` the function makes with
  `secret(v)` and wipes, when `v` is allocated in the call — `new`, an array
  literal or an object literal — and the `Secret` is held by a `const`
  (`tests/link/thread_task_wipe_secret`). Wiping the task's argument, a
  captured local, a field, an element, an array a call answered, a `Secret`
  held by a `let`, made from a call's answer, from a local moved into it or
  from a record whose constructor is handed an object, a `Secret` a call
  answers (wiped, or written by a helper first), or one a holder keeps in a
  field, is NL2471 (`reject_thread_wipe_param`, `_capture`, `_field`,
  `_element`, `_helper`, `_call_result`,
  `reject_thread_wipe_secret_call_result`, `_moved`, `_holder`, `_let`,
  `_call_secret`, `_call_secret_helper`, `_ctor_param`). A helper may write
  the task's own `Secret` before the wipe. A borrowed `Secret` parameter is
  refused before it
  (`reject_thread_wipe_secret_borrowed`). The wipe itself is unchanged, one
  volatile `llvm.memset`.
  A lookup in a shared `Map` or `Set` — `get`, `has`, `size` — is a read, so
  tasks of one scope may look keys up in the same table
  (`tests/link/thread_scope_task_map_reads`). A mutator — `set`, `add`,
  `delete`, `clear`, `getOrInsert` — writes it, a walk counts itself into it
  (`walkOpen`), and what a lookup answers is the table's memory, so each is
  refused (`reject_thread_task_map_set`, `_map_delete`, `_map_clear`,
  `_map_get_or_insert`, `_set_add`, `_set_delete`, `_set_clear`,
  `_map_walk_keys`, `_map_walk_values`, `_set_walk`, `_map_readback_write`).
  A task may `panic`, as a parallel body may: the first panic of the program
  prints and exits 1, and a task that panics after it prints nothing. Output
  stays a write (`reject_thread_task_console_error`,
  `reject_thread_task_process_exit`), and so does the parent's: between the
  first `spawn` and the join it may neither change a `Map` or `Set` it holds
  nor walk one — `for (const k of s)`, `m.keys()`, `m.values()`, or a helper
  that does (`reject_thread_region_parent_table_set`, `_set_walk`,
  `_map_keys_walk`, `_map_values_walk`, `_helper_walk`). The rule is
  conservative: it judges the call by what it writes through its receiver,
  not by which tables a task holds, so a walk of a table no task can reach is
  refused too (`reject_thread_region_parent_unreached_walk`), and so is a
  mutator or a walk called straight on a table made in the block. Proving
  that no task reaches one table would mean following every pointer each
  task is handed; the walk moves before the first `spawn`, after the block,
  or into a helper that makes and fills its own table
  (`thread_scope_region_own_tables`).
  A store into an array the task allocated and hands to nothing that keeps it
  is not counted, as for a [parallel body](#data-parallelism-nishthreads): a
  sieve may fill its own table, and a helper may fill the array it is handed
  (`tests/link/thread_task_private`). Returned, stored into its argument's
  field, pushed onto its argument's array, kept by a helper or a constructor,
  or bound to a second name in a later declarator, the array is shared
  (`tests/cases/reject_thread_task_private_returned`, `_field`, `_pushed`,
  `_kept`, `_new`, `_declarator`). A constructor that hands `this` out can
  lead to the array only by keeping it, so that route is `_new`'s. A store through a `?:` with the
  array in one arm is a store into either (`_ternary`), and an element of a
  private array of arrays is the array it holds
  (`reject_thread_task_private_nested`). The same holds for the task's other
  own memory: a method that writes only the fields of an object the task made,
  `const h = new Holder(); h.poke()`; `set`, `add` and `delete` on a `Map` or
  a `Set` it made; a store into an array field of an object it made, whose
  constructor filled it with a fresh array; a second name for its array bound
  in the same statement, `xs = new Array<i32>(n), ys = xs`; and a store
  through what a helper answers when the helper answers its argument, the
  task's own array, all write nothing shared
  (`tests/link/thread_task_own_writes`). What the argument reaches is not the
  task's own, even when the `spawn` made it there, because where an argument
  was made is not tracked: an object the task makes that holds the argument's
  array from its constructor on, has a field re-pointed at it, or is handed it
  by a helper or a method, and a helper that may answer either its own array
  or the caller's, all write the caller's memory
  (`reject_thread_task_own_holds_param`, `_repointed`, `_helper_stores_param`,
  `_method_adopts_param`, `_either_returned`), and so does a second name bound
  in the same statement as a fresh array when it names the argument's
  (`reject_thread_task_own_declarator_binds_arg`). A helper's fresh answer
  that holds the caller's memory, `[ys]` or `new H(ys)`, is the task's at its
  top level only, so a write below it is refused
  (`reject_thread_task_own_fresh_holds_array`, `_new`, `_object`). That
  refusal starts with what to write: `` make scratch only this task uses inside it, because an object handed in as the argument is shared memory even when the `spawn` made it, since where an argument was made is not tracked. Write memory the tasks share only through the guard of a `Mutex`; hand a value the parent needs back as the task's answer, or run it on the thread that called it, `out[0] = bump(c)` ``.
  A task inside a task, or
  inside a data-parallel body, is refused by this rule, because a scope's join
  stores into memory (`tests/cases/reject_thread_task_nested_spawn`); and a
  data-parallel call inside a task is refused by it too
  (`reject_thread_task_nested_map`).
- **It answers a number, a `boolean`, an enum, a `string`, or an array of
  numbers, booleans or enums**, because a task's thread frees its arena when it
  exits. A string or a scalar array crosses by copy-at-join: the worker copies
  its answer into a `malloc`'d transfer block before its arena goes
  (`nish_cross_out`), and the parent, once the scope has joined, copies each
  block into its own arena and frees it (`nish_cross_in`), so the block lives
  only between the two and is freed on every path out of the scope. An answer
  the task did not allocate — a literal, or a string its argument already held
  — passes through uncopied (`tests/link/thread_task_string`: a built label, a
  field of a made object, a substring and a slice, a returned fresh array, and
  a task that also stores into a `Mutex`, all read after `churn()`). Anything
  else is
  `` `words` answers `string[]`, and `spawn` hands back only a number, a `boolean`, an enum, a `string` or an array of numbers, booleans or enums, which the join copies out of the worker's arena: anything else would point into memory the worker frees or reuses ``
  (NL2348, `tests/cases/reject_thread_task_result_strings`;
  `reject_thread_task_result_type` for a class, `reject_thread_task_result_nested`
  for `i32[][]` and `reject_thread_task_result_map` for a `Map`). What a task
  allocates on the way is freed with its thread.
- **It leaves the arena alone**, because the first task runs in the arena of
  the thread that opened the scope:
  `` `wipe` reads or moves the arena, and `spawn` runs it on several threads that each have an arena of their own: a parallel body may not call `Arena.mark` or `Arena.used`, nor open a `using a = arena()` block, nor call `region`, `regionWith`, `child`, `childWith`, `enter`, `enterWith` or `free` (`nish:region`) ``
  (`tests/cases/reject_thread_task_arena`).
- **Its argument is not a `Result` small enough to travel as its parts**:
  `` The argument of `spawn` is `Result<i32, i32>`, which a task cannot be handed: a `Result` is passed as its parts rather than as one value, so hand the task the value it holds ``
  (`tests/cases/reject_thread_task_result_arg`).

Under Node, `scope()` is an object whose `spawn` runs its task at once and
stores the answer there; the rule above is what makes that print the same as
the compiled program ([RUN_UNDER_NODE.md](RUN_UNDER_NODE.md)). `using` needs
`--js-explicit-resource-management` on Node 22 and is native from Node 24.

`parallelFor`, non-scalar results and `scope(n)` are not in this stage
([wp29-thread-surface.md](wp29-thread-surface.md) §7); the lock is the next
section, [atomics](#atomics-atomici32-and-atomici64) the one after it, and
[channels](#channels-channelt) the one after that.

### A lock that owns its data: `Mutex<T>`

A `Mutex` lets a scope's tasks share one value they all update: the data lives
inside the lock, and the only way to it is the guard `lock()` answers, bound by
`using`, which holds the lock until its block ends
([wp29-thread-surface.md](wp29-thread-surface.md) §4.3). It is Rust's
`Mutex<T>`, narrowed until no borrow checker is needed.

```typescript
import { Mutex, scope } from "nish/threads";

class Counter {
  n: i32 = 0;
}

const addMany = (total: Mutex<Counter>): i32 => {
  for (let k: i32 = 0; k < 100000; k++) {
    using g = total.lock();          // waits for the lock, and holds it to the block's end
    g.value.n = g.value.n + 1;
  }                                  // released here, on every pass
  return 0;
};

export const main = (): i32 => {
  const total = new Mutex<Counter>(new Counter());
  const done: i32[] = [0, 0, 0, 0];
  {
    using s = scope();
    for (let t: i32 = 0; t < 4; t++) {
      s.spawn(addMany, total, done, t);
    }
  }
  using g = total.lock();
  console.log(`${g.value.n}`);       // 400000
  return 0;
};
```

- **Natively the lock is one word inside the guard**, taken with an acquire
  compare-and-swap in `lock()` and given back with a release store, so a lock
  nobody holds costs one atomic instruction and allocates nothing; a `lock()`
  that finds the word held calls the runtime's `nish_mutex_wait`, which spins
  briefly and then yields until it can take it (`tests/link/thread_mutex_counter`,
  whose `threads.ll` is the lowering, and `tests/link/thread_mutex_histogram`).
  On `wasm32` a scope's tasks run one after another, as they do for every
  scope there, so no lock is ever found held: the same program links for
  `--profile wasi`, its atomics lowered for a module without shared memory,
  and prints the same total (`tests/run.js`, "the `--profile wasi` build").
- **The release is emitted at every exit of the guard's block**: its end, a
  `break` or `continue` that leaves it, and a `return` or an `orReturn` — after
  the returned value is computed and before control leaves, unlike a scope's
  join, which runs before the value, so `return g.value.n` reads under the
  lock (`tests/link/thread_mutex_or_return`, whose `main.ll` pins the order) —
  and inside an `arena()` block it is given back before the arena releases
  (`tests/link/thread_mutex_exit_paths`, which locks again after each exit and
  would wait on itself if one kept the lock).

Eight rules keep every path to the data behind the lock, and a program that
breaks one is refused with that rule's own code:

- **R1: the data is fresh all the way down, and only the guard reaches it.**
  `new Mutex<T>(init)` takes a scalar, or a `new` expression or a literal whose
  every argument, element or value is a number, a `boolean`, an enum, a string
  literal — immutable, and never stored over — or itself fresh by this rule,
  because a value the program already holds would be a path to the data that
  skips the lock:
  `` `new Mutex` takes a value that is fresh all the way down — a `new` expression or a literal whose every argument or element is a number, a `boolean`, an enum, a string literal or itself fresh — because the data a `Mutex` owns is reachable only through its guard, and a value the program already holds would be a path to it that skips the lock ``
  (NL2463, `tests/cases/reject_mutex_not_fresh`,
  `reject_mutex_not_fresh_deep` for `new Hist(bins)` with a named `bins`, and
  `reject_mutex_not_fresh_literal` for `[row]` with a named `row`;
  `new Mutex<Label>(new Label("total", 0))` compiles,
  `tests/link/thread_mutex_scalar`). And `lock` is the only member
  of a `Mutex` a program may name:
  `` `guard` is not a member a program may name: the data a `Mutex` owns is reachable only through the guard its `lock()` answers, `using g = m.lock()`, so every path to it takes the lock ``
  (NL2464, `reject_mutex_member`).
- **R2: `m.lock()` is only the initialiser of a `using` declaration**, the
  third disposable beside `scope()` and `arena()`, and one `using` takes one
  lock (a second declarator's `lock()` is R5's, below). A lock may share a
  `using` with a scope opened before it or with an arena on either side, and
  the declarators close in the reverse of the order they opened, each opening
  before the next declarator's initialiser runs (an `orReturn()` there closes
  the ones before it), so in
  `using a = arena(), g = m.lock()` the lock is given back before the arena
  releases (`tests/link/thread_mutex_using_mixed`); a scope opened after the
  lock, `using g = m.lock(), s = scope()`, is R5's
  (`reject_mutex_using_lock_then_scope`). A `lock()` anywhere but a `using`
  initialiser is
  `` `lock()` must be the initialiser of a `using` declaration: the lock is released when the block that declares it ends, so a guard bound any other way would be one nobody releases; declare it as `using g = m.lock()` ``
  (NL2465, `reject_mutex_lock_not_using`; `reject_mutex_lock_expr_body` for
  an arrow whose expression body is `m.lock()`).
- **R3: a guard is used only as `g.value`, and what it reaches only as the base
  of another access.** Bound, stored, returned or walked, a guard is
  `` A guard is used only as `g.value`, and `g.value` only as the base of a field or element read or store: passed, bound, stored, returned or walked, what it reaches would outlive the block that holds the lock; write `g.value.n` where the value is used, or hand `g` to a helper whose parameter is a `MutexGuard<Counter>` ``
  (NL2466, `reject_mutex_guard_helper_return`, `reject_mutex_guard_helper_field`,
  `reject_mutex_guard_helper_ternary`). The one place a guard may go is to a
  **guard helper**: a function named at the call, neither a method, a
  constructor nor a generic, whose parameter in that position is declared as
  the guard is, `MutexGuard<T>`, with the guard named once among the call's
  arguments:

  ```ts
  const bump = (g: MutexGuard<Counter>): void => {
    g.value.n = g.value.n + 1;
  };

  {
    using g = m.lock();
    bump(g);
  }
  ```

  A guard helper is named, never held: naming it as a value is
  `` `bump` takes a `MutexGuard`: a guard is handed only to a function named at the call, so a function reference cannot name it; call the helper by name ``
  (NL2739, `reject_mutex_guard_helper_ternary_alias`,
  `reject_mutex_guard_helper_nullish`), because the rules below follow the
  function a call names.

  The helper's parameter is held to R3–R5 in its body exactly as `g` is in the
  block, so it can only read and store through it, and R5 follows the call, so
  a helper that locks, opens a scope, spawns or receives is refused at the call
  (`reject_mutex_guard_helper_spawn`, `reject_mutex_guard_helper_receive`). A
  helper that passes the guard on is judged by the same rule at that call
  (`reject_mutex_guard_helper_forward`), through helpers that call each other
  (`reject_mutex_guard_helper_mutual`) and across an import
  (`link/reject_mutex_guard_helper_import`); a helper that locks a `Mutex`
  it is handed is refused by R5 at the call
  (`reject_mutex_guard_helper_second_lock`), and `g.value` handed beside the
  guard by NL2467 (`reject_mutex_guard_helper_value_arg`). A helper has no
  default, rest or destructured parameter, which Nish has none of
  (`reject_mutex_guard_helper_default`, `_rest`, `_destructured`).
  `link/thread_mutex_helper` is three helpers deep on four threads. Any other call is
  `` `g` is passed to `push`, a method: a guard is handed only to a function named at the call, neither a method, a constructor nor a generic, whose parameter is declared as the guard is, `MutexGuard<T>`, once per call, because that parameter is held to the rules of the guard's block; write the helper as `const useGuard = (g: MutexGuard<Counter>): void => { console.log(g.value.n) }` and call it as `useGuard(g)` ``
  (NL2536; `reject_mutex_guard_helper_array`, `_map`, `_method`, `_new`,
  `_ctor_this`, `_generic`, `_twice`, `_nullable`, and `_callback` for a
  helper that takes a function, which makes it a generic), because a method or a
  constructor has `this` as a second way out, a generic's body treats `T` as any
  value, and a guard passed twice is two names for one lock. Anything read through it that is
  not a number, a `boolean`, an enum or a `string` — `const c = g.value`,
  `g.value.xs` as a value, a `for...of` over it — is
  `` This reads `Counter` through a guard, whose chains are only the base of a further field or element read or store: a value that is not a number, a `boolean`, an enum or a `string`, which the read copies, would outlive the block that holds the lock; do the work inside the guard's block, or read the numbers and strings it holds one at a time, `const n = g.value.n` ``
  (NL2467, `reject_mutex_guard_alias`; `reject_mutex_guard_alias_array` for
  `const b = g.value.bins`, which would race a guarded write once the block
  ends; `reject_mutex_guard_return` and `reject_mutex_guard_return_array` for a
  return; `reject_mutex_guard_store_field` and `reject_mutex_guard_store_element`
  for a store; `reject_mutex_guard_for_of` for a walk). An arrow's expression
  body is its answer and is judged as a `return` of it is, so a helper written
  `(g: MutexGuard<Box>): Box => g.value` is refused as one that writes
  `return g.value` (`reject_mutex_guard_helper_expr_value`, `_field`, `_paren`,
  `_index`, `link/reject_mutex_guard_helper_expr_import`; `_call`, `_new` and
  `_cond` for `g.value` handed to a call or a `new`, or written as an arm of
  `? :`, inside the body), and
  `reject_mutex_guard_helper_expr_churn` is the use-after-free it would open: the
  object kept past the lock, its string replaced under a second lock, and
  `churn()` reusing the memory before the old one is printed. An arrow argument,
  which may read its function's `const` locals, may not read a guard among
  them, whether it runs on this thread (`reject_mutex_guard_capture`) or is
  passed to a data-parallel form (`reject_par_capture_guard`). A scalar read through the guard is a value like any other, `.length`
  of an array it reaches included. When `T` is itself a scalar, `g.value` is
  read and stored directly — `g.value = g.value + 1` on a `Mutex<i32>` — and
  the store reaches the `Mutex` under Node as natively, because the guard is
  the `Mutex`'s own storage rather than a copy (`tests/link/thread_mutex_scalar`).
- **R4: a store through a guard stores a scalar or a string, and no method is
  called through it.** A number, a `boolean`, an enum or a `string`, into a
  field or an element of an array that already exists:
  `` This stores `string[]` through a guard, which stores only a number, a `boolean`, an enum or a `string`, which the store copies, into a field or an element that already exists: anything else is a pointer, which may point into a task's arena, freed when the task is joined; build the value into the one the `Mutex` is made with, or store what it holds one at a time into slots that already exist, `g.value.names[i] = v[i]` ``
  (NL2468, `reject_mutex_guard_store`; `reject_mutex_guard_store_class` for a
  class). A `null` is stored through a guard only into a `string | null` slot —
  a field, an element or a `Mutex<string | null>` — where the store frees the
  copy the slot held and keeps nothing, so a later read through `?.` answers
  `null` (`tests/link/thread_mutex_null_store`, natively and under Node, read
  back after `churn()`). Into any other nullable slot, a `Link | null` field,
  element or `Mutex<Link | null>`, it is refused, since such a slot holds a
  pointer, which a guard stores in no form:
  `` This stores `null` through a guard into a slot that holds an object, and a guard stores only a number, a `boolean`, an enum or a `string`, and a `null` only into a `string | null` slot, where the store frees the copy the slot held; keep a `boolean` field beside the slot, `g.value.hasNext = false`, and test it before reading the object ``
  (NL2537, `reject_mutex_guard_null_class`, `_link_element`, `_link_value`,
  `_link_nested` for `g.value.inner.next = null`, and `_link_paren` for
  `g.value.next = (null)`). Only the literal `null` is stored: a
  `string | null` *value*, a variable or a `??`, is refused as NL2468 above,
  since the store copies what it is given and a value that may be `null` would
  need a test the store does not make. A string stored through a guard is copied into memory the mutex
  owns: `nish_guard_keep` `malloc`s the copy, records it, and frees the copy
  the slot held before, if that one was its own; a string read through a guard
  is copied out into the reader's arena (`.length` excepted, which keeps
  nothing), so no reader holds the block the next store frees. The block a
  slot holds when the `Mutex` itself is dropped is not freed — the arena that
  held the `Mutex` does not say when it goes — and is reported by valgrind as
  still reachable, one block per guarded string slot
  (`tests/link/thread_mutex_string`). A program that makes and drops many such
  `Mutex`es keeps all of them: 100,000, each holding one 850-byte string,
  peaked at 89 MB against 11 MB for the same loop without the store. The
  record of those copies is one for the process, behind a lock of its own, so
  stores through two different `Mutex`es wait on each other while it is held.
  `push` — which can move the array into the task's arena — and every other
  method are
  `` `push` is called through a guard, which reads and stores fields and elements and calls no method: a method could keep what it reaches, or grow an array into a task's arena, which is freed when it is joined; write what it does as reads and stores through the guard, into slots that already exist, `g.value.xs[0] = 1` ``
  (NL2469, `reject_mutex_guard_push`). So a `Mutex<i32[]>` or a class with an
  `i32[]` field holds a histogram, sized when it is made.
- **R5: one lock at a time, and nothing waited on while it is held.** Inside a
  guard's block — directly, or through any function it calls — a second
  `lock()`, `scope()`, `spawn`, `parallelMapInto` or `parallelReduce` is
  `` A second `lock()` is reached while `ga` holds its lock: inside a guard's block, directly or through any function it calls, there is no second `lock()`, no `scope()` or `spawn`, and no `parallelMapInto` or `parallelReduce`, so one lock is held at a time and nothing is waited on while it is held; move `b.lock()` below the end of the block that opens with `using ga = a.lock()`, which releases the lock ``
  (NL2470; `reject_mutex_nested_lock`, and `reject_mutex_using_two_locks` and
  `reject_mutex_using_two_mutexes` for a second declarator of the same `using`;
  `reject_mutex_lock_through_call` for a callee that locks, and
  `reject_mutex_held_new` for a constructor that does, reached by `new`;
  `reject_mutex_held_scope` and `reject_mutex_held_scope_call` for a scope;
  `reject_mutex_held_map` and `reject_mutex_held_reduce` for the data-parallel
  calls). That is the whole
  argument that **a program cannot deadlock**: a task holding a lock never
  waits for anything, so every lock is given back.
- **R6: a store through a guard is the one shared write a task may make.** P2's
  rule is otherwise unchanged (above, NL2471).
- **R7: from the statement that holds a scope's first `spawn` to the end of
  its block, the parent does not lock what the scope's tasks share**, directly
  or through any function or constructor it calls — P2's own window, so a lock
  before the `spawn` in the same loop body is inside it: on the loop's second
  pass that lock runs after the first pass's `spawn`
  (`reject_mutex_region_lock_loop`).
  Natively the tasks have not run yet there, and under Node each has run at its
  spawn, so the parent would see a different value:
  `` This `lock()` locks a `Mutex` a task of `s` can reach through `arg`, before the scope joins: natively the scope's tasks run when its block ends and under Node each runs where it is spawned, so the parent locks what they share only before the statement that holds the first `spawn` or after the join; move `m.lock()` above the block that opens with `using s = scope()`, or below the end of that block ``
  (NL2472, `reject_mutex_region_lock`; `reject_mutex_region_lock_field` for a
  `Mutex` the task reaches as a field of its argument;
  `reject_mutex_region_lock_call` for a call that takes the lock, and
  `reject_mutex_region_lock_new` for a `new` whose constructor does). It is asked by type: a `Mutex<T>` of the
  type a task's argument reaches, or, for a call that takes a lock, any
  `Mutex` a task reaches. Before the first `spawn` and after the join the
  parent locks freely, as `tests/link/thread_mutex_counter` does.
- **R8: a `Mutex` reaches a task as its argument, or as a field of the class
  its argument is.** An array of them, a deeper field, or a `Mutex` inside
  another's data is
  `` The argument of `spawn` is `Mutex<Counter>[]`, which reaches a `Mutex` through `ms[i]`: a `Mutex` reaches a task as its argument or as a field of the class its argument is, never deeper, so which tasks share a lock is a question the checker can answer; hand the task the `Mutex` itself, `s.spawn(first, ms[i], done, 0)`, and declare its parameter a `Mutex` of the same data ``
  (NL2473, `reject_mutex_task_array`; `reject_mutex_task_nested` for a `Mutex`
  inside another's data, `reject_mutex_task_deep` for one two classes deep,
  `reject_mutex_task_nullable` for a nullable carrier, `reject_mutex_task_map`
  for a `Map` holding them). A task's destination holds numbers, so a
  `Mutex` is never one.

And a lock is a scope's: the body of `parallelMapInto` or `parallelReduce`,
which runs on many threads at once, takes none
(`` `tally` takes a `Mutex`'s lock, and `parallelMapInto` runs it on several threads at once: a lock is taken by a scope's task or by the thread that opened the scope, never by a parallel body; run it as a scope's tasks instead, `{ using s2 = scope(); for (let i = 0; i < src.length; i++) { s2.spawn(tally, src[i], dst, i) } }` ``,
NL2474, `reject_mutex_parallel_body`; `reject_mutex_parallel_body_call` and
`reject_mutex_parallel_body_new` for a lock taken in a callee or a
constructor).

**What a guarded program means.** The tasks' critical sections run one at a
time, in some order. Natively the order is the scheduler's; under Node, where
`lock()` answers the guard at once and its `[Symbol.dispose]` does nothing, it
is spawn order, which is one of the native orders
([RUN_UNDER_NODE.md](RUN_UNDER_NODE.md)). A program prints the same both ways
when its guarded updates commute exactly — integer sums and counts, a minimum,
a histogram; an `f64` sum does not, because the order changes its bits — and
no task's answer or control flow depends on guarded state it read. Anything
else is its author's obligation, as an associative operator is for a named
function given to `parallelReduce`; the checker does not try to prove it. It
is the one place the lock weakens the scope's promise above, that the checker
refuses anything that could tell the two orders apart.

### Atomics: `AtomicI32` and `AtomicI64`

An atomic is one integer a scope's tasks, and the bodies of the data-parallel
forms, update at once without a lock: each method is a single indivisible
operation on the word, so no update is lost to a race and none waits for
another. Where a `Mutex` guards a whole value, an atomic guards one counter.
The fast way to use one is the example's: each task counts into a local tally
no other core touches and adds it to the shared counters once, at its end, so
the atomics see one update per bin per task rather than one per value
("Measured", below).

```typescript
import { AtomicI32, parallelMapInto, scope } from "nish/threads";

class Shard {
  xs: i32[];
  bins: AtomicI32[];
  constructor(xs: i32[], bins: AtomicI32[]) {
    this.xs = xs;
    this.bins = bins;
  }
}

const binShard = (s: Shard): i32 => {
  const local: i32[] = [0, 0, 0, 0]; // this task's own counts: no core shares them
  for (const x of s.xs) {
    const bin: i32 = x & 3;
    if (bin < local.length) {
      local[bin] += 1;
    }
  }
  for (let b = 0; b < local.length; b++) {
    s.bins[b].add(local[b]);         // one indivisible add per bin, no lock
  }
  return 0;
};

export const main = (): i32 => {
  const bins: AtomicI32[] = [new AtomicI32(0), new AtomicI32(0), new AtomicI32(0), new AtomicI32(0)];
  const done: i32[] = [0, 0];
  {
    using s = scope();
    s.spawn(binShard, new Shard([1, 2, 3, 4, 5], bins), done, 0);
    s.spawn(binShard, new Shard([6, 7, 8], bins), done, 1);
  }
  const big = new AtomicI32(0);
  const xs: i32[] = [3, 9, 4];
  const ys: i32[] = [0, 0, 0];
  parallelMapInto(xs, ys, (x) => big.max(x));  // the one shared write a body may make
  console.log(`${bins[0].load()} ${bins[1].load()} ${big.load()}`); // 2 2 9
  return 0;
};
```

- **The methods.** `load()` and `store(v)`; `add(n)`, `sub(n)`, `min(v)`,
  `max(v)` and `exchange(v)`, each answering the value the word held before
  it; and `compareExchange(expected, desired)`, which stores `desired` when the
  word holds `expected` and answers the value it saw either way, so a loop
  that retries until the answer is its `expected` builds any other update
  (`tests/link/thread_atomic_tasks`). `add` and `sub` wrap at the width;
  `min` and `max` compare signed. `AtomicI64` is the same over `i64`.
- **Natively each method is one instruction**, sequentially consistent: a
  `load atomic` or `store atomic ... seq_cst`, an `atomicrmw add`, `sub`,
  `min`, `max` or `xchg ... seq_cst`, or a `cmpxchg ... seq_cst seq_cst`,
  aligned to the width (`align 4`, `align 8`), the whole body of the method's
  instance in `nish/threads`'s module (`tests/link/thread_atomic_tasks`, whose
  `threads.ll` is the lowering; docs/IR_COOKBOOK.md, "an atomic"). On
  `wasm32` a scope's tasks and a parallel call's chunks run one after another,
  and the same IR is lowered for a module without shared memory.
- **Under Node each method is the plain operation** on an ordinary field,
  which is exact because Node runs every task at its `spawn` and every parallel
  body in order. Node holds an `AtomicI64` as a `number`, and it agrees with
  native while values stay within ±2^53; wrapping at 2^63 is native-only, the
  same limit as every `i64` ([RUN_UNDER_NODE.md](RUN_UNDER_NODE.md)), so a
  program meant to run under Node as well passes it `i64`-typed values, not
  `toI64` of a number, which is a BigInt there.

Three rules keep every touch of the word indivisible and every program's
answer the same natively and under Node:

- **R1: an atomic is reached only by calling its methods.** Its word is a
  field, `value`, that no program may name, read or store:
  `` `value` is not a member a program may name: an atomic is read and updated only by calling its methods, `load()`, `add(n)` and the rest, each one indivisible: a plain read or store of its word would race with the update a task makes at the same moment ``
  (NL2514, `tests/cases/reject_atomic_member_read`, `reject_atomic_member_store`,
  and `reject_atomic_member_nested` for `h.a.b.value`). A method named without
  a call is refused by the rule every class's methods keep, not by NL2514:
  `` Unknown field `add` on class `AtomicI64` (it is a method; call it) ``
  (`reject_atomic_member_unbound`). `new AtomicI32(v)` takes a number, so an
  atomic is fresh when it is made, and `new` is the only way one is made. An
  object literal of any class of `nish/threads` — an atomic, a `Mutex`, its
  `MutexGuard`, a `Channel` or a `ThreadScope` — would be a plain record under
  Node, without the methods, and is refused with
  `` `AtomicI32` is a class of `nish/threads`, and its objects are made only as the module makes them: `new AtomicI32(v)`, `new AtomicI64(v)`, `new AtomicI32Array(n)`, `new AtomicI64Array(n)`, `new Mutex(v)`, `new Channel()`, `m.lock()` and `scope()`. An object literal would be a plain record under Node, with none of the methods the class is used through ``
  (NL2515, `tests/cases/reject_atomic_literal`, `reject_atomic_literal_i64`,
  `reject_thread_literal_channel`, `reject_thread_literal_mutex` and
  `reject_thread_literal_mutex_only`, whose `Mutex` literal is refused by this
  rule rather than by `new Mutex`'s fresh-value one, and
  `reject_thread_literal_scope`).
- **R7: from the statement that holds a scope's first `spawn` to the end of its
  block, the parent does not touch an atomic the scope's tasks can reach** —
  with a method, or through any function, method or constructor it calls,
  or by a data-parallel call that does — `Mutex`'s R7, for the same reason:
  natively the tasks have not run there, and under Node each has run at its
  spawn, so a `load()` would answer differently:
  `` This `load()` reaches an atomic a task of `s` can reach through `arg`, before the scope joins: natively the scope's tasks run when its block ends and under Node each runs where it is spawned, so the parent touches what they share only before the statement that holds the first `spawn` or after the join; move `a.load()` above the block that opens with `using s = scope()`, or below the end of that block ``
  (NL2513, `reject_atomic_region_direct`; `reject_atomic_region_capture` for
  an arrow task that captures it; `reject_atomic_region_field`,
  `reject_atomic_region_array`, `reject_atomic_region_map` and
  `reject_atomic_region_generic` for one the task's argument reaches through a
  field, an element, a `Map`'s value or a generic's field;
  `reject_atomic_region_call`, `reject_atomic_region_method` and
  `reject_atomic_region_new` for a function, a method and a constructor that
  touch it; `reject_atomic_region_this` for one reached through `this` handed
  out of a constructor; `reject_atomic_region_declarators` for the second
  declarator of a declaration; `reject_atomic_region_spawn_arg` for a second
  `spawn`'s argument; `reject_atomic_region_parallel` for a parallel call).
  It is asked by type, as `Mutex`'s is: an atomic of the type a task's argument
  or capture reaches, at any depth, so an alias through `?:` or a function's
  answer is the same atomic (`reject_atomic_region_ternary`,
  `reject_atomic_region_return`), and so is any other atomic of that type the
  task cannot in fact reach. An atomic of a type no task reaches is the
  parent's alone, and its methods are not counted as writes the scope's tasks
  may read (`tests/link/thread_atomic_unreached`). Before the first `spawn` and
  after the join the parent touches it freely.

  The scopes of one `using` are judged against each other too: natively they
  join in reverse order, so a task of `t` in `using s = scope(), t = scope()`
  runs before every task of `s`, and under Node each runs at its spawn. A
  `spawn` on one of them whose task shares a destination, an atomic or a lock
  with a task of another scope of the same statement is refused, naming the
  other scope and the path it shares:
  `` This `spawn` on `t` hands its task an atomic through `a`, which a task of `s` also reaches: the scopes one `using` statement opens join one after the other natively, the last declared first, while under Node each task runs where it is spawned, so the tasks of sibling scopes share no lock, no atomic and no destination; open each scope in a block of its own, so the first joins before the second opens, `{ using s = scope(); s.spawn(() => { a.add(1); }) } { using t = scope(); t.spawn(() => { b.store(a.load()); }) }` ``
  (NL2516). A destination is shared when two scopes' spawns name the same
  array, at the same slot or at different ones
  (`reject_thread_sibling_destination`, `_slots`, `_arrow` for arrow tasks,
  `_three` for three declarators). A task that reaches another scope's
  destination — to read the answer that scope's task returns, or to write it —
  hands the array on, which the destination rule refuses before this one:
  `_void` writes it, `_read` reads it through an arrow's capture, `_new`
  through a constructor reached by `new`, and `_this` through a field of an
  object whose constructor hands `this` out. An atomic or a lock is told apart by the `const` it was made in by
  `new`: a task handed that binding, as its argument or a capture, reaches that
  object and no other, and two such bindings are two objects. Reached any other
  way — through another binding, a field, an element, a function's answer —
  it is read as any object of its type, which meets every one
  (`reject_atomic_sibling_load`, `reject_atomic_sibling_exchange`,
  `reject_atomic_sibling_arrow`, `reject_atomic_sibling_three`,
  `reject_thread_mutex_sibling`, `reject_thread_mutex_sibling_alias` for a
  second name of one lock, `reject_thread_mutex_sibling_field` for one reached
  through a field). Every way a task reaches the object counts: through a
  field of a field (`reject_atomic_sibling_field_field`,
  `reject_thread_mutex_sibling_field_field`), through an object whose
  constructor hands `this` out (`reject_atomic_sibling_this`,
  `reject_thread_mutex_sibling_this`), in a constructor reached by `new`
  (`reject_atomic_sibling_new`, `reject_thread_mutex_sibling_new`), in a
  helper the task calls (`reject_atomic_sibling_helper`,
  `reject_thread_mutex_sibling_helper`), from an arrow's capture
  (`reject_thread_mutex_sibling_arrow`), and between any two declarators of
  the statement (`reject_thread_mutex_sibling_three`). Tasks that take no lock share none, and tasks that call no
  atomic method share no atomic. Sibling scopes whose tasks reach disjoint
  locks or atomics, of one type or of two, run as before
  (`tests/link/thread_sibling_disjoint_mutex`, `_mutex_types`, `_atomics`).
- **R8: an atomic reaches a task at any depth** — as its argument, a field of
  it, an element of an `AtomicI32[]`, or a capture — unlike a `Mutex`, which
  stops one field down: an atomic holds no data a task could keep, so which
  tasks share it is a question R7 answers by type, without the exact sharing
  set a lock's R5 needs.

**An atomic update is the one shared write a task or a parallel body may make
beside a guard.** A task that calls `add` on an atomic its argument reaches
writes nothing the rule above counts, and neither does the body of
`parallelMapInto`, `parallelMap`, `parallelFrom` or `parallelReduce`, which
takes no lock but may update an atomic it captures or an element reaches
(`tests/link/par_atomic`). Any other write beside it is refused as before
(`reject_atomic_par_shared_write`). A parallel body answers a number, never
an atomic (`reject_atomic_par_result`).

**What an atomic program means.** The updates land in some order: natively
the scheduler's, under Node spawn order and element order. A program prints
the same both ways when its updates commute exactly — `add` and `sub`, `min`,
`max`, a count, a histogram — and no task's answer or control flow depends on
a value it read from a word another task updates. A `store`, an `exchange` or a
`compareExchange` that wins against another task is order-dependent. A
`parallelReduce`'s blocks depend on `n` alone, the same on one core or sixty
four, but natively they run at once and under Node one after another, so what
a body does to an atomic must not depend on which block reaches it first. That is the
author's obligation, as it is for a `Mutex`'s critical sections; the checker
does not try to prove it.

**Measured.** `examples/histogram-atomic.ts` bins 4 × 2,000,000 values per
round into one `AtomicI32Array` of 256 bins, four rounds, on four tasks. On a
four-core machine, over seven interleaved rounds whose seeds move every round,
the medians are: each task counting into a local tally and adding it with one
`add` per bin, 29 ms (a byte-identical copy of it, the noise band, 23 ms; the
two copies' runs 22–49 ms); one thread binning into plain counters, 80 ms
(2.8× slower); one atomic `add` per value, 554 ms (19× slower), because every
increment contends for a cache line another core is writing; and one `Mutex`
taken per value, 2,155 ms. An atomic
is far cheaper than a lock and still far dearer than a counter no other core
touches: update it once per batch, not once per value.

### Atomic arrays: `AtomicI32Array` and `AtomicI64Array`

An atomic array is `length` atomic counters in one contiguous buffer. It is
`AtomicI32` (or `AtomicI64`) with the element's index first: every method of
the one has a twin on the other, with the same meaning, the same ordering and
the same rules, R1, R7 and R8 above, and the same one shared write a task or a
parallel body may make. Where an `AtomicI32[]` is one object per counter, each
its own allocation, so sixteen counters land on several cache lines that the
cores writing them pass back and forth, an `AtomicI32Array(16)` is sixteen
adjacent `i32`s in 64 contiguous bytes, which is the layout Rust's
`[AtomicI32; 16]` and Go's `[16]atomic.Int32` have. The buffer starts on a
64-byte boundary at least one line into its own allocation, which ends past the
line the last element is on, so no other object shares a line with the
elements, the lines the counters' writers fight over.

```typescript
import { AtomicI32Array, AtomicI64Array, parallelMapInto, scope } from "nish/threads";

class Shard {
  xs: i32[];
  bins: AtomicI32Array;
  constructor(xs: i32[], bins: AtomicI32Array) {
    this.xs = xs;
    this.bins = bins;
  }
}

const binShard = (s: Shard): i32 => {
  for (const x of s.xs) {
    s.bins.add(x & 3, 1);            // one indivisible add on element x & 3
  }
  return 0;
};

export const main = (): i32 => {
  const bins = new AtomicI32Array(4);   // four counters in one buffer, each 0
  const done: i32[] = [0, 0];
  {
    using s = scope();
    s.spawn(binShard, new Shard([1, 2, 3, 4, 5], bins), done, 0);
    s.spawn(binShard, new Shard([6, 7, 8], bins), done, 1);
  }
  const bytes = new AtomicI64Array(2);
  const one: i64 = 1;
  const xs: i32[] = [3, 9, 4];
  const ys: i32[] = [0, 0, 0];
  parallelMapInto(xs, ys, (x) => {
    bytes.add(x & 1, one);             // the one shared write a body may make
    return x;
  });
  console.log(`${bins.load(0)} ${bins.load(1)} ${bins.length} ${bytes.load(1)}`); // 2 2 4 2
  return 0;
};
```

- **The methods.** `load(i)` and `store(i, v)`; `add(i, n)`, `sub(i, n)`,
  `min(i, v)`, `max(i, v)` and `exchange(i, v)`, each answering the value
  element `i` held before it; and `compareExchange(i, expected, desired)`.
  `length` is a `readonly` field, fixed by `new AtomicI32Array(n)`, which
  makes `n` elements, each `0`; a negative `n` stops the program as
  `new Array` of one does. `AtomicI64Array` is the same over `i64`, its index
  still an `i32`.
- **An index is checked as an array index is**: one out of range stops the
  program with `index out of range: 16 >= 16` and exit status 1, and never
  touches memory outside the buffer (`tests/link/atomic_array_out_of_range`).
  The check is an ordinary one, which the prover may discharge.
- **Natively each method is the bounds check and then one instruction** on a
  `getelementptr` into the buffer: a `load atomic` or `store atomic ...
  seq_cst`, an `atomicrmw add`, `sub`, `min`, `max` or `xchg ... seq_cst`, or a
  `cmpxchg ... seq_cst seq_cst`, aligned to the element (`align 4`,
  `align 8`); no element is an object of its own, so there is no per-element
  pointer to load (`tests/link/thread_atomic_array`, whose `threads.ll` is the
  lowering; docs/IR_COOKBOOK.md, "an atomic array").
- **Under Node each method is the plain operation** on an element of an
  ordinary array, exact for the reason an `AtomicI32`'s is, with the same
  ±2^53 limit on an `AtomicI64Array`'s elements.
- **The rules are `AtomicI32`'s.** Its buffer, `values`, is a field no program
  may name (R1, NL2514, `reject_atomic_array_member_read`,
  `reject_atomic_array_member_store`), and a method named without a call is
  refused as any class's is (`reject_atomic_array_member_unbound`); `length`
  is assigned only by the constructor
  (`reject_atomic_array_length_store`); an object literal of either class is
  refused by NL2515 (`reject_atomic_array_literal`); the parent does not
  touch one a scope's tasks reach before the scope joins (R7, NL2513,
  `reject_atomic_array_region_direct`); the tasks of sibling scopes share none
  (NL2516, `reject_atomic_array_sibling_load`); and a parallel body may update
  one and write nothing else shared
  (`reject_atomic_array_par_shared_write`, `tests/link/par_atomic_array`).

Choose an atomic array over an `AtomicI32[]` when the counters are many or hot
— a histogram's bins, a counter per route or per worker — and an `AtomicI32`
for one counter, or for counters that live in different objects. A counter no
other core writes is still cheaper than either: count into a task's own tally
and add it once per batch, as the example under "Atomics" does.

### Channels: `Channel<T>`

A `Channel` passes scalars from a scope's tasks to one receiver: the tasks that
produce call `send`, and the one that consumes walks the channel with
`for...of`, which waits for values and ends once every task that may send on
it has returned and it is drained
([wp29-thread-surface.md](wp29-thread-surface.md) §4.4). Nobody closes a
channel, so nobody can close one too early, or twice.

```typescript
import { Channel, scope } from "nish/threads";

class Pipe {
  ch: Channel<i32>;
  n: i32;
  constructor(ch: Channel<i32>, n: i32) {
    this.ch = ch;
    this.n = n;
  }
}

const produce = (p: Pipe): i32 => {
  for (let i: i32 = 1; i <= p.n; i++) {
    p.ch.send(i);                                 // never waits
  }
  return p.n;
};

const consume = (p: Pipe): i32 => {
  let sum: i32 = 0;
  for (const x of p.ch) {                         // waits; ends once the sender has returned
    sum = sum + x;
  }
  return sum;
};

export const main = (): i32 => {
  const sent: i32[] = [0];
  const sums: i32[] = [0];
  const ch = new Channel<i32>();                  // for one run of the scope below
  {
    using s = scope();
    s.spawn(produce, new Pipe(ch, 100), sent, 0); // every sender first
    s.spawn(consume, new Pipe(ch, 0), sums, 0);   // then the one receiver
  }
  console.log(`${sums[0]}`);                      // 5050
  return 0;
};
```

- **Natively a channel is a buffer of 8-byte slots outside every arena**, behind
  the channel's `state` word, with a lock, a condition to wait on and a count
  that keeps it open (runtime/runtime-parallel.c). `send` widens the value into
  a slot and never waits; the loop takes a slot and narrows it back, and waits
  while the channel is empty and open. The count starts at one for the scope:
  a `spawn` whose task may send on the channel adds one before the task is
  filed and takes it away when the task returns, and the scope takes its own
  away at every exit of its block, just before the join — whether or not the
  join finds a task to run — so a channel whose only sender was never spawned
  closes too (`tests/link/thread_channel_pipeline`, whose `main.ll` and
  `threads.ll` are the lowering; `tests/link/thread_channel_exit_paths` for the
  end of the block, a `return`, a `break` and a scope that runs nothing). On
  `wasm32` a scope's tasks run one after another in spawn order, every sender
  before the receiver, and the same programs print the same thing
  (`tests/run.js`, "the `--profile wasi` build").
- **The buffer is given back when a loop drains the channel closed**, and the
  channel records that, so a second loop over it ends at once rather than
  reading what was freed; a loop that stops early with `break` leaves the rest
  for the next one (`tests/link/thread_channel_parent_drain`). Only that drain
  gives anything back. A channel whose last loop stopped early with `break` or
  `return`, or that no loop ever walks, keeps its bookkeeping — a few dozen
  bytes for its lock, its count and its buffer's bounds — and the values left
  in its buffer until the program exits, one such allocation per run of the
  declaration.
- **Under Node a channel is an array queue.** `send` pushes, and the loop takes
  values off the front as it walks, so a second loop finds what the first left
  ([RUN_UNDER_NODE.md](RUN_UNDER_NODE.md)). That is correct because a task runs
  at its spawn under Node and every sender is spawned before the receiver, so
  every value has been sent by the time the receiver's loop starts.

Seven rules keep "every sender has returned" a single moment and the one
receiver from waiting on what never comes, and a program that breaks one is
refused with a code of that rule's own: ten codes, NL2475 to NL2484, because
C2 has one for where a channel is declared, one for how it is used and one for
a channel inside an arrow, and C6 one for spawn order and one for a task that
sends and receives:

- **C1: a channel carries a number, a `boolean`, an enum or a `string`.** A
  sender's arena is freed when its scope joins, so a string is copied on the
  way: `send` copies it into a `malloc`'d block the buffer slot holds
  (`nish_cross_send`, a copy in time that grows with the string alone:
  `tests/link/thread_channel_string_many` sends a million it also keeps), and
  `receive`, or a `for...of` step, copies it into the receiver's arena and frees the block (`nish_cross_in`). A string a receiver
  never takes — the loop that left with `break` — stays in the buffer, which
  is itself given back only once it has been drained closed, so the two leak
  together. Anything else would be a pointer into the sender's arena:
  `` A `Channel` carries a number, a `boolean`, an enum or a `string`, and this one would carry `string[]`: a sender's arena is freed when its scope joins, and only a string is copied out of it on the way, so anything else would point into freed memory; keep the values in an array the receiver can read and send each one's index, `const words = new Channel<i32>()` ``
  (NL2475, `tests/cases/reject_channel_element`). A `Channel<string>`
  pipeline — two producers, a rewriting stage and a consumer that keeps what
  it receives in an array — matches Node (`tests/link/thread_channel_string`). An `f64` channel
  (`tests/link/thread_channel_two_producers`), a `boolean` one
  (`thread_channel_parent_drain`), and an `i64`, an enum and a `u8` one
  (`thread_channel_kinds`) compile and carry their values exactly.
- **C2: a channel is a `const` declared beside its scope, and used only as a
  channel.** `new Channel<T>()` initialises a `const` in the block that holds
  the scope's `using s = scope()`, or in the block that has the scope's block
  as one of its statements, before it, with no loop, condition or function
  between, so each run of the declaration makes a channel for one run of one
  scope — a scope in a loop gets a fresh one every pass:
  `` `new Channel` must be the initialiser of a `const`: a channel is a `const` declared in the block that holds its scope's `using s = scope()`, or in the block that has the scope's block as one of its statements, before it, so each run of the declaration makes a channel for one run of one scope; write `const ch = new Channel<i32>()` on the line before `using s = scope()` ``
  (NL2476, `reject_channel_not_const`, `reject_channel_let_second_declarator`
  for a `let` that declares it beside something else, `reject_channel_scope_conditional`
  for a scope inside an `if`, and `reject_channel_scope_loop` for one inside a
  loop the declaration is outside; a function boundary between them is C4's,
  below). A channel is the receiver of `send`, the
  iterable of a `for...of`, an argument, or a field its class's constructor
  sets from a parameter — never bound to another name, stored, returned or
  compared, and no member but `send` is named:
  `` A `Channel` cannot be bound, stored, returned or compared here: a channel is used only as the receiver of `send`, the iterable of a `for...of`, an argument, or a field its class's constructor sets from a parameter, so it is never bound, stored, returned or captured, and which tasks reach it is a question the checker can answer ``
  (NL2477, `reject_channel_bound`, `reject_channel_member`, `reject_channel_member_take`, `_ready`,
  `_head` and `_state`, `reject_channel_returned_expr` for an arrow whose
  expression body is a channel, which is its answer, and `reject_channel_stored` for a class that holds one
  made anywhere but at the `spawn`; `reject_channel_nullable` for a task's
  argument whose channel may be `null`, which the `spawn` could not count as a
  sender). A type holds a channel only as exactly `Channel<T>`: never as one
  that may be `null`, an array's element, a `Result`'s arm or another
  generic's type argument, wherever the type is written — a local, a
  parameter, a result or a field, a type alias read as the type it names
  (`reject_channel_nullable`, `reject_channel_array`, `reject_channel_map_value`,
  `reject_channel_result_type`, `reject_channel_alias_type`,
  `reject_channel_field_generic`). An argument is one only
  to a parameter its function declares a `Channel`, not to a generic's `T`
  (`reject_channel_generic_argument`). It reaches a task as R8 says a `Mutex`
  does: as the task's argument, or as a field of the object made for it at the
  `spawn`, `new Pipe(ch, 100)`, and by one path only, so a task never holds it
  in two fields (`reject_channel_two_paths`). A constructor uses a channel it
  is handed only to set a field from it, `this.ch = ch` (`reject_channel_ctor_bound`);
  one it declares itself it uses as any function does. And a channel is used
  only in a top-level function's own body, never inside an arrow, which is
  lifted into a function of its own that these rules do not follow:
  `` A `Channel` is used inside an arrow here: an arrow is lifted into a function of its own that the channel rules do not follow, so a channel is declared, sent on and received from only in a top-level function's own body; write the arrow as a module function, `const relayBody = (q: Pipe): i32 => { const c = q.ch; c.send(1); return 1; }`, and pass `relayBody` where the arrow was ``
  (NL2484, `reject_channel_arrow`, and `reject_channel_arrow_nullable` for a
  channel type an arrow writes but never uses).
- **C3: a channel is unbounded**, so `send` never waits, because under Node a
  scope's tasks run one at a time and nothing would drain a full one:
  `` `new Channel` takes no capacity: a channel is unbounded and `send` never waits, because under Node a scope's tasks run one at a time and nothing would drain a channel that was full; write `new Channel<i32>()` ``
  (NL2478, `reject_channel_capacity`).
- **C4: one scope's tasks reach a channel, and the parent sends on it only
  before that scope's block.** After the join it only receives. "May send" is
  the call graph from a task's entry reaching `send` on a channel its argument
  holds, so an over-count only closes the channel later:
  `` This sends on `ch` once its scope's block has begun: a channel is reachable from the tasks of one scope, the parent sends on it only before the block that holds that scope's spawns, and nobody closes it: it closes once the scope has started to join and every task that may send on it has returned; move `ch.send(7)` above the block that opens with `using s = scope()` ``
  (NL2479, `reject_channel_parent_send`, `reject_channel_send_after_join` for a
  send through a call after the join, and `reject_channel_two_scopes` for the
  two scopes of one `using`). A `spawn` hands its task only a channel the
  function declared, never one it was handed, so no function boundary comes
  between a channel and its scope (`reject_channel_spawn_handed`, and
  `reject_channel_spawn_handed_direct` for the channel as the argument itself).
  In the constructor of a class that holds a channel, directly or through a
  field's class, `this` appears only as the base of its own field, `this.f`,
  used in one of three ways: as the target of a store (`this.f = ...`,
  `this.f += ...`); as any value, except as the callee of a call, when the field is a
  number, a `boolean`, an enum, a string or an array of those, from which
  nothing reaches a channel (`this.total = this.a + this.b`,
  `this.width = this.name.length`, `this.items.push(x)`); or as the base of a
  store into a field or element of what it holds, when that is no channel and
  holds none (`this.span.lo = 1`; `tests/link/thread_channel_ctor_reads`). A
  method called on it, an argument (to a function or to a constructor), a store
  elsewhere, a second name (in any declarator), an array element, a read of the
  channel or of an object that holds one, or `this` stored even into its own
  field would carry a send the count would not see:
  `` The constructor of a class that holds a channel uses `this` other than to read or set its own fields, `this.f`, where a send made through it could not be counted: … ``
  (NL2479; `reject_channel_ctor_this`, `reject_channel_ctor_this_stored`,
  `reject_channel_ctor_this_bound`, `reject_channel_ctor_this_array`,
  `reject_channel_ctor_this_new`, `reject_channel_ctor_this_declarator`,
  `reject_channel_ctor_this_self`, `reject_channel_ctor_this_deep_carrier`,
  `reject_channel_ctor_this_send`, `reject_channel_ctor_this_carrier`).
- **C5: a channel has one receiver** — one task, from a `spawn` outside any
  loop, or the parent in a later statement of the block that has the scope's
  block as one of its statements, never both — and inside a scope's block the
  parent receives nothing, directly or through any function it calls, so its
  one wait is the join:
  `` `ch` has a second receiver here: a channel has one receiver, either one task spawned outside any loop or the parent in a later statement of the block that has the scope's block as one of its statements, and inside a scope's block the parent receives nothing, so the parent's one wait is the join ``
  (NL2480, `reject_channel_two_receivers`, `reject_channel_parent_and_task`,
  `reject_channel_receiver_loop`, `reject_channel_parent_receive_inside` for a
  call that receives inside the block, `reject_channel_receive_in_spawn_argument`
  for one in a `spawn`'s argument, which is the parent's code, and
  `reject_channel_receive_before_using` for one before the `using` in the
  scope's own block). A call counts as a receive when its function may receive
  on a channel it is handed; one that receives only on a channel of its own has
  joined that channel's scope first, and is not one. One receiver is what makes
  "the receiver sees every value sent" true natively and under Node alike.
- **C6: every task that may send on a channel is spawned before the one that
  receives on it**, in the block's statement order. Under Node a receiver
  spawned first would find the channel empty, and the same order makes the
  graph from senders to receivers acyclic, so **channels cannot deadlock**
  either:
  `` `produce` may send on `ch` and is spawned after its receiver: under Node a task runs where it is spawned, so every task that may send on a channel is spawned, in the block's statement order, before the one task that receives on it, which is also what keeps channels from deadlocking; move the `spawn` of the receiving task below every `spawn` that sends, `s.spawn(produce, new Pipe(ch, 3), out, 1)` above `s.spawn(consume, new Pipe(ch, 0), out, 0)` ``
  (NL2481, `reject_channel_receiver_first`). And no task both sends and
  receives on one channel:
  `` `echo` may both send and receive on `ch`: no task both sends and receives on one channel, because a channel closes only once every task that may send on it has returned, and this one would wait in its own loop for its own return; split it into a task that sends and a task that receives, or answer the result through a second channel ``
  (NL2483, `reject_channel_send_and_receive`,
  `reject_channel_both_through_new` for a send made by a constructor a `new`
  runs, and `reject_channel_both_untraceable` for a task that reaches a
  channel through a second name for what holds it, which counts as using
  every channel it holds, and says so).
- **C7: nothing receives while a lock is held**, directly or through any
  function it calls — R5's "nothing is waited on while it is held". A `send`
  never waits and may stay:
  `` A loop over a channel is reached while `g` holds its lock: a receive waits, and nothing waits while a lock is held, so there is no receive inside a guard's block, directly or through any function it calls (a `send` never waits, and may stay) ``
  (NL2482, `reject_channel_loop_held`, and `reject_channel_receive_held_call`
  for a function that receives on a channel it is handed;
  `reject_channel_receive_held_expr` for one reached through an arrow whose
  expression body calls it). A function that
  receives only on a channel of its own opens a scope to fill it, which R5
  refuses under a lock already.

**What a channel program means.** The receiver sees every value sent, each
sender's in its send order. How two senders' values interleave is the
scheduler's natively and spawn order under Node, so a receiver whose answer
depends on it — not a count or an integer sum, but the first value, or an
`f64` sum whose partial sums are not exact — is its author's obligation, as
for the lock. A task's channel is checked where it can be read, at the
`spawn`; a parallel body has no way to reach one, because a task calls no
`parallelMapInto` and a channel is made only beside a scope. `select` stays
declined (wp29 §9).

### What `nish --fix` writes for a thread program

The thread refusals end with the code to write instead (each pinned whole by
its `tests/wordings` case), and six of them carry a fix that `nish --fix` applies, each only where the source alone decides the
replacement (`tests/fix/thread-*`; the refused shapes are its `thread-nofix-*`
cases):

| Refusal | The fix | Left alone |
| --- | --- | --- |
| NL2388, a `scope()` not bound by `using` | `const s = scope()` becomes `using s = scope()` | a `let`, which is assigned again |
| NL2465, a `lock()` not bound by `using` | `const g = m.lock()` becomes `using g = m.lock()` | a `let` |
| NL2511, a `spawn` with no destination, whose task answers a number or a `boolean` | `const answer = new Array<T>(1)` above the scope's `using`, and `, answer, 0` after the arguments | a `spawn` in a loop, where every task would write one slot; an answer that is not a number or a `boolean` |
| NL2506, a task's arrow that captures a `let` | `const kNow = k` just before the statement, and the arrow reads `kNow`: the value it would have read when it ran | a `let` another argument names; a `let` a `for` header declares, where no statement before the call is in the loop |
| NL2500, the same in a `parallelMap` | the same | the same |
| NL2484, an arrow that uses a `Channel` | the arrow moves to a `const` above the top-level statement it is written in, named for the function and `Task` (`mainTask`), and the call names it | an arrow that captures, or leaves a parameter's or its result's type out, which would not check at the top level |

### Shared memory between processes: `nish/sync/shm` and `nish/sync/ring`

Threads share an address space; processes share nothing unless they map the
same memory. `nish/sync/shm` maps a **named region** that every process of
the same user can open, and `nish/sync/ring` builds lock-free queues of byte
records in one, so prefork workers can hand work to an owner process without a
socket:

```typescript
import { ACQ_REL, ACQUIRE, createRegion, unlinkRegion } from "nish/sync/shm";
import { initSpscRing, spscRingBytes } from "nish/sync/ring";

export const main = (): i32 => {
  const region = createRegion("lang-demo", 64 + spscRingBytes(4096)).expect("create");
  region.addI64(0, toI64(1), ACQ_REL); // a counter every process may bump
  const ring = initSpscRing(region, 64, 4096, true); // a ring after it
  const job: u8[] = [1, 2, 3];
  ring.tryPush(job, 0, job.length); // false when full
  const got: u8[] = new Array<u8>(16);
  const n: i32 = ring.tryPop(got, 0); // 3, or RING_EMPTY
  console.log(`${region.loadI64(0, ACQUIRE)} ${n}`);
  unlinkRegion("lang-demo").expect("unlink");
  return 0;
};
```

- **A region is named, never inherited.** A Nish program has no `fork`, and
  every descriptor is close-on-exec, so an anonymous mapping or a `memfd`
  cannot reach a child; a name can. `createRegion(name, bytes)` makes one,
  zeroed, mode 0600, and refuses a name that exists (`SHM_EXISTS`), so a name
  another user planted is never adopted. `openRegion(name)` maps one this
  user made, and refuses one owned by someone else, open to group or others,
  reached through a symbolic link, or (on Linux) not a regular file or with a
  second hard link (`SHM_ACCESS`). A name is 1 to 30 of `A-Z a-z 0-9 . _ -`,
  not starting with `.`; a size is 1 byte to 1 GiB. Errors are a `Result`
  with the errno (`SHM_NOT_FOUND`, `SHM_INVALID`, `SHM_TOO_MANY`, ...).
- **Lifetime.** The name lasts until `unlinkRegion`, even past every process
  that mapped it, which is how a process started later finds it. A mapping
  lasts until `close()` or the process's exit, when the kernel unmaps it. A
  thread may hold 63 regions at once.
- **Every access is checked, as an array index is.** `loadI32`, `storeI32`,
  `addI32`, `exchangeI32`, `compareExchangeI32` and their `I64` twins take an
  `i32` byte offset; a slot must lie wholly inside the region and at a multiple
  of its width, or the access panics naming the offset (`nish/sync/shm: slot
  offset 4 is not a multiple of 8, the slot's width`). `read` and `write` copy
  a byte window, checked against both the region and the buffer. No offset
  reaches outside the mapping, whatever a peer wrote into it.
- **Windows: a `u8[]` that is the region's bytes.** `region.lend(at, len)`
  answers a `u8[]` of length `len` whose data is bytes `[at, at + len)` of the
  mapping, checked as `read`'s window is (`nish/sync/shm: byte window at 60 is
  outside the region of 64 bytes`). An index store, `copyBytes` into it or
  `netRead` into it writes the region itself, and every process mapping it
  sees the bytes, with no copy. The window is not atomic: order it with a slot
  (`storeI32(.., RELEASE)` after the bytes, `loadI32(.., ACQUIRE)` before
  reading them), as a ring does. `region.giveBack(window)` answers its length
  and empties it, and `close()` empties every window the region lent, so an
  index after either is `index out of range: 0 >= 0`, never a read of an
  unmapped page. A `pop` or a shorter `length` keeps a window; a **push past
  its length moves it** off the region into the program's memory, as any push
  past capacity does, and `giveBack` then panics (`window of length 17 is no
  longer the region's bytes: a push moved it`), as it does for a window
  given back twice or lent by another region.
- **The reuse rule.** Each `lend` without `reuse` takes a header of 48 bytes
  that lasts until the process exits, since the program may hold the array
  past any `giveBack` or `close`. A loop that lends again passes the window it
  gave back, `region.lend(at, len, window)`, which re-points that header and
  takes no memory; a `reuse` that is still lent, or not this region's, panics.
  Windows belong to the thread that lent them, as the region does.
- **Why an intrinsic, not FFI.** `lend` and `giveBack` are the module's two
  compiler-known functions (`src/shm-window.ts`), whose bodies the compiler
  writes as a call of `nishshm_lend` / `nishshm_give_back`: a foreign function
  may take a `u8[]` but answers no array, and a window must be one the program
  indexes. Known by its package and path, as `nish:region` is, the call is
  marked as writing through and keeping its array and as possibly changing
  any array's length, so no length the bounds proof knew survives it, and a
  region's `close()` is marked the same way.
- **Orderings are C11's**: `RELAXED`, `ACQUIRE`, `RELEASE`, `ACQ_REL`,
  `SEQ_CST`, plus `fence(order)`. Each access is one LLVM `load atomic`,
  `store atomic`, `atomicrmw` or `cmpxchg` with that ordering; an ordering an
  access cannot take (a load with `RELEASE`) panics. A compare-exchange
  answers the value it found, so it succeeded when that equals `expected`.
- **Waking.** `waitI32(at, expected, timeoutMs)` sleeps while the slot holds
  `expected` and `wake(at, count)` wakes sleepers, in any process: Linux's
  shared futex. Darwin and wasi answer `SHM_UNSUPPORTED` (-95) from both, and
  a program there polls.
- **Rings.** `SpscRing` (one producer, one consumer, records of any length
  up to its capacity) and `MpscRing` (any number of producers, fixed slots)
  live at a 64-byte-aligned `base` in a region: `initSpscRing` /
  `initMpscRing` write the header once, `attachSpscRing` / `attachMpscRing`
  read it in another process. `tryPush` answers `false` when full; `tryPop`
  answers the record's length, `RING_EMPTY` or `RING_TOO_SMALL`; `popBatch`
  takes every record ready. A ring made with the doorbell lets `popWait`
  sleep, and a push rings it only when the consumer is asleep, so a busy ring
  makes no system call. Two consumers, or two producers on an `SpscRing`, lose
  or repeat records but never leave the region; a length no record can have
  panics as `the ring is corrupt`.
- **What a program reaches.** The modules call C, so a program that imports
  them reaches [`ffi`](#capabilities) (and `clock`, for `popWait`'s deadline)
  and `--deny ffi` refuses it; under `--sandbox` a region, being a file in
  `/dev/shm`, needs `fs.read` and `fs.write` as well. They are native only:
  `--emit-ts` refuses them, since Node's `SharedArrayBuffer` is shared between
  threads of one process, not between processes. A region belongs to the
  thread that mapped it. A program that imports neither module is unchanged.
  Tested by `tests/link/sync_shm`, `tests/link/sync_shm_window`,
  `tests/link/sync_ring` and `tests/link/sync_shm_deny_ffi`; the design, its measurements and the threads
  it was weighed against are `docs/wp47-shared-memory.md`, and the threat model
  is [`docs/security/shm.md`](security/shm.md).

### Random numbers: `Rng` in `nish/random`

`new Rng(seed)` is a generator of pseudo-random numbers whose every answer
depends on its `i32` seed alone, and is the same natively and under Node:

```typescript
import { Rng } from "nish/random";

export const main = (): i32 => {
  const r = new Rng(42);
  const die: i32 = r.nextInt(1, 6); // 1 to 6, each with equal chance
  const u: f64 = r.nextF64(); // in [0, 1)
  console.log(`${die} ${u < 1.0}`);
  return 0;
};
```

- **`nextI32()`** answers the next 32 bits as an `i32`, and **`nextF64()`** a
  double in [0, 1) built from 53 bits of two steps. The state walks a Weyl
  sequence (an odd increment, wrapping) through all 2^32 values, and each
  answer is MurmurHash3's 32-bit finaliser of it, so every seed, 0 included,
  starts a full sequence, and seeds 1, 2 and 3 start unrelated ones. It is not
  for cryptography: a key comes from `crypto.getRandomValues`.
- **`nextInt(lo, hi)`** answers an `i32` in [lo, hi], both ends included, each
  with equal chance. It refuses the few `nextI32()` draws below 2^32 mod the
  span and answers `lo` plus the draw mod the span, so no answer is likelier
  than another; fewer than half the draws are refused, so a call takes under
  two steps on average. `nextInt(-2147483648, 2147483647)` is one `nextI32()`,
  and `lo > hi` panics with `Rng.nextInt: lo is greater than hi`.
- **The same bits under Node** are the point of the design. The
  operations that wrap are `wrappingAdd`, `wrappingSub` and `wrappingMul` from
  [`nish:unsafe`](#nishunsafe-unchecked-access-and-defined-wrapping), every shift has a constant count,
  `nextInt` reads its unsigned counts through `i32` compares and remainders of
  non-negative values, and `nextF64`'s double is exact, so `tests/link/std_random` prints the same lines
  both ways.
- **A parallel body or a task steps an `Rng` it made itself**, which is its
  own memory (`const r = new Rng(i)`, "Nor is a write into an object's own
  slots" under [data parallelism](#data-parallelism-nishthreads)); a
  generator shared by several tasks would be a shared write, and is refused as
  one. Seed each task's own from its index.

### Byte search: `indexOfAny` in `nish/text`

`indexOfAny(text, bytes, from)` answers the first index at or after `from`
whose byte is one of `bytes`, or -1 ([wp38-simd.md](wp38-simd.md) §3.1). It is
the scan a parser spends its time in — the next `"` or `\` in a JSON string,
the next delimiter in a line — and natively it reads 16 or 32 bytes at a time.

```typescript
import { indexOfAny } from "nish/text";

export const main = (): i32 => {
  const line = "key: \"value\", next";
  console.log(`${indexOfAny(line, "\":", 0)}`);   // 3, the colon
  console.log(`${indexOfAny(line, ",", 99)}`);    // -1: `from` is clamped to the length
  return 0;
};
```

- **The set is 1 to 16 ASCII bytes, or the call panics.** An empty set
  (`indexOfAny: the set must hold 1 to 16 bytes`) matches nothing and is a
  mistake rather than a search; seventeen bytes is more than one vector of the
  kernel compares; and a byte of 128 or more
  (`indexOfAny: every byte of the set must be ASCII`) would be one byte of a
  multi-byte sequence natively and a UTF-16 unit under Node, which find
  different things (`tests/link/std_text_index_of_any_empty_set`,
  `_long_set`, `_non_ascii_set`).
- **`from` is clamped to `[0, text.length]`**, as `substring` clamps: a
  negative `from` searches from the start, and one at or past the length
  answers -1. The answer is a byte offset, like `s.length`; an ASCII byte
  never occurs inside a multi-byte UTF-8 sequence, so a non-ASCII `text` is
  searched as it is and only its ASCII bytes match. Under Node the offset is a
  UTF-16 one, so the two agree on what was found and, once a non-ASCII
  character precedes it, not on where (`tests/link/std_text_index_of_any`).
- **The module is ordinary Nish, and the walker is the meaning.**
  `std/text.ts` writes `indexOfAny` as its checks and its clamp followed by
  one call to a private walker, a loop over `charCodeAt`, which is what runs
  under Node. The compiler recognises that call by module and name
  (`src/kernels.ts`) and emits the runtime's `nish_str_index_of_any` in its
  place; everything around it is emitted as written, so the kernel is only
  ever handed a clamped `from` and a set of 1 to 16 bytes. The package is part
  of the test: a root-package file that happens to sit at `std/text.ts` is an
  ordinary module, and its walker is called as written. The kernel picks a
  scalar, a 16-byte (SSE2 or NEON) or a 32-byte (AVX2) path on its first call,
  and `NISH_SIMD=scalar|base|avx2` pins it.
- **It is variable-time.** How long the search takes says where the first
  match is, so it is never for secret data: `std/crypto` does not call it on
  one, and `nish:secret`'s `expose` lets it through only because it touches
  nothing outside its two strings.

On a 1 MiB text with a match every 4,099 bytes, the kernel scans at 14 GB/s
with AVX2 and 7 GB/s on the 16-byte path, against 1.6 GB/s for the same
walker compiled as written (`bench/index-of-any.ts`).

### Fixed digits and a split limit: `toFixed` and `splitLimit` in `nish/text`

Nish has no methods on a number and no optional parameters, so JavaScript's
`x.toFixed(n)` and `text.split(sep, limit)` are two functions of `nish/text`.
Each is the method it stands for, read as TypeScript: under Node the module
runs as written and answers what the method answers, and natively it answers
the same bytes (`tests/link/std_text_to_fixed`, `tests/link/std_text_split_limit`,
whose every line `tests/run.js` also holds to Node's own method).

```typescript
import { splitLimit, toFixed } from "nish/text";

export const main = (): i32 => {
  console.log(toFixed(1.005, 2));                     // 1.00: 1.005 is stored a little below
  console.log(toFixed(2.5, 0));                       // 3: a tie goes away from zero
  console.log(splitLimit("a,b,c", ",", 2).join("|")); // a|b: the rest is dropped
  return 0;
};
```

- **`toFixed(x, digits)` rounds the exact binary value**, as ECMA-262 does:
  `1.005` is stored as 1.00499999999999989…, so it gives `"1.00"`, while
  `8.345` is stored a little above and gives `"8.35"`; an exact tie rounds
  away from zero, so `toFixed(-2.5, 0)` is `"-3"`. `digits` is 0 to 100, and
  any other count panics (`toFixed: digits must be 0 to 100`) where JavaScript
  throws a `RangeError`. `NaN`, the infinities and any `x` of magnitude 1e21 or
  more answer `${x}`, as JavaScript does; `-0` gives `"0.00"`, and a negative
  `x` that rounds to zero keeps its sign (`toFixed(-0.0001, 2)` is `"-0.00"`).
  It is written in Nish over an array of decimal digits, so it is exact for
  every `f64`, the subnormals included, and it needs no runtime C.
- **`splitLimit(text, sep, limit)` keeps the first `limit` pieces** of
  `split(text, sep)` and drops the rest, rather than joining them into the
  last; a limit of 0 gives `[]`. A negative limit keeps every piece, because
  JavaScript reads the limit through `ToUint32` and -1 becomes 4294967295;
  that makes `splitLimit(text, sep, -1)` the same as `split(text, sep)`. An
  empty separator panics (`splitLimit: an empty separator`) whatever the
  limit, as `split`'s does, even where JavaScript would answer `[]`.

### Byte runs: `skipBlank`, `skipDigits`, `skipJsonText`, `skipJsonPlain` and `copyBytes` in `nish/bytes`

The four runs answer the first index in `[from, to)` of a `u8[]` whose byte
is not in their class, or `to` when every byte there is; `copyBytes` copies a
window of one array into another, or into itself
([wp38-simd.md](wp38-simd.md), S6a). They are the scans and the copy a parser
spends its time in, and `std/json` is written over them.

```typescript
import { copyBytes, skipBlank, skipDigits, skipJsonPlain, skipJsonText } from "nish/bytes";

export const main = (): i32 => {
  const text: u8[] = [32, 10, 52, 50, 44, 34, 104, 105, 34]; // " \n42,\"hi\""
  const start = skipBlank(text, 0, 9);
  console.log(`${start} ${skipDigits(text, start, 9)}`);   // 2 4
  console.log(`${skipJsonText(text, 6, 9)}`);              // 8, the closing quote
  console.log(`${skipJsonPlain(text, 0, 9)}`);             // 1, the newline
  const word: u8[] = [0, 0];
  copyBytes(word, 0, text, 6, 2);
  console.log(`${word[0]} ${word[1]}`);                    // 104 105
  return 0;
};
```

- **The classes.** `skipBlank` skips JSON's four blanks (space, tab, newline,
  carriage return) and `skipDigits` the ASCII digits. `skipJsonText` skips
  what a JSON string holds as itself: printable ASCII other than `"` and `\`
  (DEL included, which JSON does not escape), and every well-formed UTF-8
  sequence (RFC 3629 §4) that ends before `to`. It stops at a quote, a
  backslash or a control byte, and at the lead byte of a sequence that is
  overlong, a surrogate, past U+10FFFF, a stray continuation byte or cut short
  by `to`, so where it stops is the byte a decoder has to look at.
  `skipJsonPlain` skips what a JSON writer copies without an escape: every
  byte from 0x20 up other than `"` and `\`, DEL and 0x80–0xff included, with
  no UTF-8 check. It stops at a quote, a backslash or a byte below 0x20.
- **The runs never panic.** `to` is clamped into `[0, b.length]` and `from`
  into `[0, to]`, as `indexOfAny` clamps: a negative `from` scans from the
  start, and a `from` at or past `to` answers it
  (`tests/link/std_bytes_runs`).
- **`copyBytes` panics on a range outside its array.** A negative `count`, or
  a window that does not lie inside `src` or `dst`, panics
  `copyBytes: the range lies outside an array` before any byte is written
  (`tests/link/std_bytes_copy_outside`). Overlapping ranges of one array copy
  as if every byte were read before any was written, as `copyWithin` does.
- **The walkers are the meaning.** Each public function clamps or checks its
  range, then makes one call to a private walker, a plain loop over the bytes,
  which is what runs under Node. Natively the compiler recognises that call by
  module and name (`src/kernels.ts`), as it does `indexOfAny`'s, and emits the
  runtime's `nish_bytes_skip_blank`, `nish_bytes_skip_digits` or
  `nish_bytes_skip_json_text` or `nish_bytes_skip_json_plain` (`runtime/runtime-bytes.c`) in its place, or one
  `llvm.memmove` for the copy. The kernels pick a scalar, a 16-byte (SSE2,
  NEON or wasm SIMD) or a 32-byte (AVX2) path on their first call, and
  `NISH_SIMD=scalar|base|avx2` pins it, except in a freestanding wasm32 build,
  which has no environment to read it from.
- **The runs are variable-time.** How long one takes says how long the run is,
  so they are for text, never for secret data: `std/crypto` does not call
  them.

### SQLite: `nish/sqlite`

`nish/sqlite` is the SQLite C library, linked into a program that imports the
module, with a `Database` and a `Statement` to drive it. A statement is
prepared once and bound, stepped and reset as often as wanted:

```typescript
import { openDatabase, OPEN_READWRITE, OPEN_CREATE } from "nish/sqlite";

export const main = (): i32 => {
  const db = openDatabase(":memory:", OPEN_READWRITE | OPEN_CREATE).expect("open");
  db.exec("CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT)").expect("create");
  const insert = db.prepare("INSERT INTO t (name) VALUES (?1)").expect("prepare");
  insert.bindText(1, "ada").expect("bind");
  insert.step().expect("insert");
  insert.reset().expect("reset");
  console.log(`${db.lastInsertRowid()}`);
  db.close().expect("close");
  return 0;
};
```

- **Every failure is a `Result`.** `openDatabase` and `prepare` answer a
  `SqliteError`, with SQLite's extended code (`extendedCode`, such as 2067 for
  `SQLITE_CONSTRAINT_UNIQUE`), its primary code (`code`, the low byte) and
  SQLite's message. Every other call answers the bare extended code, and
  `error(code)` on the `Database` or `Statement` that answered it builds the
  `SqliteError`, so a failure allocates only for the caller who asks.
  `step()` answers `true` with a row to read and `false` when the statement
  has finished.
- **A row allocates nothing.** Binding, `step`, `reset`, `columnI64`,
  `columnF64` and `columnInto` answer scalars; `columnInto(c, buf, at)` copies
  a text or blob column into the caller's `u8[]`, and answers its length,
  copying only when all of it fits. `columnText(c)` is the call that makes a
  string, and it stops at the first NUL byte. Parameters count from 1 and columns from 0, as in SQLite.
- **`exec(sql)`** runs every statement of `sql` and discards any rows, and
  `begin()`, `commit()` and `rollback()` are `exec` of `BEGIN`, `COMMIT` and
  `ROLLBACK`; pragmas, such as `journal_mode=WAL`, are SQL too. A binding is
  copied by SQLite, and `reset` keeps the bindings.
- **A handle is an `i32`** into tables the C adapter keeps per thread. `close`
  finalizes every statement the connection still has, and a handle used after
  `close` or `finalize` answers `SQLITE_MISUSE` rather than reaching freed
  memory. A connection and its statements belong to the thread that opened
  them.
- **It reaches `ffi`.** The module calls C through `declare function`, so a
  program that imports it is reported with [`ffi`](#capabilities) and
  `--deny ffi` refuses it, naming the call. The files SQLite opens are opened
  by C, which the `fs.read` and `fs.write` capabilities do not see. It is
  tested natively and under `--profile wasi` (`tests/link/std_sqlite*`).

### Interfaces and object literals

```ts
interface Pair { first: number; second: number; }

const swap = (p: Pair): Pair => ({ first: p.second, second: p.first });
```

- **A record type is always a declared name.** There is no inline object
  type: `(p: { x: i32 }) => p.x` is
  `` syntax error: expected a type name, found `{` `` (NL0001), and so is the
  same type after `type Point =`, in a field, a return type or a type
  argument (`tests/cases/reject_type_object_literal_param`,
  `reject_type_object_literal_alias`, `_field`, `_return`, `_type_arg`).
  A record type is identified by its declaration, not by its fields: two
  interfaces that declare the same fields are two types, and a value of one
  is refused where the other is wanted, the only widening being a class to an
  interface it `implements` ([Types](#types)). So a record's fields are declared
  once, in an `interface` or a `class`, and every annotation names it.
- An interface is a struct type with the same layout rules as a class, with
  fields only: a method, or an accessor signature `get x(): i32`, is
  `` Interface `Shape` cannot declare methods (interfaces describe layout only) ``
  (`tests/cases/reject_iface_method`, `reject_iface_accessor`; a field may
  still be called `get` or `set`), `extends`
  is ``Interface inheritance (`extends`) is not supported; list every field``
  (`tests/cases/reject_iface_extends`, `reject_generic_interface_extends`),
  an index signature is
  `` Index signatures are not supported in interface `Point` (object layout is fixed) ``
  (`reject_iface_index_signature`), a construct or call signature,
  `new (): Point` or `(x: i32): i32`, is
  `` Unsupported interface member in `Point`: ConstructSignature `` (or
  `CallSignature`, `reject_iface_member_unsupported`), `declare interface` is
  `` `declare interface` is not supported ``, and `new` on an
  interface is `` Cannot `new` interface `Pair` `` (`tests/cases/reject_cls_new_interface`).
- An **object literal** allocates in the arena and stores every property in
  source order. It must set every field exactly once (`` is missing field `second` ``,
  `tests/cases/reject_cls_literal_missing`; `` `Pair` has no field `third` ``,
  `reject_cls_literal_extra`), with plain identifier keys and `key: value`
  or shorthand members: a key written as a string or a number is
  `Object literal keys must be plain identifiers` (`reject_cls_literal_key`),
  and a method or an accessor is
  ``Unsupported object literal member: MethodDeclaration (only `key: value`)``
  (`GetAccessor`, `SetAccessor`; `reject_cls_literal_member`) — `get`, `set`
  and `async` stay keys and shorthands (`{ get: 1 }`, `{ get }`). It takes its type from the context: a variable
  annotation, the enclosing function's return type, the parameter it is
  passed to, the field or variable it is assigned to, or the field of an
  enclosing literal; otherwise
  `Object literal needs a contextual class or interface type`
  (`tests/cases/reject_cls_literal_no_context`, `cls_interface_literal`,
  `cls_nested`). That context reaches a *nested* object literal and a `null`,
  and stops there: a numeric literal written for a field keeps the mode's
  default type (see "Numeric literals"), and `[]` has no element type at all
  in this position — `{ xs: [] }` is `Empty array literal needs a type
  annotation` and wants a named array instead
  (`tests/cases/reject_struct_field_empty_array`). A value of the wrong type
  is `` Field `code` of `IoError` expects a value of type i32, got f64 ``
  (`reject_struct_field_f64`).
- A **nullable context** gives an object literal the struct inside it:
  wherever one of the contexts above expects `E | null` — a declared local,
  a `return`, an arrow's concise body, a ternary arm whose other arm is
  `null`, a parameter, or a field — the literal is an `E`, checked against
  `E`'s fields as above, and that `E` converts to `E | null` as any other
  `E` value does, the same pointer with no wrapper
  (`tests/cases/obj_lit_nullable_ternary`, `obj_lit_nullable_return`,
  `obj_lit_nullable_arrow`, `obj_lit_nullable_local`,
  `obj_lit_nullable_field`; `reject_obj_lit_nullable_field`). A ternary
  with no declared type around it gives neither arm a struct, so
  `const z = c ? { v: 7 } : null` is still
  `Object literal needs a contextual class or interface type`
  (`reject_obj_lit_nullable_context`).
- A **class with methods** is made only by `new`. Natively a literal would
  take the class's layout and its methods, but under Node it is a plain
  object, and a call on it throws, so wherever a context above types a
  literal as such a class it is
  `` `Counter` has methods, so it is made only by `new`: an object literal would be a plain object under Node, with none of the methods the class is used through. Write `new Counter(...)` ``
  (NL2556; `tests/cases/reject_class_literal_decl`, `…_return`,
  `…_arrow_body`, `…_call_arg`, `…_method_arg`, `…_new_arg`,
  `…_array_elem`, `…_push`, `…_index_assign`, `…_map_set`,
  `…_record_field`, `…_assign`, `…_field_assign`, `…_ternary`, `…_paren`, `…_alias`,
  `…_coalesce`, `…_coalesce_chain`, `…_coalesce_field`, `…_coalesce_call`,
  `…_coalesce_map`, `…_coalesce_optional`, `…_coalesce_ternary`,
  `…_equality`, `…_index_of`, `…_math_max`, `…_fn_param`, `…_unary`,
  `…_compound_bitwise`, `…_compound_arith`, `…_nullable`, `…_generic_class`, `…_generic_target`, `…_generic_method`,
  `…_imported`). A generic method counts as a method; a constructor does
  not. A class with fields alone, and an interface, still take a literal
  (`tests/cases/cls_literal_methodless`). The `nish/threads` classes keep
  their own refusal, NL2515 (see "Atomics"), and a class holding a `Secret`
  keeps NL2545.
- An **object spread** `{ ...s, x: 1 }` copies `s`'s fields into the
  literal, one store per field, and is otherwise the literal written out:
  the spread and `{ x: 1, y: s.y }` emit the same IR, an `alloca` where the
  literal stays local and an arena allocation where it escapes
  (`tests/run.js` "object spread", `tests/cases/obj_spread_twin`). Each
  spread is evaluated once, in source order with the entries around it, and
  the entry written later wins: a field set after a spread overrides it, and
  of two spreads the later one supplies the fields both have; only the
  fields no later entry overrides are stored
  (`tests/cases/obj_spread_order`). A field holding an object is copied as
  the reference it is (`obj_spread_nested`), a class instance spreads its
  fields and none of its methods, as Node's spread does
  (`obj_spread_class`), and a nullable source spreads once narrowed
  (`obj_spread_narrowed`); a write to the source after the spread leaves the
  copy as it was (`obj_spread_class`). The literal must still set every
  field of its type, by the spread or by name: a spread that supplies only
  some of them leaves the rest
  `` Object literal for `Point` is missing field `z` ``
  (`reject_object_spread_missing_field`). Each form whose Node reading would
  differ from the copy is refused:

  | Form | Code | Tests |
  | --- | --- | --- |
  | no contextual class or interface type, `const o = { ...s }`: ``An object literal with a spread needs a contextual class or interface type, whose layout the spread's fields are copied into: annotate the variable (`const p: P = { ...s, x: 1 }`)`` | NL2709 | `reject_object_spread_no_target`, `reject_ffi_handle_walk_spread` |
  | a source that is not a class or interface value, `{ ...n }` for an `i32` | NL2705 | `reject_object_spread` |
  | a source that may be `null`, which Node spreads as no field at all: narrow it first | NL2703 | `reject_object_spread_nullable` |
  | a union source, whose fields depend on the variant it holds | NL2704 | `reject_object_spread_union` |
  | a class instance with a field the target does not declare, which Node would carry on the object | NL2706 | `reject_object_spread_class_extra` |
  | an interface value with a field the target does not declare | NL2707 | `reject_object_spread_extra_field` |
  | a copied field whose type differs from the target's, `i32` into `i64`: the copy converts nothing. A field a later entry sets by name is not copied, so its type is not checked (`obj_spread_override_type`); one a later spread supplies is still checked | NL2708 | `reject_object_spread_field_type` |
  | a field set by name before a spread that always overwrites it, TypeScript's TS2783 | NL2710 | `reject_object_spread_overwritten` |

  An interface value may hold any class that implements it, and such a
  class may declare fields after the interface's prefix (see `implements`
  below): Node copies every own field of the instance, the native copy only
  the interface's. So once the whole program is checked, a spread of an
  interface `I` into a type that lacks a field of some class implementing
  `I` is
  `` Spread of `Named` into `Tagged` may spread an instance of `Item`, which implements it with field `weight` besides: … ``
  (NL3055, `reject_object_spread_width`); spread a value of the class type
  instead. A spread into the typed JSON options of a class is NL2711
  (`reject_json_options_spread`). One gap remains: Nish accepts `private`
  on a field and ignores it, so a class instance with a `private` field
  spreads into a type that declares that field, where `tsc` refuses the
  spread; under Node the copy is the same object either way. A computed key is still refused
  (NL1041). NL1061, Phase 0's old refusal of every object spread, is
  retired and never reused.
- `readonly` on an interface field forbids every assignment (`i.a = 2` is
  `` Cannot assign to readonly field `a` of `Config` ``,
  `tests/cases/reject_cls_readonly_interface`); literals still set it. The
  message drops the class form's "outside its constructor", because an
  interface has none to point at.
- **`class C implements I`** requires `I`'s fields to be `C`'s **first**
  fields, in the same order and with identical types; `C` may declare more
  after them (`tests/cases/cls_implements_prefix`). A missing one is
  `` does not implement `Point3`: it lacks field `z: i32` ``
  (`reject_cls_implements_short`) and a mismatched one is
  `` field 1 is `width: i32` in `Shape` but `height: i32` in `Square` ``
  (`reject_cls_implements_mismatch`); both end
  `(the interface's fields must be the class's first fields, in order)`.

  A `C` then converts to `I` wherever an `I` is expected (initializer,
  return, argument, assignment, field store, ternary arm, `I[]` element) by
  one `bitcast`, because the two address the same bytes at the same offsets
  for every field `I` names; a class with the right fields that does not
  list `I` is not assignable (`tests/cases/cls_implements`,
  `reject_cls_not_implements`). Nothing converts back: there is no downcast,
  no `as`, no `instanceof`. The class's own fields after the prefix reuse
  its tail padding, exactly as clang lays out the same C struct
  (`tests/layout/structs.ts`, classes `K`, `L`, `M`).

  **This is the only widening in the language.** Since WP25 a class is a
  prefix of nothing but the interfaces it names, which is what lets two
  classes with different tails be held in one `I[]` and operated on by one
  function (`tests/cases/cls_implements_prefix`,
  `tests/differential/corpus/class_prefix`) — the job `extends` used to do,
  without a dispatch rule to get wrong.

### Calling C

**`declare function name(params): T;` declares a C function this program calls
but does not define.** The symbol is the identifier — no mangling, no prefix —
and the call is an ordinary call:

```ts
declare function abs(n: i32): i32;
```

```llvm
declare i32 @abs(i32)
  %0 = call i32 @abs(i32 %n)
```

The spelling is TypeScript's own ambient declaration, and `declare` is a
*contextual* keyword: a variable may still be called `declare`.

**A parameter is a scalar, a `CPtr`, a borrowed `string`, a `u8[]` buffer
with its count or a borrowed `declare class`; a return is a scalar, a `CPtr` or
a copied `string`** — `i32`,
`i64`, `u8`, `u16`, `u32`, `u64`, `f32`, `f64`, `boolean`, `void`, the foreign
pointer below, `string` and `string | null` in either position, and
[a buffer](#a-u8-parameter-a-buffer-and-its-count) and
[a C struct](#a-declare-class-a-c-struct-lent-by-pointer) as a parameter. Any
other class or an interface is rejected with
`` and a declared C function takes scalars, `CPtr`, a `string` it borrows as
`const char *` and a `u8[]` buffer followed by its `u64` count, or a `declare
class` it borrows by pointer `` in a
parameter (`reject_ffi_class_param`), any other array with
`` the only array a declared C function takes is a `u8[]` or a `readonly u8[]` ``
(`tests/cases/reject_ffi_string_array_param`: a `string[]` too, which would be
a `char **` the compiler built per call) and
`` returns a scalar, a `CPtr` or a `string` it copies from a `const char *` ``
in the return position (`reject_ffi_string_array_return`). This is
not a stylistic limit: **the only pointer this compiler allocated that crosses
the boundary is a string C reads for the length of the call, and the only one
C hands back that the program keeps is a copy it made**, so there is nothing for
a foreign function to capture or free, which is what lets the escape analysis
stay correct without knowing anything about the callee.

**A `u8`, `u16` or `boolean` crosses as C's `unsigned char`, `unsigned short` or
`_Bool`, and the caller widens it** (#1755). The x86-64 SysV and Apple arm64
ABIs give the caller that job and a callee clang built reads the whole
register, so the `declare` and every `call` carry `zeroext` on each such
parameter and result; `toU8(511)` reaches C as 255
(`tests/cases/ffi_narrow_zeroext`):

```llvm
declare i32 @widen_u8(i8 zeroext)
declare zeroext i1 @is_odd(i32)
  %3 = call i32 @widen_u8(i8 zeroext %2)
```

Nish has no signed integer narrower than `i32`, so no argument takes `signext`.

#### A `string` parameter: borrowed for the length of the call

**A `string` parameter is C's NUL-terminated `const char *`, and C borrows it:
a foreign function may read the bytes until it returns and may not keep the
address.** A function that keeps its argument — `putenv`, `setvbuf`'s buffer, a
callback's context — is declared to take a `CPtr` instead, and the program hands
it a copy C made (`tests/cases/ffi_string_param`, `ffi_string_param_arena`,
[cookbook](IR_COOKBOOK.md#a-string-parameter-borrowed-as-const-char-)):

```ts
declare function strdup(s: string): CPtr | null;
declare function putenv(entry: CPtr): i32; // keeps the pointer: C's, not ours

const kept = strdup("MODE=fast");
if (kept !== null) {
  putenv(kept);
}
```

```llvm
declare i8* @strdup(i8*)
  %0 = getelementptr inbounds i8, i8* bitcast ({ i64, [10 x i8] }* @.str.0 to i8*), i64 8
  %1 = call i8* @strdup(i8* %0)
```

- **The argument is the string's own bytes, with no copy.** A `nish_str` stores
  them NUL-terminated, a literal included, so the call passes the address eight
  bytes into it. The escape analysis treats the argument as a read, the way it
  treats a string `console.log` prints: an arena scope that holds it is released
  after the call returns, and the call is never a `tail` call.
- **C may not write through it.** A literal lives in read-only constant data and
  an arena string is shared freely, so a C function that writes into its
  argument (`strtok`, `mkstemp`) corrupts a value the program still holds, or
  faults. Such a function takes a `CPtr` buffer allocated through C. The
  compiler cannot check this rule; it is the declaration's author's word, like
  the borrow.
- **A string that holds a NUL byte panics before the call**, because C would
  read the NUL as the end of the string — `"secret\0.txt"` would pass a
  `.txt` check in the program and name `secret` in C. The message names the
  callee, the argument's position and the parameter:
  `` `strlen`: argument 1 (s) holds a NUL byte, which C would read as the end of
  the string `` (`tests/cases/panics_ffi_nul`). That is the
  [`ffi-nul` panic site](#panic-sites). A literal with no NUL in it is proved
  at compile time, so `puts("hello")` has no check and no site; every other
  string is checked with one scan of the bytes C is about to read anyway.
- **`string | null` passes `NULL` for `null`**, and checks only a string.
- **The declaration carries no attribute** for a string parameter: `nocapture`
  and `readonly` would restate the borrow as an LLVM fact the C body need not
  honour, which would be a miscompile rather than a broken contract.

#### A `string` result: copied out of C's `const char *`

**A `declare function` that returns `string` or `string | null` answers C's
NUL-terminated `const char *`, and the program copies its bytes into the arena
at the call.** C keeps its buffer — `strerror`'s table, `getenv`'s environment,
`setlocale`'s static, which the next call may overwrite — and the copy is the
program's own string from then on, placed, kept and released like any other
allocation of the function that made the call (`tests/cases/ffi_string_return`,
[cookbook](IR_COOKBOOK.md#a-string-result-copied-out-of-const-char-)):

```ts
declare function strerror(errnum: i32): string;
declare function getenv(name: string): string | null;

console.log(strerror(2)); // No such file or directory
const home = getenv("HOME");
```

```llvm
  %0 = call i8* @strerror(i32 2)
  %1 = icmp eq i8* %0, null
  br i1 %1, label %ffi.null, label %ffi.copy

ffi.copy:
  %2 = call i8* @nish.ffi.str(i8* %0)
```

- **The copy is one scan for the NUL and one `nish_str_new`**, in a private
  helper the module defines once (`@nish.ffi.str`). C's pointer is never held
  past it, so a buffer C reuses or frees later cannot reach the program.
- **Every call's copy is new, and is the calling function's allocation**, as
  `s.substring(...)` is: a loop that keeps one keeps it past the pass, and a
  `using a = arena()` block that would release one held outside it is refused,
  as it is for any fresh string (`tests/cases/ffi_string_loops`,
  `reject_ffi_string_arena`).
- **The copy follows the call, so a call with a `string` result is never a
  `tail` call**: a C function that answers a pointer into its argument
  (`strchr`, `strstr`) is read before that argument's arena scope is released.
- **`string | null` reads `NULL` as `null`**, tested before the copy but with
  no panic site.
- **A `string` result that is `NULL` panics after the call**, because a
  `string` cannot hold it: `` `getenv` returned NULL for a `string` result;
  declare it `string | null` `` (`tests/cases/panics_ffi_null`). That is the
  [`ffi-null` panic site](#panic-sites). Declare the result `string | null`
  whenever the C function's manual says it may answer `NULL`.
- **A result C allocated for the caller to free (`strdup`, `realpath` with no
  buffer) is a `CPtr`, not a `string`**: the copy would leave C's allocation
  with no one to free it. Declare it `CPtr | null`, copy it with
  [`readCString`](#readcstring-a-string-out-of-a-buffer-c-owns), and pass the
  pointer back to `free`.

#### `CPtr`: the pointer a C function hands back

**`CPtr` is an address C owns.** It is eight bytes and `i8*` in the IR, and that
is the whole of what the compiler knows about it: it is not arena memory, not a
`%struct`, not a `nish_str`, and its lifetime is the C library's business
(`tests/cases/ffi_pointer`, [cookbook](IR_COOKBOOK.md#cptr-the-pointer-a-c-function-hands-back)).

```ts
declare function calloc(count: u64, size: u64): CPtr | null;
declare function free(block: CPtr): void;
```

- **It may be written in a `declare function` signature and on a local that
  holds one, and nowhere else.** A field, an array element, a `Result` arm, a
  type argument, and the parameters or return type of a function this program
  defines are all
  `` `CPtr` cannot be ...: a foreign pointer may only appear in a `declare
  function` signature or on a local bound to one ``
  (`reject_ffi_pointer_field`, `reject_ffi_pointer_array`,
  `reject_ffi_pointer_param`, `reject_ffi_pointer_return`,
  `reject_ffi_pointer_type_argument_fn`). The first group
  would put a foreign address inside a value the arena owns and the escape
  analysis walks; the second would put one across a boundary `--emit-header`,
  `--emit-dts` and `--emit-napi` describe, and none of the three has a spelling
  for an address whose provenance and lifetime are unknown. The type-argument
  clause is stated where a generic function or class is instantiated
  (`reject_ffi_pointer_type_argument`), so `new Empty<CPtr>()` is refused even
  when no member of `Empty<T>` names `T`. The fields that may hold a `CPtr`
  are a handle class's and a [`declare class`](#a-declare-class-a-c-struct-lent-by-pointer)'s, below.
- **A `null` reaches C only as the literal.** A `declare function` may return
  `CPtr | null` and may take one, and a call passes a `CPtr | null` parameter
  either the literal `null` — `realpath(path, null)`, `getcwd(null, 0)`, the
  manual's "pass NULL to have it allocated" — or a pointer narrowed with
  `if (p !== null)`. A nullable pointer the program holds is
  `` Argument 1 of `free` is a `CPtr | null` the program holds: a nullable
  foreign parameter takes the literal `null` or a pointer narrowed with
  `!== null`, so C is never handed a null by a path nobody tested ``
  (NL2539, `reject_ffi_pointer_nullable_variable`), wherever it is held: a
  local, a parenthesised one, a ternary or `??` that may answer it, inside a
  constructor reached by `new` or a method, and through a function parameter
  a `declare function` is passed to (`reject_ffi_pointer_nullable_specialised`).
  So every `NULL` C receives is one the source spells, and a pointer that may
  be `NULL` because C said so is narrowed before it goes back. The narrowing
  is the ordinary nullable one (WP6). The literal lowers to `i8* null`
  (`tests/cases/ffi_owned_string`).
- **No arithmetic, no dereference, no index, no member.** `p + 1` is
  `` Operator `+` requires two operands of the same numeric type ``
  (`reject_ffi_pointer_arithmetic`) and `p[0]` is
  `` Cannot index a value of type CPtr ``. What is left is `=== null`,
  `!== null`, comparing two `CPtr`s, assignment, and passing one to another
  foreign function.
- **It gets no pointer attributes.** `dereferenceable`, `align`, `nonnull`,
  `nocapture` and `readonly` are each a claim about memory this compiler laid
  out, and it laid out none of this; `isPointerParam` in
  `src/attributes.ts` is an allow-list so that a `CPtr` falls out of it
  by construction rather than by a case somebody remembered to write.

#### `readCString`: a string out of a buffer C owns

**`readCString(p: CPtr): string`, from
[`nish:unsafe`](#nishunsafe-unchecked-access-and-defined-wrapping), copies the
NUL-terminated bytes at `p` into a new string of the program's own.** It is the
copy a `string` result makes, offered for the pointers a `string` result cannot
be: the ones C allocated for the caller to free. The program copies, then frees
C's buffer itself (`tests/cases/ffi_owned_string`,
[cookbook](IR_COOKBOOK.md#readcstring-a-string-out-of-a-buffer-c-owns)):

```ts
import { readCString } from "nish:unsafe";

declare function strdup(s: string): CPtr | null;
declare function free(p: CPtr): void;

const owned = (s: string): string => {
  const p = strdup(s);
  if (p === null) {
    return "";
  }
  const copy = readCString(p);
  free(p);
  return copy;
};
```

```llvm
if.end:
  %6 = load i8*, i8** %p.addr, align 8
  %7 = icmp eq i8* %6, null
  br i1 %7, label %ffi.null, label %ffi.copy

ffi.null:
  call void @nish_panic(i8* bitcast ({ i64, [34 x i8] }* @.str.3 to i8*))
  unreachable

ffi.copy:
  %8 = call i8* @nish.ffi.str(i8* %6)
  store i8* %8, i8** %copy.addr, align 8
  %9 = load i8*, i8** %p.addr, align 8
  call void @free(i8* %9)
```

- **It is `nish:unsafe` because nothing proves the bytes end.** The copy scans
  for the NUL with the `@nish.ffi.str` helper a `string` result uses, and a
  pointer that is dangling, already freed, or to a buffer with no NUL is
  undefined behaviour: the import is the author's word, as `uncheckedGet`'s is.
  It is an `unsafe` call to `--deny unsafe`, and the `CPtr` it reads came from
  a `declare function`, which is `ffi`.
- **A `NULL` pointer panics before the copy**, with the
  [`ffi-null`](#panic-sites) kind, as
  [`readStruct`](#readstruct-a-struct-out-of-memory-c-owns)'s does:
  `` `readCString` read a NULL pointer ``, exit 1
  (`tests/cases/panics_ffi_read_cstring_null`). The parameter is `CPtr`, so
  an unnarrowed pointer is
  `` `readCString` expects an argument of type CPtr, got CPtr | null ``
  (`reject_unsafe_read_cstring`) and `if (p !== null)` comes first, but a
  `declare function` declared to answer `CPtr` may still answer `NULL`, so
  the copy tests its pointer: the `icmp eq` and the branch to `ffi.null`
  above. No proof removes the test, so `--deny-panics` refuses a call in its
  scope; the copy's `oom` beside it is allowed. Declare a result that may be
  `NULL` as `CPtr | null` and narrow it, rather than lean on the panic.
- **The copy is new on every call and is the calling function's allocation**,
  as a `string` result's is: kept past a loop's pass, returned, stored by a
  constructor and released with its owner, and refused inside a `using a =
  arena()` block that would release one held outside it (`` `readCString(p)` may
  be allocated inside the `using arena()` block ``,
  `reject_ffi_owned_string_arena`). C's buffer is never held past the call, so
  `free(p)` straight after it is safe.
- **On wasm32 it lowers to the same helper.** `@nish.ffi.str` is a byte scan and
  a `nish_str_new`, which every runtime has, so `readCString` adds nothing to
  the link; whether the program links there is the `declare function`'s
  question, answered by the libc the target has.

#### `cErrno`: the errno a C call left

**`cErrno(): i32`, from
[`nish:unsafe`](#nishunsafe-unchecked-access-and-defined-wrapping), answers the
errno the most recent `declare function` call on this thread left, and 0
before any.** In a program that names it anywhere, the compiler sets errno to 0
immediately before every `declare function` call and copies errno into a
per-thread runtime slot immediately after it returns, before any result is
marshalled; `cErrno()` reads the slot (`tests/cases/ffi_errno`,
[cookbook](IR_COOKBOOK.md#cerrno-errno-after-a-foreign-call),
[design](wp27-ffi.md#10-s5-as-built-cerrno)):

```ts
import { cErrno } from "nish:unsafe";

declare function strtol(s: string, end: CPtr | null, base: i32): i64;

const parse = (s: string): i64 => {
  const n = strtol(s, null, 10);
  return cErrno() === 0 ? n : -1;
};
```

```llvm
ffi.ok:
  %2 = getelementptr inbounds i8, i8* %s, i64 8
  %3 = call i32* @nish_errno_ptr()
  store i32 0, i32* %3, align 4
  %4 = call i64 @strtol(i8* %2, i8* null, i32 10)
  %5 = load i32, i32* %3, align 4
  store i32 %5, i32* @nish_errno_slot, align 4
  store i64 %4, i64* %n.addr, align 8
  %6 = load i32, i32* @nish_errno_slot, align 4
```

- **Saved before anything else runs.** The copy of a `string` result, an arena
  allocation or a `console.log` may call into libc and move errno, so the save
  is the first instruction after the call, ahead of the `NULL` check of a
  `string` result. A C function that sets errno and answers a string is read
  correctly after the copy.
- **Zeroed before, so a success reads 0.** `strtol` reports an out-of-range
  number only through errno; with the zeroing, `cErrno()` after an in-range
  call is 0 unless the callee set it. No setter is exposed.
- **Per thread.** errno is per thread in every libc, and the slot is
  `_Thread_local` under `--threads` (`thread_local(initialexec)` in the IR), so
  a thread reads what its own last call left (`ffi_errno_threads`).
- **Program-wide, and free when unnamed.** One `cErrno` anywhere makes every
  `declare function` call in every module of the program pay the zero and the
  save, and none of them is then a tail call. A program that never names it
  emits none of it.
- **Not covered:** a host-module import (`--host`) is not a C call; the close a
  `using` handle runs at scope exit is the compiler's call, not the program's,
  and is not captured.
- **Not a global.** errno is a macro over a thread-local accessor in every
  libc, so there is no `errno` symbol to declare, and `declare let errno: i32`
  is the parser's
  `` a module holds only `function`, `class`, `interface`, `const`, `type`, `enum` and `import`, found `IDENT` ``
  (`reject_ffi_errno_global`).
- **Refused:** an argument (`` `cErrno` expects exactly 0 arguments, got 1 ``,
  `reject_ffi_errno_arg`), a call without the import (NL2456,
  `reject_ffi_errno_import`), and a freestanding wasm32 build, which has no
  operating system:
  `` `cErrno` reaches the operating system, and a wasm32 build has none to reach ``
  (`reject_ffi_errno_wasm`). `--profile wasi` links wasi-libc and keeps it.
- **It is `nish:unsafe` and an `unsafe` call** to `--deny unsafe`, like every
  export of the module; it reads a defined value and is no panic site.

#### A `u8[]` parameter: a buffer and its count

**A `u8[]` or `readonly u8[]` parameter is a buffer C reads or writes, and a
run of one or more of them is followed by exactly one `u64`: the byte count C
may touch in every buffer of the run.** Pairing the count by position is the
declaration's word, not a proof. `fwrite(ptr, size, nmemb, stream)` touches
`size * nmemb` bytes, so declared as `fwrite(buf: readonly u8[], size: u64,
nmemb: u64, f: CPtr)` it pairs `size` with the buffer, and `fwrite(buf, 1,
1000, f)` on a 10-byte array overflows it. The safe spelling declares the size
as the count and passes `1` as `nmemb`: `fwrite(buf: readonly u8[], n: u64,
one: u64, f: CPtr)`, called as `fwrite(buf, n, 1, f)`. Nothing stops a call from
passing another `nmemb`, which is the same class of mistake as declaring `free`
with two parameters.

```ts
declare function memcpy(dst: u8[], src: readonly u8[], n: u64): CPtr;
declare function getentropy(buf: u8[], n: u64): i32;
declare function compare(a: readonly u8[], na: u64, b: readonly u8[], nb: u64): i32;
```

- **`memcpy(dst, src, n)` is one run of two buffers sharing a count**, and
  `(a, na, b, nb)` is two runs with a count each (`tests/cases/ffi_buffer_declared`).
  The same array passed twice in one run, `memcpy(a, a, n)`, is not refused:
  C sees two pointers to one block, and overlapping `memcpy` is undefined in C
  (`memmove` is the one that allows it).
- **`readonly u8[]` is C's `const`.** A `u8[]` parameter says C may write the
  bytes; a `readonly u8[]` says it only reads them. C can cast the `const`
  away, and the compiler cannot check that.
- **A run with no count after it is refused**, with `` takes the buffer `md`
  with no count after it: a run of `u8[]` parameters is followed by one `u64` ``
  (`reject_ffi_buffer_length_missing`, `SHA256(d, n, md)`'s fixed-size output),
  and so is a count of any other type, `` and the parameter after a run of
  `u8[]` buffers is their byte count, a `u64` `` (`reject_ffi_buffer_length_type`).
- **Only `u8` crosses.** `i32[]` or `f64[]` is
  `` the only array a declared C function takes is a `u8[]` or a `readonly u8[]` ``
  (`reject_ffi_buffer_element`).
- **A buffer is never null and never a result.** `u8[] | null` is refused
  (`reject_ffi_buffer_nullable`, and `reject_ffi_buffer_nullable_in_run` for one
  inside a run): it has no length to hold the count to, so the
  `NULL, 0` call C allows is declared with a `CPtr | null` parameter. A `u8[]`
  result is refused by the return rule above (`reject_ffi_buffer_return`).
- **A call passes the array's data block, and checks the count against every
  buffer of its run first.** Each buffer is lowered to its data pointer, a
  `uint8_t *` (`i8*` in the IR), and the count is compared, unsigned, with the
  buffer's length before C runs. A count larger than one of them stops the
  program with an `ffi-length` panic, `` `write`: argument 3 (n) counts more
  bytes than argument 2 (buf) holds ``, exit 1 (`tests/cases/panics_ffi_length`,
  and `panics_ffi_length_memcpy` for the shorter buffer of a run). The count is
  a `u64`, so `toU64(0) - toU64(1)` is the largest count there is, and fails
  (`panics_ffi_length_wrapped`).
- **The pointer and the length are read after the last argument is
  evaluated**, so C sees the array as it is at the call: an argument that
  pushes or pops before it is seen (`tests/cases/ffi_buffer_late_load`,
  `panics_ffi_length_shrink`, `panics_ffi_length_inline_pop`).
- **One count is proved: `toU64(b.length)` of the buffer itself**, where `b`
  is a `const` local or a parameter named alone and no later argument may
  resize an array. Such a call carries no check and is not a panic site, so
  `read(fd, buf, toU64(buf.length))` compiles under `--deny-panics`. A field
  path, an alias of the buffer, another array's length and a literal are
  checked (`tests/cases/ffi_buffer_count_proved`). `--deny-panics` refuses
  any other count and names the one it accepts: `` pass `toU64(buf.length)`
  of the buffer itself, which needs no check ``.
- **C borrows the bytes for the call, and writes through a `u8[]`.** As with
  a `string`, the pointer is lent for the length of the call and C may not
  keep it, so a buffer made in the call's arena scope is released after it
  (`tests/cases/ffi_buffer_read`). A `u8[]` argument is written by the call
  and a `readonly u8[]` one is not, and the compiler records it as it records
  a store. An exported function that hands its own `u8[]` parameter to such a
  call writes that parameter: its header drops the `const`, the wasm glue
  copies the bytes back, and its `define` loses `readonly`
  (`tests/cases/ffi_buffer_export_written`). A task a scope spawns may not
  reach such a call: C's body is unseen, so the call may write memory the
  parent can see, and the task is refused with `` writes memory its caller
  can see `` (`reject_ffi_buffer_call_spawn`, and
  `reject_ffi_buffer_scope_race`, `reject_ffi_buffer_scope_field_race` and
  `reject_ffi_buffer_scope_element_race` for a call reached through a
  function).
- **Every kind of call site lowers the same way**: a call by name, through a
  function parameter bound to the declaration, in a constructor reached by
  `new` and in a method (`tests/cases/ffi_buffer_call_sites`), and a call that
  passes a buffer is refused by `--deny ffi` like any other foreign call.
- **On wasm32 a `u64` count is wider than C's `size_t`.** The data pointer is
  32 bits there and the length check is the same 64-bit compare, but a C
  function whose count is a `size_t` takes 32 bits: declare its count `u64`
  only on a target where `size_t` is 64 bits, until a later release gives the
  count a target-width type. A freestanding wasm build (`--target wasm32`)
  refuses a `declare function`, so a buffer declaration is for `--profile
  wasi` there (see "Host modules" below).

#### A handle class: a class that owns a `CPtr`

**A class with a `CPtr` or `CPtr | null` field is a handle class: it owns the C
resource the pointer names, and its `[Symbol.dispose]` names the C function
that closes it** (`tests/cases/ffi_handle_positions`, `docs/wp53-ffi-buffers-handles.md`
§4a–§4d).

```ts
declare function fopen(path: string, mode: string): CPtr | null;
declare function fclose(p: CPtr): i32;
declare function fgetc(p: CPtr): i32;

class File {
  readonly file: CPtr | null;
  constructor(path: string) {
    this.file = fopen(path, "r");
  }
  read(): i32 {
    const p = this.file;
    if (p === null) {
      return -1;
    }
    return fgetc(p);
  }
  [Symbol.dispose](): void {
    const p = this.file;
    if (p !== null) {
      fclose(p);
    }
  }
}

const first = (f: File): i32 => f.read();
```

**`using` of a handle class closes it at every exit of its block, once.**
`using f = new File(p)` opens `f` as soon as its initialiser returns, before a
later declarator's initialiser runs, and calls the close its
`[Symbol.dispose]` names on every way control leaves the block: falling off
its end, `return`, `break`, `continue`, and an `orReturn()` that propagates,
including one in a later declarator's initialiser. A `return` computes its
value first and closes after it, so `return twice(n)` inside the block is not
a tail call. Each declarator opens before the next one's initialiser runs.
Falling off the end, `break` and `continue` close the declarators in the
reverse of the order they opened, beside an arena, a scope or a lock in the
same `using`. A `return` or a propagating `orReturn()` joins every `scope()`
before its value is computed (the value may read what the tasks stored), then
closes the handles and gives back the locks, innermost first, then releases
the arenas (`ffi_handle_file`, `ffi_handle_exits`, `ffi_handle_arena`,
`ffi_handle_shapes`, `tests/link/ffi_handle_mutex`,
`tests/link/using_declarator_exit`). The close is inlined as the dispose spells
it: the field is loaded and the C function called with it, behind a `null`
test only when the dispose writes one (`const p = this.f; if (p !== null)`);
a dispose that is the single call `close(this.f)` calls it with the field as
it is, `null` included (`ffi_handle_shapes`). The `using` is where the program reaches `ffi`, so
`--deny ffi` refuses it and names the close (`caps_ffi_handle`,
`reject_ffi_handle_deny`).

A panic and `process.exit` do not close: the process ends, and the operating
system takes back the descriptor. What it does not take back is what a C
library still buffers. `panic`, `expect` and a failed range entry end through
`exit(1)`, which flushes stdio, but a failed check and out of memory end
through `_exit(1)`, which does not, so bytes written to a `FILE *` with
`fwrite` and not yet flushed are lost on a bounds panic. Flush (`fflush`)
before code that may panic when those bytes matter.

- **The class.** Exactly one `CPtr` or `CPtr | null` field, `readonly` and with
  no initialiser (`reject_ffi_handle_two_fields`, `_field_mutable`,
  `_field_initialiser`). No type parameters, no `implements`, no `export`
  (`_generic_class`, `_implements`, `_export`), and no `static readonly json`
  (`_json`).
- **The write.** The constructor writes the field once, as
  `this.file = g(...)` at its top level, with `g` a `declare function` and no
  exit before it (`_field_copy`, `_field_copy_twice`, `_field_copy_branch`,
  `_field_copy_non_foreign`).
- **The read.** The pointer is read only as `this.file` inside a method of the
  class, passed straight to a `declare function` or bound once to a `const`
  (`_field_read_outside`, `_field_other_instance`, `_field_alias_copy`,
  `_field_alias_let`, `_field_position`): `` The pointer `file` of handle class
  `File` cannot be used here ``.
- **The close.** `[Symbol.dispose](): void` is `close(this.file);` or
  `const p = this.file; if (p !== null) { close(p); }` for a `declare
  function` `close` of one parameter (`_no_dispose`, `_dispose_body`,
  `_dispose_arity`, `_dispose_arg_type`, `_dispose_unknown`, `_dispose_forms`,
  `_dispose_shapes`). A class declares one, with no modifier
  (`_dispose_twice`, `_dispose_static`). Nothing else may
  call that close on the field, in a method or in the constructor
  (`_close_call`), and `[Symbol.dispose]` is never called by name
  (`_dispose_call`).
- **Where a `File` may be.** It is opened by `using` (once lowered), called
  (`f.read()`), or lent to a parameter of type `File`, which may lend it on.
  Everything else is `` A `File` cannot be used here `` (`_position`): `new`
  outside a `using` initialiser, `this` leaving the constructor, a copy into
  another binding, an array element, an object literal, a capture, a builtin's
  argument, a comparison (`_new_outside_using`, `_this_escapes`, `_alias`,
  `_array`, `_object_literal`, `_closure_capture`, `_builtin_arg`,
  `_walk_compare`).
- **Where `File` may be written.** Only as the type of such a parameter. A
  local's annotation, a field, a return, a `Result` arm, a nullable, a type
  argument and an exported function's parameter are `` `File` is a handle
  class, and its name may be written only as the type of a parameter that
  borrows one `` (`_type_position`, `_field`, `_return`, `_result`,
  `_nullable`, `_type_argument`, `_exported_param`).
- **Not after its close, and not kept past a lend.** A `using` binding's scope
  is its block, which ends where the close is emitted, so a handle named after
  its block — after it, in the loop's next iteration, in a `do` loop's
  condition, in a `for` loop's update, in a later `case`, in the `else`, later
  in a constructor — names nothing: `` Unknown builtin `f.read` `` or
  `` Unknown identifier `f` `` (`_use_after_close`, `_use_after_close_loop`,
  `_use_after_close_do_while`, `_use_after_close_for_update`,
  `_use_after_close_switch`, `_use_after_close_else`, `_use_after_close_ctor`).
  A `using` written straight into a `case` clause is refused by the clause rule
  (`_use_after_close_switch_clause`). A lent handle cannot be kept by its
  callee. The value rule refuses a local (`let saved = f`,
  `_use_after_close_keep`), an alias (`_alias`), an array (`_array`) and a
  `scope()` task (`_scope_task`); the type rule refuses a return (`_return`)
  and a type argument (`_type_argument`), among them a `Map` or a `Channel` of
  the class (`_use_after_close_keep_map`, `_use_after_close_keep_channel`);
  both refuse a field of another class, set in a method, through `new` or as
  `h.l = this` (`_use_after_close_keep_field`, `_walk_ctor_param`,
  `_use_after_close_keep_this`). Some shapes are refused by a general
  rule first: a closure by the arrow-capture rule (`_closure_capture`), and a
  module binding by the absence of a top-level `let` and the rule that a
  module constant is never assigned (`_use_after_close_keep_module`,
  `_use_after_close_keep_module_expr`). In its own constructor `this` is half
  built, and is neither lent, called, stored nor aliased (`_ctor_this_lend`,
  `_ctor_this_receiver`, `_ctor_this_store`, `_ctor_this_alias`).

**Two things stay C contracts, as a buffer's count does.** The class's methods
pass the field only to functions that use it and return, and that neither close
what it owns nor hand it back: `freopen`, a close through a C wrapper with
another name, `close(fileno(p))`, or a C function returning its argument are
not seen by the rules above. And the constructor's foreign call returns a
pointer the object owns: two objects built from one shared pointer would both
close it.

#### A `declare class`: a C struct, lent by pointer

**A `declare class` is a C struct: its fields are laid out in declaration order,
each at its natural alignment, and the size is rounded up to the widest
alignment, as a C compiler lays out the same fields. `new Name()` takes no
arguments and zero-fills it, and a `declare function` parameter typed `Name`
borrows it as a `struct Name *`** (`tests/cases/ffi_struct_param`,
`ffi_struct_layout`, [cookbook](IR_COOKBOOK.md#declare-class-a-c-struct-lent-by-pointer),
`docs/wp27-ffi.md` §9b):

```ts
declare class Timespec {
  sec: i64
  nsec: i64
}
declare function clock_gettime(clock: i32, ts: Timespec): i32

const now = new Timespec()
clock_gettime(1, now)
console.log(now.sec)
```

```llvm
%struct.Timespec = type { i64, i64 }
declare i32 @clock_gettime(i32, %struct.Timespec*)
  %Timespec.obj = alloca %struct.Timespec, align 8
  %0 = bitcast %struct.Timespec* %Timespec.obj to i8*
  call void @llvm.memset.p0i8.i64(i8* align 8 %0, i8 0, i64 16, i1 false)
  store %struct.Timespec* %Timespec.obj, %struct.Timespec** %now.addr, align 8
  %1 = load %struct.Timespec*, %struct.Timespec** %now.addr, align 8
  %2 = call i32 @clock_gettime(i32 1, %struct.Timespec* %1)
```

- **`new` zero-fills every byte, padding included**, with one `llvm.memset` of
  the struct's size: C may compare or hash the whole struct, and a
  `zeroinitializer` store need not write the padding (`ffi_struct_layout`).
- **A `CPtr` field is the target's `void *`**: eight bytes natively, four under
  `--profile wasi` (wasm32), where the struct's size and offsets are the ones
  clang gives the same C struct for that target (`tests/ffi-struct.js`).
- **A field is `i32`, `i64`, `u8`, `u16`, `u32`, `u64`, `f32`, `f64`, `CPtr`,
  `CPtr | null`, or another `declare class`, embedded by value** — C's
  `struct timespec it_value;`, not a pointer to one. A `number` field is
  refused whatever the mode and however it is spelled — in parentheses, through a
  `type` alias or a chain of them, imported or not — since `--number-mode` picks
  its width and a C struct has one layout. The resolver decides it where it meets
  `number`, so no spelling escapes; an alias of `i32` stays a field: `` has type
  `number`, whose width `--number-mode` chooses `` (NL2755,
  `reject_ffi_struct_field_number`, `_paren`, `_alias`, `_alias_paren`,
  `_alias_chain`; `tests/ffi-struct.js`: the imported alias, the `i32` alias). Any other type is
  `` Field `ok` of `declare class Flags` has type `boolean`, which has no C
  layout `` (NL2752, `reject_ffi_struct_field_type`, `reject_cls_declare`,
  `reject_ffi_struct_field_array`, `reject_ffi_struct_field_class`): a
  `boolean`, a `string`, an array and a Nish class have no C spelling the
  compiler could promise. A struct cannot embed
  itself, directly or through another (NL2749, `reject_ffi_struct_self`,
  `reject_ffi_struct_cycle`).
- **A field is plain and has no initializer, and the class has nothing but
  fields**: no `readonly`, `static` or optional field (NL2747), no initializer,
  because `new` zero-fills (NL2748), no constructor, method, accessor or other
  member such as an index signature (NL2751, `reject_ffi_struct_index_signature`), no type parameter (NL2741, `reject_generic_declare_class`), no `extends` or `implements` (NL2750),
  and no `export` (NL2746) — each pinned by a `reject_ffi_struct_*` case.
- **It stays in its module.** It cannot be a parameter or the return type of an
  exported function or an exported class's method, or a field of an exported
  class or interface: `` `declare class Point` cannot be a parameter of an
  exported function `` (`reject_ffi_struct_export_param`, `_return`, `_method`,
  `_field`, `_interface`). A type that holds one is refused there too, however deep —
  through `Result`, `T | null`, an array, a generic instance or a class of
  this program: `` `Wrap` holds a `declare class Point` and cannot be a
  parameter of an exported function `` (NL2756,
  `reject_ffi_struct_export_result`, `_generic`, `_holder`, `_holder_nullable`). So no `.d.ts`
  or N-API binding ever describes one, and `--emit-header`, which lists every
  class of the program, declares a class that holds one only as an opaque
  `typedef struct Holder Holder;` (`tests/ffi-struct.js`, `docs/wp27-ffi.md`
  §9g).
- **It is a native build's.** A wasm module a page loads — freestanding wasm,
  or any build that writes `--emit-dts` — links no C to lend a struct to, and
  its IR is laid out for wasm32 later: `` `declare class Point` declares a C
  struct, and a wasm module a page loads links no C to lend it to `` (NL2757,
  `tests/wordings/nl2757_declare_class_emit_dts`, `nl2757_declare_class_wasm32`).
  A `--profile wasi` build is wasm32 from the start and keeps it.
- **It is built with `new` and nothing else.** `new Point(1)` is refused as for
  any class without a constructor (`reject_ffi_struct_new_args`), and an object
  literal typed as one is
  `` an object literal cannot lay out a C struct `` (NL2744,
  `reject_ffi_struct_literal`).
- **C borrows it for the length of the call**, as it borrows a `string`: it may
  read and write the fields until it returns, and may not keep the address. The
  escape analysis treats the argument as a read, so an instance that does not
  otherwise escape stays in the caller's stack frame; a C function that keeps
  the pointer (an `aio_read` control block, a struct handed to a thread) is
  outside the contract. Its accesses carry no TBAA tag, so a field read after
  the call sees what C wrote, and a function of this program that passes its
  parameter on to C writes through that parameter, so the parameter is not
  `readonly` and its caller's read sees the write too (`ffi_struct_param`).
- **`Name | null` passes `NULL` for `null`**, under the rule a `CPtr | null`
  parameter follows: the literal `null`, or a value narrowed with `!== null`
  (NL2539, `reject_ffi_struct_nullable_held`).
- **An embedded struct is part of its owner.** `stamp.at.sec` reads and writes a
  field in place, and `clock_gettime(1, stamp.at)` lends C the address inside
  `stamp`; those are the only two uses. Holding it — `const at = stamp.at`, or
  passing it to a function this program defines — is
  `` cannot be held as a value `` (NL2743, `reject_ffi_struct_nested_bind`,
  `reject_ffi_struct_nested_nish_arg`), and replacing it is
  `` a `declare class` embedded in its object is written field by field ``
  (NL2745, `reject_ffi_struct_nested_assign`).
- **It is not a return type or an array element.** C returning a struct by
  value, or a pointer into memory it owns, leaves the copy with no owner on
  this side: `` a C struct is only lent to C by pointer: take a `Point`
  parameter for C to fill `` (NL2742, `reject_ffi_struct_return`); a struct
  C owns is copied out with `readStruct` (below) from the `CPtr` C returns. An array of
  them would be a C array the program lays out element by element, and is
  `` cannot be an array element `` (NL2740, `reject_ffi_struct_array`,
  `reject_ffi_struct_array_literal`, `reject_ffi_struct_array_new`), however
  the array's type is spelled.
- **Its fields are C's to fill.** Typed JSON does not decode into one or
  encode one: `` a `declare class`: C reads and writes its fields `` (NL2753,
  `reject_ffi_struct_json`). A spread copies a flat one's fields into a class
  of this program, but not one that embeds another, whose embedded struct is
  not a value: `` which a spread cannot copy `` (NL2754,
  `reject_ffi_struct_spread`).
- **`--emit-ts` refuses a module that declares one**, with the same message as
  for a `declare function` (NL4010): it is C's layout, and JavaScript has none.

#### `readStruct`: a struct out of memory C owns

**`readStruct(p)` from `nish:unsafe` copies the struct at a `CPtr` into a new
instance of the `declare class` its context names, and the copy is the
program's** (`tests/cases/ffi_struct_read`,
[cookbook](IR_COOKBOOK.md#readstruct-a-c-owned-struct-copied-out),
`docs/wp27-ffi.md` §9h). It is how a struct C keeps comes back:
`localeconv()`'s `struct lconv`, `getpwnam`'s `struct passwd`, each a buffer
the next call overwrites.

```ts
import { readStruct, readCString } from "nish:unsafe"

declare class Lconv {
  decimalPoint: CPtr
  thousandsSep: CPtr
}
declare function localeconv(): CPtr

const lc: Lconv = readStruct(localeconv())
console.log(readCString(lc.decimalPoint))
```

```llvm
%struct.Lconv = type { i8*, i8* }
  %0 = call i8* @localeconv()
  %1 = icmp eq i8* %0, null
  br i1 %1, label %ffi.null, label %ffi.copy

ffi.null:
  call void @nish_panic(i8* bitcast ({ i64, [48 x i8] }* @.str.0 to i8*))
  unreachable

ffi.copy:
  %2 = call i8* @nish_alloc_struct(i64 16)
  call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 8 %2, i8* align 1 %0, i64 16, i1 false)
  %3 = bitcast i8* %2 to %struct.Lconv*
  store %struct.Lconv* %3, %struct.Lconv** %lc.addr, align 8
```

- **The layout comes from context**, as `Ok(v)`'s does: an annotation, a
  parameter, a return type or an assignment's target, `| null` stripped. With
  none it is
  `` `readStruct(p)` needs a contextual `declare class` type to copy into ``
  (NL2764), and a context that is not a layout is
  `` `readStruct(p)` copies into a `declare class` layout, and Plain is not one ``
  (NL2765, `reject_unsafe_read_struct_context`). A type argument is not
  written at a call site: `readStruct<Lconv>(p)` is refused with the annotated
  spelling in the message (NL2763, `reject_unsafe_read_struct_type_args`).
- **One copy, the layout's size**: the arena allocation `new` makes, then one
  `llvm.memcpy` of the struct's bytes, padding included, from the source at
  `align 1`, since C promised the struct and not its address's alignment. The
  size is the target's: 16 bytes for `{ CPtr; CPtr }` natively, 8 under
  `--profile wasi` (`tests/ffi-struct.js`). After the call C may free or
  rewrite its struct; the copy is an instance like any `new` one, and a copy
  made in a callee and returned is held by its caller.
- **It does not copy deep.** A `CPtr` field of the copy is still C's pointer,
  read with [`readCString`](#readcstring-a-string-out-of-a-buffer-c-owns) while
  C keeps it live.
- **A `NULL` pointer panics before the copy**, with the
  [`ffi-null`](#panic-sites) kind:
  `` `readStruct` read a NULL pointer into a `Lconv` ``
  (`tests/cases/panics_ffi_read_struct_null`). The argument is a `CPtr`, so a
  `CPtr | null` is narrowed first
  (`` `readStruct` expects an argument of type CPtr, got CPtr | null ``,
  `reject_unsafe_read_struct_null`), but a `declare function` declared to
  answer `CPtr` may still answer `NULL`, so the copy tests its pointer: the
  `icmp eq` and the branch to `ffi.null` above.
  No proof removes the test, so `--deny-panics` refuses a call in its scope.
- **The rest of the pointer is not checked**: not that it is live, not the
  size it covers. The layout must be C's struct or a prefix of it. That is why
  it is in [`nish:unsafe`](#nishunsafe-unchecked-access-and-defined-wrapping):
  refused by `--deny unsafe` and recorded by `--emit-checked`.
- **There is no `writeStruct`.** A struct C should fill is lent to it, as
  above.

#### What a declaration cannot say

Each of these is refused, and each refusal is pinned by a case:

- **A variadic C function, spelled variadically.** A rest parameter is
  `Rest parameters are not supported here` before its type is read, `...bytes:
  u8[]` included (`reject_ffi_variadic`, `reject_ffi_buffer_rest`). A variadic function declared with a
  fixed arity, `printf(fmt: string, x: i32)`, is accepted and is the
  declaration's contract: the compiler cannot tell `open` is variadic from its
  name.
- **`syscall`, by name**: `` `declare function syscall` is refused ``
  (`reject_ffi_syscall`). It is variadic and bypasses libc; declare the libc
  function that wraps the system call.
- **A callback.** C never calls into Nish: an arrow passed to a declared C
  function is refused (`reject_ffi_callback`), and a
  [function reference](#function-references) is a tag only this program's
  dispatchers read, not an address, so it is not a `CPtr` either.
- **A read through a `CPtr`.** `p[0]` is `Cannot index a value of type CPtr`
  (`reject_ffi_pointer_deref`); `readCString` and `readStruct` above are the two reads.
- **Inline assembly.** `asm("nop")` is an unknown function (`reject_ffi_asm`).
- **An allocator from C memory.** `arena()` takes no argument, so `using a =
  arena(p)` is refused (`reject_ffi_allocator`).

**A foreign declaration has no body** (`reject_ffi_body`) and **cannot be
`export`ed** (`reject_ffi_export`), because `export` offers other modules a
function *this* module defines.

**A declared function's symbol is its name as written, in whatever package
declares it.** A function a package defines carries the package's prefix
(`@probe.probeAbs`), but a `declare function` names the C function, and C has
one namespace, so a package or a `std/` module that declares `abs` calls `@abs`
exactly as the program's own modules do (`tests/link/ffi_package_declare`).
**Two declarations of one name must agree**: the same parameter and return
types, which is what a C prototype is, so parameter names and the aliases a
type is spelled through do not count (`tests/link/ffi_package_declare_same`).
Agreeing declarations are one C function, whether they are in two packages or
in two modules of the same package, which was refused as a duplicate symbol
before. Declarations that disagree are refused, naming both:
`` C has one namespace, so every `declare function` of one name must agree on
its parameter and return types ``. A buffer's `readonly`, a `| null` and the
number of parameters each count (`tests/link/ffi_package_declare_clash`,
`tests/link/ffi_package_declare_mismatch`). So is a function whose emitted
symbol is a declared name: an exported function of the program's own package,
or a private one whose name is not reserved to C:
`` a `declare function` binds the C symbol of its name in every package, so
rename the defined function `` (`tests/link/ffi_package_declare_root_clash`).
A private function named like a C library function is emitted as `abs$`, and a
generic one's instantiations as `labs$i32`, so neither takes the C symbol and
both are accepted (`tests/link/ffi_package_declare_apart`). The two refusals
are refused rather than linked because the whole-program analysis keeps one
set of facts per symbol, and the two would share it.

**The declaration carries no LLVM attributes, and its callers pay for it.**
Nothing about a body the compiler cannot see is provable, so a function that
calls C loses `readnone` and `willreturn`, and so does everything above it in the
call graph; a function that calls no C keeps both (`tests/cases/ffi_scalar`).
`nounwind` is the one exception, and it is a **decision rather than a proof**:
unwinding out of a foreign call is undefined in this language, the same position
clang takes compiling C, because there is no `throw` and no landing pad with
which to do anything else. See
[`docs/wp27-ffi.md`](wp27-ffi.md) §2 and the
[cookbook entry](IR_COOKBOOK.md#declare-function-calling-c).

**A program that calls C is no longer one the compiler can reason about end to
end.** That is the trade the feature is: the whole-program fact fixpoint is the
performance thesis, and a foreign call is a hole in it.

**And it is outside the differential oracle by construction.** The oracle
runs a program's frozen JavaScript rewrite against `runtime/shim.mjs`, on the
premise that the same source means the same thing in both worlds; that premise
does not hold for a source whose meaning is "whatever this C function does"
([wp27-ffi.md](wp27-ffi.md) §5). The evidence for an FFI program is arranged the
other way round: a golden `.ll`, an `llvm-as` pass, a native round trip against
real libc, and the attribute assertions.

#### Host modules: the functions a page supplies

**A wasm module calls a function of the page that loads it by importing it
from a host module**: a TypeScript file of the page's, named by `--host
<file>` or by the root `package.json`'s `"nish": { "host": [...] }`
(`tests/host-import`, `docs/wp50-wasm-host.md` §3). An import from any other
file is an ordinary Nish import.

```ts
// host.ts, the page's
import type { f64, u32 } from "nish";
export type Canvas = HostHandle<"canvas">;
export function fill(c: Canvas, rgb: u32): void { canvases[c].fill(rgb); }
export function nowMs(): f64 { return performance.now(); }
```

```llvm
declare void @fill(i32, i32) #1
attributes #1 = { "wasm-import-module"="host" "wasm-import-name"="fill" }
```

- **Only the exported signatures are read.** Each `export function`'s
  parameter and result types, each exported `enum`, and each
  `export type X = HostHandle<"kind">`. A function body is skipped as a
  balanced run of tokens, so it may use anything TypeScript has. Text the
  lexer cannot skip, a regex literal or JSX, refuses the file with
  `` move that code into a module the host file imports `` (NL3049); other
  statements are skipped unread.
- **What crosses.** The integer and float widths, `boolean`, a ranged integer,
  an enum, a `HostHandle`, a `string` parameter, and `void` as a result. `i64`
  and `u64` are a `bigint` on the page's side
  (`import type { i64 } from "nish"`). Refused, each naming the explicit form:
  an object, a class, a function, `unknown` or `any` (NL2661), a generic
  function (NL2662), a `Promise` (NL2663) and a `string` result (NL2667): the
  page writes text into module storage instead (`nish/host/text`). An array
  crosses only as a buffer window, below.
- **A `string` argument is its UTF-8 bytes, lent for the call.** It lowers to
  two wasm values, the address of the string's bytes and their count, read
  from the string's own header, so nothing is copied on the module's side;
  the loader's wrapper decodes them with `TextDecoder` into a JS string before
  the page's function runs, and an invalid sequence becomes U+FFFD. The
  string may be a literal, a concatenation or a template; one the module
  built lives in the export's arena, which is released after the export
  returns (`tests/cases/host_import_string`; `tests/run.js`, section
  `host-import-text`;
  [cookbook](IR_COOKBOOK.md#a-string-to-the-page-its-bytes-and-their-count)):

  ```ts
  // web/host.ts
  export function say(s: string): void { console.log(s); }
  // app.ts
  say(`hello ${n}`);
  ```

  ```llvm
  declare void @say(i8*, i32) #2
  %1 = call i8* @nish_str_concat(i8* bitcast ({ i64, [7 x i8] }* @.str.0 to i8*), i8* %0)
  %2 = bitcast i8* %1 to i64*
  %3 = load i64, i64* %2, align 8
  %4 = trunc i64 %3 to i32
  %5 = getelementptr inbounds i8, i8* %1, i64 8
  call void @say(i8* %5, i32 %4)
  ```
- **Each host function is a declaration with the wasm import attributes**:
  module `host`, its own name. It carries no other attribute, and its callers
  lose `readnone` and `willreturn` as for a C declaration. `wasm-ld` makes it
  an import with no `--allow-undefined`.
- **A host module exists only in a freestanding wasm build.** A native or
  `--target wasm32-wasi` build that imports one is refused (NL3050). A build
  that makes a page module (`--target wasm32`, or `--emit-dts` with no
  `--target`) refuses a `declare function` (NL2666): the module links no C, so
  the declaration would be an import the page does not supply. `--target
  wasm32-wasi --emit-dts` links C, so it keeps `declare function` legal.
- **The loader and its types.** `--emit-dts` adds
  `Imports = { host: typeof import("./host") }` to the `.d.ts`, and `load`
  takes it. The loader passes a function through by reference when every
  value crosses as it stands, and wraps it once, at `load`, when a value
  converts. A `u32` or `u64` argument arrives signed and is read unsigned
  (`>>> 0`, `BigInt.asUintN(64, …)`); a `u8` or `u16` argument needs nothing,
  since the module zero-extends it. A `u8` or `u16` result is masked, a
  `boolean` crosses as 0 or 1, and a ranged integer result is checked by the
  loader's `rangeOut` (`RangeError` naming the function).
- **`--emit-ts` keeps the import** as written, pointing at the host file, so
  the TypeScript reading calls the same functions.
- **A call to a host function is an `ffi` call**: `--deny ffi` refuses it and
  `--emit-capabilities` names it.

**An array crosses as a buffer window: the array, then `at: u32, n: u32`**
(`tests/host-window`, `docs/wp50-wasm-host.md` §5.3). The host lends the page
the elements `[at, at + n)` of the array the program passes, in place, with no
copy:

```ts
// host.ts, the page's
import type { u32 } from "nish";

export function doubleF32(xs: Float32Array, at: u32, n: u32): void {
  for (let i = at; i < at + n; i++) xs[i] *= 2;
}
```

```ts
// the program
const DATA = new Float32Array(64)
export const tick = (): void => { doubleF32(DATA, 16, 8) }
```

- **Six elements lend**: `u8[]`, `u16[]`, `u32[]`, `i32[]`, `f32[]` and
  `f64[]`, their `readonly` forms and their typed-array names. Any other
  array is NL2681 (`` a buffer window lends only `u8[]`, `u16[]`, `u32[]`,
  `i32[]`, `f32[]` or `f64[]` (or the typed array of each): copy the values
  into one of those ``). The two parameters after it must be there (NL2682,
  `` a buffer window with no `at: u32, n: u32` after it ``) and be `u32`, the
  width of a wasm32 address (NL2683). NL2664, which refused every typed array
  before windows existed, is retired.
- **The window is checked in the module, before the page runs.** `at` and `n`
  are zero-extended and added in `i64`, so a sum that wraps in 32 bits still
  fails, and held against the array's length; past the end is an `ffi-length`
  panic,
  `` `doubleF32`: argument 2 (at) plus argument 3 (n) reaches past the end of argument 1 (xs) ``,
  numbered and named from the host function's own parameters
  ([cookbook](IR_COOKBOOK.md#a-host-buffer-window-checked-in-i64)). A call
  that lends `0, toU32(xs.length)` of a local array `xs` is proven in bounds
  and emits no check. A window of module storage always keeps the check,
  even `0, toU32(DATA.length)`: the range pass proves facts about locals,
  not about storage.
- **What the page gets is a view of all of memory and an index.** The
  loader's adapter passes a whole-memory view of the element type, the
  array's first element plus `at` as the index, and `n`, so the host
  function's `xs[at]` is the program's `DATA[at]`. A page that indexes outside
  `[at, at + n)` reaches the rest of the module: the page is trusted, and it
  reads only its window ([security record](security/wasm-host.md)).
- **Module storage lends to a window** like any array of a lending element,
  and so does a local array. A record storage does not.

**Module storage is the page's view of the module.** Under
`--profile wasm-host` the link exports each storage's data, and `--emit-dts`
types what the loader builds from it:

- **`layout`**, a `Layout` with one entry per storage, keyed by its name (by
  its symbol when two modules export the same name):
  `{ at, length, stride, fields? }`, where `at` is the byte address in
  `memory`, `stride` the element's size, and `fields` each record field's
  byte offset within the element. `length`, `stride` and each offset are
  literal types in the `.d.ts`, so a page that hard-codes one, or reads a
  field the module does not have, fails `tsc` once the layout changes. `at`
  is read from the instance at load and never moves. A record field is read
  through the whole-memory view of its width:
  `views().f32[(layout.bodies.at + i * layout.bodies.stride + layout.bodies.fields.x) >> 2]`.
- **`views()`**, the whole memory as `buffer` and as each typed array (`u8`,
  `i8`, `u16`, `i16`, `u32`, `i32`, `f32`, `f64`, `i64`, `u64`), and
  `storage.<key>`, a typed view of each scalar storage (a `boolean` one as
  `Uint8Array`, an enum or range as `Int32Array`, a `HostHandle` as
  `Uint32Array`). `views()` answers the same object until a growing memory
  replaces `memory.buffer`, so a page calls it again after any call into the
  module rather than keeping one view across calls.

**Under `--profile wasm-host` a panic is the page's to report**, in a
program with [module storage](#module-storage) or a
[host module](#host-modules-the-functions-a-page-supplies)
(`tests/panic`, `docs/wp50-wasm-host.md` §6). The `nish.panic` import,
`NishPanic`, the dead module, `NishReentry` (below), and the `onPanic` and
`sites` options of `load` and `loadSync` are for such a program only;
`loadSync` itself is in every loader.
Any other program gets the `.wasm`, loader and `.d.ts` it got before: a panic
is a bare `RuntimeError` trap, the module stays usable, and its next call
runs. The module of such a program imports one function
from module `nish`, `panic`, and every runtime panic calls it with its kind
and the words it would print natively; the loader turns that into an
exception:

- **The call that panicked throws `NishPanic`**, an `Error` whose `message` is
  the native text (`index out of range: 9 >= 4`,
  `slice out of range: [a, b) of length len`, an overflow's text,
  `out of memory`, `the program exited with code 3`, or `panic(…)`'s own
  words) and which carries `kind` (`panic`, `index`, `slice`, `overflow`,
  `memory`, `exit`, `divide`, or `trap`, `reentry` or `exception` for a
  module that died some other way) and `site`, the panic site's number
  (-1 for none). An array's `xs.slice` out of range throws with `kind`
  `panic`, not `slice`: its check is `std/array.ts`'s own `panic(...)`,
  though the message reads as string `slice`'s does.
- **Before it throws, the loader calls `onPanic`.** `load(bytes, { onPanic,
  sites })` takes the reporter; the default, `reportPanic` from `nish/page`,
  writes `nish: <message>` to `console.error`, as a native program writes it
  to stderr. An exception the reporter throws is swallowed: the `NishPanic` is
  thrown either way.
- **`sites` names where.** The wasm-host link writes `<out>.sites.json`
  (`app.wasm.sites.json` for `-o app.wasm`),
  `[{ kind, at }]` with one entry per panic site, indexed by `site`. Passed to
  `load` (parsed), it ends each message with ` at path:line:col`; without it
  the message is the native text alone. Under `--profile wasm` the module
  imports nothing and each panic is a bare trap, with no message and no
  site; the same loader still marks the module dead on it, so later calls
  throw as above.
- **A panic ends the module.** Its memory survives, as it was, for a page
  that reads it, but every later call throws `NishPanic`
  (`the module is dead: …`) before the module runs. An exception a host
  import throws out of a call ends the module the same way, since the call it
  interrupted never finished.
- **A bad argument does not end it.** The loader checks every argument's
  shape before the module runs: a number of the wrong type or range, a
  `Result` that is not an object with a boolean `ok` and a payload of its arm's
  type, an array argument whose brand (read off `%TypedArray%.prototype`, not
  `instanceof`) is not the typed array it names. Each throws a `TypeError`; an
  error a `Result` argument's getter throws reaches the caller as it is. Either
  way the module never ran and stays alive (`tests/run.js`, section `panic`:
  `badarg`, `badshape`).

**One call at a time.** A host import that calls an export while a call into
the module is still running gets `NishReentry` (`a call into the module was
made while another call into it was running`), and the inner call never runs.
The reporter is different: the module is already dead when `onPanic` runs, so
an export it calls throws `NishPanic` (`the module is dead: …`). The outer call's state is half changed at that point, which
is why the loader refuses rather than runs it (`docs/security/wasm-host.md`,
WH-3). Left uncaught, the `NishReentry` escapes the outer call too, and like
any exception out of a call it ends the module. A page that needs the
module's answer schedules the call for after the import returns. In a module
that links the runtime, a call also gives back, once its result is read,
everything it allocated in the arena, so a long-lived page does not grow the
module's memory call by call.

**`HostHandle<K>` is a nominal `i32` for an object the page keeps**
(`docs/wp50-wasm-host.md` §4). `K` is a string literal type, and
`HostHandle<"a">` and `HostHandle<"b">` are different types, here and under
`tsc`, where `runtime/nish.d.ts` makes it a branded `number` or `0`, so `tsc`
also refuses any number but `0` where a handle is wanted. A handle supports `===` and
`!==` against a handle of its kind or `0` ("none"), and is stored wherever a
scalar is; it has no arithmetic and no conversion to or from a number, so it
is made only by a host function that returns one. A field's or a parameter's
default may only be `0` (NL2670). A second type argument, or
a kind that is not a string literal of letters, digits and `_`, is NL2669, and a string literal type
anywhere but a `HostHandle`'s kind is NL2668. It lowers to
`i32`, so a program with no host module emits nothing new.

## Statements

### Blocks and scope

Every block (`{ ... }`, loop body, branch) opens a scope. A name may shadow
an outer one in a nested block *(CLI only)*, but redeclaring a name in the
same scope is `` Duplicate declaration of `y` `` *(CLI only)*. A `let` in a
`for` initializer belongs to the loop (`tests/cases/cf_for`). A branch or
loop body that is a single statement rather than a block is accepted
*(CLI only)*.

### `let` / `const`

- Every declaration needs an initializer (`` Variable `x` must be initialized ``
  *(CLI only)*) and takes its type from it; an annotation must match the
  initializer exactly (`Cannot initialize ... with ...`).
- Declaring a `void`-typed variable is `Cannot declare a variable of type void`
  *(CLI only)*. A local may be a destructuring pattern, `const { x, y } = p`
  or `let [a, b] = xs` ([Destructuring declarations](#destructuring-declarations));
  a module constant may not: `Destructured constants are not supported`
  (`reject_const_destructured`): a module constant's initialiser is a
  literal, another constant or arithmetic over them ([Module constants](#module-constants)),
  folded into each use with no storage of its own, and a pattern's names are
  reads of a receiver at run time. `var` is forbidden
  (`tests/cases/reject_var_keyword`, `reject_var_in_for`).
- `const` freezes the binding, not the contents: `xs[0] = 1` and
  `xs.push(1)` on a `const xs` are fine, `xs = []` is not
  (`tests/cases/arr_index_read_write`; `` Cannot assign to `x` because it is a const ``,
  `reject_assign_const`, `reject_cf_compound_const`).
- Locals live in an `alloca` slot; `opt -mem2reg` promotes them
  (`tests/cases/locals`).

### Destructuring declarations

A `const` or `let` in a function body, and the head of a `for...of`, may be an
object or an array pattern. Each name it binds is one read off the value on
the right, which is evaluated once and never copied:

```ts
const { x, y: py } = p        // x = p.x, py = p.y
let [a, , c] = xs             // a = xs[0], c = xs[2]
for (const { x, y } of points) { ... }
```

- **An object pattern** reads a class or interface value. Each entry is a
  field's name, `x`, or a field renamed, `y: py`; the name's type is the
  field's. A missing field is `` Cannot destructure field `z`: Point has no
  such field `` (NL2778, `reject_destructure_field`).
- **An array pattern** reads an array. Each name is one element read by its
  position, with the bounds check of `xs[i]`; a hole, `[a, , c]`, skips a
  position. An element past the end panics, `index out of range: 5 >= 3`
  (`destructure_out_of_range`), where TypeScript would bind `undefined`: a
  name in Nish always holds a value of its type.
- **A `for...of` head** destructures each element of an array
  (`destructure_for_of`). Over a `Set` or an iterator it is NL2785
  (`reject_destructure_for_of_set`). Over a `Map` it is NL2375, the
  refusal any `for...of` over a `Map` gets, before the pattern is read: a
  `Map`'s entries are `[key, value]` pairs of two types, a tuple, which this
  version does not have (`reject_destructure_for_of_map`,
  `reject_map_iter_entries`).
- A name is a fresh local: `let` names may be assigned, `const` names may
  not. A struct's fields are read through its pointer, so
  `const { x } = p` on a stack-allocated `p` costs one load
  (`destructure_stack`).
- **The receiver.** Over a name or a field path (`p`, `xs`, `this`,
  `o.pt`, `this.a.items`) each name is read straight off it, and the function
  compiles to the body of its hand-written reads, so every rule about an
  element of `o.items` applies to the pattern as to `o.items[0]`
  (`reject_destructure_moved_field`). Any other receiver (a call, a
  `for...of` element) is evaluated once into a hidden copy of its pointer,
  which no rule names, as no rule names the call in `f()[0]`
  (`reject_destructure_moved_call`): unoptimised that is one alloca and one
  store more than the hand-written reads, and after `opt -O2` the bodies are
  the same (`destructure_zero_cost`). A pattern works over `this`
  in a method, in an arrow's or an async body, and in a C-style `for`
  initialiser (`destructure_forms`).
- **An empty pattern**, `const {} = p`, `const [] = xs` or `const [,] = xs`,
  binds nothing; its receiver is still evaluated once, for any effect it has
  (`destructure_empty`).

Refused, each with its own diagnostic and test:

| Pattern | Diagnostic | Test |
| --- | --- | --- |
| `[a, b] = xs`, `({ x } = p)`, `({ x: px } = p)` (assignment) | NL2773 `Destructuring assignment is not supported` | `reject_destructure_assignment`, `reject_destructure_assignment_object`, `reject_destructure_assignment_renamed` |
| `{ x = 0 }`, `[a = 1]` (a default) | NL2774 | `reject_destructure_default`, `reject_destructure_default_array`, `reject_destructure_for_of_default` |
| `[a, ...rest]`, `{ x, ...others }` | NL2775 | `reject_destructure_rest`, `reject_destructure_for_of_rest` |
| `{ p: { x } }`, `[[a]]` (nested) | NL2776 | `reject_destructure_nested`, `reject_destructure_nested_object`, `reject_destructure_for_of_nested` |
| `{ ["x"]: a }`, `{ "x": a }` | NL2777 | `reject_destructure_key`, `reject_destructure_key_computed` |
| `{ default: d }` (a keyword key) | NL2778, the key is read as a field's name and no class has that field | `reject_destructure_key_keyword` |
| `{ norm }` where `norm` is a method | NL2778, call it instead | `reject_destructure_method` |
| `const { x }: Other = p` (an annotation the receiver does not match) | NL2185 ``Cannot initialize Other variable `{ x }` with Point`` | `reject_destructure_annotated` |
| a name never read | NL2712, rename it ``{ y: _y }`` (a shorthand) or `_a` | `reject_destructure_unread` |
| a value that may be absent, `Point \| null` or a `V \| undefined` from `Map.get` | NL2779, narrow it first | `reject_destructure_nullable`, `reject_destructure_undefined` |
| a `Map` | NL2780, read each value with `get` | `reject_destructure_map` |
| a `string` | NL2781, read each character by its index | `reject_destructure_string` |
| an object pattern over a number | NL2782 | `reject_destructure_object_of_number` |
| an array pattern over an object or a `Set` | NL2783 | `reject_destructure_array_of_object`, `reject_destructure_set` |
| `let { x }: Point;` (no initializer) | NL2784 | `reject_destructure_uninitialized` |
| a parameter, `({ x }: Point) => x` | `Destructured parameters are not supported` | `reject_param_destructured` |
| a module constant | `Destructured constants are not supported` | `reject_const_destructured` |
| `var [a] = xs`, `var { x } = p`, `for (var [a] of rows)` | NL1036 `` `var` is forbidden; use `let` or `const` ``, as for `var a` | `reject_destructure_var_array`, `reject_destructure_var_object`, `reject_destructure_var_for_of` |
| `using [a] = xs`, `using { s } = scope()` | none of its own: as in TypeScript, `using` binds only a plain name, so `using [a]` reads a variable named `using` and `using {` is a syntax error | `reject_destructure_using_array`, `reject_destructure_using_object` |

A pattern over `await` is refused with ``A pattern may destructure an `await` only of `awaitAll(...)`, whose names are the calls' answers: await into a name, then destructure the name``
(`nl2193_destructuring_local`), but for the answers of
`const [a, b] = await awaitAll(f(x), g(y))`
([Async functions](#async-functions-async-and-await)).

### Expression statements

Any expression may be a statement; its value is discarded *(CLI only)*.
`console.log(...)`, `process.exit(...)`, `writeFileSync(...)` and
`appendFileSync(...)` return `void` and may appear *only* as statements
(`can only be used as a statement`, `tests/cases/reject_console_log_as_value`).

### `return`

The expression's type must equal the declared return type
(`Return type mismatch: function returns ... but expression is ...`); a bare
`return` is valid only in a `void` function
(`Expected a return value of type ...`) (`tests/cases/entry_main_void`).

### `if` / `else`

The condition must be `boolean`: there is no truthiness
(`Condition must be boolean, got i32 (Nish has no truthiness)`,
`tests/cases/reject_cf_nonbool_cond`). `else if` chains are nested `if`s
(`tests/cases/cf_if`, `cf_if_else_chain`).

### `while`, `do ... while`, `for`

- Conditions must be `boolean` (`tests/cases/cf_while`, `cf_do_while`,
  `cf_for`).
- `for (init; cond; update)`: every clause is optional; the initializer is
  a `let`/`const` list or an expression (`tests/cases/cf_break_continue`
  for `for (;;)`; expression initializer *(CLI only)*).
- Loop variables are ordinary mutable locals; there is no restriction on
  assigning them (`tests/cases/cf_collatz`).
- A loop whose condition is absent or the literal `true` and whose body has
  no `break` for it never falls through (see Termination); every other loop
  may run zero times (`tests/cases/cf_while`, `firstPowerOver`).

### `for (const x of a)`

- `a` must be an array (`` `for...of` requires an array, got string ``,
  `tests/cases/reject_arr_forof_non_array`;
  [the compatibility dialect](#the-compatibility-dialect) walks a string one
  code point at a time under `for-of-string`), or a walk of the global `Map` or
  `Set`: `m.keys()`, `m.values()`, a `Set` itself, `s.keys()` or `s.values()`
  ([`Map` and `Set`](#map-and-set)), or a `Channel` from `nish/threads`, which
  takes values off it ([Channels](#channels-channelt)); `x` gets the element type and
  must not be annotated
  (`` The `for...of` variable takes the element type; remove the annotation ``,
  `tests/cases/reject_arr_forof_annotation`) or initialised
  (`` The `for...of` variable cannot have an initializer ``,
  `tests/cases/reject_arr_forof_initializer`); exactly one variable
  (`` `for...of` declares exactly one variable ``,
  `tests/cases/reject_arr_forof_two_vars`); the head is a declaration rather
  than an assignment to something already declared
  (`` `for...of` needs a `const` or `let` declaration ``,
  `tests/cases/reject_arr_forof_expression`); `let x` makes
  it assignable, `const x` does not (`tests/cases/reject_arr_forof_const_assign`).
  `for await` is not supported (`` `for await` is not supported here ``,
  `tests/wordings/nl2133_for_await`), and `for...in` is forbidden
  ([Rejected statements](#rejected-statements)).
- `a` is evaluated once; `a.length` is re-read every iteration, so a `push`
  inside the body extends the iteration, as JavaScript's array iterator does
  (`tests/cases/arr_for_of`). `break` and `continue` work
  (`tests/cases/arr_for_of`).

### `switch`

```typescript
switch (node.kind) {
  case KIND_IF:
  case KIND_WHILE:
    return checkBranch(node);
  case KIND_CALL:
    return checkCall(node);
  default:
    return ERROR;
}
```

- The discriminant is an **integer** (`i32`, `i64`, `u8`, `u16`, `u32`, `u64`;
  so a `number` in the default mode but not under `--number-mode f64`) or a
  **`enum`** of either kind ([Enums](#enums)), which is an `i32` in the jump
  table: a string enum switches on its members' ordinals, never on their
  strings.
  Any other type is `` `switch` requires an integer discriminant, got <type> ``
  (`tests/cases/reject_switch_string`). Only an integer switch lowers to
  LLVM's `switch` and a jump table; a string switch would have been a chain
  of `nish_str_eq` calls wearing a switch's clothes, and `if`/`else` says that
  honestly. [The compatibility dialect](#the-compatibility-dialect) admits
  that chain under `string-switch`.
- Every `case` label is an **integer constant expression** of the
  discriminant's type: a literal, its negation, a module constant, or an enum
  member
  (`` `case` label must be an integer literal, a module constant, or an enum member ``,
  `tests/cases/reject_switch_case_not_constant`; `` `case` label is i64 but
  the discriminant is i32 ``, `reject_switch_case_type`). A literal takes the
  discriminant's width, so `case 1:` on an `i64` switch is an `i64` one — and
  on an enum switch it is `` `case` label is i32 but the discriminant is Kind ``
  (`reject_enum_case_label`), because the integer a member stands for is not
  the member.
- Labels are distinct (``Duplicate `case` label `1` in this `switch` ``,
  `tests/cases/reject_switch_duplicate_case`), and there is at most one
  `default` (`` `switch` has more than one `default` clause `` *(CLI only)*),
  which may appear anywhere among the clauses.
- **A clause falls through, as in TypeScript.** A clause whose statements do
  not end in `break`, `return`, `continue` or `process.exit` runs on into the
  next clause's statements; the IR branches into the next clause's block, with
  no flag (`tests/cases/cf_switch_fallthrough`, `cf_label_walks`). An **empty**
  clause falls through the same way, which is how `case 1: case 2:` gives
  several labels one body (`tests/cases/cf_switch`). A clause reached by
  falling into it is reached with either label's value: a tag test does not
  narrow there (`reject_switch_fall_narrow`), and a local the clauses above it
  assigned holds its declared type.
- A clause cannot declare a variable directly; wrap its body in a block
  (``A `case` clause cannot declare a variable directly ``,
  `tests/cases/reject_switch_case_declaration`). Clauses share one scope in
  TypeScript, so a declaration in one would be visible but unassigned in the
  ones below it.
- `break` inside a `switch` leaves the switch, not an enclosing loop;
  `continue` looks past the switch to the loop
  (`tests/cases/cf_switch_break`). A labelled `break` or `continue` names
  the loop instead (see below, `cf_label_switch`).
- A `switch` terminates (see Termination) when no `break` targets it, its
  last clause terminates, and it has a `default` or is a complete `switch` on a
  union's tag, whose labels name every variant
  ([Discriminated unions](#discriminated-unions), `tests/cases/union_switch`).
  A `switch` on an integer or a plain enum without a `default` never
  terminates, whatever its labels (`reject_union_switch_enum`).

### `break` / `continue`

A label goes on a loop, a block or a `switch` (`outer: for (...)`,
`check: { ... }`, `sw: switch (...)`); on any other statement it is refused
(`` Labeled statements are forbidden in Nish except on a loop, a block or a
`switch` ``, `tests/cases/reject_label_if`). `break label` leaves the statement
the label names, from any depth inside it; `continue label` starts the next turn
of the loop it names. Each lowers to the branch a hand-kept `done` flag would
take — to that statement's exit block or its loop's step block — with no flag
(`tests/cases/cf_label_loops`, `cf_label_block`, `cf_label_switch`,
`cf_label_walks`). Leaving a scoped pass or a `Map` walk this way releases it
as an unlabelled exit would, and a `Secret` local a labelled exit skips past
must be wiped first (`reject_label_secret_break`, `reject_label_secret_block`).

- A label is not reused inside the statement it names (``Duplicate label
  'outer'``, `reject_label_duplicate`).
- `continue label` names a loop (`` A `continue` can only jump to a label of
  an enclosing loop ``, `reject_label_continue_block`), and `break label` a
  statement around it (`` A `break` can only jump to a label of an enclosing
  statement ``, `reject_label_unknown`).
- A jump does not leave an arrow for a label outside it (``Jump target cannot
  cross function boundary``, `reject_label_crosses_arrow`).

Unlabelled, `break` needs an
enclosing loop or `switch` (`` `break` outside of a loop or `switch` ``,
`tests/cases/reject_cf_break_outside`) and `continue` an enclosing loop
(`` `continue` outside of a loop ``, `reject_cf_continue_outside`), which it
finds past any `switch` in between. `tests/cases/cf_break_continue`,
`cf_switch_break`.

### `throw` (removed)

`throw` is forbidden by Phase 0 (`tests/cases/reject_throw`). Until WP16 it
compiled to `llvm.trap` — it aborted the process and discarded its value —
which made it an abort wearing the syntax of error handling, and let a program
report a failure in a way no caller could see. The two things it was used for
have their own spelling now:

- a failure a caller should handle is a **[`Result<T, E>`](#result-and-error-handling)**;
- an invariant that cannot hold is **`panic(message)`**, which keeps the
  message `throw` threw away.

`try`/`catch`/`finally` is forbidden for the same reason
(`tests/cases/reject_try_catch`).

### `process.exit(code)` as a statement

Terminates the process with `code` (an `i32`) and, for control-flow
purposes, the current path: a non-`void` function may end with it
(`tests/cases/process_exit`), and code after it is
`Unreachable code after process.exit` (`tests/cases/reject_exit_unreachable`).

### Termination, definite return, and unreachable code

A statement *terminates* when control cannot fall out of it: `return`,
`break`, `continue`, `process.exit(...)`, `panic(...)`; an `if` whose branches
both terminate; a `switch` with a `default` or one complete on a union's tag,
no `break` aimed at it and a terminating last clause; a loop with no condition or the condition `true` and
no `break` aimed at it; a labelled block whose statements terminate and no
`break` names. A `break` aimed at a statement is an unlabelled one directly
inside it or a labelled one that names it from any depth, so a `break outer`
in an inner loop makes `outer: while (true)` one that may finish. Any other
loop may run zero times and does not terminate. Rules (`src/statements.ts`, `checker.ts`):

- A non-`void` function's body must terminate
  (`must return a value of type i32 on every path`,
  `tests/cases/reject_missing_return`, `reject_cf_missing_return_loop`;
  `if (true) { return 1; }` alone is not enough *(CLI only)*).
- A statement after a terminating one is `Unreachable code after <what>`,
  where `<what>` is `return`, `break`, `continue`, `process.exit`,
  `` an `if` whose branches all return ``, `` a `switch` whose clauses all
  return ``, or `an infinite loop`
  (`tests/cases/reject_unreachable`, `reject_cf_unreachable_after_break`,
  `reject_exit_unreachable`; the `if` form *(CLI only)*).

### Mistakes every type accepts

Some lines type-check and still cannot be what their author meant. Rust
warns about most of them and Clippy denies the rest. Here each one is an
error, because it is a bug far more often than it is a choice. Each rule fires only
where the answer is certain, and each has a spelling that says "on purpose".
Rules (`src/hygiene.ts`):

- **A local is read at least once** (NL2712). A `let` or `const`, a
  `for...of` binding included, that nothing reads is
  `` `x` is declared but never read `` (`reject_unread_local`,
  `reject_unread_for_of`). Storing into a local is not reading it: `n++` or
  `n += 1` on a line of its own, or as a `for` loop's step, writes `n` and
  uses nothing, so a counter nothing reports is
  `` `n` is assigned but its value is never read ``
  (`reject_unread_local_written`); `const m = n++` reads it. A capture by an
  arrow is a read. A lone name on its own line, `x;`, is not a read
  (`reject_unread_lone_name`). A name that starts with `_` is never reported,
  which is how a loop that only counts its turns is written:
  `for (const _item of xs)` (`hygiene_quiet`). A `using` binding is exempt,
  because its block's end uses it. A `Result` local has its own rule (NL2032,
  [Result and error handling](#result-and-error-handling)).
- **A statement has an effect** (NL2713). An expression statement with no
  call, `new`, store, `++`, `--` or `await` anywhere in it is
  `This statement has no effect` (`reject_no_effect_statement`,
  `reject_no_effect_member`). `state === next;` adds
  `` (to assign, write `=`) ``. A lone name is left to the rule above.
- **A value is not assigned to itself** (NL2714). `x = x`, `p.x = p.x`
  and `xs[i] = xs[i]` do nothing (`reject_self_assign`).
- **An operator has two different operands** (NL2715). With the same
  operand on both sides, `===` `!==` `==` `!=` `<` `<=` `>` `>=` `&&` `||` `&`
  `|` `^` `-` `/` `%` give an answer that does not depend on it, so the
  expression is refused (`reject_same_operands`, `reject_same_operands_index`).
  Two operands are the same when they are the same pure expression over the
  same variables: the same local, field path, element by the same index, or
  the same operators over those. A literal-only expression is not refused. On
  `f32` and `f64`, `x !== x` is the NaN test and `x - x === 0` the finite
  test, so only `<` and `>` are refused there, which are false for every
  value (`reject_same_operands_float_ordered`). To compare a value with
  itself on purpose, copy it to a second `const` first (`hygiene_quiet`).
- **An `else if` tests something new** (NL2716). A condition the same as an
  earlier one in the same `if`/`else if` chain can never pass, because the
  earlier branch took every case it would match (`reject_repeated_condition`).
  A condition with a call in it can answer differently the second time, and
  is not compared.
- **An unsigned value is not compared with zero for its sign** (NL2717).
  `u < 0` and `0 > u` are always false, and `u >= 0` and `0 <= u` always
  true, for a `u8`, `u16`, `u32` or `u64` (`reject_unsigned_zero`,
  `reject_unsigned_zero_reversed`).

These findings are reported only once every other rule has passed: a program
with any other error is told that error alone (`reject_hygiene_held`), so
an unread local never crowds out the error that left it unread. They are held
to the program's own package and the standard library. A dependency's
findings are left to its author, as Cargo caps the lints of a crate it pulls
in.

### Rejected statements

`with` (`tests/cases/reject_with_statement`), `try` (`reject_try_catch`),
`debugger` (`reject_debugger`), a label on a statement other than a loop, a
block or a `switch` (`reject_label_if`),
`var` (`reject_var_keyword`), `for...in` (`` `for...in` is forbidden in Nish
(it enumerates property names, and object layout is fixed at compile time); use
`for...of` ``, NL1056, `reject_for_in`), nested `function`, `enum`, `type`,
`namespace` (`reject_namespace`), `declare global` (`reject_declare_global`).
`with`, `try` and `var` are not reserved: a function or a variable may be
called one, and a statement opens only where the word could not be that
name. `with (…)` is the statement when a statement follows it on the same
line, and `var` when a name follows it on the same line. `try` is the
statement when a block follows it on the same line, or when a block follows
it and a handler follows that block (`catch {`, `catch (e) {` or `finally {`,
not a call such as `finally();`), whatever line breaks and comments sit
between (`reject_try_allman_catch`, `reject_try_allman_finally`,
`reject_try_comment_newline`). A catch binding may be a name or a
destructuring pattern, with or without an annotation, and is refused the same
way (`reject_try_catch_destructured`). So a `try`-named block followed by
`catch(<a binding>)` — a name or a pattern, `catch(n)` or `catch([n])` — and
then a block is a `try` statement, even where 0.13.0 read a call to a function
named `catch` (`reject_try_catch_call_newline`,
`reject_try_catch_pattern_call_newline`): the one shape of program this rule
stopped compiling. An argument that is no binding, such as `catch([1, 2])` or
`catch({ first: 1 })`, is the call it was (`tests/parser/names-catch-array.ts`,
`names-catch-object.ts`). A line break inside a block comment counts as
one, as it does for semicolon insertion. So `try` alone on a line before a
block that nothing handles is a name and a block, as it was before
(`tests/parser/names.ts`). `tsc` reserves all three, so this is Nish
accepting what TypeScript does not, as it did before these statements
parsed.
`enum` and `type` are top-level declarations ([Enums](#enums),
[Type aliases](#type-aliases)); it is only inside a function body that they are
a rejected statement.

The empty statement, a lone `;` where a statement stands, is refused in a
body: `Unsupported statement in Phase 1: EmptyStatement` (NL2260,
`tests/cases/reject_stmt_empty`). It is the sentence every statement kind with
no checker gets, named by its syntax kind as a nested `function` or `import`
is; every other such kind is refused earlier by a rule of its own. It is
refused where a body is checked, so a `;` in a template nothing instantiates
still compiles, as it did in every release. A `;` at the top level is the
syntax error `` a module holds only `function`, `class`, `interface`, `const`,
`type`, `enum` and `import`, found `;` `` (NL0001).

## Expressions

Evaluation is left to right, operands before operators, as in JavaScript;
the specific orders for compound assignment and element assignment are
under [Semantics decisions](#semantics-decisions).

### Operators

| Operator | Works on | Gives |
| --- | --- | --- |
| `+ - * / %` | two numbers of one type | that type |
| `+` | two `string` | `string` |
| unary `-` | any numeric type | same |
| unary `!` | `boolean` | `boolean` |
| `& \| ^` | two integers of one type | that type |
| `<< >> >>>` | two integers of one type | that type |
| unary `~` | any integer type | same |
| `< <= > >=` | two numbers of one type | `boolean` |
| `=== !==` | two values of one type | `boolean` |
| `== !=` | forbidden | – |
| `&& \|\|` | two `boolean` | `boolean` |
| `c ? a : b` | `boolean`, two of one type | that type |
| `a ?? d` | a `Map.get` result | `V` |
| `a ?? d` | a `T \| null` | `T` or `T \| null` |
| `x = e` | a mutable target | the target's type |
| `x op= e` (`+= -= *= /= %=`) | a numeric mutable target | the target's type |
| `x op= e` (`&= \|= ^= <<= >>= >>>=`) | an integer mutable target | the target's type |
| `++x --x x++ x--` | numeric mutable local | new / old value |
| `,` | forbidden | – |
| `a?.b ?? d`, `a?.m() ?? d` | a `T \| null` chain | the last link's type |
| `await f(x)` | a direct `async` call | the call's `T` |
| `== != ?.[ ?.() in instanceof typeof delete void yield` | forbidden | – |
| `** **=` | not supported | – |
| `+x` | not supported | – |

**`+ - * / %`** take two numbers of one type (`i32`, `i64`, `u8`, `u16`,
`u32`, `u64`, `f32`, or `f64`) and give that type. On the signed integer
widths an overflow branches to `nish_panic_overflow`
([Semantics decisions](#semantics-decisions)); it is plain through a
`nish:unsafe` `wrapping*` call. An integer division is preceded by a divisor
check that branches to `nish_panic_div`
([Checked integer division](#checked-integer-division)).

- *Lowering:* `add sub mul` / `fadd fsub fmul fdiv frem` (on `float` for an
  `f32`, `double` for an `f64`); on a page module (above, `Math.sin`) or
  under [`--deterministic`](#--deterministic) a float `%` or `%=` is a call
  to `std/math.ts`'s `fmodF64` in place of `frem`, whose libm `fmod` that
  link lacks, an `f32` widened to `f64` and the exact result narrowed back;
  on the signed integer widths `nsw` where proven to fit and otherwise
  `llvm.s*.with.overflow` and a branch to `nish_panic_overflow`, plain
  through a `nish:unsafe` `wrapping*` call, never `nuw`; integer `sdiv` / `srem` (`udiv` / `urem` on an unsigned type)
  are preceded by a divisor check that branches to `nish_panic_div`.
- *Tests:* `add`, `locals`, `i64_basic`, `f64_mode`, `div_checked`,
  `ovf_checked`, `ovf_matrix`, `u_arith_wrap`, `u_udiv_urem`, `f32_arith`,
  `wasm_math_rem`; `reject_type_mismatch`, `reject_u_mixed_signedness`,
  `reject_f32_mixed`

**`+`** on two `string` gives a `string`.

- *Lowering:* `nish_str_concat`.
- *Tests:* `str_concat`; `reject_str_plus_number`
  (`no implicit string conversion`)

**unary `-`** takes any numeric type and gives the same type.

- *Lowering:* `sub <T> 0, x` for an integer, `fneg float` / `fneg double`
  for a float.
- *Tests:* `cf_if` (`-x`), `i64_basic`, `f32_arith`; `f64` *(CLI only)*

**unary `!`** takes a `boolean` and gives a `boolean`.

- *Lowering:* `xor i1 x, true`.
- *Tests:* `cf_logical`; `!s` on a string is
  `` Unsupported unary operator `!` on string `` *(CLI only)*

**`& | ^`** take two integers of one type and give that type.

- *Lowering:* `and` / `or` / `xor`, one instruction, no panic path.
- *Tests:* `bit_and_or_xor`, `bit_i64`, `bit_attributes`; `reject_bit_f64`,
  `reject_bit_width`, `reject_bit_number_mode`, `reject_bit_boolean`
  (`` Operator `&` is not available on boolean (use `&&`) ``)

**`<< >> >>>`** take two integers of one type and give that type. `>>` is
sign-filling on a signed type and zero-filling on an unsigned one, so `>>`
and `>>>` are the same instruction there; `>>>` is always zero-filling. The
count is masked to the operand width (31, 63, or 7/15 on the narrow unsigned
widths); see [Shifts](#shifts).

- *Lowering:* `shl`; `>>` is `ashr` (sign-filling) on a signed type and
  `lshr` (zero-filling) on an unsigned one; `>>>` is always `lshr`. A
  constant count is masked at compile time and emits no `and`.
- *Tests:* `bit_shifts`, `bit_shift_const`, `bit_shift_fill`,
  `bit_shift_narrow`, `bit_i64`, `u_shift_logical`; `reject_u_shift_mixed`;
  `tests/differential/corpus/bit_shifts`

**unary `~`** takes any integer type and gives the same type.

- *Lowering:* `xor x, -1` (LLVM has no `not`).
- *Tests:* `bit_not`; `reject_bit_not`
  (`` Operator `~` requires an integer operand, got f64 ``)

**`< <= > >=`** take two numbers of one type (`i32`, `i64`, the unsigned
widths, `f32`, or `f64`), and nothing else, and give a `boolean`.

- *Lowering:* `icmp slt ...` signed, `icmp ult ...` unsigned, `fcmp olt ...`
  for both float widths.
- *Tests:* `cf_if`, `f64_mode`, `u_compare_above_intmax`, `f32_arith`;
  booleans (`reject_bool_ordering`), strings (`reject_str_lt`,
  `reject_str_lt_str`), and structs (`reject_cls_ordering`) are
  `` Operator `<` requires two numeric operands, got boolean and boolean ``

**`=== !==`** take any two values of the same type except `void`, and give a
`boolean`. A `T | null` compares only against the literal `null`. Strings
compare by content; arrays and objects by identity (the pointer). On an
`f64`, `x !== x` is true for NaN. `a === undefined` is allowed for a
`Map.get` result only, and tests its found bit, negated.

- *Lowering:* integers and booleans: `icmp eq` / `icmp ne`; `f64`:
  `fcmp oeq` / `fcmp une` (so `x !== x` is true for NaN); strings:
  `nish_str_eq` (content); arrays and objects: `icmp eq` on the pointer
  (identity); `p === null`: `icmp eq` against `null`; `a === undefined`, for
  a `Map.get` result only: its found bit, negated.
- *Tests:* `str_eq`, `cls_this_method_call`, `conversions`, `mem_nullable`,
  `map_get_narrow`; arrays *(CLI only)*; `reject_null_compare_two`,
  `reject_map_get_undefined_compare`

**`== !=`** are forbidden.

- *Tests:* `reject_loose_equality`, `reject_loose_inequality`

**`&& ||`** take two `boolean` and give a `boolean`, short-circuit.

- *Lowering:* short-circuit: `br` + `phi`.
- *Tests:* `cf_logical`; `reject_cf_logical_numbers`
  (`requires boolean operands`)

**`c ? a : b`** takes `c: boolean`, and `a`, `b` of the same non-`void`
type, and gives that type.

- *Lowering:* `br` + `phi`.
- *Tests:* `cf_ternary`; `reject_cf_ternary_mismatch`,
  `reject_cf_ternary_void`

**`a ?? d`** on a `Map.get` result: `a` is a `Map.get` result
(`V | undefined`) and `d` a `V`; it gives a `V`. It sits at the level of
`||`, and is not mixed with `||` or `&&` unparenthesised
([`Map` and `Set`](#map-and-set)).

- *Lowering:* `br` to `valueAt` or `d`, then `phi`; `select` for a `const`
  with a literal or a name as `d`.
- *Tests:* `map_get_nullish`, `map_get_narrow`, `map_get_pointer_value`;
  `reject_nullish`, `reject_nullish_default_type`, `reject_nullish_mixed_or`

**`a ?? d`** on a nullable: `a` is a `T | null` that is not an element
read, and `d` a `T` or a `T | null`, with the same precedence. It gives a
`T`, or a `T | null` for a nullable `d`
([Nullable types](#nullable-types)).

- *Lowering:* `icmp ne` against `null`, then `select` for a literal or a
  name as `d`; otherwise `br` to `d` and `phi`.
- *Tests:* `nullish_nullable`, `nullish_nullable_field`,
  `nullish_nullable_default_null`, `nullish_nullable_default_context`,
  `nullish_nullable_escapes`; `reject_nullish_nullable`,
  `reject_nullish_element`, `reject_nullish_nullable_default_type`

**`x = e`** assigns to a mutable local, field, or element; `e` is of the
target's type, and the expression gives the target's type.

- *Lowering:* `store`.
- *Tests:* `locals`, `cls_field_write`, `arr_index_read_write`

**`x op= e` (`+= -= *= /= %=`)** works on a numeric mutable local, numeric
field, or numeric element, with `e` of the same type, and gives the target's
type.

- *Lowering:* load, op, store.
- *Tests:* `cf_compound_assign`, `cls_compound_field`,
  `arr_index_read_write`; `reject_cf_compound_const`,
  `reject_cf_compound_string`, `reject_cf_compound_widths`

**`x op= e` (`&= |= ^= <<= >>= >>>=`)** works on a mutable local, field, or
element of integer type, with `e` of the same type, and gives the target's
type. The shift forms use the same shift-count mask. The target expression
is evaluated exactly once.

- *Lowering:* load, op, store, with the same shift-count mask; a field is
  addressed by one GEP and an element bounds-checked once, so the target
  expression is evaluated exactly once.
- *Tests:* `bit_compound`, `cls_field_bitwise_assign`,
  `arr_element_bitwise_assign`; `reject_cls_field_bitwise_readonly`,
  `reject_arr_element_bitwise_f64`;
  `tests/differential/corpus/bit_compound_target`

**`++x --x x++ x--`** work on a numeric mutable local only, and give the new
/ old value.

- *Lowering:* load, `add 1`, store.
- *Tests:* `cf_incdec`; `reject_cf_incdec_param`, `reject_cls_field_incdec`

**`,`** is forbidden.

- *Tests:* `reject_comma_expression`

**`a?.b ?? d`, `a?.m() ?? d`** take `a`, a `T | null`, and a chain of `?.`
and `.` links, field reads, `length` and method calls, that is the left
operand of `??`. It gives the last link's type, as `a ?? d` on a `T | null`
types it ([Nullable types](#nullable-types)).

- *Lowering:* `icmp eq` against `null` at each `?.` link's receiver, then
  `br` to `nullish.default`; `phi` at `nullish.end`.
- *Tests:* `optional_chain_field`, `optional_chain_order`,
  `optional_chain_generic`, `optional_chain_bounds`;
  `reject_optional_chain`, `reject_optional_chain_never_null`

**`await f(x)`** takes a direct call to an `async` function, at the top of a
statement in an `async` function, and gives the call's `T`
([Async functions](#async-functions-async-and-await)).

- *Lowering:* a call when `f` awaits nothing; otherwise `f`'s frame is laid
  out in the caller's, `@f.resume` is called, and the caller saves its state
  and answers `false` while it pends.
- *Tests:* `async_await_single`, `async_await_chain`, `async_lowered`;
  `reject_await`, `reject_async_await_value`, `reject_async_await_nested`

**`== != ?.[ ?.() in instanceof typeof delete void yield`** are forbidden by
the validator ([Forbidden constructs](#expressions-1)).

- *Tests:* `reject_loose_equality`, `reject_optional_chain_element`,
  `reject_optional_call`, `reject_in_operator`, `reject_instanceof`,
  `reject_typeof_operator`, `reject_delete`, `reject_void_expression`,
  `reject_yield`

**`** **=`** are not supported: `` Unsupported binary operator `**` `` /
`` Unsupported assignment operator `**=` ``.

- *Tests:* `reject_op_exponent`, `reject_op_exponent_template`,
  `reject_exponent_assign_local`, `reject_cls_compound_operator`

**`+x`** is not supported.

- *Tests:* `Unsupported unary operator` *(CLI only)*

### Checked integer division

`a / b` and `a % b` on `i32` or `i64` follow Rust, not C: the divisor is
checked first, and a zero divisor or `MIN / -1` (`-2147483648 / -1`,
`-9223372036854775808 / -1`, and the same for `%`) prints
`attempt to divide by zero` or `attempt to divide with overflow` to stderr
and exits with status 1 (`tests/cases/div_checked`, `div_zero_panic`,
`div_overflow_panic`; `tests/differential/corpus/int_div_zero`,
`int_div_overflow`). Otherwise the result is the truncating `sdiv` / `srem`:
`-7 / 2` is `-3`, `-7 % 3` is `-1`, `-2147483648 / 1` is `-2147483648`. The
check is two compares and a branch to a cold `div.fail` block that calls the
`noreturn` `nish_panic_div`; because that path exists, a function containing
an integer division is neither `willreturn` nor `readnone`, exactly like one
containing a checked `a[i]`. The rule applies to `/`, `%`, `/=`, and `%=` on
locals, fields, and elements. **A divisor the checker proves is left
unchecked**, as a proven index is: one that is neither 0 nor -1 — a constant
(`a / 2`, `a % -3`, a folded module constant), a ranged or unsigned divisor
whose declared range leaves both out, a local behind `d > 0` or behind
`d !== 0 && d !== -1` — or one that is not 0 against a dividend known to be
non-negative, which cannot be the minimum. Such a division is the bare
`sdiv` / `srem` and no `div.fail` block (`tests/cases/panics_divide`,
`deny_panics_clean`). Floating-point division is never checked: `x / 0` on
`f64` is `Infinity` and `0 / 0` is `NaN`.

**Unsigned division is checked more cheaply.** `udiv` and `urem` have no
overflow case at all — there is no unsigned value whose negation leaves the
range, so `MIN / -1` has no counterpart — and the check collapses to a
*single* compare against zero, with no `and` and no `or`.
`tests/cases/u_div_one_check` pins the signed and the unsigned sequence side
by side:

```llvm
; u32 a / b                          ; i32 a / b
%0 = icmp eq i32 %b, 0               %0 = icmp eq i32 %b, 0
br i1 %0, ...                        %1 = icmp eq i32 %a, -2147483648
                                     %2 = icmp eq i32 %b, -1
                                     %3 = and i1 %1, %2
                                     %4 = or i1 %0, %3
                                     br i1 %4, ...
```

A zero divisor still prints `attempt to divide by zero` and exits 1, and the
function still loses `willreturn` because the panic is `noreturn`; `attempt to
divide with overflow` is simply unreachable on an unsigned type.

### Calls

- `f(args)` calls a top-level function or an imported one, or — inside a
  template — a [function parameter](#function-parameters), which is a direct
  call to the function the instantiation was given; the callee must
  be a plain identifier (`Only direct calls to named functions are supported`),
  known (`` Unknown function `String` `` *(CLI only)*), and called with
  matching arity and types (see [Functions](#functions)).
- `obj.method(args)` calls a class method with `obj` as `this`
  (`tests/cases/cls_this_method_call`); `this.method(args)` inside a method
  likewise.
- An array has the methods of [Arrays and strings as receivers](#arrays-and-strings-as-receivers)
  (`tests/cases/arr_push`); any other is
  `` Unknown method `shift` on i32[] (supported: push, pop, …) ``.
- Builtins are called by dotted name (`console.log`, `Math.sqrt`,
  `process.exit`) or bare name (`toI32`, `parseInt`, `Number`,
  `readFileSync`); a user function with the same bare name shadows the
  builtin. Unknown dotted builtins are `` Unknown builtin `Math.foo` ``
  (`tests/cases/reject_unknown_builtin`).

### `new`

- `new C(args)` for a class: allocates `sizeof(C)` bytes in the arena, or
  on the stack when the object provably does not escape
  ([Memory model](#memory-model)), and runs the constructor (or the inline
  initializers) (`tests/cases/cls_point`, `mem_stack_struct`).
- `new Array<T>(n)`: `n` zero-filled elements; `T` must be a scalar, a
  `nish:simd` vector (every lane zero) or a
  `U | null` (whose zero fill is `null`); type argument and length required
  (`tests/cases/arr_new_zeroed`, `mem_nullable`, `simd_zero_fill`;
  `reject_arr_new_string`: `` would zero-fill with null string values ``).
  A length no array can hold panics with `array length out of range` before
  anything is allocated: past 2^31 − 1 under `--number-mode i32`, past 2^53
  under `f64`, a negative `i32` or `i64` (a ranged integer is read as an
  `i32`, so it is checked as one), or a NaN. A narrower unsigned length and a
  literal up to 2^31 − 1 are not checked (`tests/cases/cg_sec_new_array_guard`, `cg_sec_new_array_negative`,
  `tests/link/cg_sec_new_array_*`; [docs/security/codegen.md](security/codegen.md), CG-1 and CG-2).
- `new Int32Array(n)`, `new Float64Array(n)`, `new BigInt64Array(n)`: the
  same as `new Array<i32>(n)`, `new Array<f64>(n)`, `new Array<i64>(n)`, with
  the same lowering (`tests/cases/arr_typed_views`), and no `push` or `pop`
  on the result ([Typed-array names have no `push` or `pop`](#typed-array-names-have-no-push-or-pop)); a type argument is
  `` `new Int32Array` takes no type argument ``
  (`reject_arr_typed_view_typearg`).
- Anything else is `` Unsupported `new X` `` / `` Unknown class `X` ``;
  `new Function` and `new Proxy` are forbidden (`reject_new_function`,
  `reject_proxy`).

### Member access

- `s.length` on a string: the UTF-8 byte length as a `number`
  (`tests/cases/str_length`; `reject_length_on_number`, `reject_unknown_property`).
- `a.length` on an array: read-only (`tests/cases/arr_length`;
  `` Cannot assign to `length` of i32[] ``, `reject_arr_length_assign`).
- `p.f` on a class or interface value (`tests/cases/cls_point`).
- `Math.PI`, `Math.E` (`tests/cases/math_i32`); `process.argv`,
  `process.platform`, `process.arch` (see [`process`](#process));
  `Arena.*` (see [`Arena`](#arena)). Any other bare
  identifier before a dot is `` Unknown identifier `os` `` *(CLI only)*.
- Member access on a `T | null` value requires narrowing first, or a `?.`
  in a chain that ends in `??` ([Nullable types](#nullable-types);
  `tests/cases/reject_optional_chain`).

### Element access

`a[i]` requires an array `a` (`Cannot index a value of type i32`,
`tests/cases/reject_arr_index_non_array`) and a numeric `i`
(`Array index must be a number, got string`, `reject_arr_string_index`).
The index is sign-extended from `i32` (or truncated toward zero from
`double` in f64 mode) to `i64` and checked against `len` with an unsigned
compare, so negative indices fail too (`tests/cases/arr_bounds_panic`,
`arr_index_read_write`, `arr_f64`).

**The check is not emitted when the checker has proved the index in range**
(WP15 §2.1/§2.2). The proof is flow-sensitive. A fact's index is a local or a
parameter, and its length holder `w` is a local, a parameter, or a **property
path** — a local, a parameter or `this`, then field reads: `h.xs`,
`this.state.idx` (#106). An access `w[i]` needs `i >= 0` and `i < w.length`,
and both come from the program as written:

  - `i >= 0` from a literal initialiser, from `i = w.length`, from a test that
    reaches the access (`if (i >= 0)`, `0 <= i`, the false arm of `i < 0`), or
    from the type — an `u8`/`u16`/`u32`/`u64` index is never negative, and
    neither is an `integer<Lo, Hi>` with `Lo >= 0`.
  - **a bound read off the type.** A declared range bounds its index from
    above as well: a `u8` is below 256, a `u16` below 65536 and an
    `integer<Lo, Hi>` below `Hi + 1`, so with a length guard that covers the
    range (`if (table.length < 256) { return }`) the access needs no check.
    `const k = toI32(b)` keeps the bound of a `u8` or `u16` `b`, because the
    conversion is a `zext`. A `u32` or `u64` has no upper bound an `i32` fact
    can carry, and a range wider than the length that is known keeps its
    check (`tests/cases/arr_bounds_ranged`). Nothing is recorded and nothing
    is forgotten: every write into a ranged place is an entry, so the value
    is inside its range at every point.
  - `i < w.length` from a test that reaches the access — a loop condition, an
    `if`, the right operand of `&&`, the statements after
    `if (i >= w.length) { return; }` — or, through `const n = w.length`, from
    `i < n`. A constant index `w[3]` needs `w.length >= 4` instead, which a
    length guard (`if (w.length >= 4)`) or an array literal of known size
    gives.
  - for a `u8`, `u16` or `u32` index, `toU32(i) < toU32(w.length)` — or
    `i < toU32(w.length)` for a `u32` — the same way: an unsigned index
    cannot be compared with the `i32` length as it is, its type is its lower
    end, and this is the upper one. `toU32` widens a `u8` or `u16` and is the
    identity on a `u32`, and of a length it can only answer the length or
    less (in f64 mode it is a saturating `fptoui`), so the `u32` compare is
    `i < w.length` or stronger. Only in the test itself: a `u32` copy of the
    length is not a length, because `toU32(w.length) - toU32(1)` wraps on an
    empty array. A `u64` index is not credited — `toU32` keeps its low 32
    bits — and neither is `toI32(i) < w.length` on a `u32`, which reads an
    index past `2^31 - 1` as negative
    (`tests/cases/arr_bounds_unsigned_guard`, `arr_bounds_unsigned_guard_f64`;
    `arr_bounds_unsigned_guard_kept` keeps every check).
  - **a guard that ends the path.** After `if (i < 0 || i >= w.length) { … }`
    the negation of the test holds for the rest of the block when the guarded
    branch ends in `return`, `break`, `continue`, or a call to the
    builtin `panic(…)` or `process.exit(…)` (`exit` from `nish:process` too).
    Only the builtins count: a parameter or local called `process`, or a
    function parameter called `panic`, is the call it resolves to and falls
    through, and so does any other call. Such an access keeps its check and
    the NL9007 warning (`tests/cases/bounds_panic_guard`, `bounds_exit_guard`;
    `bounds_guard_not_exit`, `bounds_guard_shadowed_exit` and
    `bounds_guard_shadowed_panic` keep it). `Map.keyAt`, `Map.valueAt` and
    `Set.keyAt` in `std/collections.ts` guard their reads this way.
  - **both at once from a check that has already passed.** A checked `w[i]`,
    read, store or compound assignment, and a checked `s.charCodeAt(i)`
    either panic or leave `0 <= i < w.length` behind, because the panic does
    not return; a checked `w[3]` leaves `w.length >= 4`. So the same index on
    the same holder is proved on every path that runs through the first
    check, until one of the rules below ends the fact — which they do exactly
    as they end a fact a test wrote. `const t = v[i]; v[i] = v[j]; v[j] = t`
    carries two checks, not four. The fact is taken where the emitter runs
    the check: `v[i] = v[j]` checks `v[j]` before `v[i]`, and `v[i] op= x`
    checks before `x` runs. A store whose value calls anything proves nothing
    about a *path* holder, because its check passed on the array the path
    named before the call (`tests/cases/arr_repeat_check`,
    `arr_repeat_check_local`; the repeats that keep their check are
    `arr_repeat_check_call`, `_push`, `_field_store`, `_reassign` and
    `_flow`, and `arr_repeat_check_panic` panics past the end on three of
    them).

    **`toI32(w.length)` is `w.length`** wherever a length appears above: in
    the hoist `const n: i32 = toI32(w.length)`, in `i < toI32(w.length)` and
    in a length guard. It is the spelling that compiles in both number modes
    — under `--number-mode f64` `.length` is an `f64`, and `i < w.length`
    with an `i32` `i` is a type error — so a program written for both
    (`std/text` is one) keeps every proof the bare hoist gets. It is sound in
    both: in i32 mode the conversion is the identity, and in f64 mode it is a
    saturating `fptosi` of an exact integer, which can only answer the length
    or less, never a negative. Only the builtin counts: a user function named
    `toI32` wins over the builtin and may answer anything, so it proves
    nothing (`tests/cases/perf_bounds_toi32_user`, which panics on the pass
    past the end), and neither does `toI32` of anything that is not a bare
    length (`perf_bounds_toi32_loop`). The builtin converts inline and calls
    nothing, so unlike any other call it leaves the array-length facts
    standing, and `const m: i32 = toI32(ys.length)` does not undo the
    `const n: i32 = toI32(xs.length)` above it (`perf_bounds_toi32`,
    `perf_bounds_toi32_f64`).

  - **`i - c` and `w.length - c`** (`c` a non-negative literal) carry
    bounds too: removing `c` lowers every floor of `i` by `c` — `i >= 1`,
    which `if (i !== 0)` on a non-negative `i` gives, leaves `i - 1 >= 0` —
    and with `c >= 1` turns `i <= w.length` into `i - 1 < w.length`;
    `w.length - 1` is below the length whatever the array holds. A copy
    `let j = i` has every bound `i` has
    (`tests/cases/arr_range_call_countdown`).

  - **`i + c`** (`c` a literal of 1 or more) is an index too, and a test on
    it is a bound on `i`. `i + c < w.length` says the length reaches `c`
    past `i`, and so does `i + c < n` with `n` a hoisted length;
    `i + c <= w.length` reaches `c - 1`; `i + c < N`, for a literal `N`, is
    `i < N - c`. An access `w[i + k]` then needs `i >= 0` and a reach of at
    least `k`, or a literal bound `i < M` with `w.length >= M + k`, so a
    loop that reads four elements a pass under `i + 3 < w.length` keeps none
    of its four checks. A checked `w[i + c]` that ran leaves
    `i + c < w.length` behind, and nothing about `i >= 0`. Both halves rest
    on the sum being exact: a signed `i + c` panics on overflow or is proven
    not to overflow, so it is never a wrap to a small value. For an unsigned
    `i`, whose add wraps by definition, an offset proves nothing and the check
    stays (`tests/cases/arr_bounds_offset`; `arr_bounds_offset_reach` reads one
    past its reach and `arr_bounds_offset_floor` has no floor, and each keeps
    its check and panics).

  - **Any other integer index is proved by its range.** Where none of the
    rules above proves `w[e]`, the values `e` can take decide: every local's
    bounds from the facts above and its declared range, carried through
    `+`, `-`, `*`, a mask, a conversion and a call's known return range;
    a quotient converted to its own type, `toI32(a / 4)` of `i32` operands
    (or `toU8`, `toU16`, `toU32` of theirs), keeps the quotient's range,
    since that conversion emits nothing. If
    the lowest is not negative and the highest is below a length `w` is
    known to have (`w.length >= n`, from an array literal, a
    `new Array(n)`, a guard or a check that ran), the access needs no
    check: `freeMaxs[c + r]` and `freeMins[c - r + 7]` with `r` and `c`
    each below 8 into arrays made with 16, or `cells[r * 4 + c]` over a 4
    by 4 board. The range is the value's own only where the arithmetic is
    exact, which is a signed `i32` or `i64`; an unsigned index, whose
    arithmetic wraps by definition, and an `f64` one keep their check. The length is the one
    the index leaves behind, so a call inside the index that shrinks the
    array, a `new` whose constructor does included, proves nothing
    (`tests/cases/arr_bounds_range`; `arr_bounds_range_past` reaches the
    length, `arr_bounds_range_negative` goes below zero, and
    `arr_bounds_range_call` and `arr_bounds_range_new` shrink the array, and
    each keeps its check and panics; `arr_bounds_range_kept` keeps its own).

  - **A helper's fresh array has the length it was built with.** A length
    `w` is known to have comes from an array literal or `new Array(n)`
    written in place, and also from a call of a function that builds one and
    returns it: `const xs = filled(8)`, or `this.rows = filled(8)`, starts
    `xs` or `this.rows` with 8 elements when `filled` declares
    `const arr = new Array<T>(n)` (a typed-array `new` or an array literal
    too), touches it only by indexing it, reading `arr.length` and
    `arr.push(...)`, and returns it. Every `return` hands back that local or
    a fresh array written in place, and the call gives the shortest of them.
    A size is a literal, a constant of the helper's module (read where the
    call is in that module), or a parameter, whose argument gives the length
    by its declared floor: a literal, a constant or a ranged type's `Lo`. The
    helper's body is read as written, so the rule takes only what it can see
    there: a plain function, not a method, a generic or an arrow; a body
    with no arrow, nested function, class or `try`; a size whose name the
    body never declares again or writes. The array may be handed to a
    function of the same module whose parameter keeps its length in turn:
    the parameter is only indexed, read for `.length`, pushed to, or handed
    on to another such parameter, recursion included, and never returned.
    Storing the array, `pop`, returning it from a callee, a method's or a
    builtin's argument, or any other use gives no length, because each is a
    way another holder could shrink it; so does a helper in another module
    that hands its array on, whose call the caller's module cannot resolve.
    A store `recv.f = filled(8)` gives one only when `recv` is `this` or a
    `const` local, which the call cannot point elsewhere
    (`tests/cases/arr_bounds_returned`, `arr_bounds_returned_through`;
    `arr_bounds_returned_pop`, `_passed`, `_stored`, `_least`, `_rebind`,
    `_shadow`, `_shadow_param`, `_through_return`, `_through_deep`,
    `_through_cycle`, `_through_store`, `_through_param` and `_through_memo`
    each keep their check and panic; `tests/link/arr_bounds_returned_import` keeps its check;
    `arr_bounds_returned_kept` keeps its seven).

A fact ends where it stops being true: at any assignment to `i` that is not
`i = i + <non-negative literal>` (`i++` and `i += n` included) or
`i = i - <non-negative literal>` (`i--` and `i -= n` included), at any
assignment to `w`, and — for an **array** — at any call to something that
may resize it, because a callee holding the same array may `push` or `pop`
and move `len` (`tests/cases/arr_bounds_shrink_panic` is the program that
still panics because of that rule). A decrement keeps the upper bounds and
loses the lower ones, the mirror of an increment, so the loop that counts
down from the last index needs only its own `i >= 0`. A **string**'s length cannot change once the variable
holding it is bound, so a string fact survives calls, which is what makes a
scanner's cursor check-free (`tests/cases/str_bounds_proven`). The increment
exception needs `nsw`: the step past `INT_MAX` panics, so the lower bound holds
for the same reason the overflow check is there; a counter stepped with
`wrappingAdd` has no lower bound, and its check stays. An `f64` index is never proved, because a bound on the double is
not a bound on its truncation. `tests/cases/arr_bounds_proven` and
`perf_bounds_quiet` pin the proofs; the surviving checks warn, below.

**A fact is taken where it is true, and only then.** Two orderings decide
that, for a local and a path alike:

  - in `a && b` and `a || b`, `a`'s facts are proved before `b` runs, so they
    reach the code the condition guards only if nothing `b` does can undo
    them. A call, an assignment or a field store in `b` drops them by the
    rules below, and `i < xs.length && xs.pop() > 0` proves nothing about
    `xs[i]` (`arr_bounds_cond_effect`, `arr_bounds_cond_assign`, and the path
    forms `arr_path_cond_*`: a call, a store, a root reassignment, `||`, a
    ternary, a `while`, a string path, a generic class and f64 mode);
  - an element store is judged where its check runs against the values it
    stores through. `a[i] op= v` checks before `v` runs and is judged there.
    `a[i] = v` reads `a` and `i`, runs `v`, then checks, so it is proved only if
    `v` leaves `i` and `a` alone: `xs[i] = (i = 0)` keeps its check
    (`arr_bounds_store_rhs`, `arr_path_store_rhs`,
    `arr_path_store_rhs_compound`). A field store evaluates its receiver before
    its value, and `g.hs[i].n = (i = 0)` is judged that way round
    (`arr_path_store_rhs_field`);
  - a `for` update and a `do/while` condition are reached from the end of the
    body *and* from every `continue`, so they are judged against what holds
    on all of those edges: a `continue` branch that rebinds the array, moves
    the index or calls anything takes the proof away from the update or the
    condition (`arr_path_continue_for`, `arr_path_continue_do`,
    `arr_bounds_continue_for`, `arr_bounds_continue_do`), and one that does
    none of that keeps it (`arr_bounds_continue_proven`). A `continue` in a
    `switch` clause reaches the loop's update (`arr_bounds_continue_switch`),
    and one in an inner loop reaches only the inner update
    (`arr_bounds_continue_nested`);
  - the code after a `for` or a `while` is reached where the condition fails
    *and* from every `break`, which leaves with the body's writes applied. A
    fact the condition re-established about something the body then changed
    does not survive the loop (`arr_bounds_break_for`, `arr_bounds_break_while`,
    `arr_bounds_break_for_string`, `arr_bounds_break_while_string`). A `break`
    in a `switch` clause leaves only the `switch`;
  - `r.unwrapOr(d)` evaluates `d` and `r.expect(m)` evaluates `m` only when
    `r` is an `Err`, so neither argument proves anything after the call. What
    `d` might undo is undone, and `m` is followed by the exit
    (`arr_bounds_lazy_unwrap_or`, `arr_bounds_lazy_expect`).

All of these were unsound for locals before property paths existed; the fixes
and the tests cover both.

**A property path has to earn what a local gets for free**, because a field
can be written through an alias and a local cannot. `h.xs.length` proves
`h.xs[i]` only while nothing between the test and the access can rebind the
path or resize the array, and a path fact ends at:

  - a store to a field whose name is anywhere on the path, through *any*
    holder — `g.xs = ys` ends `h.xs`'s facts even where `g` is a different
    object, because the name is compared rather than the aliasing guessed
    (`arr_path_reassign`, `arr_path_alias_store`);
  - a store of a whole element into an array of inline records, which
    rewrites a record in place with no field name written
    (`arr_path_record_store`). It ends the facts of a path with a link read
    off a holder *declared* as that record type — `r.xs` for `const r = rs[0]`
    — because a struct field is a pointer and interfaces are nominal, so
    nothing else can point into the slot. An array of classes holds pointers,
    so a store there rewrites no object and ends nothing;
  - an assignment to the root (`arr_path_root`);
  - **any call** and any `new` that may resize an array or store to a field
    on the path, for a string path as well as an array one: a callee may
    `push` or `pop` the array or store a new value in the field, and a `pop`
    through a second holder of the same array is a call too
    (`arr_path_callee_pop`, `arr_path_callee_string`, `arr_path_alias_shrink`).
    `charCodeAt` and the builtin `toI32` call nothing, as they do for a
    local; what else a call may do is its summary, below.

A path is never built through a link whose **declared** type is nullable —
the root's included — whatever a guard narrowed it to, and neither is one
whose last link is `T[] | null` (`arr_path_nullable`). Each of those tests is a
program that proves `i < h.xs.length`, breaks it by one rule, and reads
`h.xs[i]`; each must panic, and each reads past the array with its rule
removed. `arr_path_hold` pins where the fact holds, and
`tests/cases/arr_header_hoist` pins the measured point of it: a loop over
`h.xs` compiles to the loop `const xs = h.xs` does, with one bounds check fewer
than before and so one loop exit fewer. The hoist that lifts `h.xs` out of the
loop refuses a loop that stores a whole element into an array of inline
records, by the same rule the proof drops its path facts by
(`arr_header_hoist_record_store`), and keeps hoisting through a store into an
array of classes (`arr_header_hoist_record_class`) and a path read off
classes beside a record store (`arr_header_hoist_record_class_root`).
A path the proof cannot take keeps its
check without a warning, because the rewrite the warning would name is that
`const xs = h.xs` hoist.

**What crosses a call** (WP15 §2.4). Once every body is checked, each
function gets a summary of what it can do to a caller's facts: the field
names it — or anything it calls — may store to, and the record types it may
store whole. A function that calls `push`, `pop` or any builtin handed an
array or an object, `Arena`, a foreign function or an instantiation has no
summary, and a call to it ends every array and path fact as above. A call
with a summary resizes no array, so it keeps every array-length fact and
every path fact whose fields and links it leaves alone: `c.touch()`, which
stores `calls`, keeps `i < xs.length` and `i < c.v.length`
(`arr_range_call_loop`), and one that stores `v` ends `c.v`'s facts
(`arr_range_call_rebind`). A builtin handed only numbers, booleans and
strings — `console.log`, `panic`, a string method — has the empty summary,
since a call handed no function reference can reach only what it is handed:
the one mutable module state, [module storage](#module-storage), is named
only by the program's code (its module's, or an importer's when it is
exported), never reached by a builtin, and its length never changes, so no call can
end a length fact about it.

A function every call to which the compiler can see is **entered with what
every call site proves** about its parameters: a floor and an upper bound of
an integer parameter, and length facts about a holder read off a parameter or
`this` — `this.v.length >= 6`, `i < this.v.length`. Each site is judged once
its arguments have run, a fact about the local an argument named is carried
only while no later argument writes it (`arr_range_call_arg_rebind`), and an
argument handed to a parameter of a different integer type carries nothing.
The sites are joined — the weaker floor, the higher bound, the shorter
length, a relation only where every site states it
(`arr_range_call_two_sites`, `arr_range_call_no_proof`) — and recursion is a
fixpoint, so `permute(n)` calling `permute(n - 1)` under `if (n !== 0)` keeps
`n <= 6` and a recursion that grows its index keeps nothing
(`arr_range_call_grow`). Inside the function the facts end by the rules above
(`arr_range_call_rebind_callee`). **Not entered with anything:** `main`; an exported
function or a method of an exported class, since a host may call it with
anything (`arr_range_call_exported`) — unless the build is a closed-world
`--link`, where `export` means only "importable" (see
[`export` and `import`](#export-and-import): `tests/link/range_export`, and
`range_export_unproven` for a caller that proves nothing); a `hidden` one, a
constructor, a lifted arrow, a function taking a compile-time function, and
any function called from an arrow or from an instantiation's body
(`arr_range_call_arrow`, `arr_range_call_generic`). AWFY Permute with its
class not exported is proved throughout: `swap` carries no check
(`arr_range_call`), and with it exported the same holds in a `--link` build.

A generic's instantiations are proved one at a time, each against its own
verdicts: `rs[0] = x` rewrites a record when `T` is an inline record and
stores a pointer or a value otherwise, so an access one instantiation proves
may keep its check in another (`arr_bounds_generic_instances`, and the
`_prim`, `_method` and `_iface` forms).

The proof changes what the program *costs*, never what it *means*: an
out-of-range index that reaches a check still panics.
`uncheckedGet` and `uncheckedSet` from
[`nish:unsafe`](#nishunsafe-unchecked-access-and-defined-wrapping) are the
opposite trade and a separate thing: each removes the check at its own site
and makes an out-of-range index there undefined behaviour.

String-keyed access is forbidden by the
validator (`reject_string_key_access`, `reject_non_numeric_index`), and so
is an index outside the "numeric-shaped" forms listed under
[Forbidden constructs](#forbidden-constructs-phase-0-validator): `a[k++]`
and `a[--k]` are `Element access requires a numeric index` *(CLI only)*.

### Array literals

`[a, b, c]` allocates a header and `n` elements; every element must have
one type (`Array literal elements must all have the same type`,
`tests/cases/reject_arr_mixed_literal`). `[]` needs a contextual `T[]` type
(annotation, return type, assignment target, `push` argument, enclosing
literal, or parameter) (`Empty array literal needs a type annotation`,
`reject_arr_empty_literal`; `tests/cases/arr_push`, `arr_literal`). Holes and
spread are not supported (`Holes in array literals are not supported`,
`reject_arr_hole`; `Spread in array literals is not supported`,
`reject_arr_spread`).

### Arrays of records are contiguous

An array whose element type is an **`interface`** is one block of records, `N`
of them end to end at exactly the stride and alignment clang gives the matching
C array. `ps[i]` is an interior pointer into that block — a `getelementptr`,
with no pointer to load and chase — which is what makes a loop over `Point[]`
vectorisable and what lets a C host read `((struct Point *)a->data)[i]`
(`tests/cases/arr_struct_contiguous`, `tests/layout/structs.c`).

Three element kinds are **not** records and keep one pointer per slot:

- a **`class`**. The two struct kinds already mean different things: an
  `interface` is fields and nothing else, so copying one into a slot cannot be
  told apart from pointing at it, while a `class` has identity — a constructor
  and methods that run on one object — and every other position in the language
  passes a class value by reference.
- an **`interface` some class `implements`**. That array is the language's only
  polymorphic container (`tests/cases/cls_implements_prefix`): a `Shape[]` holds
  a `Square` and a `Circle` at once, and both are longer than `Shape`, so a
  value slot would copy the prefix and drop the rest. The property is
  program-wide — one compilation, one layout for `Shape[]` in every module of it.
- a **`T | null`** of any kind: a null element has no bytes to be, and `null` is
  the pointer. That spelling is also how to ask for a sparse array of records.

Three consequences, each of them a rule:

- **A record put into an array is copied into the slot.** `ps.push(p)`,
  `ps[i] = p` and `[p, q]` copy `sizeof` bytes, exactly as a C array of structs
  does; afterwards `ps[i]` and `p` are two records, and writing one does not
  change the other (`tests/cases/arr_struct_push_copy`).
- **An element reference may not be held across a mutation of its array.**
  `push` may move the block (`nish_array_grow` bumps a fresh one and copies)
  and `pop` hands the slot back to the next `push`, so a pointer taken before
  either names memory that is no longer the element. A `const` bound to `a[i]`
  or `a.pop()`, and the variable of a `for (const p of a)`, are element
  references; using one after a `push` or `pop` on the same array — or after a
  call that could push through it, which is any call handed the array as a
  non-`readonly` parameter — is
  `` `p` refers to an element of `ps`, and `ps.push(...)` may move or reuse
  that storage; index `ps` again afterwards rather than holding the element
  across it `` (`reject_arr_element_across_push`,
  `reject_arr_element_loop_push`). A second name for the element is one too:
  `const q = p`, `q = p` (in a nested block as well, since `q` outlives it),
  and either side of `c ? p : r` or `m ?? p` (`tests/cases/arr_ref_alias_*`);
  a call's result is not, since a helper may return a copy
  (`arr_ref_alias_clone`). A loop is checked as a whole, because a
  `push` at the bottom of the body reaches a reference taken at the top on the
  next pass. `ps.push(ps[i])` is refused for the same reason, in one message of
  its own (`reject_arr_element_push_self`).

The rule rejects some programs that would have been safe — a call is taken to
mutate every mutable array it is handed, because whether the callee pushes is a
whole-program question the checker does not answer. `readonly T[]` is how a
signature promises it does not.

### Fixed-length array fields are stored inline

A class field `f: T[]` is normally one pointer to an array header that lives
somewhere else in the arena, so `this.f[i]` loads the pointer, then the
header's `data`, then the element. When the whole program shows that the field
can only ever hold an array nobody else can reach, of a length known at every
assignment, the compiler stores the header and its elements **inside the
object** instead, and `this.f[i]` becomes a load at a constant offset from
`this` (`tests/cases/cls_inline_array`). This is a layout decision, not a
language rule: no program can tell the two layouts apart, which is the whole of
what the conditions below guarantee.

A field qualifies only when all of these hold, over every module of the
program:

- **Every assignment is a fresh array of a constant length**, as a statement of
  its own (`x.f = e;`, never `y = x.f = e`): an array literal of `n` elements
  (`[]` is one, with `n = 0`), `new Array<T>(n)` or a typed-array `new` with an
  integer literal `n`, or a call to a top-level function that is proven to
  return a fresh array whose length is a constant or one of its parameters,
  passed a literal there. That function returns only `new Array<T>(p)`, a
  literal, or a `const` local initialised with one, which it only indexes and
  reads `.length` of (`filledBooleans(8)` in AWFY Queens,
  `tests/cases/cls_inline_array_call`). The slot is sized for the largest
  length `K` any assignment gives; the header still records the current length,
  so `.length` answers what it always did.
- **Nothing takes the field as a value.** `x.f[i]` (read, write, compound) and
  `x.f.length` are the only uses. Reading it into a local, passing it to a
  function, returning it, iterating it with `for ... of`, capturing it, or
  calling any method on it — `push` and `pop` included — keeps today's layout
  (`cls_inline_array_local`, `cls_inline_array_push`, `cls_inline_array_passed`).
- **Every assignment's length is a literal.** A length the compiler does not
  know cannot size a slot, and the field is boxed instead (below,
  `cls_inline_array_dynamic`).
- **No element access can reassign the field under itself.** `x.f[i]`
  evaluates `x.f` before `i`, and `x.f[i] = v` before `v`; when the index or
  the value calls something that can assign `f` (directly or through its own
  calls), the access uses the array `f` held *before*, which a single set of
  slots cannot be. Such a field keeps today's layout
  (`tests/cases/arr_repeat_check_call`, `cls_inline_array_order`).
- **No host can see the class's layout.** The class is not host-visible as
  [`export`](#export-and-import) decides it for a call (`hostVisible` in
  `src/visibility.ts`): an exported class keeps today's layout in every build
  that is not a closed-world `--link`. And no build that describes or shares
  layouts with code this compiler did not write inlines anything at all —
  `--emit-header` (whose C structs list every class), `--emit-dts`,
  `--emit-napi`, a wasm target, `--profile wasi`, or a module that declares a C
  function (`cls_inline_array_header`, `tests/link/cls_inline_array_*`).
- **It is a plain class**: not generic, not one that `implements` an interface,
  and its element type is not a record (an [inline
  record](#arrays-of-records-are-contiguous) would hand out interior pointers
  into the object).
- **`K` elements fit in 256 bytes** and `K` is at least 1. The cap bounds how
  much an object grows, since every object of the class carries the slots
  whether it uses them or not. It does not bound the cost of reassigning: a
  literal or `new Array` writes the slots in place and allocates nothing, which
  is faster than the pointer layout at every `K` measured, while an assignment
  from a call still makes its array and then copies it, a cost that is about
  the same at 8 slots as at 64. A field reassigned from a call and read fewer
  than a few dozen times per assignment is therefore slower inline; the
  measurement is in the header of `src/inline-arrays.ts`.

**A field that fails only on its lengths is boxed.** When every condition
holds except that some assignment's fresh array has a length the compiler does
not know (`new Array<T>(n)` with a parameter `n`, a fresh-returning call
passed a non-literal), or except that `K` elements would pass 256 bytes, the
object holds only the array's length and data pointer, 16 bytes as
`{ i64, i8* }`, and the elements are one block of their own
(`tests/cases/cls_boxed_array`). Against the pointer layout this drops the
separate 24-byte header and its allocation: an object with a boxed field is 8
bytes larger and its array 24 bytes smaller, and `this.f[i]` loads `data` from
`this` directly instead of first loading the header's address. A literal or
`new Array` allocates the data block alone; an assignment from a call takes the
`len` and `data` of the array the call made. Reference semantics are unchanged
for the same reason as inline: no one else ever holds the array. A field taken
as a value anywhere, `push` included, keeps the pointer layout
(`cls_boxed_array_push`).

Why reference semantics are unchanged: the object is still a pointer, so a
class holding an inline field can be stored in arrays and passed around as
before. Assigning the field copies the fresh array's elements into the slot
(an array literal and `new Array` write the slot directly and allocate
nothing). That copy is observable only through another reference to the fresh
array or to the field's array, and neither exists — the first because it is
fresh, the second because the field is never taken as a value. An inline array
lives and dies with its object, on the stack when the object does.

### Template literals

`` `text ${e} text` `` accepts holes of type `string`, `number`, `i64`,
`f64`, or `boolean` (`Template literal hole must be string, number, or boolean`);
each hole is converted and the parts are concatenated left to right
(`tests/cases/str_template`, `i64_basic`). `` `${s}` `` with a single string
hole is `s` itself (`tests/cases/str_param_passthrough`).

A concatenation or a template whose result would pass 2^31 − 1 bytes fails as
an allocation does, `nish: out of memory` and exit 1, in both number modes
([docs/security/runtime.md](security/runtime.md), RT-2), and so does a `join`
whose result would (CG-3 in [docs/security/codegen.md](security/codegen.md);
`tests/link/cg_sec_join_limit`). No string can therefore pass that length.

### `this` and object literals

See [Classes](#classes) and [Interfaces](#interfaces-and-object-literals).

## Builtins

No `import` is needed; builtins are resolved by name. The libc-backed ones may
also be imported from a `nish:` module, which is the same builtin under a name
that cannot be shadowed (see [Builtin modules](#builtin-modules-nish) below).
Effects (`none`, `read`, `write`) are what the call does to the purity of the
enclosing function
([ARCHITECTURE.md](ARCHITECTURE.md#attribute-soundness-rules)).

### Builtin modules (`nish:`)

The builtins backed by the C runtime can be imported instead of reached for as
globals. `nish:` is the only bare specifier the language accepts; but for
`nish:secret` and `nish:region`, which have source behind them
([Secrets](#secrets-nishsecret), [Regions](#regions-nishregion)), it
resolves to no file, and the import *renames a builtin rather than introducing one* —
the call checks through the same rule and emits the same IR as the global
spelling, which `tests/run.js` pins by compiling `tests/cases/io_nish_import`
and `io_nish_import_global` and comparing the two bodies.

| Module | For |
| --- | --- |
| [`nish:fs`](reference/nish-fs.md) | files and directories |
| [`nish:process`](reference/nish-process.md) | processes, environment, clocks |
| [`nish:io`](reference/nish-io.md) | standard output and error, panic |
| [`nish:secret`](reference/nish-secret.md) | secrets that are wiped |
| [`nish:region`](reference/nish-region.md) | region allocation |
| [`nish:net`](reference/nish-net.md) | sockets and the readiness loop |
| [`nish:term`](reference/nish-term.md) | terminal input |
| [`nish:unsafe`](reference/nish-unsafe.md) | unchecked access, wrapping arithmetic |
| [`nish:async`](reference/nish-async.md) | tasks: spawn, await, wait, cancel |
| [`nish:simd`](reference/nish-simd.md) | sixteen-byte vectors |

**[`nish:fs`](reference/nish-fs.md)** exports `readFileSync`,
`readFileSyncOrNull`, `readFileBytesSync`, `writeFileSync`,
`appendFileSync`, `writeFileBytesSync`, `renameSync`, `unlinkSync`,
`writeFileSyncMode`, `createFileExclusiveSync`, `mkdirSync`,
`mkdirSyncMode`, `isDirectorySync`, `readdirSync`, `realpathSync`,
`statMtimeSync`.

**[`nish:process`](reference/nish-process.md)** exports `exit` (the global
`process.exit`), `getenv`, `spawnSync`, `spawnSyncTo`, `spawnPiped`,
`spawnPipedWithin`, `spawn`, `spawnWithFds`, `kill`, `waitPid`, `availableParallelism`,
`totalMemory`, `setNice`, `setIdlePriority`, `setCpuAffinity`,
`monotonicNanos`, `wallClockNanos`, `signalFd`, `readSignal`, `argv`,
`platform`, `arch`.

**[`nish:io`](reference/nish-io.md)** exports `write`, `writeError`,
`writeBytes`, `panic`.

**[`nish:secret`](reference/nish-secret.md)** exports `Secret`, `secret`,
`expose`, `exposeWith`, `wipe`. It is the one module with source behind it
([Secrets](#secrets-nishsecret)).

**[`nish:region`](reference/nish-region.md)** exports `Region`, `region`,
`regionWith`, `enter`, `enterWith`, `free`. It has source behind it too
([Regions](#regions-nishregion)).

**[`nish:net`](reference/nish-net.md)** exports `netAddress`,
`netLocalPort`, `tcpListen`, `tcpListenFlags`, `tcpAccept`, `netRead`,
`netWrite`, `netWrite2`, `netShutdown`, `netClose`, `netMss`,
`netSetOption` and its option ids `NET_TCP_NODELAY`, `NET_TCP_QUICKACK`,
`NET_SO_KEEPALIVE`, `NET_SO_SNDBUF`, `NET_SO_RCVBUF`, `tcpConnect`,
`connectResult`, `udpBind`, `udpSendTo`, `udpRecvFrom`, `pollCreate`,
`pollAdd`, `pollModify`, `pollRemove`, `pollWait`, `unixListen`,
`unixListenMode`, `unixConnect`, `unixAccept`, `unixSocketPair`, `sendFd`,
`recvFd`, `peerCredentials`, `netRingState` and the constants
`NET_UNIX_UNLINK_STALE`, `NET_UNIX_STREAM`, `NET_UNIX_SEQPACKET`,
`NET_LISTEN_RING`. Each is a global too
([`nish:net`](#nishnet-addresses-non-blocking-tcp-and-udp-and-the-readiness-loop)).

**[`nish:term`](reference/nish-term.md)** exports `readStdin`, `waitStdin`,
`isTerminal`, `terminalSize`, `setRawMode`, `setTerminalRestore`. Each is a
global too ([`nish:term`](#nishterm-terminal-input)).

**[`nish:unsafe`](reference/nish-unsafe.md)** exports `uncheckedGet`,
`uncheckedSet`, `wrappingAdd`, `wrappingSub`, `wrappingMul`,
`readCString`, `readStruct`, `cErrno`. They are **reached only through the import**
([`nish:unsafe`](#nishunsafe-unchecked-access-and-defined-wrapping)).

**[`nish:async`](reference/nish-async.md)** exports `spawn`, `awaitAll`,
`sleep`, `readable`, `writable`, `readableWithin`, `writableWithin`,
`taskId`, `cancel`, `cancelled`, `cancelAfter`.
They are **reached only through the import**
([Async functions](#async-functions-async-and-await)).

**[`nish:simd`](reference/nish-simd.md)** exports the vector types `u8x16`,
`u16x8`, `i32x4`, `u32x4`, `f32x4`, `f64x2` and their constructors,
`splatU8x16` … `splatF64x2`, `loadU8x16` … `loadF64x2`, `store`, `extract`,
`replace`; the masks `mask8x16` … `mask64x2`; the lane operations `add` …
`asF64x2`, among them `shl`, `shr`, `rotl` and `rotr`. They are **reached
only through the import**
([`nish:simd`](#nishsimd-sixteen-byte-vectors),
[lane operations](#nishsimd-lane-operations-and-masks)).

```ts
import { readFileSync } from "nish:fs";
import { argv } from "nish:process";
import { write } from "nish:io";
```

- The forms are the ones every other import allows: a named import, with `as`
  (`tests/cases/io_nish_rename`). Default, namespace, side-effect and type-only
  imports are refused under the same messages a relative specifier gets.
- An unknown module is `` Unknown builtin module `nish:sqlite` ``
  (`reject_nish_unknown_module`); a name a module does not export is
  `` Module `nish:fs` has no export `statSync` ``
  (`reject_nish_unknown_export`). Both list what does exist.
- **An imported builtin cannot be shadowed**, and that is the reason to prefer
  one. A global builtin is consulted only when no user function of that name is
  in scope, so declaring one silently replaces it; declaring one that collides
  with an import is `` `panic` is already declared in this module `` instead
  (`reject_nish_import_clash`).
- A name keeps its kind. `argv`, `platform` and `arch` are values, and calling
  one is refused (`reject_nish_property_call`); the functions are not values:
  a builtin is not a capture-free top-level function of this program, so it
  cannot be a reference (`reject_nish_builtin_value`).
- `exit` terminates control flow exactly as `process.exit` does, so a
  non-`void` function may end with it (`io_nish_rename`).
- Diagnostics name the canonical builtin whatever the call site calls it:
  `exit(1, 2)` reports `` `process.exit` expects exactly 1 argument ``, which
  is the rule to look up.
- Everything else stays global — `Math.*`, the width conversions,
  `console.log` / `console.error`, `String.fromCharCode`, `Arena.*`, `Ok` and
  `Err`. They lower to an LLVM intrinsic or a single instruction and cost no
  runtime at all, so they read as language rather than as library.
  `String.fromBytes` is global too, beside `String.fromCharCode` on the same
  `String`, though both make their answer with one `nish_str_new`.
  `Date.now()` and `crypto.getRandomValues` are global too, though each is a
  runtime call, because JavaScript spells them as globals and a program that
  runs under Node unchanged has to find them where Node has them
  ([The host](#the-host-the-wall-clock-entropy-file-times-and-signals)).

### `console`

The reference for each of these, with its parameters, its answer and its capability, is its doc comment in [`runtime/nish.d.ts`](../runtime/nish.d.ts); the rules are here.

| Function | Takes | Gives | Effect |
| --- | --- | --- | --- |
| `console.log` | `string \| number \| i64 \| f64 \| boolean` | `void` | write |
| `console.error` | as `console.log` | `void` | write |
| `write` | `string` | `void` | write |
| `writeError` | `string` | `void` | write |
| `writeBytes` | `readonly u8[], i32, i32` | `i32` | write |
| `panic` | `string` | `void` | write |

**`console.log(x: string | number | i64 | f64 | boolean): void`** writes `x`
and a newline to stdout. It is allowed in statement position only, and takes
exactly one argument.

- *Lowering:* one `write(2)`.
- *Tests:* `str_console_log`, `i64_basic`; `reject_console_log_noargs`,
  `reject_console_log_two_args`, `reject_console_log_as_value`; arrays and
  objects are rejected
  (`` `console.log` accepts string, number, or boolean, got i32[] ``
  *(CLI only)*).

**`console.error(x): void`** is the same, on **stderr**: the stream a
compiler's diagnostics belong on (WP14 B2). It has identical rules and
identical messages under its own name.

- *Tests:* `io_streams`; `reject_console_error_type`.

**`write(s: string): void`** writes `s` to stdout with **no** trailing
newline and no conversion (a `string` only). It is allowed in statement
position.

- *Tests:* `io_streams`.

**`writeError(s: string): void`** is the same, on stderr.

- *Tests:* `io_streams`.

**`writeBytes(bytes: readonly u8[], off: i32, len: i32): i32`** writes the
bytes of `bytes[off..off+len)` to stdout as they are. It answers `len`, or a
**negative errno** if the stream refuses them, never a panic. A pipe whose
reader has gone raises SIGPIPE natively, where Node answers `-32` EPIPE. A
range outside `bytes` **panics** with
`slice out of range: [off, off+len) of length n` and exits 1 (a `slice`
site), under Node too. It needs no capability, as for `write`. A `wasm32`
build has no stdout to reach and refuses it.

- *Tests:* `io_write_bytes`, `io_write_bytes_bounds`;
  `reject_write_bytes_arity`, `reject_write_bytes_type` (NL2268),
  `reject_write_bytes_wasm`.

**`panic(message: string): void`** writes `message` and a newline to stderr,
then exits 1: the same ending an out-of-range index has. It is allowed in
statement position, and it **terminates control flow** like `process.exit`,
so a non-`void` function may end with it (WP14 D1, WP16).

- *Tests:* `io_streams`; `reject_panic_value`.

Numbers print as JavaScript's `String(x)`: exact decimal for `i32`/`i64`,
shortest round-trip digits for `f64` (`0.1`, `1e+21`, `1e-7`, `NaN`,
`Infinity`, `-0` as `0`) (`tests/runtime-test.c`, `tests/cases/str_f64_mode`,
`math_intrinsics`). Booleans print `true`/`false`.

Reference: [`nish:io`](reference/nish-io.md).

### `Math`

The reference for each member of `Math`, with its parameters, its answer and its capability, is its doc comment in [`runtime/nish.d.ts`](../runtime/nish.d.ts); the rules are here.

| Function | Takes | Gives | Effect |
| --- | --- | --- | --- |
| `Math.sqrt/floor/ceil/trunc/sin/cos/exp/log` | `f64` | `f64` | none |
| `Math.tan` | `f64` | `f64` | none |
| `Math.atan2`, `Math.hypot` | `f64, f64` | `f64` | none |
| `Math.pow` | `f64, f64` | `f64` | none |
| `Math.round` | `f64` | `f64` | none |
| `Math.abs` | any numeric `T` | `T` | none |
| `Math.min`, `Math.max` | `T, T` | `T` | none |
| `Math.clz32` | `i32 \| u32` | `integer<0, 32>` | none |
| `Math.sign` | any numeric `T` | `T` | none |
| `Math.imul` | two of `i32 \| u32` | `i32` | none |
| `Math.random` | nothing | `f64` | write |
| `Math.PI`, `Math.E` | — | `f64` | none |

**`Math.sqrt/floor/ceil/trunc/sin/cos/exp/log(x: f64): f64`** take and
answer an `f64`. `floor`, `ceil` and `trunc` have two paths on x86-64 (see
*Lowering*), and the answers are the same bits on either path.

- *Lowering:* LLVM intrinsics (`llvm.sqrt.f64`, ...), except `floor`,
  `ceil` and `trunc` in an x86-64 module that is not a wasm build: there
  they call the runtime's `nish_floor`, `nish_ceil` and `nish_trunc`, which
  run SSE4.1's `roundsd` on a CPU that has it and libm's routine on one that
  does not, chosen once before `main` (`NISH_SIMD=scalar` pins libm); with
  no `--target` that is an x86-64 host. On a page module (a wasm build with
  no WASI, or an `--emit-dts` compile, whose IR `--profile wasm` or
  `wasm-host` links with no libm), `sin`, `cos`, `exp` and `log` are calls
  to `std/math.ts`'s `sinF64`, `cosF64`, `expF64` and `logF64` instead,
  fdlibm's, copied in like `tan`, within one ulp of V8; `--profile wasi`
  keeps the intrinsics. Under [`--deterministic`](#--deterministic) they
  are those calls on every target, `--emit-ts` included.
- *Tests:* `math_intrinsics`, `math_rounding`, `wasm_math_exp`,
  `wasm_math_std`; `reject_wasm_math_f32`
  (`` `Math.sin` requires an f64 argument, got f32 ``); `reject_math_i32`
  (`` requires an f64 argument, got i32 (use --number-mode f64 or toF64(x)) ``).

**`Math.tan(x: f64): f64`** is exact near every multiple of π/2 and within
one ulp.

- *Lowering:* a call to `std/math.ts`'s `tanF64`, fdlibm's, copied into the
  module as `internal @nish.tanF64`, so no target calls libm.
- *Tests:* `math_tan`, `math_std_edges`.

**`Math.atan2(y: f64, x: f64): f64`, `Math.hypot(x: f64, y: f64): f64`**
follow ECMAScript's special cases (`atan2(0, -0)` is π, `atan2(-0, -0)` is
−π, `hypot(Infinity, NaN)` is `Infinity`). `Math.hypot` takes exactly two
arguments, not JavaScript's any number.

- *Lowering:* calls to `std/math.ts`'s `atan2F64` and `hypotF64`, copied in
  like `tan`.
- *Tests:* `math_atan2`, `math_hypot`; `reject_math_atan2_f32`
  (`` `Math.atan2` requires an f64 argument, got f32 (use --number-mode f64 or toF64(x)) ``),
  `reject_math_hypot_arity`
  (`` `Math.hypot` expects exactly 2 arguments, got 3 ``).

**`Math.pow(x: f64, y: f64): f64`** gives ECMAScript's answer where it and
C99 differ: `pow(x, NaN)` and `pow(±1, ±Infinity)` are `NaN` (C gives `1`);
`pow(x, ±0)` is `1`, `pow(NaN, 0)` is `1`, and every other special case
agrees with C.

- *Lowering:* `llvm.pow.f64` plus a `select` for the cases where ECMAScript
  and C99 differ. On a page module it is a call to `std/math.ts`'s
  `powF64`, copied in like `tan`, which answers ECMAScript's cases itself,
  within one ulp of V8.
- *Tests:* `math_intrinsics`, `wasm_math_std`;
  `tests/differential/corpus/f64_pow_spec`; `reject_wasm_math_arity`
  (`` `Math.pow` expects exactly 2 arguments, got 1 ``).

**`Math.round(x: f64): f64`** is JavaScript's round-half-up, and keeps `x`'s
sign: `2.5` -> `3`, `-2.5` -> `-2`, `0.49999999999999994` -> `0`, and a
value in `[-0.5, 0)` or `-0` itself -> `-0`, as in JavaScript; `NaN` ->
`NaN`.

- *Lowering:* `Math.floor`'s `floor` + compare + `select`, then
  `llvm.copysign.f64` puts `x`'s sign back.
- *Tests:* `math_intrinsics`, `math_round_negzero`, `math_rounding`.

**`Math.abs(x: T): T` for any numeric `T`** answers the magnitude, wrapping
for `INT_MIN`. On an unsigned type the value is its own magnitude.

- *Lowering:* `llvm.abs.*` (wrapping for `INT_MIN`) / `llvm.fabs.f32` /
  `llvm.fabs.f64`; on an unsigned type, no instruction at all.
- *Tests:* `math_i32`, `math_intrinsics`; `i64`, `f32` and the unsigned
  widths *(CLI only)*.

**`Math.min(a: T, b: T): T`, `Math.max(a: T, b: T): T`** take exactly two
operands of one numeric type. On floats they give JavaScript's answer: a NaN
operand gives NaN and `-0` is below `+0` (`Math.min(0, -0)` is `-0`).

- *Lowering:* signed integers: `llvm.smin/smax`; unsigned: `llvm.umin/umax`.
  A native float build branches as clang compiles the C a programmer writes
  for it: `fcmp uno` to a quiet NaN, else `fcmp olt`/`ogt` and a `select`,
  and on `fcmp oeq` the operand whose sign bit is set (`min`) or clear
  (`max`), the three joined by a `phi`; x86 has no instruction for
  `llvm.minimum`, whose expansion measured 25–55% slower in `bench/math`. A
  wasm build keeps `llvm.minimum/maximum.<f32|f64>`, which are wasm's
  `f64.min`/`f64.max`, so no libm is linked for them.
- *Tests:* `math_i32`, `math_intrinsics`, `math_minmax_float`,
  `math_minmax_nan`; `reject_math_min_arity`
  (`` `Math.min` expects exactly 2 arguments, got 1 ``).

**`Math.clz32(x: i32 | u32): integer<0, 32>`** answers the leading zero bits
of `x`'s 32 bits, JavaScript's answer (an `i32` and a `u32` are the bits
ToUint32 gives), so `0` answers `32`. The answer is ranged
(`integer<Lo, Hi>`, see [Types](#types)), so `31 - Math.clz32(word & (0 - word))`,
the index of a word's lowest set bit, needs no overflow check. Any other
operand type is refused rather than converted.

- *Lowering:* `llvm.ctlz.i32` with `i1 false`.
- *Tests:* `math_clz32`; `reject_math_clz32_type`
  (`` `Math.clz32` expects an i32 or a u32, got f64 (convert with toI32 or toU32) ``).

**`Math.sign(x: T): T` for any numeric `T`** answers `-1`, `0` or `1` in
`x`'s own type (a ranged `x` answers its base type). A float `-0` and `NaN`
come back as JavaScript gives them.

- *Lowering:* a float answers `llvm.copysign(1.0, x)` unless
  `fcmp ueq x, 0.0`, when it answers `x` itself; a signed integer is
  `zext (x > 0) - zext (x < 0)`, an unsigned one `zext (x != 0)`.
- *Tests:* `math_sign`; `reject_math_sign_type`
  (`` `Math.sign` expects a number, got string ``).

**`Math.imul(a: i32 | u32, b: i32 | u32): i32`** answers the low 32 bits of
the product, read signed, with no overflow check, which is JavaScript's
answer for any operands an `i32` or a `u32` holds
(`Math.imul(0x7fffffff, 2)` is `-2`). Any other operand type is refused
rather than converted, for `Math.clz32`'s reason.

- *Lowering:* one wrapping `mul i32`.
- *Tests:* `math_imul`; `reject_math_imul_f64`
  (`` `Math.imul` expects an i32 or a u32, got f64 (convert with toI32 or toU32) ``).

**`Math.random(): f64`** answers 53 random bits in `[0, 1)`, seeded from
time and pid.

- *Lowering:* xorshift64\* in the runtime (`nish_random`).
- *Tests:* `math_random`.

**`Math.PI: f64`, `Math.E: f64`** are constants, also in i32 mode.

- *Tests:* `math_i32`, `math_intrinsics`.

The f64-only functions reject `i32`/`i64` arguments; `number` in i32 mode is
an `i32`, so write `Math.sqrt(toF64(n))` or use f64 mode. A numeric literal
argument is typed `f64` by context (`Math.sqrt(2)` works in both modes).

### Numeric conversions

The reference for each conversion, with its parameter and its answer, is its doc comment in [`runtime/nish.d.ts`](../runtime/nish.d.ts), on [the globals page](reference/builtins.md) (`Number` under `NumberConstructor`); the rules are here.

| Function | Takes | Gives |
| --- | --- | --- |
| `toI32` | any number | `i32` |
| `toI64` | any number | `i64` |
| `toU8`, `toU16`, `toU32`, `toU64` | any number | that unsigned type |
| same width, other signedness | any integer | the other integer |
| `toF32` | any number | `f32` |
| `toF64` | any number | `f64` |
| `f64ToBits` | `f64` | `i64` |
| `f32ToBits` | `f32` | `i32` |
| `bitsToF64` | `i64` | `f64` |
| `Number` | `string \| i32 \| i64 \| f64 \| boolean` | `f64` |
| `parseInt` | `string` | `i32` |
| `parseFloat` | `string` | `f64` |

**`toI32(x): i32`** at narrower or equal width wraps. A float source (`f32` or `f64`) saturates: NaN -> 0, and out of range clamps.
On an `i32` it is the identity.

- *Lowering:* narrower or equal width: `trunc` (wraps); wider signed
  source: `sext`, wider unsigned source: `zext`; a float source: saturating
  `llvm.fptosi.sat.i32.<f32|f64>`; `i32`: identity.
- *Tests:* `conversions`, `u_conv_roundtrip`; `reject_toi32_string`.

**`toI64(x): i64`** saturates from an `f64`, and on an `i64` it is the
identity.

- *Lowering:* signed source: `sign-extend`; unsigned source: `zext`; `f64`:
  saturating; `i64`: identity.
- *Tests:* `conversions`, `u_conv_widths`.

**`toU8`, `toU16`, `toU32`, `toU64`** widen a signed source by its sign, so
`toU64(-1: i32)` is 2^64 - 1, as `-1i32 as u64` is in Rust. Narrowing
truncates. A float source saturates, clamped to `0 .. 2^bits-1`, so a
negative value is `0`.

- *Lowering:* widening: `zext` from an unsigned source, `sext` from a signed
  one; narrowing: `trunc`; a float source: saturating `llvm.fptoui.sat`,
  whose clamp is `0 .. 2^bits-1`.
- *Tests:* `u_conv_widths`, `u_conv_f64`, `u_conv_roundtrip`;
  `reject_u_conversion_arg`.

**any integer -> an integer of the same width and other signedness** keeps
the bits as they are (`toU32(i)` on an `i32`, `toI64(q)` on a `u64`).

- *Lowering:* **no instruction at all**: signedness is not part of the LLVM
  type and the bits do not move.
- *Tests:* `u_conv_same_width`.

**`toF32(x): f32`** rounds an `f64` to nearest, and on an `f32` it is the
identity.

- *Lowering:* signed integers: `sitofp`; unsigned integers: `uitofp`; `f64`:
  `fptrunc` (rounds to nearest); `f32`: identity.
- *Tests:* `f32_conversions`, `f32_constant`.

**`toF64(x): f64`** widens an `f32` exactly, and on an `f64` it is the
identity.

- *Lowering:* signed integers: `sitofp`; unsigned integers: `uitofp`; `f32`:
  `fpext` (exact); `f64`: identity.
- *Tests:* `conversions`, `u_conv_f64`, `f32_conversions`.

**`f64ToBits(x: f64): i64`** reinterprets the 64 bits and never converts the
value: `toI64(1.5)` is `1`, `f64ToBits(1.5)` is `0x3FF8000000000000`.
Under [`--deterministic`](#--deterministic) a NaN gives
`0x7FF8000000000000` (`quietBitsF64`).

- *Lowering:* one `bitcast`, so a function that only reinterprets bits stays
  `readnone`.
- *Tests:* `conv_f64_bits`; `reject_f64tobits_type`,
  `reject_f64tobits_arity`.

**`f32ToBits(x: f32): i32`** is the same for an `f32`'s 32 bits, signed as an
`i32`: `f32ToBits(1.5)` is `0x3FC00000`, and `f32ToBits(-0)` is
`-2147483648`. Under [`--deterministic`](#--deterministic) a NaN gives
`0x7FC00000` (`quietBitsF32`).

- *Lowering:* one `bitcast float to i32`; under Node, `runtime/nish.mjs`
  supplies it from a `DataView`.
- *Tests:* `f32_to_bits`; `reject_f32_to_bits_f64`
  (`` `f32ToBits` expects an argument of type f32, got f64 ``).

**`bitsToF64(b: i64): f64`** is the inverse. `bitsToF64(f64ToBits(x)) === x`
for every `x` except `NaN`, which is not `===` to itself.

- *Tests:* `conv_f64_bits`; `reject_bitstof64_type`.

**`Number(x: string | i32 | i64 | f64 | boolean): f64`** parses a string with
JavaScript's `Number(s)` rules (below). A `boolean` converts with `true` as
`1`, and an `f64` is the identity. A numeric literal argument is typed `f64`
(`Number(2.5)` works in i32 mode). Under
[`--deterministic`](#--deterministic) a string goes to `std/math.ts`'s
`numberExact` instead, which reads a `0x` integer the same on every target.

- *Lowering:* `i32`/`i64`: `sitofp`; `boolean`: `uitofp`; `f64`: identity.
- *Tests:* `parse_numbers`; `reject_number_array`
  (`` `Number` expects a string, number, or boolean, got i32[] ``).

**`parseInt(s: string): i32`** reads base 10 only: ASCII whitespace, an
optional sign, then digits; it stops at the first other character.
**Deviations from JavaScript:** no `NaN` in an `i32`, so no digits give `0`
(`parseInt("abc")`, `parseInt("")`); values beyond the `i32` range saturate
exactly like `toI32` (`parseInt("99999999999")` is `2147483647`); a `0x`
prefix is not hexadecimal (`parseInt("0x10")` is `0`). It is always `i32`,
also under `--number-mode f64` (use `Number` there).

- *Lowering:* `strtoll`.
- *Tests:* `parse_numbers`; `reject_parseint_number`
  (`` `parseInt` expects a string, got i32 ``).

**`parseFloat(s: string): f64`** reads ASCII whitespace, then the longest
decimal literal (`[sign] digits [. digits] [e [sign] digits]`, `. digits`,
or `[sign] Infinity`), correctly rounded. It answers `NaN` when there is none
(`parseFloat("abc")`, `""`, `"."`); `parseFloat("3.14xyz")` is `3.14`,
`"1e"` is `1`. **Deviation:** a `0x` prefix is read as hexadecimal like
`strtod` (`parseFloat("0x1A")` is `26`; JavaScript stops at the `x` and
gives `0`). Under [`--deterministic`](#--deterministic) a string goes to
`std/math.ts`'s `parseFloatExact` instead, which reads a `0x` integer the
same on every target.

- *Lowering:* `strtod`.
- *Tests:* `parse_numbers`.

The string parsers accept only ASCII whitespace (` \t\n\v\f\r`), not the
Unicode spaces JavaScript also trims. `Number(s)` trims it on both sides and
then requires the whole string to be one literal: `Number("")` and
`Number("   ")` are `0`, `Number("  7.5  ")` is `7.5`, `Number("12px")`,
`Number("1e")`, `Number("Infinityx")`, `Number("nan")` and `Number("inf")`
are `NaN`, `Number("0x1A")` is `26` (as in JavaScript; hex floats such as
`0x1p3` are also accepted by `strtod`, which JavaScript rejects), and the
`0b`/`0o` prefixes are `NaN` (JavaScript reads them). All three lower to
`nish_parse_number(s, mode)` in the runtime (mode 0 `parseFloat`, 1 `Number`,
2 `parseInt`, the last followed by `llvm.fptosi.sat.i32.f64`); their effect
is write (`strtod`/`strtoll` may set `errno`), so a function that parses is
never `readonly` ([wp7-runtime.md](wp7-runtime.md#string-to-number)).

### `nish:unsafe`: unchecked access and defined wrapping

Two things the language otherwise never does are each a decision about one
site: reading or writing an element without the bounds check, and letting a
signed `+ - *` wrap. `nish:unsafe` holds the five functions that make them,
two, `readCString` and `readStruct`, that read a C string or a C struct
through a pointer nothing proves, and an eighth, `cErrno`, that reads the
errno a C call left. A program reaches them only through an import, so every module that
gives up a check or defines a wrap says so at its top and every site that does
is a call a reader can find.

Reference: [`nish:unsafe`](reference/nish-unsafe.md).

| Signature | Lowering | Effect | Test |
| --- | --- | --- | --- |
| `uncheckedGet(xs: T[], i: i32): T` | the GEP and load `xs[i]` lowers to, with no `len` load, no compare and no branch to the bounds panic | read | `unsafe_get_set`; `reject_unsafe_arity`, `reject_unsafe_type` |
| `uncheckedSet(xs: T[], i: i32, v: T): void` | the GEP and store `xs[i] = v` lowers to, likewise unchecked; a statement | write | `unsafe_get_set`; `reject_unsafe_arity`, `reject_unsafe_type`, `reject_unsafe_par_shared_write` |
| `wrappingAdd(a: T, b: T): T` | `add`, never `nsw` and never checked | none | `unsafe_wrapping`; `reject_unsafe_arity`, `reject_unsafe_type` |
| `wrappingSub(a: T, b: T): T` | `sub`, never `nsw` and never checked | none | `unsafe_wrapping`; `reject_unsafe_type` |
| `wrappingMul(a: T, b: T): T` | `mul`, never `nsw` and never checked | none | `unsafe_wrapping`; `reject_unsafe_type` |
| `readCString(p: CPtr): string` | a NULL test that panics `ffi-null`, then a call to `@nish.ffi.str`, the scan-and-copy a `string` result of a `declare function` uses ([`readCString`](#readcstring-a-string-out-of-a-buffer-c-owns)) | read; allocates; may panic | `ffi_owned_string`, `panics_ffi_read_cstring_null`; `reject_unsafe_read_cstring`, `reject_ffi_owned_string_arena` |
| `readStruct(p: CPtr): T` | a NULL test that panics `ffi-null`, then `nish_alloc_struct` of the layout's size and one `llvm.memcpy` into it, `T` the `declare class` the context names ([`readStruct`](#readstruct-a-struct-out-of-memory-c-owns)) | read; allocates; may panic | `ffi_struct_read`, `panics_ffi_read_struct_null`; `reject_unsafe_read_struct_context`, `_null`, `_type_args` |
| `cErrno(): i32` | a `load i32` of `@nish_errno_slot`; naming it brackets every `declare function` call with a zero of errno and a save into the slot ([`cErrno`](#cerrno-the-errno-a-c-call-left)) | read | `ffi_errno`, `ffi_errno_threads`; `reject_ffi_errno_arg`, `reject_ffi_errno_import`, `reject_ffi_errno_wasm`, `reject_ffi_errno_global` |

- **The import is required.** The seven are declared as globals in
  `runtime/nish.d.ts`, as every `nish:` export is, so `tsc` reads either
  spelling; the compiler refuses the global one with
  `` `uncheckedGet` is a `nish:unsafe` function and is called only through an import of it ``
  (NL2456, `reject_unsafe_no_import`). An import may rename (`as`) and cannot
  be shadowed, as every builtin import (above). A user function of the same
  name, with no import, is the user's function, as with every builtin.
- **`uncheckedGet` and `uncheckedSet` take an array of numbers**: `i32`,
  `i64`, `u8`, `u16`, `u32`, `u64`, `f32` or `f64` elements, and nothing else
  is `` `uncheckedGet` takes an array of numbers (i32, i64, u8, u16, u32, u64, f32 or f64), got string[] ``
  (NL2455). A number is copied in and out and held by nothing, so the store
  needs none of the escape and inline-array reasoning `xs[i] = v` carries. The
  index is an `i32`, and an `f64` one is
  `` `uncheckedGet` expects an argument of type i32, got f64 ``; the value of a
  store is the element type. A `readonly` array may be read and not written
  (`` Cannot `uncheckedSet` through readonly u8[] ``). An index outside
  `[0, xs.length)` is undefined behaviour, which is the whole of the trade.
  The receiver is an argument, so an array field handed to either is a value
  and is not stored inline ([Fixed-length array fields are stored
  inline](#fixed-length-array-fields-are-stored-inline)); a store is a write
  of the receiver for every rule that asks, the parallel-body rule included
  (`reject_unsafe_par_shared_write`).
- **`wrappingAdd`, `wrappingSub` and `wrappingMul` take two operands of one
  type, `i32` or `i64`**, which is also the answer: the signed words are the
  ones whose operators are checked, and an unsigned operator already wraps.
  `` `wrappingMul` takes i32 or i64 operands (convert with toI32 or toI64), got u32 ``
  is NL2454, and two widths are
  `` `wrappingAdd` needs every operand of one type, got i32 and i64 `` (NL2400,
  as `ctSelect`'s). A bare literal takes the other operand's type, wherever it
  stands. The answer is the two's-complement wrap at that width, defined for
  every pair (`unsafe_wrapping`). In a module
  constant's initialiser the call folds, wrapping, where `2147483647 + 1` is
  refused ([Module constants](#module-constants)).
- **Under Node** `runtime/nish.mjs` answers the import, and the five are
  `xs[i]`, `xs[i] = v`, `(a + b) | 0`, `(a - b) | 0` and `Math.imul` on an
  `i32`, and `BigInt.asIntN(64, …)` on the BigInt an `i64` is there; a program
  that stays in range prints the same as natively (`unsafe_get_set` and
  `unsafe_wrapping` are run both ways by `tests/run.js`). `readCString` and
  `readStruct` have no Node form: a `CPtr` comes only from a `declare function`, which Node cannot
  call, so a program that reads one is native only, as every FFI program is
  outside the differential oracle (`docs/wp27-ffi.md` §5).
- **Every import and every call is a recorded fact.** `--emit-checked` prints,
  per module, an `unsafe import <line>:<col> <name> from "nish:unsafe"` line for
  each name imported and an `unsafe call <line>:<col> <name> (node <id>)` line
  for each site, so a report of where a program opts out of a check reads them
  rather than the source (`tests/self/goldens/checked/`, one file per module).
- **The import is the opt-in the no-panic scope takes.** Under `--deny-panics`
  or `"nish".noPanic`, `uncheckedGet` and `uncheckedSet` are allowed, listed
  as `unchecked` sites with `"allowed": true`, because they cannot panic and
  the import has already said, at the top of the module, that an index out of
  range is the author's to rule out ([The no-panic scope](#the-no-panic-scope),
  `deny_panics_unsafe`). `readCString` and `readStruct` are not: each tests
  its pointer for `NULL`, an `ffi-null` site no proof removes
  (`panics_ffi_read_cstring_null`, `tests/ffi-string.js`;
  `panics_ffi_read_struct_null`, `tests/ffi-struct.js`), so `--deny-panics`
  refuses a call to either in its scope. The
  `wrapping*` three are not sites at all: they are defined for every pair.
- **To the bounds proof `uncheckedGet` and `uncheckedSet` are the load and
  the store** `xs[i]` and `xs[i] = v` are, less the check: a call moves no
  length, so in `uncheckedGet(a, at[0]) + b[at[1]]` with `at` an array of
  two, `at[1]` stays proven after the call. Neither records a passed check,
  because neither has one: a checked `xs[i]` after either keeps its check,
  and a resize in the value stored still takes the length away
  (`tests/cases/arr_bounds_unchecked_kept`).
- **There is no flag that turns the checks off.** `--unchecked-indexing` and
  `--wrapping` were removed before 1.0, and the CLI refuses each with exit 2
  and a line naming its replacement (`` `--wrapping` is gone ``,
  `tests/nish/cli.ts`): an opt-out is written at the site, where `--emit-checked`
  and the no-panic scope can see it.

### `nish:simd`: sixteen-byte vectors

A vector is sixteen bytes of lanes of one number type, held and passed as one
value: an LLVM `<N x T>` in a register, a local, a field or an array slot. The
module names six of them, and the calls that make one, read one out of an
array, write one back and take one lane out or put one in. Nothing here names a
target: the IR is `insertelement`, `shufflevector`, `extractelement` and a
vector `load` or `store`, and LLVM picks the instructions (`tests/run.js`'s
`simd` section greps every `simd_*.ll` for `llvm.x86.` and `llvm.aarch64.`).
The lane operations, the masks a compare answers and the shifts are in
[the next section](#nishsimd-lane-operations-and-masks).

The six are `u8x16` (`<16 x i8>`), `u16x8` (`<8 x i16>`), `i32x4` and `u32x4`
(`<4 x i32>`), `f32x4` (`<4 x float>`) and `f64x2` (`<2 x double>`). Each has
a constructor of one argument per lane, a splat (`splatU8x16` … `splatF64x2`)
and a load (`loadU8x16` … `loadF64x2`) from an array of its lane type; the
table below spells each family with `i32x4`.

Reference: [`nish:simd`](reference/nish-simd.md).

| Function | Takes | Gives |
| --- | --- | --- |
| `i32x4` | one `i32` per lane | `i32x4` |
| `splatI32x4` | one `i32` | `i32x4` |
| `loadI32x4` | `readonly i32[], i32` | `i32x4` |
| `store` | `i32x4, i32[], i32` | `void` |
| `extract` | `i32x4`, constant `k` | one lane |
| `replace` | `i32x4`, constant `k`, lane | `i32x4` |

**`i32x4(a, b, c, d)`, one argument per lane** makes a vector of its
arguments.

- *Lowering:* one `insertelement` per lane into `undef`, which `opt` folds
  to a constant vector when every lane is one.
- *Tests:* `simd_lanes`; `reject_simd_arity`, `reject_simd_lane_type`.

**`splatI32x4(x)`** makes a vector with `x` in every lane.

- *Lowering:* one `insertelement` into lane 0 and a `shufflevector` whose
  mask is `zeroinitializer`.
- *Tests:* `simd_lanes`.

**`loadI32x4(xs, i)`** reads a vector out of `xs` at `i`, after one bounds
check for the whole vector, `i < len` and `i + N <= len`.

- *Lowering:* the bounds check branches to `nish_panic_index(i, len)`; then
  the element's address bitcast to `<N x T>*` and one `load` aligned to the
  lane, with the `!alias.scope`, `!noalias` and `!tbaa` of a scalar element
  access of the lane type. The check is left out where the bounds proof
  (`src/bounds.ts`, `judgeVectorAccess`) already knows every lane is in range:
  `i` non-negative under a guard such as `i <= n - N` or `i + N - 1 < n` on the
  array's length, or a literal index into an array of known length. A guard one
  lane short proves nothing, and the access keeps its check.
- *Tests:* `simd_access`, `simd_access_proven`, `simd_access_alias`,
  `simd_access_oob`, `simd_access_oob_first`, `simd_access_oob_negative`,
  `simd_access_oob_guard`; `reject_simd_lane_type`.

**`store(v, xs, i)`** writes `v` back into `xs` at `i` after the same check.
It is a statement.

- *Lowering:* the same check, then one `store`.
- *Tests:* `simd_access`, `simd_store_oob`; `reject_simd_lane_type`,
  `reject_simd_arity`.

**`extract(v, k)`** takes lane `k` out of `v`; `k` is a constant.

- *Lowering:* `extractelement` at the constant `k`.
- *Tests:* `simd_lanes`; `reject_simd_lane_index`.

**`replace(v, k, x)`** puts `x` in lane `k`, a constant, and answers a new
vector: `v` is unchanged.

- *Lowering:* `insertelement` at the constant `k`.
- *Tests:* `simd_lanes`, `simd_values`; `reject_simd_lane_index`.

- **The import is required.** The six types and every call are declared in
  `runtime/nish.d.ts` under `declare module "nish:simd"` only, and a module
  that spells one without the import is refused with
  `` `i32x4` is a `nish:simd` name and is used only through an import of it: add `import { i32x4 } from "nish:simd"` ``
  (NL2578, `reject_simd_no_import`). An import may rename (`as`) and cannot be
  shadowed, as every builtin import.
- **A load or store takes an array of the lane type, exactly**: a `u8x16` is
  loaded from a `u8[]` and nothing else, so the sixteen bytes it reads are the
  sixteen elements the index names, and an `f64[]` handed to `loadF32x4` is
  `` `loadF32x4` takes an array whose elements are the vector's lane type, f32[], got f64[] ``
  (NL2579). A `readonly` array may be loaded from and not stored to
  (`` Cannot `store` through readonly u8[] ``). The index is an `i32`; the
  check is one compare pair for the whole vector, so a load whose last lane is
  past the end panics before it reads, naming a lane past the end (the first
  when it is out of range, else the last) and the length, as `xs[i]` does (`simd_access_oob`, run by `tests/run.js` natively and under
  Node). The access is aligned to the lane, not to sixteen: an array's
  elements are where the arena put them.
- **A lane index is an integer literal in range.** `extract(v, k)` and
  `replace(v, k, x)` take `k` as a literal from 0 to one less than the lane
  count, because a constant lane is one instruction and needs no check at run
  time: a variable is
  `` `extract` takes a lane index that is an integer literal, from 0 to 3: i32x4 has 4 lanes `` (NL2580)
  and a literal past the end is
  `` `extract` lane index 4 is out of range for i32x4, whose lanes are 0 to 3 `` (NL2583,
  `reject_simd_lane_index`). The first argument must be a vector
  (`` `extract` takes a `nish:simd` vector as its first argument, got i32 ``, NL2582),
  and a lane given to a constructor, a splat or `replace` is the lane type, as
  any argument is (`reject_simd_lane_type`).
- **A vector is a value.** It is copied by assignment, passed and returned in
  registers, and held in a local, a class field or an array (`simd_values`).
  In an object or an array it is sixteen bytes aligned to sixteen, the layout
  clang gives `__attribute__((vector_size(16)))`, which `tests/layout/simd.c`
  asserts against the IR's struct and reads lane by lane; an array of vectors
  steps by sixteen. The arena hands out objects aligned to eight, so a field
  access is `align 8`.
- **A vector has no operators, and no comparison.** `+`, unary `-`, a
  truthiness test, a template hole and `console.log` of a whole vector or a
  mask are refused with the usual operand-type diagnostics
  (`reject_simd_operators`); the lane-wise forms are the functions of the next
  section. `===`, `!==`, `<` and the rest, and the `===` inside an array's
  `indexOf`, are
  `` `===` does not compare `nish:simd` vectors or masks (got i32x4): compare lane by lane with `eq`, `lt` and the rest, which answer a mask, and ask it `all` or `any` ``
  (NL2581, `reject_simd_compare`): a lane-wise compare answers a mask, not a
  boolean, and under Node a vector is a typed array whose `===` is identity. A
  vector is not a `Map` key (`reject_simd_map_key`), not `Secret`
  (`reject_simd_secret`) and not nullable (`reject_simd_nullable`).
- **Under Node** `runtime/nish.mjs` resolves the import to `runtime/core.mjs`,
  where a vector is a typed array whose element type does the lane's
  arithmetic: a `u8` lane wraps through `Uint8Array`, an `f32` lane rounds
  through `Float32Array`. `--emit-ts` writes the import as `nish/runtime`'s. A load or a
  store checks the whole vector and panics with the native words.
  `tests/run.js`'s `simd` section runs every `simd_*` program with a `.out`
  natively, under `--profile wasi` (where a sysroot is installed) and under
  Node, and holds the three to one output.
- **A vector does not cross the interop boundary yet.** An exported function
  whose parameter or result holds a vector at any depth (the vector itself,
  an array of them, a `Result` with a vector arm, an array of a class that
  holds one) is left out of `--emit-header`, `--emit-napi` and the
  `--emit-dts` typings and wasm loader, with a comment naming the type, as
  every type the sidecars cannot spell is. A class that holds a vector
  anywhere (a field, an element, a `Result` arm, another class it points at)
  is opaque in the header (`typedef struct Name Name;`), as a `Map` or
  `Secret` holder is: C has no portable vector type to lay it out with. A bare
  pointer to such a class still crosses, as an opaque `struct Name *`.

### `nish:simd`: lane operations and masks

Every operation on a vector is a free function of `nish:simd`, because a
TypeScript program cannot overload `+`. The operand types pick the lowering,
and each lowers to LLVM vector IR or a target-independent `llvm.*` intrinsic:
no golden holds `llvm.x86.` or `llvm.aarch64.` ([wp38-simd.md](wp38-simd.md)
§3.2).

Reference: [`nish:simd`](reference/nish-simd.md).

| Signature | Lowering | Test |
| --- | --- | --- |
| `add`, `sub`, `mul`, `div(a, b)` on `f32x4`, `f64x2` | `fadd`, `fsub`, `fmul`, `fdiv`, no fast-math flags | `simd_ops_float`; `reject_simd_op_operands` |
| `neg`, `abs`, `sqrt(a)` on `f32x4`, `f64x2` | `fneg`, `llvm.fabs`, `llvm.sqrt` | `simd_ops_float`; `reject_simd_op_operands` |
| `addWrapping`, `subWrapping`, `mulWrapping(a, b)` on `u8x16`, `u16x8`, `i32x4`, `u32x4` | `add`, `sub`, `mul` with no `nsw` or `nuw`: each lane wraps | `simd_ops_int`; `reject_simd_op_operands` |
| `shl(v, n)`, `shr(v, n)`, `n` a literal below the lane width | `shl`; `shr` is `lshr` on an unsigned lane and `ashr` on `i32x4` | `simd_shifts`; `reject_simd_shift_count` |
| `rotl(v, n)`, `rotr(v, n)` on the same four | `llvm.fshl`, `llvm.fshr` with `v` as both halves | `simd_shifts`, `simd_chacha_quarter`; `reject_simd_shift_count` |
| `and`, `or`, `xor(a, b)`, `not(a)` on an integer vector or a mask | `and`, `or`, `xor`; `not` is `xor` with all-ones | `simd_ops_int` |
| `min`, `max(a, b)` on every vector | `llvm.umin`/`smin`/`umax`/`smax`; floats `llvm.minimum`/`llvm.maximum`, NaN-propagating with -0 below +0, as `Math.min` | `simd_ops_int`, `simd_ops_float` |
| `eq`, `ne`, `lt`, `le`, `gt`, `ge(a, b)` | `icmp` (unsigned on `u*` lanes) or ordered `fcmp` (`une` for `ne`), answering the lane width's mask | `simd_ops_int`, `simd_ops_float`; `reject_simd_op_operands` |
| `select(m, a, b)` | `select`: lane `k` of `a` where lane `k` of `m` is set, else of `b` | `simd_ops_int`; `reject_simd_op_operands` |
| `any(m)`, `all(m)` | `llvm.vector.reduce.or`, `.and` on `<N x i1>` | `simd_ops_int` |
| `bitmask(m)`, an `i32` with bit `k` lane `k` | `bitcast <N x i1>` to `iN`, `zext` | `simd_ops_int` |
| `sum(v)` on `u8x16`, `u16x8` (an `i32`, exact) and `f32x4`, `f64x2` (the lane type, lanes added 0 to N-1) | `zext` and `llvm.vector.reduce.add`; floats `llvm.vector.reduce.fadd` without `reassoc` | `simd_ops_int`, `simd_ops_float`; `reject_simd_sum` |
| `sumWrapping(v)` on `i32x4` (an `i32`) and `u32x4` (a `u32`) | `llvm.vector.reduce.add`, wrapping | `simd_ops_int`; `reject_simd_sum` |
| `shuffle(a, b, i0, …)`, one literal index per lane, from 0 to 2N-1 | `shufflevector` | `simd_ops_int`; `reject_simd_shuffle` |
| `asU8x16(v)` … `asF64x2(v)` | `bitcast`: the same sixteen bytes read as other lanes | `simd_ops_int` |

- **Every operand is one vector type.** Two types are
  `` `min` takes operands of one type, got i32x4 and u32x4; reinterpret the lanes with `asU8x16` and the rest ``,
  a scalar where a vector goes is
  `` `eq` takes a `nish:simd` vector, got i32 `` (NL2638), and a vector a
  family does not take names the family:
  `` `add` is float lane arithmetic and takes an `f32x4` or an `f64x2`, got i32x4: an integer lane can overflow, so its form is `addWrapping` ``
  (NL2623, `reject_simd_op_operands`). Integer lane arithmetic wraps, and its
  name says so: making a lane trap as scalar `+` does would cost the speed the
  type is for.
- **A shift count is a literal below the lane width.** `shl`, `shr`, `rotl`
  and `rotr` take the count as an integer literal from 0 to 7, 15 or 31, so
  each is one instruction with a splat constant and nothing is shifted by a
  variable: a variable count is
  `` `shl` takes a count that is an integer literal below the lane width, from 0 to 31: a lane of u32x4 is 32 bits `` (NL2630),
  and the width or more is
  `` `rotl` count 32 is not below the lane width of u32x4, 32 bits: a shift by the width or more moves every bit out, and a rotate by it is a rotate by 0 ``
  (NL2631, `reject_simd_shift_count`). LLVM gives a shift by the width no
  meaning, and a rotate by it is a rotate by 0. `shr` is logical on `u8x16`,
  `u16x8` and `u32x4` and arithmetic (it copies the sign) on `i32x4`; a
  rotate is the same on either. They are what ChaCha20, SHA-256 and other
  add-rotate-xor code is built from (`simd_chacha_quarter`).
- **A mask is a compare's answer, held only as a value.** `eq` and the rest on
  two vectors answer `mask8x16`, `mask16x8`, `mask32x4` or `mask64x2` by lane
  width, an `<N x i1>`; there is no constructor
  (`` `mask32x4` is a mask type and has no constructor: a mask is what a lane-wise compare (`eq`, `lt` and the rest) answers ``,
  NL2621). `select` takes the mask of its vectors' width
  (`` `select` between two i32x4 takes the mask their compare answers, mask32x4, got mask64x2 ``,
  NL2629). A mask lives in a local, a parameter or the return of a function
  the module keeps, and is
  `` `mask32x4` cannot be a field: a `nish:simd` mask is a value held only in a local, a parameter or a return of a function this module keeps; store the vectors it selects, or its `bitmask` ``
  (NL2622) as a field, an array element, a `Result` arm, a type argument, a
  method's parameter or result, or an exported signature
  (`reject_simd_mask_storage`, `reject_simd_mask_in_body`): it has no size in
  memory that all three targets share.
- **A sum says whether it wraps.** `sum` of `u8x16` or `u16x8` adds in an
  `i32` and cannot overflow; `sum` of `i32x4` or `u32x4` can, and is
  `` `sum` of i32x4 can overflow its lane type, so its total is `sumWrapping`, which wraps as the lanes do ``
  (NL2636, `reject_simd_sum`). A float sum adds lane 0 first and lane N-1
  last, so it is the same bits on every target.
- **A shuffle names every lane.** `shuffle(a, b, …)` takes one literal per
  lane of the answer, each from 0 to 2N-1, where N and up are `b`'s lanes;
  a wrong count, a variable or an index past the end is refused
  (NL2632 to NL2635, `reject_simd_shuffle`).
- **Under Node** each operation is a function of `runtime/core.mjs` over the
  typed arrays: an integer lane wraps through its array type, a float lane
  rounds through `Float32Array`, a mask is an array of booleans, and a rotate
  is two shifts and an `or`. `tests/run.js`'s `simd` section holds the native,
  WASI and Node outputs to one.

### Constant time: `ctSelect` and `ctEq`

Crypto code must not branch on a secret or index memory by one, and LLVM
promises neither: a `select` it can see through may become a branch, and a mask
it can prove is a boolean may become a `select`. These two builtins are how a
program selects and compares on a secret without giving the optimiser that
choice (WP34 N6).

| Function | Takes | Gives | Effect |
| --- | --- | --- | --- |
| `ctSelect` | `T, T, T` | `T` | none |
| `ctEq` | `T, T` | `T` | none |

**`ctSelect(mask: T, a: T, b: T): T`** answers `(a & mask) | (b & ~mask)`:
`a` when `mask` is all-ones, `b` when it is zero.

- *Tests:* `ct_select_u32`, `ct_u64`; `reject_ct_select_i32`,
  `reject_ct_select_i32_literal`, `reject_ct_select_f64`,
  `reject_ct_select_f32`, `reject_ct_select_bool_mask`,
  `reject_ct_select_mixed`, `reject_ct_select_arity`,
  `reject_ct_select_float_mask`.

**`ctEq(a: T, b: T): T`** answers all-ones of `T` when `a === b`, zero
otherwise.

- *Tests:* `ct_eq_u32`, `ct_u64`; `reject_ct_eq_i64`, `reject_ct_eq_u8`,
  `reject_ct_eq_f64`, `reject_ct_eq_f32`, `reject_ct_eq_bool`,
  `reject_ct_eq_ranged`, `reject_ct_eq_mixed`, `reject_ct_eq_arity`,
  `reject_ct_eq_literals`, `reject_ct_eq_value`.

- **`T` is `u32` or `u64`, one type for every operand.** A mask is a bit
  pattern, and the unsigned words are the only types whose all-ones is not also
  a number with a sign: `i32`, `i64`, the narrow `u8` and `u16`, a ranged
  integer (an `i32` underneath, and named so), `f32`, `f64` and `boolean` are
  each `` `ctEq` takes u32 or u64 operands (convert with toU32 or toU64), got i64 ``
  (NL2399). A boolean in particular is not a mask: `ctEq` makes the mask
  without the compare a boolean would need. Operands of two types are
  `` `ctSelect` needs every operand of one type, got u32 and u64 `` (NL2400),
  since a `u32` mask over `u64` words would leave half of each unselected. The
  type is judged at the operand it was read from before any other operand is
  measured against it, so a boolean mask is told the first message rather than
  the second, and `ctSelect(m, 0x80000000, 0)` on an `i32` mask is NL2399
  rather than "does not fit in i32" (`reject_ct_select_i32_literal`).
- **A bare numeric literal takes its type from the first operand that is not
  one**, wherever it stands: `ctEq(0, x)` and `ctSelect(m, a, 0)` are both
  words of `x`'s and `m`'s type. A fraction is then refused as a fraction
  (`` Non-integer literal `0.5` where u32 is expected ``,
  `reject_ct_select_float_mask`), and with nothing but literals there is no
  width to take, so `ctEq(1, 2)` is an `i32` and refused (`reject_ct_eq_literals`).
- **The mask convention is all-ones or zero, and it is not checked**, because
  the check would be the branch. `ctEq` only ever answers one of the two. Any
  other mask is a defined bitwise blend, bit by bit as the formula says —
  `ctSelect(0xf0f0f0f0, a, b)` takes the high nibble of each byte from `a` —
  and the Node reading below computes the same blend (`ct_select_u32`).
- **They are globals, not a `nish:` module**, by the rule
  [Builtin modules](#builtin-modules-nish) sets: what is backed by the C runtime
  may be imported, and what lowers to instructions reads as language. These call
  nothing (`reject_ct_nish_module`). Like every function, neither is a value
  (`reject_ct_eq_value`).
- **The lowering is the formula behind an optimisation barrier.** The barrier is
  an empty inline `asm` that hands a value back in the same register —
  `call i32 asm "", "=r,0"(i32 %mask) readnone nounwind` — which costs no
  instruction and which no pass can see into, the idiom BoringSSL and Rust's
  `subtle` crate use. `ctSelect` puts it on the mask before the blend; `ctEq`
  computes `((d | -d) >>> (w - 1)) - 1` from `d = a ^ b` and puts it on the
  answer, so a caller's `ctSelect(ctEq(a, b), x, y)` never shows LLVM a
  boolean. `readnone nounwind` is what clang writes on the same statement and is
  true of an empty string, so a function that only selects stays `readnone`.
  [IR_COOKBOOK.md](IR_COOKBOOK.md#ctselect-and-cteq) shows the IR. Without the
  barrier `opt -O2` folds `ctSelect(ctEq(a, b), x, y)` into one `select` on
  `a === b` — `tests/run.js` checks both halves of that sentence, so it learns
  if LLVM ever sees through the `asm` or stops needing it.
- **What the barrier promises: no branch and no secret-indexed load in these
  primitives**, checked where the promise lives, in the machine code.
  `tests/run.js` compiles every `tests/cases/ct_asm_*` fixture with
  `clang -O2 -S` for x86-64 and aarch64 and reads each function a fixture names
  by its symbol (`tests/ct-asm.js`). It refuses any conditional branch
  (`j<cc>`, `b.<cond>`, `cbz`, `tbz` and the rest), any call or jump out of
  the function, and any load or store whose address a secret reaches,
  following secrets through registers, flags and stack slots and erring
  towards refusal wherever its model of the machine is not exact. The fixtures are both builtins at both widths, a mask
  straight into a select, a 32-byte MAC compare over `u8[]` and a table read
  that loads every entry (`ct_asm_primitives`, `ct_asm_mac`); and
  `ct_asm_refused` holds an early-exit compare and a secret-indexed table
  lookup that the check must refuse, one for each kind, so a check that read
  nothing fails.
- **It also refuses an instruction whose latency follows a secret**: an
  integer divide (`div`/`idiv`, `udiv`/`sdiv`) or a floating divide or square
  root whose operand a secret reaches (the `latency` kind, seeded by
  `ct_asm_refused`'s `secretDivide`). It reads what `clang -O2` emits for the
  baseline CPU of each target, and for x86-64 at `x86-64-v3`, the one level
  [`--cpu`](#the-cpu-level) offers, and nothing else, so a build with another
  profile or `-march` is not what was read
  ([docs/security/ct-verification.md](security/ct-verification.md), CT-2, CT-16).
  It reads only the functions a fixture names, so a module function that is
  not one — every loop in `std/crypto`, for instance — rests on review; that
  record lists them.
- **What it does not promise: anything about the caller's own code.**
  `if (ctEq(a, b) !== 0)` branches on a secret because the program wrote a
  branch; `table[secret]` indexes by one; `===` on a secret is a compare LLVM
  may branch on; a loop whose trip count is secret leaks it; and `/` and `%`
  take time that depends on their operands on many processors. The fixtures
  show the shapes that stay constant time, and a new one belongs beside them.
  On `wasm32` the builtins compile with the same barrier, but the engine
  compiles the module again, so the `.s` this check could read is not what
  runs and nothing is promised there. Weekly, and never from `npm test`,
  `.github/workflows/ct-timing.yml` runs `tests/ct-timing.js` on an x86-64 and
  an aarch64 runner — a dudect-style Welch's t-test of every function the
  fixtures name, a fixed secret against a random one, filed as an issue when
  |t| passes 4.5 — which measures whether their running time on that hardware
  moves with the secret, and cannot promise more: a difference below a shared
  runner's noise, a secret index into a table that fits in the L1 cache, or
  another processor goes unseen.

The TypeScript reading ([wp33-round-trip.md](wp33-round-trip.md) §2):
`runtime/nish.mjs` supplies both as pure functions of their operands, so the
answers agree and only the timing is not claimed. Over **`u32`** they are
**class A**: a `u32` is a `number` there, the shim puts each answer back in
range with `>>> 0` (JavaScript's `&` answers a signed 32-bit integer), and
`ct_select_u32` and `ct_eq_u32` run unmodified under the prelude and print what
the native build prints. Over **`u64`** the prelude takes BigInts and answers
BigInts, and the `ct_prelude` check in `tests/run.js` holds its answers to
`ct_u64`'s native output line for line. A `u64` program is still **class C**
under Node, as all 64-bit arithmetic is ([RUN_UNDER_NODE.md](RUN_UNDER_NODE.md)):
a bare `u64` literal is a `number` there, and mixing one with a BigInt throws a
`TypeError` rather than comparing the two and answering zero.

### Wiping a secret: `secureZero`

A key, a secret scalar or another secret intermediate has to be cleared once it
is used, and a store the program never reads again is exactly what the optimiser
removes: `key.fill(0)` just before a key goes out of scope is a dead store at
`-O2`, and a `memset` in the runtime is one too once `-flto` inlines it into
that caller. This builtin is the store that stays (#385).

| Signature | Semantics | Effect | Test |
| --- | --- | --- | --- |
| `secureZero(bytes: u8[]): void` | every byte of `bytes` set to zero, in stores no optimisation removes; an empty array is a call that clears nothing; a statement | write | `wipe_bytes`; `reject_wipe_i32`, `reject_wipe_string`, `reject_wipe_readonly`, `reject_wipe_value`, `reject_wipe_arity`, `reject_wipe_region` |

- **A `u8[]` only**, as `crypto.getRandomValues` takes, because the byte is the
  unit a secret is written in: anything else is
  `` `secureZero` fills a `u8[]`, got i32[] `` (NL2402), a string included,
  which is immutable and has nothing to clear (`reject_wipe_i32`,
  `reject_wipe_string`). The call writes its argument, so a `readonly u8[]` is
  `` Cannot `secureZero` through readonly u8[] (declare it u8[] to write through it) ``
  (NL2264, `reject_wipe_readonly`), and a function that wipes a parameter does
  not get `readonly` on it (`wipe_bytes`). In a scope's region it is refused
  where `fill` is (NL2394, `reject_wipe_region`).
- **A statement**: there is nothing to answer, so
  `` `secureZero` returns void and can only be used as a statement `` (NL2105,
  `reject_wipe_value`), and it takes exactly one argument (NL2061,
  `reject_wipe_arity`).
- **The lowering is one call**, `call void @nish_wipe(%struct.nish_array* %key)`,
  declared `nounwind willreturn` and `nocapture` without `readonly` and with no
  memory attribute, so LLVM may not treat it as a store it can drop.
  `nish_wipe` in `runtime/runtime.c` writes each byte through a `volatile`
  pointer, which the C standard makes behaviour no optimisation may remove
  even once LTO has inlined the body, and is `noinline` besides, so the call
  stays visible in a disassembly. [IR_COOKBOOK.md](IR_COOKBOOK.md#securezero)
  shows the IR.
- **It is pinned under `-O2 -flto`, where it matters.** The runtime unit test
  builds a probe the way `--link` builds, `-O2 -flto` over the runtime's
  sources: a key written to a block, used, wiped and freed, then read back
  through a pointer the optimiser cannot follow. With no wipe the key is still
  there, and with a `memset` wipe in another translation unit it is still there
  too, dropped as a store before `free`; with `nish_wipe` nothing is left. The
  same test fails when `nish_wipe` is written as a `memset`.
- **What it does not promise: the copies the program made.** It clears the
  bytes of the array it is handed. A copy taken before (`slice`, a `push` into
  another array, an element read into a local, a register spilled to the stack)
  is the program's to clear, and nothing clears what the operating system
  swapped out.
- **It is a global, and not in a `nish:` module.** It is backed by the C
  runtime, so by the rule [Builtin modules](#builtin-modules-nish) sets it may
  be imported, but no module exports it yet. It works under the wasi profile,
  which links `runtime.c`; a freestanding wasm module has no `nish_wipe`:
  it links `runtime-wasm.c`, which supplies the arena, arrays, the panics and
  `floor`/`ceil`/`trunc` but no wipe, and, when it uses
  strings, `runtime-text.c`, which has the strings and the digits but not the
  wipe.

The TypeScript reading ([wp33-round-trip.md](wp33-round-trip.md) §2) is
**class A**: `runtime/nish.mjs` supplies it as a loop that sets every element
to zero, and `wipe_bytes` prints the same lines under the prelude as natively.
What Node cannot promise is the native build's stronger claim, because a
collector that moved the array may have left the old bytes behind.

### Who owns a path: `lstatOwnerModeSync`, `geteuid` and `isExecutableSync`

What a driver asks before it trusts a directory or a program it found on its
own: who owns this path, may anyone else write to it, and will the shell run
it (#386; [security/cli.md](security/cli.md), CLI-7 and CLI-9).

| Function | Takes | Gives | Effect |
| --- | --- | --- | --- |
| `lstatOwnerModeSync` | `string` | `i64` | write |
| `geteuid` | nothing | `i64` | write |
| `isExecutableSync` | `string` | `boolean` | write |

**`lstatOwnerModeSync(path: string): i64`** does one `lstat` of `path`. It
answers the owner's uid in the high 32 bits and `st_mode` (the file type and
the permission bits) in the low 32, or **-1** when the path does not resolve
or holds a NUL. A symbolic link answers for **itself**, not for what it
names.

- *Tests:* `owner_checks`; `reject_owner_arity`, `reject_owner_i32`,
  `reject_owner_wasm`.

**`geteuid(): i64`** answers the effective user id, the one to compare an
owner with.

- *Tests:* `owner_checks`; `reject_owner_euid_arity`,
  `reject_owner_euid_wasm`.

**`isExecutableSync(path: string): boolean`** is `access(path, X_OK)`:
whether the real user may run `path`. It answers `false` for a path that
does not resolve or holds a NUL.

- *Tests:* `owner_checks`; `reject_owner_type`, `reject_owner_exec_wasm`.

- **The owner and the mode are one answer.** Both come out of one `lstat`, so
  they describe the same file however the path changes in between; two calls
  could describe two. Take them apart with `(om >> 32) & 0xffffffff` (the
  owner) and `om & 0xfff` (the permission bits) or `om & 0xf000` (the type:
  `0x8000` a regular file, `0x4000` a directory, `0xa000` a symbolic link).
  The mask is not optional: a uid is unsigned and one of 2^31 or more fills
  bit 63, which `>>` on an `i64` copies down, so `om >> 32` alone answers a
  negative owner for a file such a user owns and never equals their
  `geteuid()`. `>>>` would say the same natively, but a BigInt has no `>>>`, so
  the mask is the spelling that reads the same under Node (`owner_checks`). A uid fills
  32 bits, so the answer is an `i64` in both number modes, as `geteuid`'s is,
  and an `i32` is refused rather than truncated
  (`` Cannot initialize i32 variable `om` with i64 ``, `reject_owner_i32`).
- **Not following a link is the point.** A directory that is a symbolic link
  to one this user owns is not a directory this user owns, and the test of a
  path that has to be trusted is of the path as written. That a link answers
  for itself is pinned by RT-9 in `tests/runtime-test.c`, since a program
  cannot make one.
- **`isExecutableSync` is the shell's question,** asked for the real user as
  `access` asks it: a file with no execute bit is not executable, root
  included, and a readable file is not the same answer.
- **Refused on a wasm32 build,** as `statMtimeSync` is: there is no file system
  and no user there, so each is
  `` `lstatOwnerModeSync` reaches the operating system, and a wasm32 build has none to reach ``
  (`reject_owner_wasm`, `reject_owner_euid_wasm`, `reject_owner_exec_wasm`).
  Each takes exactly its arguments (NL2061, `reject_owner_arity`,
  `reject_owner_euid_arity`), and a path is a `string`
  (`reject_owner_type`).
- **The lowering is one call each,** `call i64 @nish_lstat_owner_mode(i8* %p)`,
  `call i64 @nish_euid()` and `call zeroext i1 @nish_is_executable(i8* %p)`,
  declared `nounwind willreturn` and ordered with every write, because the file
  system is not memory LLVM tracks and a failure stores `errno`
  ([IR_COOKBOOK.md](IR_COOKBOOK.md#lstatownermodesync-geteuid-and-isexecutablesync)).
- **Globals, and not in a `nish:` module** yet, as `secureZero` is.

The TypeScript reading ([wp33-round-trip.md](wp33-round-trip.md) §2) is
**class A**: `runtime/nish.mjs` supplies `fs.lstatSync`'s `uid` and `mode`
packed the same way as a BigInt, `process.geteuid()`, and `fs.accessSync` with
`X_OK`, and `owner_checks` prints the same lines under the prelude as natively.

### Secrets: `nish:secret`

Key material is a `Secret<T>`: an opaque value that the checker keeps from
leaving the program by any road but one, and that is zeroed, with a store no
optimiser may remove, before the function that made it lets go of it.

Reference: [`nish:secret`](reference/nish-secret.md).

| Export | Meaning | Test |
| --- | --- | --- |
| `Secret<T>` | an opaque class holding an array or record of integers | `secret_wipe`, `secret_flow`; `reject_secret_shape` |
| `secret(v)` | `v`, which nothing else holds, wrapped; a local is moved | `secret_flow`, `secret_inferred`; `reject_secret_moved`, `reject_secret_unmovable`, `reject_secret_alias_*`, `reject_secret_inferred_*` |
| `expose(s, f)` | `f(value)`, under the rules below | `secret_wipe`; `reject_secret_expose_*` |
| `exposeWith(s, arg, f)` | `f(value, arg)`, under the same rules | `secret_wipe`; `reject_secret_expose_writes_arg` |
| `wipe(x)` | zero a `Secret`, or an array or record of integers `expose`'s function holds | `secret_wipe`, `secret_wipe_o2`, `secret_wipe_o2_inferred`; `reject_secret_wipe_shape`, `reject_secret_wipe_nullable` |

`nish:secret` is the one builtin module with source behind it: `std/secret.ts`,
loaded like a standard-library module, imported only by the builtin name
(`` `nish/secret` is the builtin module `nish:secret` ``, NL2453,
`reject_secret_std_spelling`) and copied, as `std/collections.ts` is, into each
module that uses it, so it writes no `.ll` of its own. `runtime/nish.d.ts`
declares it for `tsc`, with a private constructor and field so that `tsc`
refuses `new Secret` and `s.value` too. Under Node (`runtime/nish.mjs`) a
`Secret` is a plain wrapper and `wipe` zero-fills it.

**A `Secret` local needs no annotation.** `const k = secret(v)` gives `k` the
type `secret` answers, `Secret<T>` for the `T` that `v` is, and every rule
below holds for it as for `const k: Secret<T> = secret(v)`: the payload's
shape, the move and the second reference, each judged where `v` is written
(`secret_inferred` binds an array literal, `new Array`, a call, a moved local,
a ternary, a record and a class unannotated; `reject_secret_inferred_literal`,
`_alias`, `_call`, `_field` and `_moved_class` are refused unannotated as
annotated). The same holds for any generic an imported module declares:
`const b = box(7)` holds the `Box<i32>` that `box` answers, whose layout comes
with the call (`tests/link/generic_import_inferred`), with its methods even
where the module already held `Box<i32>` as a type argument
(`tests/link/generic_import_inferred_held`), and with those of every struct
its fields reach, through an array, a nullable, a `Result` or a nested
instance, in either order (`tests/link/generic_import_inferred_closure`).

**What a `Secret` may hold.** One run of integers, so that `wipe` reaches every
byte with one store: `` `Secret<string>` is not key material `` (NL2428,
`reject_secret_shape`). `wipe` takes a `Secret`, never a nullable one (narrow it
first), or an array or record of integers, and anything else is
`` `wipe` zeroes a `Secret`, or an array or record of integers, and `string` is neither ``
(NL2438, `reject_secret_wipe_shape`, `reject_secret_wipe_nullable`).

**Where a `Secret` may not go.** Each place is refused at the point it is
written, before the general rule it would also break, so the one diagnostic
names the secret:

- a template literal hole (NL2431, `reject_secret_template`);
- an argument of any builtin — `console.log`, a file write, `nish:net`, a
  process, an environment read, `crypto.getRandomValues` — named or imported
  (`` `console.log` cannot be handed a `Secret` ``, NL2432,
  `reject_secret_console`, `reject_secret_file_write`, `reject_secret_net_write`);
- `===` and `!==` against anything but another `Secret` or `null` (NL2433,
  `reject_secret_equality`): `k === null` is how a nullable one narrows;
- the condition of an `if`, a loop or a ternary (NL2434, `reject_secret_condition`);
- an index, as the receiver or as the index (NL2435, `reject_secret_index`,
  `reject_secret_as_index`);
- a member read, written or called anywhere but `std/secret.ts` (NL2436,
  `reject_secret_member`), and `new Secret` (NL2437, `reject_secret_new`);
- an array element, a `Result` payload, or a type argument of any class,
  `Map` and `Set` included (NL2429, `reject_secret_array`,
  `reject_secret_result`, `reject_secret_generic_class`). A `Secret` lives in a
  local, a parameter, or a holder's field ([A `Secret` field](#a-secret-field)),
  and `Secret<T> | null` is how a function hands back one it may not have. Any
  other field — of an interface, of a generic class, not `readonly`, or not
  exactly `Secret<T>` — is NL2430 (`reject_secret_field`,
  `reject_secret_field_interface`, `_generic_class`, `_not_readonly`,
  `_nullable`).

**A `Secret` leaves the function that made it returned or wiped, on every
path.** This is Result rule 1's analysis in its two places — the statement that
drops a value, and the body that never handles one — with the second walked
path by path rather than counted, because "wiped on one arm of an `if`" is not
"wiped" (`reject_secret_one_branch`):

- A `Secret` a call makes has an owner: a `const` or `let`, a `return`, or
  `wipe`. Anywhere else — a statement, a call's argument — it is
  `` `Secret<u8[]>` is made here and nobody owns it `` (NL2439,
  `reject_secret_discarded`, `reject_secret_temporary`).
- Every `return`, `break`, `continue` and `orReturn()` that leaves a `Secret`
  the function made neither wiped nor returned is
  `` `k` holds a `Secret<u8[]>` that this exit leaves neither wiped nor returned `` (NL2440,
  `reject_secret_unwiped_return`, `reject_secret_break`, `reject_secret_or_return`),
  and a block that can reach its end with one is NL2441 (`reject_secret_scope_end`).
  A branch that proves the local `null` (`if (k === null)`) holds none, a
  `panic` or `process.exit` ends the process and the key with it, and a loop is
  walked to its fixpoint, so a `wipe` inside a loop that may run no pass does not
  count (`secret_flow`).
- A `Secret` local may not be assigned while it still holds one (NL2442,
  `reject_secret_overwrite`), read once any path has wiped it (NL2443,
  `reject_secret_after_wipe`), or copied: `const j = k` moves `k` when the
  function made it, and `k` is not read again (NL2446, `reject_secret_moved_out`),
  but a parameter, an element of an array literal or an arm of a ternary is a
  second name for one key (NL2444, `reject_secret_copy_param`).
- `secret(v)` takes a value nothing else holds, and moves it, because a
  second name for the bytes would read the key outside the `Secret`, and
  zeros once `wipe` has run. A local handed in is not read again (NL2445,
  `reject_secret_moved`, whose message says the plain array, and
  `reject_secret_inferred_moved_class` and `reject_secret_moved_interface`,
  where it names the class or interface the plain value is), and neither is
  the local in either arm of `secret(c ? a : b)`. A parameter, a field or an element,
  whose owner keeps the plain bytes, is refused (NL2447,
  `reject_secret_unmovable`). Everything else is judged where it is written:
  - an array or object literal, `null`, and a ternary of fresh values are
    fresh, and so is a `new` whose constructor keeps no `this`;
  - a call is fresh when its callee answers a fresh value, judged over the
    callee's own body by this same rule, through every depth of calls (a
    recursive one included); `expose` and `exposeWith` answer what the
    function they run answers, and `r.orReturn()`, `r.expect(m)` and
    `r.unwrapOr(d)` what `r` carries in its `Ok` (`d` too, which may not be a
    local here, since the move does not reach it). A method of a value,
    `rows.pop()`, may answer what the value holds;
  - a local is fresh when it is the sole reference to its value: every value
    it is given is fresh (another local is not, because that local still
    names it), it is not a `for...of` binding, which names an element, and no
    other use of it leaves a second name. Reading an integer element or field,
    `.length`, an array method on it, `===`, iterating over it, `wipe`, and
    handing it to a builtin, or to a function or method the whole-program
    facts say keeps nothing of it, are all such uses. An initialiser, an
    assignment's value, a field or element store, a literal's element, a
    ternary arm, either side of `??`, the argument of `Ok` or `Err`, an
    assignment to it used as a value (`alias = raw = [1]`, `xs.push(raw =
    [1])`; one whose value is dropped, as a statement or in a `for` header,
    is not), a later declarator of the same statement, a `return`, an argument of a method of
    another value (`rows.push(raw)`, `m.set(k, raw)`), a read by an arrow
    that captures it (a data-parallel body or a spawned task), and a function or constructor
    that keeps it each leave one.

  Each is `` `secret` takes a value nothing else holds, and `raw` has a second
  reference: `const alias = raw` (line 6) ``, naming the reference and its
  line, or the callee and its parameter that keep it (NL2512,
  `reject_secret_alias_const`, `reject_secret_alias_let`,
  `reject_secret_alias_reassigned`, `reject_secret_alias_assign_chain`,
  `_assign_init`, `_assign_push`, `_assign_field`, `_assign_kept`,
  `_assign_helper`, `_assign_parents`, `_assign_constructor`,
  `_assign_source`, `reject_secret_alias_declarators`,
  `reject_secret_alias_field`, `reject_secret_alias_element`,
  `reject_secret_alias_param`,
  `reject_secret_alias_return`, `reject_secret_alias_mutual`,
  `reject_secret_alias_ternary`, `reject_secret_alias_nullish`,
  `reject_secret_alias_ok`, `reject_secret_alias_err`,
  `reject_secret_alias_unwrap_or`, `reject_secret_alias_unwrap_helper`,
  `reject_secret_alias_unwrap_local`, `reject_secret_alias_constructor`,
  `reject_secret_alias_receiver`, `reject_secret_alias_pop`,
  `reject_secret_alias_for_of`, and `reject_secret_alias_capture_map`,
  `_from`, `_map_into`, `_reduce` and `_spawn`, and
  `reject_secret_alias_spawn_arg` and `_spawn_with` for a task's argument,
  which the scope keeps until the task has run). Pass a fresh value instead, or a copy: `const copy: u8[] = new Array<u8>(raw.length);
  copy.set(raw)`, then `secret(copy)`. A declarator that reads `raw` after
  `secret(raw)` in the same statement is a moved read, NL2445
  (`reject_secret_alias_declarator_moved`). The rule refuses some programs
  that are safe, each with the reference named: a data-parallel arrow that
  reads the local before the move, a `Result` local copied into another
  (`reject_secret_alias_result_copy`), and a `let` given another local even
  after the move (`reject_secret_alias_reassigned_after`).
- A `Secret` parameter is borrowed. The callee may read it through `expose`
  or hand it on, and owes nothing: the caller wipes what it made. It neither
  returns it, which would give the caller a second name for a key it already
  owns (NL2546, `reject_secret_field_launder_function` and its siblings, among
  them `reject_secret_field_launder_local` for a caller's own local), nor
  wipes it, which would leave the caller reading zeroes and wiping it again
  (NL2548, `reject_secret_field_wipe_param` and its siblings, among them
  `reject_secret_field_wipe_param_local`). The cases are listed under
  [A `Secret` field](#a-secret-field).

  **This narrows 0.18.0.** Up to 0.18.0 a callee could also return or wipe a
  borrowed `Secret`; from the release after it, both are refused, for every
  `Secret` parameter and not only a holder's field. A function that returned
  its parameter is called for its effect and the caller goes on using the key
  it passed; a function that wiped its parameter leaves the wipe to the owner,
  the function or holder that made the key.

#### A `Secret` field

A key that lives as long as an object does — a connection's traffic secret, a
signer's private scalar — is kept in a `readonly` field of exactly `Secret<T>`,
in a class with no type parameters. Such a class is a *holder*. The checker
proves three things of it: the field is set once, from a fresh value; it is
read only where the key cannot get out; and the holder's `wipe()` ends it.

```ts
class Session {
  readonly key: Secret<u8[]>;
  constructor() {
    this.key = secret(new Array<u8>(32));   // once, from a fresh value
  }
  rekey(by: u8): void {
    exposeWith(this.key, by, refill);       // rewritten in place, never replaced
  }
  wipe(): void {
    wipe(this.key);                         // every field, on every path
  }
}
```

- **The releaser.** A holder declares `wipe(): void`, taking no parameters
  (`` `Holder` holds the `Secret` field `k`, so it declares `wipe(): void` ``,
  NL2540, `reject_secret_field_no_wipe`, `_wipe_signature`). Its body calls
  `wipe(this.f)` itself for every `Secret` field, on every path: the field is
  walked as an owned local would be, so a `return` before it, one arm of an
  `if`, a loop that may run no pass, and a helper method that wipes it are each
  `` `this.k` can leave this `wipe()` unwiped `` (NL2541,
  `reject_secret_field_wipe_missing`, `_wipe_return`, `_wipe_branch`,
  `_wipe_loop`, `_wipe_helper`, and `_wipe_new`, where a constructor `new`
  reaches zeroes the key in place). That method is the only place a field
  ends: `wipe(h.f)` anywhere else — a function, another method, a
  constructor, or a function the constructor hands `this` to or stores it
  for — is `` `k` is wiped outside its holder's `wipe()` `` (NL2547,
  `reject_secret_field_wipe_outside`, `_wipe_through`, `_wipe_method`,
  `_wipe_ctor`, `_this_fin`, `_this_store`); call the holder's `wipe()`.
- **Construction.** The field is set in the constructor, by `this.f =
  secret(v)` and nothing else, and `v` is judged by the sole-reference rule
  above (NL2512, `reject_secret_field_alias_raw`). A parameter, a call that
  answers a `Secret`, or a local holding one is
  `` `this.k` is set from something other than `secret(...)` `` (NL2542,
  `reject_secret_field_param`, `_call`, `_local`); a second store while the
  first may still be there, a later loop pass included, is NL2543
  (`reject_secret_field_twice`, `_ctor_loop`). The field is `readonly`, so a
  store anywhere else — a method, a function, a compound `+=`, or a second
  name for `this` — is the `readonly` refusal, NL2181
  (`reject_secret_field_store_method`, `_store_outside`, `_compound`,
  `_this_escape`). The store is a statement of its own: `const x = (this.k =
  secret(v))` binds the key a second time, and is NL2544
  (`reject_secret_field_store_value`). A holder is made only by `new`: an
  object literal is NL2545 (`reject_secret_field_object_literal`), and typed
  JSON neither encodes nor decodes one (NL2485, `reject_secret_field_json`, `_json_decode`).
- **Reads.** `h.f` is borrowed, as a `Secret` parameter is: it is an argument
  of a call or a `new` — `expose`, `exposeWith`, or a function that
  takes a `Secret`, and `wipe` only in the holder's own `wipe()` (NL2547) — or an operand of `===` or `!==` against another `Secret`
  (a field is never `null`, so `h.k === null` is a type error, NL2024). Bound to a local, assigned, returned, chosen by a ternary or `??`,
  or read through `?.` or a chain of fields, it would be a second owner of the
  key, and is `` `k` is a `Secret` field, which is read only as a call's
  argument or an `===`/`!==` operand `` (NL2544, `reject_secret_field_bind`,
  `_assign_local`, `_return`, `_ternary`, `_nullish`, `_optional_chain`,
  and `_nested` for `o.h.k`; `_chain` is the chained store `this.k = this.j =
  secret(v)`). What a borrow receives stays borrowed: a function, an arrow or
  a generic `id<T>` that takes a `Secret` and returns it would hand the
  caller a second name for the holder's key, and is
  `` `s` is a `Secret` parameter, which its caller owns and wipes: returned ``
  (NL2546, `reject_secret_field_launder_function`, `_launder_arrow`,
  `_launder_generic`, `_launder_method`, and `_launder_local` for a caller's
  own local); one that wipes it is NL2548 (`reject_secret_field_wipe_param`,
  `_wipe_param_new`, `_wipe_param_method`, and `_wipe_param_local` for a
  caller's own local). A ternary that picks one of two borrowed parameters to
  return is refused before it gets there, as a copy (NL2444,
  `reject_secret_field_launder_ternary`). Every place a `Secret` may not go is closed to the field too:
  `reject_secret_field_console` (NL2432), `_template` (NL2431), `_equality`
  (NL2433), `_condition` (NL2434), `_index` (NL2435), `_member` (NL2436),
  `_array`, `_array_literal` and `_result` (NL2429), `_new_arg` (NL2439: a
  `Secret` made for a constructor that keeps none, beside an accepted
  `new Box(h.k)` that borrows the field), and `_secret_arg` and
  `_holder_payload` (NL2428: neither a `Secret` nor a holder is key material).
- **The holder is a value.** It may be aliased and kept in an array, a `Map`,
  another object's field or a `Result`. The rules that follow are the general
  ones, applied to a holder as to any class: a data-parallel body may not
  capture one (NL2504, `reject_secret_field_capture`) nor may a task (NL2509,
  `_task_wipe`), the scope's own thread may not wipe one a task of it may read
  before the join — through `wipe()`, a helper or a constructor
  (`_scope_wipe`, `_scope_helper`, `_scope_new`) — and `using` does not take
  one (NL2387, `reject_secret_field_using`).

`secret_field` runs all of it, and `tests/run.js` holds the wipe to `-O2`
("nish:secret: a holder's wipe survives opt -O2"): `secret_field_wipe_o2`'s
`wipe()` is a volatile `llvm.memset` of the key after `opt -O2`, where its twin
`secret_field_wipe_o2_plain`, zeroing the same bytes with `fill(0)`, has an
ordinary one. An exported holder appears in an `--emit-header` sidecar as an
opaque struct, a `typedef` with no fields: with its layout a host could
allocate one and skip the constructor that sets the key, so it reaches C only
as a pointer. A `Secret` an exported function takes or returns is likewise a
pointer to an opaque struct, as a `Map` is, and `--emit-dts` and `--emit-napi`
bridge no function that takes or returns a holder or a `Secret`
("nish:secret: --emit-header keeps a Secret and its holder opaque, and
--emit-dts / --emit-napi bridge neither").

What the rule leaves out, so a review need not look for it here:

- **A holder nobody wipes.** The checker proves that `wipe()` ends every key,
  not that anybody calls it: a holder dropped, or released with its arena,
  without `wipe()` leaves its key in memory. Holders are values that cross
  functions, aliases and containers, and their owner is not tracked.
- **Aliases.** `wipe()` through one alias zeroes the key for every alias, and
  an `expose` through another reads zeros afterwards: a wrong answer, never a
  leak.
- **Plain temporaries.** What an exposed function copies out of the key is a
  plain value, and is wiped only if that function wipes it.
- **Per-packet and per-record keys.** These cannot be a `Secret` under today's
  `expose`: sealing writes the output buffer (NL2450) and the AES kernels are C
  (NL2448).

**`expose` and `exposeWith`.** The function either runs is a
[function parameter](#function-parameters): a top-level function named at the
call, or an arrow written there. It is judged once the whole-program facts are
in, at the call, and what it returns is the only thing that leaves:

- It reaches no I/O — no builtin that touches a file, a directory, a process,
  the environment, a socket, a stream, the clock or entropy — and no C, through
  any depth of calls (`` `leak` reaches `writeFileSync` through `store` ``,
  NL2448, `reject_secret_expose_io`, `reject_secret_expose_io_deep`,
  `reject_secret_expose_c`). A `panic` or exit is allowed only with a literal,
  since a computed message or status is output (`reject_secret_expose_panic`).
  A failed runtime check — an index, a slice, a division — still stops the
  program with its message, which carries the operand it failed on; an index
  that depends on a key is already a cache-timing defect, and is for the
  constant-time checks of WP34 N6 to find.
- It keeps nothing of the value: returning it, storing it or passing it where
  it is kept is NL2449 (`reject_secret_expose_keeps`). `exposeWith`'s function
  writes nothing through the argument it is handed either (NL2450,
  `reject_secret_expose_writes_arg`), which would be a road out its result type
  does not name.
- Its result is a declared type that holds no `Secret` (NL2451,
  `reject_secret_expose_secret_result`), and an arrow writes that type down
  (NL2452, `reject_secret_expose_undeclared`).

**The wipe.** Each `wipe` instance is one `llvm.memset` with its volatile flag
set, over an array's whole capacity — a `pop` leaves the old element in the
buffer — or a record's `sizeof`. LLVM never removes, merges or narrows a
volatile memory intrinsic, so the store survives every optimisation, inlining
included: `tests/run.js` compiles `secret_wipe_o2`, whose wiped bytes nothing
reads again, beside a twin that zeroes them with `fill(0)`, and after
`opt -O2` the twin holds no store and the wipe holds one volatile zero per byte.
`secret_wipe_o2_inferred` does the same for a `Secret` bound with no
annotation, beside `secret_wipe_o2_inferred_plain` ("nish:secret: an inferred
`Secret`'s wipe survives opt -O2 (a volatile memset of its key), where the
twin's fill(0) is deleted").
Two things it does not reach, and says so: a buffer a `push` outgrew, which is
no longer the array's, and a string, which is immutable and is not key material.

`wipe` and [`secureZero`](#wiping-a-secret-securezero) both make a store no
optimisation removes, and differ in what they take and where the store is
written. `secureZero` is a global over a bare `u8[]`, one call into the C
runtime; `wipe` is the `Secret`'s own, takes any integer width or a record of
integers, and is an intrinsic emitted into the program, so it needs no runtime
function and works wherever the program's IR does. Key material belongs in a
`Secret`, and `secureZero` is for bytes that never were one.

### Compact classes

`class R implements Compact` (`import { Compact } from "nish:compact"`)
stores every field typed exactly `R` or `R | null` — a *link*, in `R` itself
or in any other class — as a 32-bit offset into the one address range the
arena reserves, where a plain class stores a 64-bit pointer. A list or tree
node of an `i32` and two links is 12 bytes instead of 24, so twice as many fit
in a cache line.

```ts
import { Compact } from "nish:compact"

class Cell implements Compact {
  value: i32
  next: Cell | null
  constructor(value: i32, next: Cell | null) {
    this.value = value
    this.next = next
  }
}
```

- **Only a link moves.** A local, a parameter, a return, an array element, a
  `Map` key or value, and a field whose type is a wider union all stay full
  pointers. A load of a link widens it back to a pointer and a store narrows
  it; what the program reads and prints is the same as without the marker
  (`compact_list`).
- **The class's own layout follows its fields.** A compact class whose fields
  are all 4 bytes or narrower is 4-aligned and rounded to 4, so `Cell` is 8
  bytes; one with a `string` or an `f64` keeps 8. Its objects are allocated
  in the range and never on the stack.
- **Where a pointer is already 4 bytes, nothing moves.** On wasm32
  (`--profile wasi`, `--target wasm32`), in a page module built for the host
  with `--emit-dts` (it runs on the wasm runtime, whose root trace reads each
  link as a pointer: `compact_root_page`), and under `NISH_ASAN`, the marker
  compiles to the IR the class has without it.
- **The marker changes nothing under Node.** Type stripping removes the
  `implements Compact` clause, and the `nish:compact` import resolves to the
  frozen values `runtime/core.mjs` exports, so the program runs unmodified
  there.
- **A generic field instantiated as exactly a compact class is narrowed.**
  `Box<Cell>.inner`, with `Cell` compact, holds a compact link, so an
  interface view of the field and its implementer agree on the layout.
- **A compact class is refused where C, Node or the runtime would read its
  layout as full pointers**, each with its own code: in a build with `--emit-header`, `--emit-napi` or
  `--emit-napi-async`, at the class (NL4021, `compact_reject_header`), or at an
  export whose signature holds one (NL4020, `compact_reject_export`); as a
  `declare class` (NL2795, `compact_reject_declare`), or held by one (NL2796,
  `compact_reject_declare_field`); and holding a `Secret`, whose wipe reads it
  through a full pointer (NL2797, `compact_reject_secret`); and as a generic
  class, whose instantiations keep full-pointer links (NL2798,
  `compact_reject_generic`).

`Wide` is accepted and changes nothing yet; it is reserved for a class to
refuse a compact layout the compiler would pick on its own.

Reference: [`nish:compact`](reference/nish-compact.md).

### Regions: `nish:region`

A region is memory a program frees when it says so: an arena of its own,
reached through a handle. A long-running program — a cache, a server's
per-connection state — keeps each thing that lives and dies together in one
region and gives the whole of it back with one `free`, where the thread's arena
would hold it until the program ends.

Reference: [`nish:region`](reference/nish-region.md).

| Export | Meaning |
| --- | --- |
| `Region<T>` | a handle to a region whose root is a `T`: a 64-bit number, not a pointer |
| `region(f)`, `regionWith(arg, f)` | a new region, whose root is what `f` answers; `f`'s allocations land in it |
| `child(f)`, `childWith(arg, f)` | a new region whose *parent* is the region entered now; called only in the `f` an `enter` or `enterWith` runs |
| `enter(r, f)`, `enterWith(r, arg, f)` | `f(root)` (or `f(root, arg)`), allocating in the region |
| `free(r)` | gives the region's memory back; `r` and every copy of it are dead. Freeing a parent frees its children first, deepest first; freeing a child unlinks it from its parent |

`f` is an arrow or a named function, and an arrow captures nothing (NL2335),
so the ways into a region are its root, `arg` and module state. The checker
follows each (`src/region-rules.ts`), with two kinds of value: *region memory*
(the root, and whatever `f` allocates) and *outer memory* (`arg`, module state,
what a callee answers from outside). A number, a `boolean`, an `enum` and a
`Region` are copied, never pointed at, so they cross freely
(`tests/cases/region_cache`).

| Refused | Code |
| --- | --- |
| region memory stored into outer memory: a field or an element, including `this` stored by a constructor `f` reaches (`h.l = this`). Module state cannot hold region memory at all, since a module binding is a number, `boolean` or string constant or [module storage](#module-storage), whose elements are pointer-free, and a top-level `let` is refused first (`reject_region_ctor_module_state`) | **NL2609** (`reject_region_to_outer`, `reject_region_ctor_this_arg`, `reject_region_store_string`, `reject_region_arrow_keep`, `reject_region_arrow_generic`; a spawned task's region into what it shares, `reject_async_spawn_store_region`) |
| outer memory that is not a number, `boolean`, `enum` or string literal stored into region memory: a field or element store, a constructor argument (`new Game(g.host)`) or a field of a literal | **NL2610** (`reject_region_outer_string_ctor`, `reject_region_outer_string_literal`, a spawned task's shared object kept by its own memory, `reject_async_spawn_keep_holder`, `reject_region_arrow_link`, `reject_region_arrow_result`, `reject_region_arrow_compose`, `reject_region_arrow_twice`, `reject_region_fixpoint_chain`) |
| `enter`'s or `enterWith`'s `f` answering anything but a number, a `boolean`, an `enum` or a `Region`: an array, an object or a string | **NL2611** (`reject_region_enter_result`, `reject_region_enter_string`) |
| `scope()`, `spawn`, a parallel body or a channel inside `f`, directly or through a callee | **NL2612** (`reject_region_threads`) |
| a value whose type holds a `Region` at any depth crossing to another thread: a task's argument or answer, a parallel body's capture, a value sent on a channel | **NL2613** (`reject_region_task_arg_field`, `reject_region_task_answer`, `reject_region_channel_map`, `reject_region_parallel_capture`) |
| `region`'s or `regionWith`'s `f` answering anything but memory it allocated: `region(() => moduleValue)`, `regionWith(g, (a) => a)` | **NL2614** (`reject_region_root_module`, `reject_region_root_arg`) |
| outer storage growing inside `f`, directly or through a callee: `push` on an outer array (arrays have no `unshift` or `splice`; the rule names them so it holds if they come), `Map.set` or `Set.add` on an outer `Map` or `Set` | **NL2615** (`reject_region_grow_push`, `reject_region_grow_map`, `reject_region_grow_set`, each with a `_callee` twin, `reject_region_arrow_grow`; a spawned task growing what it shares, `reject_async_spawn_grow`) |
| a call inside `f` the region rules have no facts for. No program reaches it today, since every function, instantiation, lifted arrow and `declare function` has whole-program facts; it stays so that such a callee is never let through unexamined (`tests/wordings/unreachable.txt`) | **NL2616** |
| `Arena.mark` or `Arena.used` inside `f`, or a callee reaching one: inside a region they would read the region's own arena, not the thread's | **NL2617** (`reject_region_arena_mark` through `region`, `reject_region_arena_used_callee` through `enter` and a callee) |
| `new Region<T>()` | **NL2618** (`reject_region_new`) |
| `child` or `childWith` outside the `f` an `enter` or `enterWith` runs, or in a function that something other than an `enter` also calls: with no region entered there is no parent | **NL2702** (`reject_region_child_outside`, `reject_region_child_callee`; a helper making the child, called from `main`, `reject_region_child_helper_main`, or from the function `enter` runs, `reject_region_child_helper_f`) |
| `region`, `regionWith`, `child`, `childWith`, `enter`, `enterWith` or `free` in a parallel body or a spawned function, directly or through a callee | NL2351 (`reject_region_enter_spawned`, `reject_region_parallel_callee`, `reject_region_child_parallel`, `reject_region_child_spawned`, `reject_region_child_with_parallel`, `reject_region_child_plain_spawned`) |
| `using r = region(f)`, in any declarator: a block does not free a region | NL2387 (`reject_region_using_first`, `reject_region_using_second`) |

- **`Arena.mark` and `Arena.used` are refused inside `f`** (NL2617). Inside a
  region they read the region's arena, not the thread's, so a mark taken there
  names nothing the thread's arena knows once `f` returns
  (`docs/security/runtime.md`, RT-45).
- **An arrow handed to a function runs inside `f`, and is judged as `f`'s
  own code.** Its body is walked with what it captures, its parameters take
  what the call is handed, what any arrow of the same call answers (the callee
  may feed one arrow's answer to another, or to itself) or memory the callee
  allocated, and what it answers is part of what the call answers, so
  `pick(() => a.node)` stored in the root is NL2610 as `a.node` is
  (`reject_region_arrow_keep`, `_grow`, `_link`, `_result`, `_generic`,
  `_compose`, `_compose_temp`, `_twice`, `_twice_temp`). The walk runs to a fixpoint however long a chain of
  assignments is, never a fixed number of rounds (`reject_region_fixpoint_chain`).
- **The rules are on types for threads, on values inside `f`.** NL2613 follows
  the type, so a handle hidden in a field of a task's argument is caught where
  it crosses, whatever route brought it there. A handle stored in region
  memory, or answered by `enter`, stays on its thread and is allowed.
- `using a = arena()` inside `f` is allowed, and so is `enter` of a second
  region: only numbers come out of it.
- **A child region may point into its parent's memory that existed before the
  current `enter`**: what the root `enter` handed in reaches, and, in the
  child's `f`, what `childWith`'s `arg` reaches when the root reaches it
  (`tests/cases/region_child_keep`, `region_child_chain`, `region_child_map`).
  The parent outlives the child, since freeing the parent frees the child,
  and nothing can release that memory while the parent lives: a scope opened
  during an `enter` rewinds only to a mark taken after the `enter` began, so
  it releases only what this `enter` allocated. That memory *new in this
  `enter`* is what the child may not keep (NL2610,
  `reject_region_child_new_memory`). The other rules hold the parent as outer
  memory: the child's memory stored into the parent's is NL2609
  (`reject_region_child_to_parent`), growing a parent array, `Map` or `Set`
  in the child's `f` is NL2615 (`reject_region_child_grow`), and the parent's
  memory as the child's root is NL2614 (`reject_region_child_root_parent`,
  and `reject_region_child_root_listed`, where it is read back out of a list
  the child's `f` made). The child's `f` may keep the parent's memory in the
  root it allocated, by a field or element store or a `push` onto that
  root's own array (`tests/cases/region_child_builder_list`). Only `f`'s
  own body may: a function it calls that keeps what it is handed in the
  memory it answers makes that answer NL2614, under `regionWith` as under
  `childWith` (`reject_region_helper_keeps_arg`,
  `reject_region_child_helper_keeps_arg`).
  A plain `region()` made inside `enter` stays independent of the region
  entered, and keeps the rules above.
- **What the root reaches counts as older than this `enter` only while `f`
  stores nothing into memory the root may reach.** Once `f` stores into
  memory that may be older than this `enter` — a field, `push`, or a callee
  that writes into what it is handed, such as `Map.set` — anywhere in its
  body, a value read off the root may be one it allocated, so `childWith`
  handing it is NL2610 (`reject_region_child_root_readback`,
  `reject_region_child_root_push`). A store into memory `f` made counts only
  when `f` also puts the root's reach (other than a string) into memory it
  made, as `[root]` or `new Holder(root)` does
  (`tests/cases/region_child_fresh_list`, `tests/cases/region_child_local_map`);
  then a store through it may put new memory in the root's reach
  (`reject_region_child_alias_field`, `reject_region_child_alias_element`).
  The check is not ordered: a store after the `childWith` counts too, and
  one such store makes every `childWith` in `f` hand outer memory rather
  than the parent's. To collect root nodes in a list, collect them in the
  child's `f`, as above. A call's result handed to `childWith` is memory
  this `enter` may have allocated, even when the callee only reads the root,
  so a child may not keep it.
- **In an `enter` of a handle that may be a child's, the root's reach may be
  its ancestors' memory as well as the child's own.** A child made there may
  keep it, but it may not grow (NL2615), keep memory other than an ancestor's
  (NL2610 for outer memory, `reject_region_child_handle_in`; NL2609 for memory
  new in this `enter`, `reject_region_child_handle_new`), nor be stored into
  outer memory (NL2609, `reject_region_child_handle_out`). Nor may such a
  root grow: a handle that reaches `enter` through a parameter is one, even
  when every caller hands a plain region (NL2615,
  `reject_region_child_handle_param`). A handle may be a child's when its type
  is one `child` or `childWith` answers somewhere in the program, unless the
  handle is a call of `region` or `regionWith` or a variable bound only ever
  to one: a parameter, a field or an element of that type may hold a child's
  (`tests/cases/region_child_plain`).
- **Every call checks its handle at run time.** `enter`, `enterWith` and
  `free` stop the program on a handle that is 0, freed already, or another
  thread's; `enter` of a region already entered and `free` of an entered one
  (or of a parent with an entered child) stop it too, so freeing twice is a
  panic and never a double free. A child's handle is dead once its parent is
  freed (`tests/link/region_child_stale`), and `child` with no region entered
  stops the program. Each call
  is a `region` site under [`--deny-panics`](#panic-sites)
  (`reject_deny_panics_region`), and no proof removes it. Past 16,777,216 live
  regions `region` stops the program as well.
- A program run under Node as it is written (`runtime/nish.mjs`) gets a
  region as an entry in a table, `free` drops it, and the same handle checks
  throw. `--emit-ts` output is different: the runtime it imports
  (`nish/runtime`) has no regions yet, so it refuses the module (NL4015,
  `reject_emit_ts_region`).

### `process`

The reference for each member of `process`, with its parameters, its answer and its capability, is its doc comment in [`runtime/nish.d.ts`](../runtime/nish.d.ts); the rules are here.

| Member | Takes | Gives | Effect |
| --- | --- | --- | --- |
| `process.exit` | `i32` | `void` | write, `noreturn` |
| `process.argv` | (property) | `string[]` | read |
| `process.platform` | (property) | `string` | none |
| `process.arch` | (property) | `string` | none |

**`process.exit(code: i32): void`** ends the program with `code`. The stdio
buffers of linked C code are flushed; the arena is abandoned. It is used in
statement position, and it is a terminator.

- *Lowering:* `nish_exit` -> libc `exit(code)`.
- *Tests:* `process_exit`, `reject_exit_unreachable`.

**`process.argv: string[]`** is the command line. `process.argv[0]` is the
program path (C's `argv[0]`, one index earlier than Node, whose `argv[0]` is
the `node` binary and `argv[1]` the script), and the rest are the arguments
as UTF-8 byte strings. It is read-only.

- *Tests:* `argv_echo` (run with `argv_echo.argv`), `link/argv_import`;
  `reject_argv_assign`, `reject_argv_push`
  (`` `process.argv` is read-only ``).

**`process.platform: string`** is the operating system the **program** is
running on, spelled as Node spells it: `"linux"`, `"darwin"`, or
`"unknown"` for anything this compiler has no target triple for (every WASI
build included).

- *Tests:* `io_host`; `reject_platform_assign`
  (`` Cannot assign to `process.platform` ``).

**`process.arch: string`** is the architecture, likewise: `"x64"`,
`"arm64"`, or `"unknown"`.

- *Tests:* `io_host`; `reject_arch_call`
  (`` Unknown builtin `process.arch` ``).

`process.platform` and `process.arch` are what `--target host` asks the
machine (WP14 §7a): the pair maps to `x86_64`/`aarch64` plus
`-unknown-linux-gnu`/`-apple-darwin`, and anything else means this compiler has
no triple for the host and says so. Each is one call to the runtime, which
answers the address of a string in its own constant data — settled when
`runtime.c` was compiled, so a cross build reports the *target*, and nothing is
allocated or loaded, which is why the declarations are `readnone` and a
function built only from these stays pure. They carry no rule about the entry
point, unlike `process.argv` below: there is nothing for a wrapper to build, so
a wasm or N-API library may read them too. Neither can be assigned to.

`process.argv` is an ordinary `string[]` value (`length`, `a[i]`, `for...of`,
passing it to functions, aliasing it with `const args = process.argv`) that
the `@main` wrapper builds once with `nish_argv_init(argc, argv)` before the
program runs; every module of the program may read it, and each read is one
`load` of the runtime global `@nish_argv` (a memory read: the function is at
most `readonly`). The array lives outside the arena, so no arena scope's
release invalidates it. Storing into it (`process.argv[i] = s`, `op=`,
`++`/`--`, `push`) is rejected. A program without `export const main`, as
for a wasm or N-API library, has nothing to build it from and rejects every
use with `` `process.argv` requires a `main` entry point `` (`reject_argv_no_main`,
`tests/link/argv_no_main`). Under the `wasi` build profile the WASI host
supplies the arguments (`examples/wasi-host.mjs`).

Reference: [`nish:process`](reference/nish-process.md).

### File I/O

Reference: [`nish:fs`](reference/nish-fs.md).

| Function | Takes | Gives | Effect |
| --- | --- | --- | --- |
| `readFileSync` | `string` | `string` | write |
| `readFileSyncOrNull` | `string` | `string \| null` | write |
| `readFileBytesSync` | `string` | `u8[] \| null` | write |
| `writeFileSync` | `string, string` | `void` | write |
| `appendFileSync` | `string, string` | `void` | write |
| `writeFileBytesSync` | `string, readonly u8[]` | `i32` | write |
| `renameSync` | `string, string` | `i32` | write |
| `unlinkSync` | `string` | `i32` | write |
| `writeFileSyncMode` | `string, string, i32` | `i32` | write |
| `createFileExclusiveSync` | `string, string, i32` | `i32` | write |
| `mkdirSyncMode` | `string, i32` | `i32` | write |
| `fileOpen` | `string` | `i32` | write |
| `fileReadAt` | `i32, u8[], i32, i32, i64` | `i32` | write |
| `fileSize` | `i32` | `i64` | write |
| `fileClose` | `i32` | `i32` | write |

**`readFileSync(path: string): string`** reads the whole file as one arena
string. A failure prints `nish: cannot read <path>` to stderr and exits 1.

- *Tests:* `io_files`; `reject_readfile_number`
  (`` `readFileSync` expects an argument of type string, got i32 ``).

**`readFileSyncOrNull(path: string): string | null`** is the same read,
with `null` where the other exits (WP14 B3): `null` for exactly the set of
paths `readFileSync` prints `nish: cannot read <path>` for, a **directory**
included. The result is narrowed with `if (text !== null)` like any other
nullable.

- *Tests:* `io_streams`; `reject_readfile_or_null_unchecked`.

**`readFileBytesSync(path: string): u8[] | null`** answers the file's
**bytes**, as they are on disk, or `null` for exactly the paths
`readFileSyncOrNull` answers `null` for; there is no exiting twin. The
result is an ordinary arena `u8[]` with `length === capacity`, narrowed with
`if (b !== null)`. A `wasm32` build has no `readFileBytesSync`, as it has no
`readFileSync`. The TypeScript reading is class A (WP34 N2).

- *Tests:* `bytes_read`, `bytes_read_import`, `mem_read_bytes_scope`;
  `reject_bytes_read_unchecked`, `reject_bytes_read_arity` (NL2061),
  `reject_bytes_read_type` (NL2268).

**`writeFileSync(path: string, data: string): void`** creates or truncates
the file (`0644`) and writes; it is used in statement position. A symbolic
link as the last component of `path` is refused
(`nish: cannot write <path>`), where Node follows it.

- *Tests:* `io_files`.

**`appendFileSync(path: string, data: string): void`** creates or appends
and writes; it is used in statement position. A symbolic link as the last
component is refused, as for `writeFileSync`.

- *Tests:* `io_files`.

**`writeFileBytesSync(path: string, bytes: readonly u8[]): i32`** creates or
truncates the file (`0644`) and writes the array's bytes as they are. A
symbolic link as the last component is refused (`-40` ELOOP). Where
`writeFileSync` exits, this **answers** `bytes.length` or a negative errno,
never a panic.

- *Tests:* `io_write_file_bytes`, `io_write_bytes`;
  `reject_write_file_bytes_arity`, `reject_write_file_bytes_type` (NL2268),
  `reject_write_file_bytes_wasm`.

**`renameSync(from: string, to: string): i32`** is `rename(2)`: `from`
replaces `to` in one step, so a reader sees the old file or the new one and
never neither. It answers `0`, or a negative errno; `-18` **EXDEV** across
file systems, since nothing is copied. Never a panic.

- *Tests:* `io_rename`, `caps_fs_replace`; `reject_rename_arity`,
  `reject_rename_type`, `reject_rename_wasm`.

**`unlinkSync(path: string): i32`** is `unlink(2)`: it removes the name, and
a symbolic link itself rather than what it names. A **directory is refused**
(`-21` EISDIR on Linux, `-1` EPERM where the kernel answers so), with no
fallback to `rmdir`. It answers `0`, or a negative errno. Never a panic.

- *Tests:* `io_unlink`, `caps_fs_replace`; `reject_unlink_arity`,
  `reject_unlink_type`, `reject_unlink_wasm`.

**`writeFileSyncMode(path: string, data: string, mode: i32): i32`** is
`writeFileSync` with the file left at exactly `mode`. An `fchmod(2)` sets it
**before the first byte is written**, so the umask cannot widen it and a
wider existing file is narrowed before it holds the new contents. A
descriptor opened before is not revoked. The file is written **in place**: a
failure leaves it empty or partial, and a file this process may write but
does not own is emptied before `-1` EPERM, so a secret that replaces another
goes through a temporary and `renameSync`. A symbolic link as the last
component is refused (`-40` ELOOP), its target untouched. A mode outside
`0..0o777` is `-22` (the setuid, setgid and sticky bits are refused, not
applied). It answers the length written, or a negative errno. Never a panic.

- *Tests:* `io_write_file_mode`, `caps_fs_mode`, `fs_mode` (modes read back
  by `stat`, umask `022` and `077`); `reject_write_file_mode_arity`,
  `reject_write_file_mode_type`, `reject_write_file_mode_wasm`.

**`createFileExclusiveSync(path: string, data: string, mode: i32): i32`** is
`O_CREAT|O_EXCL` at exactly `mode`, set as for `writeFileSyncMode`. It
answers `-17` **EEXIST** when any name is already there, a dangling symbolic
link included, which is never followed. Exactly one of any number of racing
processes wins, so it is a lock file; a winner whose write fails removes the
file before it answers. It answers the length written, or a negative errno.
Never a panic.

- *Tests:* `io_create_exclusive`, `fs_mode` (eight children race, one wins;
  a failed write leaves no file); `reject_create_exclusive_arity`,
  `reject_create_exclusive_type`, `reject_create_exclusive_mode_type`,
  `reject_create_exclusive_wasm`.

**`mkdirSyncMode(path: string, mode: i32): i32`** is `mkdir(2)` of one level
at `mode`, with the process umask applied. An existing name is `-17` EEXIST,
its mode never changed; a mode outside `0..0o777` (the sticky, setuid and
setgid bits included) is `-22`. It answers `0`, or a negative errno. Never a
panic.

- *Tests:* `io_mkdir_mode`, `caps_fs_mode`, `fs_mode`;
  `reject_mkdir_mode_arity`, `reject_mkdir_mode_type`,
  `reject_mkdir_mode_mode_type`, `reject_mkdir_mode_wasm`.

#### A file a window at a time

`readFileBytesSync` answers the whole file; these four read it **a window at
a time** into a `u8[]` the program owns, so memory follows the window rather
than the file, and a file past 2^31 − 1 bytes is readable (WP44,
[wp44-streaming-files.md](wp44-streaming-files.md)). No call allocates. Every
answer that is not a count is the **negated Linux errno, on every platform**,
WASI and Node included: `-2` not found, `-6` a Unix-domain socket (`ENXIO`),
`-9` a bad descriptor, `-13` permission denied, `-20` a component is not a
directory, `-21` a directory, `-22` not a regular file or a refused position,
`-23`/`-24` descriptors exhausted, `-29` not seekable, `-36` name too long,
`-40` too many symbolic links, and `-5` for any other failure, WASI's
`ENOTCAPABLE` among them. They are exported by `nish:fs` and global.

**`fileOpen(path: string): i32`** opens a **regular file** for reading and
answers its descriptor (`>= 0`), or a negative errno. It opens with
`O_CLOEXEC`, so a spawned child does not inherit it, and `O_NONBLOCK`, so a
FIFO with no writer cannot hang it. Anything that is not a regular file is
closed again and refused: a directory is `-21`, a FIFO or a device `-22`, and
a Unix-domain socket `-6`, as `open(2)` answers for one. An empty path, or one
holding a NUL, is `-2` before the file system is asked. Symbolic links are
followed.

- *Tests:* `file_read_at`, `file_open_errors`.

**`fileReadAt(fd: i32, buf: u8[], off: i32, len: i32, pos: i64): i32`** reads
at most `len` bytes of the file from byte `pos` into `buf[off, off + len)`,
with `pread(2)`: there is no cursor, so one descriptor serves any number of
readers. It answers the count, `0` at or past the end of the file, or a
negative errno. **A short read is allowed** before the end: loop until `0`, or
until the size planned for is read. `len` of `0` answers `0`. A `pos` below
`0`, or a `pos + len` past 2^63 − 1, is `-22` before the kernel is asked. The
window is [checked](#bounds) as `netRead`'s is, and `buf` is written, so a
`readonly u8[]` is refused (`` Cannot `fileReadAt` through readonly u8[] ``)
and another element type is NL2402, as `netRead`'s are.

- *Tests:* `file_read_at`, `file_read_at_eof`, `file_read_at_pos`,
  `file_read_at_bounds`, `file_size_large`, `mem_file_stream_flat`;
  `reject_file_read_readonly`, `reject_file_read_element`.

**`fileSize(fd: i32): i64`** answers the file's size in bytes now, or a
negative errno. **The size can change**: a file may shrink or grow between
`fileSize` and the reads, so a reader that gets `0` before the size it planned
for has a file that shrank, and a server that has sent `Content-Length` must
close the connection there.

- *Tests:* `file_read_at`, `file_size_large`.

**`fileClose(fd: i32): i32`** closes the descriptor and answers `0` or a
negative errno; either way the descriptor is gone. It is never retried. A
call on a closed descriptor is `-9`, as is one on a negative descriptor
(under Node too, where `fs` would throw a range error), but nothing checks a use after close: the
number may already name another file the program opened since (recorded
open, [docs/security/runtime.md](security/runtime.md), RT-50).

- *Tests:* `file_read_at_pos`.

All four are **`fs.read`** ([capabilities](#capabilities); `caps_file_read`,
`reject_file_read_denied`) and `write` effects, so none may be called in a
`scope()` task or a parallel body (`reject_file_fd_type` for the descriptor's
`i32`, `reject_file_read_task`). Under Node they read through `fs.openSync`,
`fs.readSync`, `fs.fstatSync` and `fs.closeSync`, with the size a `bigint`.
Under `--profile wasi` they read through WASI's `path_open`, `fd_pread` and
`fd_filestat_get`, from the directories the host preopens. **A freestanding
`wasm32` build has no file system to read**, and a call is refused at check
time: `` `fileOpen` reads a file, and a freestanding wasm32 build has no file
system to read (build with `--profile wasi`) `` (NL2718;
`reject_file_open_wasm`). The `--profile wasm` runtime defines the four
answering `-38` (`ENOSYS`), so a link that names them never fails.

The ones that answer an `i32` answer the platform's errno values,
untranslated, and the same numbers under Node; the ones shown here are
Linux's, so compare against a negative result. A `wasm32` build has none of
these, and a WASI build answers `-ENOSYS` from the three that take a mode, as
WASI has no file modes to set.

**Bytes out, and the string route.** A native string is `{len, bytes}`,
never validated as UTF-8, and `write`, `writeError`, `writeFileSync` and
`appendFileSync` send its `len` bytes as they are, so a string built by
`String.fromBytes` from any bytes, all 256 values included, leaves exactly
as it came in (`tests/cases/io_write_bytes`, compared with
`io_write_bytes.bin` byte for byte). That route is native-only. Under the
prelude (`runtime/nish.mjs`) `String.fromBytes` makes each byte one UTF-16
unit, which leaves as UTF-8, so a byte above 127 becomes two; under
`--emit-ts` the bytes decode as UTF-8 and a byte that is not UTF-8 becomes
U+FFFD. `writeBytes` and `writeFileBytesSync` send a `u8[]` as it is on
every host, and are the route for bytes that are not text.

Paths are relative to the working directory. `readFileSync`,
`readFileSyncOrNull` and `readFileBytesSync` treat a file longer than
2^31 − 1 bytes as one they cannot read, in both number modes, which matches
Node. Every path, name and argument a builtin hands the OS that holds a NUL
byte is refused as a missing path is — `null`, `false`, `-1` or
`cannot …`, whichever that builtin answers — where Node refuses it by
throwing ([docs/security/runtime.md](security/runtime.md), RT-1, RT-3, RT-4). These are globals, not
`import { readFileSync } from "fs"` (bare imports are rejected), and so are
`write`, `writeError` and `panic` above. A user function of the same name
wins, as it does for every identifier builtin.

### Directories and subprocesses

Reference: [`nish:fs`](reference/nish-fs.md), [`nish:process`](reference/nish-process.md).

| Function | Takes | Gives | Effect |
| --- | --- | --- | --- |
| `mkdirSync` | `string` | `boolean` | write |
| `isDirectorySync` | `string` | `boolean` | write |
| `spawnSync` | `string[]` | `number` | write |
| `spawnSyncTo` | `string[], string, string` | `number` | write |
| `spawnPiped` | `string[], readonly u8[], u8[], u8[]` | `i32` | write |
| `readdirSync` | `string` | `string[] \| null` | write |
| `realpathSync` | `string` | `string \| null` | write |

**`mkdirSync(path: string): boolean`** creates **one** directory, mode
`0777 & ~umask`, not recursive, exactly like Node's `fs.mkdirSync(p)` with
no options. It answers `true` when a directory exists at `path` once the
call returns, whoever made it; `false` for every other outcome, a plain file
at `path` included.

- *Tests:* `io_mkdir`; `reject_mkdir_arity`, `reject_mkdir_type`.

**`isDirectorySync(path: string): boolean`** does one `stat`: `true` when a
directory exists at `path` as the call runs, `false` for everything else. It
is the question `-o <dir>` asks of a path, and the `stat` half of
`mkdirSync`, which calls it (WP14 §7a).

- *Tests:* `io_is_directory`; `reject_is_directory_arity`,
  `reject_is_directory_type`.

**`spawnSync(argv: string[]): number`** runs `argv[0]`, searched on `PATH`,
and waits for it. It answers its exit status, or `128 + n` when signal `n`
killed it (the shell's convention). It answers `-1` for an **empty** vector,
a child that cannot be started or waited for, and always on WASI, which has
no processes. The child inherits this process's environment, streams and
working directory.

- *Tests:* `io_spawn`; `reject_spawn_arity`, `reject_spawn_element_type`.

**`spawnSyncTo(argv: string[], stdoutPath: string, stderrPath: string): number`**
is the same run, with each stream sent to a file created or truncated at
`0644`. An **empty** path leaves that stream inherited, and a
symbolic link as a path's last component is refused, which answers `-1`.
The two paths must not name one file; capture them apart and concatenate.

- *Tests:* `io_spawn_to`, `io_spawn_to_inherit`; `reject_spawn_to_arity`,
  `reject_spawn_to_type`.

**`spawnPiped(argv: string[], stdin: readonly u8[], stdout: u8[], stderr: u8[]): i32`**
is the same run, with every stream a pipe: the child reads
`stdin` and then end of file, and its stdout and stderr are **appended** to
`stdout` and `stderr`. It answers the status, `128 + n`, or `-1` as for
`spawnSync` (and for a failed pipe or `poll`). A stream past **16 MiB**
(`NISH_PIPED_CAP`) kills the child with `SIGKILL` and answers `-2`. The
child holds no descriptor of the program but its three streams, and the
program's SIGPIPE from a child that stopped reading is absorbed. The two
output arrays are grown by the runtime, so they are push receivers to the
arena analysis, and `readonly` is refused for them, as is a typed-array
spelling (`Int32Array`, ...), whose length is fixed.

- *Tests:* `io_spawn_piped`, `mem_spawn_piped_scope`;
  `reject_spawn_piped_arity`, `reject_spawn_piped_element_type`,
  `reject_spawn_piped_stdin_type`, `reject_spawn_piped_output`,
  `reject_spawn_piped_typed_output`, `reject_spawn_piped_wasm`,
  `reject_using_arena_spawn_piped`.

**`spawnPipedWithin(argv: string[], stdin: readonly u8[], stdout: u8[], stderr: u8[], timeoutMs: i32): i32`**
is `spawnPiped`'s run with a deadline `timeoutMs` milliseconds after the
call, on the monotonic clock; a **negative** `timeoutMs` is none, and the run
is `spawnPiped`'s. It gives every answer `spawnPiped` gives, and **`-3`** when
the deadline passes first: the child's pid is killed with `SIGKILL` and
reaped, and the bytes read before then stay in `stdout` and `stderr`. The
deadline covers the **whole** run, the wait for the child after its streams
close included, so a child that closes its output and keeps running is `-3`
too. Only the child's own pid is killed, never a process group: a grandchild
still holding an output pipe keeps the run going until the deadline, which
turns an exit 0 into `-3`, and is left running. The arguments are checked as
`spawnPiped`'s, the fifth as an `i32`.

- *Tests:* `io_spawn_piped_within`; `reject_spawn_piped_within_arity`,
  `reject_spawn_piped_within_element_type`,
  `reject_spawn_piped_within_timeout_type`,
  `reject_spawn_piped_within_output`,
  `reject_spawn_piped_within_typed_output`,
  `reject_spawn_piped_within_wasm`,
  `reject_using_arena_spawn_piped_within`.

**`readdirSync(path: string): string[] | null`** answers the directory's
entries, **sorted ascending by bytes**, without `.` and `..`. It answers
`null` when the directory cannot be read at all, a *different* answer from
the empty array of an empty directory. A WASI build always answers `null`:
`fd_readdir` lists a preopened directory rather than a path, which is a
different contract and not a port of this one.

- *Tests:* `io_readdir`, `io_readdir_null`; `reject_readdir_arity`,
  `reject_readdir_type`, `reject_readdir_unchecked`.

**`realpathSync(path: string): string | null`** answers `path` resolved to
an **absolute** path with no symbolic link, `.`, `..` or repeated
separator, or `null` when it does not resolve. POSIX `realpath` needs every
component but the last to exist, so "does not resolve" is one answer rather
than several, and the answer the caller asked for rather than an error. The
result is copied into the arena and narrowed with `if (p !== null)` like any
other nullable (WP19 §5a item 4).

- *Tests:* `io_realpath`; `reject_realpath_arity`, `reject_realpath_type`.

All five answer a value where they could have exited, for the reason
`readFileSyncOrNull` answers `null` (WP14 B3): the language has no exceptions,
so a driver has to be able to turn the failure into its own diagnostic. They
exist so that a compiler written in Nish can create its own `-o dir/`,
tell `-o out` meaning a directory from `-o out` meaning a file, and shell out
for `--link` — `mkdirSync` and `spawnSync` are the calls
[wp14-selfhost.md](wp14-selfhost.md) §3a D4 named as the price of a
self-hosted link step, and `isDirectorySync` is the one §7a named as the price
of the last spelling of `-o` that, at the time, only the TypeScript compiler
handled.

`spawnSync` and `spawnSyncTo` are the two builtins whose pointer argument the
runtime keeps: the spawn path copies each element's bytes pointer into a vector
that outlives the call, so the array escapes, a parameter passed to either is
never `nocapture`, and an array literal handed to one is never stack-allocated
(`io_spawn` pins all three). Nothing that can reach either is `willreturn`
either, because the child may never exit. The argument is checked down to its
element type: an `i32[]` is an array but not a command line
(`reject_spawn_element_type`). Arguments are passed as bytes, so an embedded NUL
truncates one.

`spawnSyncTo` is a second builtin rather than two more parameters on the first
because the language had no default parameters when it was added — and the alternative shape, answering
the output as a string, was refused for two reasons: the runtime would have to
buffer a child that can print more than memory holds, and a harness comparing
output against a golden wants the bytes on disk anyway, to diff and to keep
after a failure.

`spawnPiped` is the run whose streams stay in memory, for a child that takes
a secret: a password manager's or keychain's CLI reads it on stdin, and stdin
is the one place `ps`, `/proc/<pid>/environ` and the file system do not show.
Its shape is four arguments with the outputs as out-parameters, the way
`readBytesInto` fills a caller's array. The rejected shape answered a record
(`{ status, stdout, stderr }`): no builtin returns a class, and there is no
way to declare one the checker, both emitters and the TypeScript prelude would
share, so the record would have been the first and its own construct. The
out-parameters cost a caller two `const out: u8[] = []` lines; they also let a
loop reuse one pair of arrays. The runtime writes `stdin` and drains both
outputs in one `poll` loop, so a child that fills one pipe while the parent
waits on another cannot deadlock it, and the 16 MiB cap is the answer to the
reason `spawnSyncTo` gave for refusing to buffer: a child that prints more
than memory holds is stopped, with a code no exit status can be, rather than
followed (`docs/security/runtime.md`, RT-27 to RT-31).

`spawnPipedWithin` is the same run for a child that may never answer: a
credential helper waiting on a prompt nobody sees, or a tool hung on the
network. It is a fifth argument on a second builtin rather than an optional
one on `spawnPiped`, so `spawnPiped`'s IR and every program that calls it are
unchanged; `-3` is a code of its own because a caller tells a slow child from
a failed one (the deadline was the program's choice, so it may retry with a
longer one). The deadline is a point in time rather than a budget per wait:
the poll loop's waits and the final wait for the child all end at it, so the
whole call returns within `timeoutMs` plus the time a kill and a reap take.
It kills the pid and not a process group, because putting the child in a
group of its own would take it out of the terminal's job control, and the
program cannot know the child would not mind (`docs/security/runtime.md`,
RT-49).

`spawnWithFds` numbers the descriptors from 3 rather than taking a target
for each, because 3 onward is where a child that is handed descriptors looks
for them (systemd's socket activation, `LISTEN_FDS`), and a target list would
let a program aim one at 0 to 2 and lose the child's streams. The runtime
duplicates each source above the targets before the child's `dup2` reads it,
so an entry that is its own target or another's is never overwritten first
(`docs/security/runtime.md`, RT-40).

`readdirSync` sorts, which neither `readdir(3)` nor Node's `fs.readdirSync`
does, and that is a decision about this language rather than a convenience:
every caller of an unsorted listing would have to sort it before reading it,
and a run whose order is the file system's is a run that
differs between two machines. The sort is by **bytes**, like every other string
comparison here, so it agrees with Node's `.sort()` for ASCII names and can
differ for names that are not (`docs/wp13-differential.md`).

### The environment

Reference: [`nish:process`](reference/nish-process.md).

| Function | Takes | Gives | Effect |
| --- | --- | --- | --- |
| `getenv` | `string` | `string \| null` | write |

**`getenv(name: string): string | null`** answers the value of environment
variable `name` as the call runs, or `null` when it is **unset**; a variable
set to nothing (`CC=`) answers a zero-length string. The bytes are copied
into the arena, so the result outlives any later change to the environment.
It is narrowed with `if (cc !== null)` like any other nullable (WP19 R1).

- *Tests:* `io_getenv`; `reject_getenv_arity`, `reject_getenv_type`,
  `reject_getenv_unchecked`.

It is a **call and not `process.env.CC`**, and that is a language decision
rather than a spelling: `process.env.NAME` is member access on a key chosen at
runtime, which Phase 0 forbids outright
([wp19-stage0-retirement.md](wp19-stage0-retirement.md) §4). The two
`process.*` values the language does have — `process.argv`, and
`process.platform` / `process.arch` below — are fixed names with no key.

`null` and `""` are different answers, and a driver acts on the difference: an
unset `CC` means "use the default", and `CC=` means someone set it to nothing.
That is why the result is `string | null` and not a string that is empty when
nothing is there.

There is no `setenv`: a program can read its environment and pass an
environment on to a child through `spawnSync`, which inherits this process's,
but it cannot change its own. Nothing in the compiler needs to, and a setter
would make `getenv`'s "as the call runs" a much sharper caveat than it is.
Because of that, a test that depends on a variable is given one by the harness
— `tests/cases/<name>.env`, one `NAME=value` per line, read by both
`tests/run.js` and the differential runner so the native binary and the Node
rewrite see the same environment.

Two reads of one variable in a function are two calls: the declaration is not
`readonly`, because a `setenv` from linked C — this program cannot call one,
but a library linked beside it can — may change the answer between them, so
LLVM may not fold the second read into the first.

The value is what `getenv(3)` answers, so it is bytes, and every offset into
it is a byte offset.

### The clock

Reference: [`nish:process`](reference/nish-process.md).

| Function | Takes | Gives | Effect |
| --- | --- | --- | --- |
| `monotonicNanos` | nothing | `i64` | write |
| `wallClockNanos` | nothing | `i64` | write |

**`monotonicNanos(): i64`** reads `CLOCK_MONOTONIC` in nanoseconds. The
origin is arbitrary, so only the **difference** between two reads means
anything.

- *Tests:* `io_monotonic`; `reject_monotonic_arity`.

**`wallClockNanos(): i64`** reads `CLOCK_REALTIME` in nanoseconds since
1970-01-01 UTC, as an `i64`. It can go backwards when the system time is
set, so a duration is `monotonicNanos`'s job. It is not refused on wasm, as
the monotonic clock is.

- *Tests:* `wall_clock`; `reject_wall_clock_arity`.

It is an `i64` in both number modes and not a `number`, because a `number` is an
`i32` by default and would overflow inside a tenth of a second, and an `f64`
loses nanoseconds after about 104 days of uptime.

It is the **monotonic** clock and not the wall clock, and the type cannot say so,
so the name does. An elapsed time measured from a wall clock has to survive that
clock being corrected mid-run, and it cannot: the difference can come out
negative. The wall clock is `Date.now()`, below, and it is the only part of
`Date` there is: a program that formats a date needs a calendar, a time zone
database and a locale, none of which the language has. The ISO calendar is a
library instead: `nish/temporal` is TC39 `Temporal`'s dates, times, instants
and durations, with no zone but UTC yet ([`nish/temporal`](reference/temporal.md)).

The effect is `write` rather than `none` for the reason `getenv` is not
`readnone`: the clock is not memory LLVM is tracking, so two reads with work
between them must not fold into one. A `readnone` clock would make every measured
interval exactly zero, which `io_monotonic` is the test for.

### The host: the wall clock, entropy, file times and signals

Four facts a program that runs for days asks of the machine (WP34 N3): what time
it is, bytes nobody can predict, whether a file was renewed, and whether it has
been asked to stop. All four are C in `runtime/runtime-host.c`, a translation
unit of its own with its own `.text*` ceiling, which `scripts/build.sh` compiles
beside `runtime.c` as it does the others.

Reference: [`nish:fs`](reference/nish-fs.md), [`nish:process`](reference/nish-process.md), and [the globals page](reference/builtins.md) for `Date.now` (under `DateConstructor`) and `crypto`.

| Function | Takes | Gives | Effect |
| --- | --- | --- | --- |
| `Date.now` | nothing | `f64` | write |
| `crypto.getRandomValues` | `u8[]` | `void` | write |
| `statMtimeSync` | `string` | `f64` | write |
| `signalFd` | nothing | `i32` | write |
| `readSignal` | `i32` | `i32` | write |

**`Date.now(): f64`** answers the wall clock, `CLOCK_REALTIME`, in **whole
milliseconds** since 1970-01-01 UTC, as JavaScript answers it. The
milliseconds are counted as integers and then converted, so the value is
exact and a time before 1970 floors. It is an `f64` in both number modes,
because an `i32` of milliseconds overflowed in January 1970. It can go
backwards when the clock is corrected, so an interval is
`monotonicNanos`'s job, not this one's.

- *Tests:* `os_now`, `os_now_i32`; `reject_os_date_now_arity`.

**`crypto.getRandomValues(bytes: u8[]): void`** fills every byte of `bytes`
from the kernel's CSPRNG. It takes **a `u8[]` only**, where the Web API
takes any integer typed array: the byte is the unit a key or a nonce is
written in, and a wider element would make the answer's byte order a fact
about the machine. It is **a statement**, where the Web API also answers its
argument, which the caller already holds. An empty array is filled with
nothing. It fills **at most 65,536 bytes a call**, the Web API's limit: more
is a panic,
`crypto.getRandomValues: <n> bytes asked for, and one call fills at most 65536`,
exit 1. A source that fails is a panic too; nothing weaker is ever
substituted.

- *Lowering:* `getrandom(2)` on Linux, looping over `EINTR` and short reads,
  and `getentropy(3)` in 256-byte chunks on macOS.
- *Tests:* `os_random`, `os_random_limit`; `reject_os_random_i32`,
  `reject_os_random_u32`, `reject_os_random_string`,
  `reject_os_random_readonly`, `reject_os_random_value`,
  `reject_os_random_arity`, `reject_os_crypto_member`,
  `reject_os_crypto_value`, `reject_thread_region_random`.

**`statMtimeSync(path: string): f64`** answers the modification time in
milliseconds since the epoch, **with the sub-millisecond fraction** kept. It
is computed as Node's `mtimeMs` is (seconds × 1e3 plus nanoseconds ÷ 1e6,
in doubles), so the two print the same digits. It answers **NaN** when the
path cannot be stat'd, because an `f64` has no `null`
([Nullable types](#nullable-types)); test it with `m !== m`. `stat` follows a
symbolic link, and a directory has a time of its own. Also exported by
`nish:fs`.

- *Tests:* `os_mtime`, `os_mtime_import`; `reject_os_mtime_type`,
  `reject_os_mtime_arity`, `reject_os_mtime_nullable`.

**`signalFd(): i32`** answers a descriptor that becomes readable when
**SIGTERM or SIGINT** arrives: the read end of a pipe a `sigaction` handler
writes one byte to per signal, so the signals' default action never runs.
The handler runs in whichever thread the signal lands on, so a `scope()`
task or a parallel worker running when `signalFd()` is called cannot take
the signal and end the process, and nothing is blocked for a spawned child
to inherit. It overrides a disposition the process started with, as
`process.on("SIGTERM")` does under Node. It is made **once**; `-1` when it
cannot be made. Also exported by `nish:process`.

- *Tests:* `os_signal`, `os_signal_import`; `reject_os_signal_fd_arity`.

**`readSignal(fd: i32): i32`** blocks until one of the two signals arrives
and answers **15** or **2**; `-1` for an `fd` that is not `signalFd()`'s and
for a read that fails. The argument is an `i32` in both number modes, and an
`f64`, an `i64` or a string is refused rather than converted. Also exported
by `nish:process`.

- *Lowering:* not `willreturn`.
- *Tests:* `os_signal`, `os_signal_import`; `reject_os_signal_f64`,
  `reject_os_signal_i64`, `reject_os_signal_string`,
  `reject_os_signal_arity`.

**`Date` has one member.** `new Date()`, `Date()`, `Date.parse`, `Date.UTC`,
any other member, and `Date` or `Date.now` used as a value are all refused under
one rule: `` `new Date()` is refused: Nish has no `Date` object; the one `Date`
member is `Date.now()`, the wall clock in milliseconds `` (NL2401;
`reject_os_date_new`, `reject_os_date_call`, `reject_os_date_parse`,
`reject_os_date_utc`, `reject_os_date_value`, `reject_os_date_bare`). A local
named `Date` shadows the global as any local does, so calling it is the
ordinary `` Unknown function `Date` `` (`reject_os_date_shadowed`). **`crypto`
has one member** the same way: `` `crypto.randomUUID` is refused: the one
`crypto` member is `crypto.getRandomValues(bytes)` `` (NL2403). The array
`getRandomValues` fills is written, so a `readonly u8[]` is refused as a store
through it is, a parameter it fills is never `readonly` in the IR, and inside a
scope's region it is refused on an array a task may read, as `fill` is. Anything
but a `u8[]` is `` `crypto.getRandomValues` fills a `u8[]`, got i32[] ``
(NL2402).

**A descriptor, not a handler.** A handler would be a callback the runtime
calls, which a [function reference](#function-references) is not, and would
run between any two instructions of the program. A descriptor is what a server's loop can wait on beside its sockets
(WP34 N5 will add that wait); until then `readSignal` is the blocking read.
Underneath it is a handler rather than a Linux `signalfd`, because a `signalfd`
hears only a signal blocked in every thread, and a mask reaches only the thread
that sets it. A child that `spawnSync` or `spawnSyncTo` starts after
`signalFd()` can still be stopped by either signal, because `exec` resets a
caught signal to its default (`os_signal`). Signals other than SIGTERM and
SIGINT are not in the language.

**On wasm.** A `wasm32` target and the `wasi` profile have no host for these to
reach, and `runtime-host.c` is empty there, so all five are refused by the
checker: `` `Date.now` reaches the operating system, and a wasm32 build has none
to reach `` (NL2404; `reject_os_now_wasm`, `reject_os_random_wasm`,
`reject_os_mtime_wasm`, `reject_os_signal_fd_wasm`, `reject_os_read_signal_wasm`).

**The TypeScript reading** ([wp33-round-trip.md](wp33-round-trip.md) §2).
`Date.now` is **class A**: Node's is the same floored `CLOCK_REALTIME`, and the
`os_` block of `tests/run.js` holds both readings between two reads of Node's
own clock. `statMtimeSync` is **class A** under `runtime/nish.mjs`, which answers
`fs.statSync(path, { throwIfNoEntry: false })?.mtimeMs`, or NaN: the `os_`
block sets a file's mtime to a fraction of a millisecond and requires the
native build and the prelude both to print Node's `mtimeMs` for it.
`crypto.getRandomValues` is **class A under the prelude** and class C without
it: Node's own takes only a typed array and a `u8[]` is a plain `Array` there,
so the prelude replaces the method on Node's `crypto` with one that fills a
plain array too and panics past 65,536 with the native words; `os_random` and
`os_random_limit` run unmodified under it. `signalFd` and `readSignal` are
**class C**, with no synchronous reading at all: Node delivers a signal only to
its event loop, which a blocking `readSignal` never returns to, so the prelude's
versions throw rather than answer. The row in
[wp33-round-trip.md](wp33-round-trip.md) §3.5 gives the translation.

### Children and the machine: `spawn`, `kill`, `waitPid`, `availableParallelism`, `totalMemory`

What a supervisor asks of the host (WP34 N12): start a child without waiting
for it, stop it, reap it when it ends, and size itself to the machine it runs
on. All five are C in `runtime/runtime-os.c`, beside `spawnSync`, and each is
exported by `nish:process` as well as being a global.

Reference: [`nish:process`](reference/nish-process.md).

| Function | Takes | Gives | Effect |
| --- | --- | --- | --- |
| `spawn` | `string[]` | `i32` | write |
| `spawnWithFds` | `string[], readonly i32[]` | `i32` | write |
| `kill` | `i32, i32` | `i32` | write |
| `waitPid` | `i32, i32` | `i32[]` | write |
| `availableParallelism` | nothing | `i32` | none |
| `totalMemory` | nothing | `i64` | none |

**`spawn(argv: string[]): i32`** starts `argv[0]` exactly as `spawnSync`
does and answers the child's **pid** at once, **without waiting**, or a
**negative errno** (-22 for an empty vector or an argument holding a NUL).
**Test `pid > 0` before handing the answer on**: a failure passed to
`waitPid` reads as "any child". A child never reaped stays a zombie until the
program exits.

- *Tests:* `os_spawn`; `reject_os_spawn_type`, `reject_os_spawn_wasm`.

**`spawnWithFds(argv: string[], fds: readonly i32[]): i32`** is `spawn`,
with the child holding `fds[i]` as descriptor **`3 + i`**, close-on-exec
cleared there. **No other descriptor** of this process reaches it but one
opened without close-on-exec, which nothing the runtime opens is. More than
**64** descriptors, or a negative one, is `-22` before anything is opened or
started. The child shares each descriptor's open file, offset and status
flags, and this process keeps its own. It answers its pid, or a negative
errno.

- *Tests:* `spawn_fds_child`, `caps_process_spawn_fds`;
  `reject_spawn_fds_arity`, `reject_spawn_fds_element`,
  `reject_spawn_fds_argv`, `reject_spawn_fds_wasm`.

**`kill(pid: i32, sig: i32): i32`** sends `sig` to `pid` and answers 0, or a
negative errno. It takes **only 0, 2 (SIGINT), 9 (SIGKILL) and 15
(SIGTERM)**, whose numbers are the same on Linux and Darwin; any other `sig`
is -22, and so is a `pid` of 0 or below, which `kill(2)` reads as more than
one process. A positive pid may be any process of this user, not only a
child ([RT-19](security/runtime.md)).

- *Tests:* `os_kill`; `reject_os_kill_f64`, `reject_os_kill_wasm`.

**`waitPid(pid: i32, flags: i32): i32[]`** reaps a child (`pid` a child's or
**-1 for any child**; flag **1 is WNOHANG**) and answers a fresh
**`[pid, status]`**, the status as `spawnSync`'s; a failure puts the
negative errno first. After `signalFd()` a blocking wait never sees EINTR,
because that handler is installed with `SA_RESTART` and the wait restarts.
It is an array because the language has no tuple.

- *Tests:* `os_wait`, `os_spawn`, `os_kill`; `reject_os_wait_arity`,
  `reject_os_wait_wasm`.

**`availableParallelism(): i32`** answers the CPUs this program may use,
**at least 1**: the smallest of the CPUs online, its affinity mask or
cpuset, a cgroup v2 CPU quota rounded up, and a positive
`NISH_NUM_THREADS`, which can lower the count and never raise it. It needs
no `--threads`.

- *Tests:* `os_cpu`; `reject_os_cpu_arity`, `reject_os_cpu_wasm`.

**`totalMemory(): i64`** answers bytes of **physical memory**, or **-1**
where the host does not say. It is the machine's, not a cgroup's limit.

- *Lowering:* `_SC_PHYS_PAGES` times the page size on Linux, `hw.memsize` on
  Darwin.
- *Tests:* `os_memory`; `reject_os_memory_wasm`.

**Capabilities.** `spawn`, `kill` and `waitPid` carry `process.spawn`, the
label `spawnSync` carries: each reaches other processes — `kill` any process of
this user, as kill(1) does, not only a child `spawn` started — so none takes a
label of its own (`caps_process_wait`).
`availableParallelism` and `totalMemory` carry **none**: how many cores and
bytes the machine has is a fact about the host, as `process.platform` is, read
to size a program rather than to reach anything (`caps_host`).

**In a task.** `spawn`, `kill` and `waitPid` write state outside the program,
so a scope's task or a parallel body that calls one — under any import alias —
is refused as any shared write is (`reject_os_spawn_task`,
`reject_os_kill_task`, `reject_os_wait_task`, `reject_os_kill_task_alias`,
`reject_os_kill_parallel`). `availableParallelism` and `totalMemory` write
nothing and may be called there (`tests/link/thread_host_facts_task`).

**On wasm.** A `wasm32` target has no processes and no host to ask, so all five
are refused by the checker with the N3 rule's words: `` `spawn` reaches the
operating system, and a wasm32 build has none to reach `` (NL2404;
`reject_os_spawn_wasm`, `reject_os_kill_wasm`, `reject_os_wait_wasm`,
`reject_os_cpu_wasm`, `reject_os_memory_wasm`).

**The TypeScript reading.** `kill`, `availableParallelism` and `totalMemory`
are **class A** under `runtime/nish.mjs`: `kill` checks the signal and the pid
as the native one does and turns Node's error code back into its errno;
`availableParallelism` is `os.availableParallelism()` lowered by
`NISH_NUM_THREADS` (Node reads no cgroup quota, so inside a container with one
the two can differ); and `totalMemory` is `os.totalmem()`, a `bigint` as every
`i64` is there. `spawn` and `waitPid` are **class C**: Node reaps its children
itself, on the event loop, so a synchronous wait has nothing to find, and the
prelude's versions throw, naming themselves, rather than answer (the `os_`
block of `tests/run.js`).

### Scheduling: `setNice`, `setIdlePriority`, `setCpuAffinity`

How much of the CPU the program asks for, and where: a batch job or a background indexer
steps aside for the interactive work on the machine, and a prefork worker keeps to one core. Each is C in
`runtime/runtime-os.c`, and each is exported by `nish:process` as well as
being a global.

Reference: [`nish:process`](reference/nish-process.md).

| Function | Takes | Gives | Effect |
| --- | --- | --- | --- |
| `setNice` | `i32` | `i32` | write |
| `setIdlePriority` | nothing | `i32` | write |
| `setCpuAffinity` | `i32` | `i32` | write |

**`setNice(n: i32): i32`** sets the **nice value** with
`setpriority(PRIO_PROCESS, 0, n)` and answers 0, or a negative errno. It is
**lower-only**, even as root: outside 0..19 is `-22` and below the current
value is `-13`, both with no system call, so the priority never rises.
Children started afterwards inherit it.

- *Tests:* `os_nice`; `reject_os_nice_wasm`, `reject_os_nice_task`.

**`setIdlePriority(): i32`** moves the program to **`SCHED_IDLE`** with
`sched_setscheduler(0, SCHED_IDLE, …)` and answers 0 or a negative errno. It
is **Linux only**: Darwin answers -95 (Linux's EOPNOTSUPP, as `nish:net`
spells it). **An unprivileged process can never leave `SCHED_IDLE`**, and an
idle process can **starve** on a saturated machine, so a caller keeps a
normal-priority fallback for work that must finish.

- *Tests:* `os_nice`; `reject_os_idle_wasm`.

**`setCpuAffinity(cpu: i32): i32`** pins the calling process to the one CPU
`cpu` with `sched_setaffinity` and answers 0, or a negative errno. It is
**narrow-only**: a `cpu` outside the CPUs the process may already run on
(`taskset`, a cgroup) is `-22` with no change. `availableParallelism()`
answers 1 afterwards. It is **Linux only**: -95 on Darwin and under Node.

- *Tests:* `link/net_prefork_pin`; `reject_os_affinity_wasm`,
  `reject_os_affinity_task`.

**Per thread.** Linux keeps both the nice value and the policy per thread: a
call sets the calling thread's and every thread started after it. So both
belong at the top of `main`, before a `scope()` or a parallel loop starts the
pool, and a task or a parallel body that calls one is refused as any shared
write is (`reject_os_nice_task`). Neither ever crashes the program: a failure
is only the answer.

**Capabilities.** Both carry `process.spawn`, the label `kill` carries: neither
reaches another process, but the priority is the one the program's children
inherit, and a step down cannot always be taken back.

**On wasm.** A `wasm32` target schedules nothing of the host's, so both are
refused by the checker with the N3 rule's words (NL2404;
`reject_os_nice_wasm`, `reject_os_idle_wasm`).

**The TypeScript reading.** Both are **class C** under `runtime/nish.mjs`:
Node has `os.setPriority` but no `SCHED_IDLE`, and a reading of one without
the other would differ from the native build on the same host, so both throw,
naming themselves.

### `nish:net`: addresses, non-blocking TCP and UDP, and the readiness loop

Sockets for a program that owns its loop (WP34 N5): a server listens, accepts
and reads and writes bytes, a client connects, or either binds and trades
datagrams, and every socket is
**non-blocking**, so a call that
would wait answers "would block" instead, and the program decides what to do
next. There is no callback, and an [`async` function](#async-functions-async-and-await)
cannot wait on a socket yet (its tasks run on an in-process queue): the program
is the loop, and it waits in [`pollWait`](#the-readiness-loop) for
whichever of its descriptors is ready. Every socket is also **close-on-exec**,
so a child that `spawnSync` starts inherits none of them. All twenty-six functions
are C in
`runtime/runtime-net.c`, a translation unit of its own with its own `.text*`
ceiling, which `scripts/build.sh` compiles beside `runtime.c` as it does the
others; section GC leaves every one of them out of a program that calls none
(the `net_` block of `tests/run.js` links one and counts the symbols). Each is
exported by `nish:net` and is a global too, as every `nish:` export is.

Reference: [`nish:net`](reference/nish-net.md).

| Function | Takes | Gives | Effect |
| --- | --- | --- | --- |
| `netAddress` | `u8[], string, i32` | `i32` | write |
| `netLocalPort` | `i32` | `i32` | write |
| `tcpListen` | `string, i32, i32` | `i32` | write |
| `tcpListenFlags` | `string, i32, i32, i32` | `i32` | write |
| `tcpAccept` | `i32, u8[]` | `i32` | write |
| `netRead` | `i32, u8[], i32, i32` | `i32` | write |
| `netWrite` | `i32, readonly u8[], i32, i32` | `i32` | write |
| `netWrite2` | `i32`, two ranges | `i32` | write |
| `netShutdown` | `i32, i32` | `i32` | write |
| `netClose` | `i32` | `i32` | write |
| `netSetOption` | `i32, i32, i32` | `i32` | write |
| `netMss` | `i32` | `i32` | write |
| `unixListen` | `string, i32, i32` | `i32` | write |
| `unixListenMode` | `string, i32, i32, i32` | `i32` | write |
| `unixConnect` | `string` | `i32` | write |
| `unixAccept` | `i32` | `i32` | write |
| `unixSocketPair` | `i32, i32[]` | `i32` | write |
| `sendFd` | `i32, i32, readonly u8[], i32, i32` | `i32` | write |
| `recvFd` | `i32, u8[], i32, i32, i32[]` | `i32` | write |
| `peerCredentials` | `i32, i32[]` | `i32` | write |
| `netRingState` | none | `i32` | write |

**`netAddress(out: u8[], host: string, port: i32): i32`** writes the
[address form](#the-address-form) of a **numeric** host and `port` into
`out`. It answers `0`, or `-22`, leaving `out` as it was. No `nish:net` call
looks a name up; [`nish/net/dns`](../std/net/dns.ts) resolves it first.

- *Tests:* `net_tcp_calls`, `net_tcp_import`; `reject_net_unknown_export`.

**`netLocalPort(fd: i32): i32`** answers the port the socket is bound to: the
one the kernel chose for a listen on port `0`.

- *Tests:* `net_tcp_calls`, `net_tcp_echo`.

**`tcpListen(host: string, port: i32, backlog: i32): i32`** answers a
listening socket on a numeric host with `SO_REUSEADDR`. `"::"` hears both
families, and on a kernel without IPv6 it is IPv4's `0.0.0.0`. It answers
`-98` when the port is in use.

- *Tests:* `net_tcp_calls`, `net_tcp_echo`, `net_dual_stack`;
  `reject_net_arity`, `reject_net_wasm`.

**`tcpListenFlags(host: string, port: i32, backlog: i32, flags: i32): i32`**
answers `tcpListen`'s socket, with flags. `1` is `SO_REUSEPORT`, which
differs by platform as the table below shows. `2` is `TCP_NODELAY`, which the
runtime sets on every accepted connection, on every platform, closing one on
which it cannot. `4`, with `1`, steers each connection to the listener of the
CPU that received it, Linux only (`-95` elsewhere, `-22` without `1`). `8`
(`NET_LISTEN_RING`) accepts into io_uring slots on Linux, as
[slot handles](#slot-handles) say, and does nothing elsewhere. Any other bit
is `-22` before a socket is made.

- *Tests:* `net_tcp_reuseport`, `net_tcp_nodelay`, `net_ring_calls`,
  `link/net_tcp_reuseport_spread`, `link/net_tcp_nodelay_shared`;
  `reject_net_reuseport_wasm`, `reject_net_nodelay_wasm`.

**`tcpAccept(fd: i32, peer: u8[]): i32`** answers the next waiting
connection, non-blocking and close-on-exec, with the peer's address in
`peer`. It answers `-11` when none is waiting, and a `peer` shorter than 18
bytes is `-22` before a connection is taken.

- *Lowering:* not `willreturn`: on a blocking socket the program inherited it
  waits.
- *Tests:* `net_tcp_calls`, `net_tcp_echo`; `reject_net_accept_readonly`.

**`netRead(fd: i32, buf: u8[], off: i32, len: i32): i32`** reads at most
`len` bytes into `buf[off, off + len)`. It answers the count, `0` at the end
of the stream, or `-11` when nothing is waiting. The range is
[checked](#bounds).

- *Tests:* `net_tcp_echo`, `net_tcp_bounds`; `reject_net_readonly`,
  `reject_net_element`, `reject_net_import_wasm`.

**`netWrite(fd: i32, buf: readonly u8[], off: i32, len: i32): i32`** writes
at most `len` bytes of `buf[off, off + len)`. It answers the count, which may
be short. A peer that has gone is **`-32`, never SIGPIPE**, so a closed
connection cannot end the process. The range is [checked](#bounds).

- *Tests:* `net_tcp_echo`, `net_tcp_bounds`; `reject_net_write_element`.

**`netWrite2(fd: i32, a: readonly u8[], aOff: i32, aLen: i32, b: readonly u8[], bOff: i32, bLen: i32): i32`**
writes two ranges in **one system call**, answered as `netWrite` is, `-32`
and never SIGPIPE included. Both ranges are [checked](#bounds), `a`'s first.
As for every call here, a `wasm32` build refuses it and Node throws.

- *Lowering:* `sendmsg` with two `iovec`s.
- *Tests:* `tests/link/net_write2`, `net_write2_bounds`;
  `reject_net_write2_element`, `reject_net_write2_element_a`,
  `reject_net_write2_wasm`.

**`netShutdown(fd: i32, how: i32): i32`** shuts the read side (`0`), the
write side (`1`) or both (`2`).

- *Tests:* `net_tcp_calls`.

**`netClose(fd: i32): i32`** closes the descriptor, which is gone after the
call whatever the answer.

- *Lowering:* not `willreturn`, because a socket the program inherited with a
  linger time can wait.
- *Tests:* `net_tcp_calls`, `net_tcp_echo`; `reject_net_fd_type`.

**`netSetOption(fd: i32, option: i32, value: i32): i32`** sets one
[socket option](#socket-options) from a whitelist. Any other `option` is
**`-22`**, so there is no way to pass a raw level and name through.
`NET_TCP_QUICKACK` is Linux's, **`-95` elsewhere**.

- *Tests:* `net_set_option`; `reject_net_set_option_wasm`.

**`netMss(fd: i32): i32`** answers the maximum segment size a connected TCP
socket sends, or **a plain `-1`, never an errno,** for every other descriptor
and every call on wasm. It never panics.

- *Lowering:* Linux's `TCP_INFO` `tcpi_snd_mss`, or `TCP_MAXSEG` where that
  is not above `0` and on Darwin.
- *Tests:* `net_mss`; `reject_net_mss_arity`, `reject_net_mss_type`;
  `net_mss` in `tests/run.js` for wasm32 and WASI.

**`unixListen(path: string, backlog: i32, flags: i32): i32`** answers a
listening [Unix-domain](#unix-domain-sockets) stream socket at `path`, whose
file only its owner may connect to (`0600`). Its paths and refusals are under
that heading.

- *Tests:* `net_unix_calls`, `net_unix_paths`, `net_unix_fds`;
  `reject_net_unix_arity`, `reject_net_unix_wasm`.

**`unixListenMode(path: string, backlog: i32, flags: i32, mode: i32): i32`**
answers `unixListen`'s socket with the file's mode chosen, `0` to `0o777`,
set before the listen so no connect gets in under a wider one. An abstract
name is `-22`.

- *Tests:* `net_unix_paths`, `net_unix_calls`.

**`unixConnect(path: string): i32`** answers a new socket, non-blocking and
close-on-exec, connected to the listener at `path`. A full backlog is `-11`
on Linux and `-111` on Darwin.

- *Tests:* `net_unix_calls`, `net_unix_paths`; `reject_net_unix_path_type`.

**`unixAccept(fd: i32): i32`** answers the next waiting connection,
non-blocking and close-on-exec; no peer address is written.

- *Tests:* `net_unix_calls`.

**`unixSocketPair(kind: i32, fds: i32[]): i32`** writes two connected
sockets into `fds`, non-blocking and close-on-exec, of kind `1`
(`NET_UNIX_STREAM`) or `2` (`NET_UNIX_SEQPACKET`). Kind `2` is **`-95` on
Darwin**.

- *Tests:* `net_unix_calls`, `net_unix_fds`; `reject_net_unix_pair_element`,
  `reject_net_unix_pair_readonly`.

**`sendFd(sock: i32, fd: i32, buf: readonly u8[], off: i32, len: i32): i32`**
sends bytes over the Unix socket `sock` with one copy of `fd` riding on them
(`SCM_RIGHTS`). A `len` of `0` is **`-22`**, a socket of another family
**`-95`**, and a gone peer `-32`, never SIGPIPE. The range is
[checked](#bounds).

- *Tests:* `net_unix_scm`, `net_unix_scm_bounds`; `reject_net_unix_scm_arity`,
  `reject_net_unix_scm_wasm`.

**`recvFd(sock: i32, buf: u8[], off: i32, len: i32, fd: i32[]): i32`**
receives bytes from the Unix socket `sock`, with the first descriptor the
message carried in `fd[0]`, or **`-1`**; every further one is closed before
the answer. The one kept is close-on-exec and **not** made non-blocking. The
range is [checked](#bounds).

- *Tests:* `net_unix_scm`, `net_unix_scm_bounds`;
  `reject_net_unix_scm_element`, `reject_net_unix_scm_readonly`,
  `reject_net_unix_scm_buf_readonly`, `reject_net_unix_scm_wasm`.

**`peerCredentials(fd: i32, out: i32[]): i32`** writes the pid, uid and gid
of the process at the other end of a connected Unix socket, as the kernel
recorded them **when the connection was made**, not who holds the other end
now. A socket with no peer is **`-107`** on every platform. On Darwin the pid
is `-1` where the SDK has no `LOCAL_PEERPID` or the kernel refuses it.

- *Tests:* `net_unix_scm`, `caps_net_peer`; `reject_net_unix_peer_arity`,
  `reject_net_unix_peer_readonly`, `reject_net_unix_peer_element`,
  `reject_net_unix_scm_wasm`.

**`netRingState(): i32`** answers whether `NET_LISTEN_RING` listeners accept
into rings: `1` when they do, `0` until a listener has found rings or a
refusal, or the negative errno the kernel refused rings with (`-1` when a
seccomp filter refuses `io_uring_setup`, `-38` for a kernel without it), and
then they serve descriptors. The first listener that finds rings or a refusal
decides for the process; one whose rings fail for want of descriptors or
memory serves descriptors itself, and a later listener asks again.
It is `-95` on Darwin.

- *Tests:* `net_ring_calls`, `link/net_ring_fallback`;
  `reject_net_ring_arity`, `reject_net_ring_wasm`.

#### Slot handles

A connection `tcpAccept` takes from a `NET_LISTEN_RING` listener on Linux is
a **slot handle**: a number at or above 2^20 that names a slot in one of the
process's io_uring rings, not a descriptor, so a process holds connections
past its `RLIMIT_NOFILE`. Its `peer` is written as zeros.

- `netRead`, `netWrite`, `netWrite2`, `netClose`, `netLocalPort`,
  `pollAdd`, `pollModify`, `pollRemove` and `pollWait` take a slot handle as
  they take a descriptor, with the same readiness contract: `-11` until
  `pollWait` reports it, then progress. A slot is in one loop at a time: a
  `pollAdd` to a second loop answers `-17` until the first loop removes it
  or is closed.
- `netShutdown` shuts a slot down through the ring, behind the bytes already
  written: the peer reads them and then the end of the stream. After a shut
  writing side (`how` 1 or 2) `netWrite` answers `-32`; after a shut reading
  side (`how` 0 or 2) `netRead` answers what is queued and then `0`. A `how`
  past 2 answers `-22`.
- `netMss` answers `-1`: the ring has no route to `TCP_MAXSEG`.
- `netSetOption` answers `-95`: the slot's socket belongs to the ring. Every
  other call that takes a descriptor (`sendFd`, `peerCredentials`, FFI)
  answers `-9`, and so does every call on a handle after its `netClose`.
- `tcpAccept` answers `-23` when every slot its listener may hold is taken:
  up to 64 rings, each of as many slots as the soft descriptor limit, at most
  16,384. A slot freed by `netClose` takes a waiting connection again.
- A ring listener whose accept finds memory short (`-12`, `-105`) answers
  that errno from `tcpAccept` once, as a descriptor does, pauses accepting
  for 10 ms, doubling to 640 ms while it recurs, and then accepts again.
  Waiting connections stay in the listener's backlog meanwhile. Any other
  errno but `-11`, `-4`, `-103` or `-71` means the listener is broken: it
  stops accepting and `tcpAccept` answers that errno from then on. Close the
  listener and listen again.
- A slot holds at most 256 KiB of bytes the kernel has not yet sent: a
  `netWrite` past that copies what fits, and a full slot answers `-11` until
  the peer reads. Its received bytes queue up to the same bound before the
  runtime stops receiving for it.
- A slot whose connection has failed, a peer's reset or a failed send,
  answers `netWrite` and `netWrite2` with the errno, `-104` for a reset.
  `netRead` answers it once the queued bytes are read, and on every read
  after, where a descriptor answers it once and then `0`.
- Where the kernel refuses rings, the listener serves descriptors and
  `netRingState` answers why; a program written against the readiness
  contract runs the same either way.

- *Tests:* `link/net_ring_beyond_limit`, `link/net_ring_full`,
  `link/net_ring_sink`, `link/net_ring_flood`, `link/net_ring_halfclose`,
  `link/net_ring_starve`, `link/net_ring_reset`, `link/net_ring_transient`,
  `link/net_ring_fallback`.

What `tcpListenFlags`'s flag `1` does on each platform:

| Platform | Flag `1` |
| --- | --- |
| Linux | Listeners that share the port each get new connections, spread by a hash of the connection's 4-tuple; only listeners of the same user may share |
| Darwin | Listeners share the port, but one of them takes the connections: the flag buys a restart without a gap rather than a spread; flag `4` is `-95` |
| `wasm32`, `--profile wasi` | Refused at compile time with NL2404, as every `nish:net` call is |

**Errors are numbers.** Every call answers an `i32`: `>= 0` is success (a
descriptor, a count, `0`), and a negative number is the failure's errno,
negated. The codes a loop branches on are **Linux's numbers on every platform**:
`-11` would block, `-95` unsupported, `-32` the peer has gone, `-104` the
connection was reset, `-98` the address is in use, `-111` the connection was
refused, `-110` it timed out, `-88` not a socket and `-22` a bad argument; the Darwin runtime
translates its own. Any other failure is the host's `-errno`
(`-9` for a descriptor that is not open, on both). `-95` is what `tcpAccept`
answers for a datagram socket, on both (`net_udp_calls`). A number rather than a
`Result`, because no builtin answers one and a failure here is routine, and
because a number allocates nothing. It follows the shape `signalFd` set, where
a negative `i32` is a failure, and adds the errno to it: `signalFd` and
`readSignal` answer a plain `-1` for any failure (and `readFileBytesSync`
answers `null`), while a `nish:net` call says which failure it was, so a loop
tells "would block" from "the peer has gone" without asking again. No
`nish:net` call touches the arena (`net_tcp_echo` serves two hundred messages
in a loop whose pass scope gives back what each pass builds, and prints `flat`
when that moved the arena no further than one message did).

#### Socket options

`netSetOption`'s `option` is one of five ids `nish:net` exports, each an `i32`
and each a global too. They are the runtime's own numbers, not the kernel's,
so a program reads the same on Linux and Darwin, and the runtime maps each to
its level and name; there is no raw passthrough, because a level, a name and a
length the program spells is an untyped call into the kernel.

| Id | Value | Sets | `value` |
| --- | --- | --- | --- |
| `NET_TCP_NODELAY` | `1` | `IPPROTO_TCP`, `TCP_NODELAY` | `1` sends a small write at once, `0` lets Nagle's algorithm batch it |
| `NET_TCP_QUICKACK` | `2` | `IPPROTO_TCP`, `TCP_QUICKACK`, Linux only; **`-95` on Darwin** | `1` acknowledges at once, `0` lets the kernel delay the ACK. Linux does not keep the mode: it leaves it on its own, so a server that wants one sets it again after every response |
| `NET_SO_KEEPALIVE` | `3` | `SOL_SOCKET`, `SO_KEEPALIVE` | `1` probes an idle connection |
| `NET_SO_SNDBUF` | `4` | `SOL_SOCKET`, `SO_SNDBUF` | bytes; Linux doubles the value it stores |
| `NET_SO_RCVBUF` | `5` | `SOL_SOCKET`, `SO_RCVBUF` | bytes; Linux doubles the value it stores |

An id is read as a value, as `platform` is: it folds to its number in the IR,
cannot be assigned, and is not a [module constant](#module-constants), so a
module constant cannot be initialised from one. A local of the same name
shadows the global spelling.

`netMss`'s `-1` is one answer, not an errno, because a program does the same
thing for every reason there is no MSS: it uses a size of its own. That is also
why it compiles on wasm when `netSetOption` is refused there: a socket option a
program sets is an effect a wasm build cannot have, while a size it reads has
an honest answer everywhere, "none".

#### The address form

An address is **18 bytes of a `u8[]`**: the 16 bytes of an IPv6 address, with
an IPv4 address written as the mapped `::ffff:a.b.c.d`, then the port,
big-endian, so `127.0.0.1:8080` is ten zeros, `255 255`, `127 0 0 1`, `31 144`
(`net_tcp_calls`). One form for both families, in memory the caller owns, so a
server that accepts a million connections allocates nothing to learn who they
are from.

**Both families on one socket.** `net_dual_stack` listens on `"::"`, and the
`net_` block of `tests/run.js` connects to it from Node over `127.0.0.1` and
then over `::1`: the first peer arrives as `::ffff:127.0.0.1` and the second as
`::1`, each with Node's own port in the last two bytes, and both are echoed.
Its UDP socket, bound to `"::"` too, sends itself a datagram with each ECN mark
to its IPv4 address and to its IPv6 one, and reads every mark back from
`meta[1]` over both. That needs a host with IPv6: where `::1` cannot be listened
on, `"::"` is the IPv4 fallback above, and the check says so and passes rather
than counting a skip. CI's `ubuntu-latest` has IPv6 and runs it.

#### The client half

| Function | Takes | Gives | Effect |
| --- | --- | --- | --- |
| `tcpConnect` | `readonly u8[]` | `i32` | write |
| `connectResult` | `i32` | `i32` | write |

**`tcpConnect(addr: readonly u8[]): i32`** makes a new TCP socket,
non-blocking and close-on-exec, that starts connecting to the
[address](#the-address-form) in `addr`, and answers its descriptor **at once,
while the connection is still being made**; the loop reports it writable when
that has finished. Any other failure closes the socket and is answered
instead of it.

- *Tests:* `net_tcp_connect`, `net_tcp_connect_import`;
  `reject_net_connect_element`, `reject_net_connect_arity`.

**`connectResult(fd: i32): i32`** answers how the connection went, asked once
`fd` is writable: `0`, or its failure from `SO_ERROR`, such as **`-111` for a
port nobody listens on**. The kernel clears the failure as it is read.

- *Tests:* `net_tcp_connect`, `net_tcp_connect_import`;
  `reject_net_connect_wasm`.

A connection is made the way everything else here waits: in the loop. Linux
answers `EINPROGRESS` even over loopback, so a program asks for writability and
not for an answer from the call. Neither call waits, so both are `willreturn`,
and neither allocates. `net_tcp_connect` is a Nish client and a Nish server in
one loop: two exchanges of 1 and 200 messages come back byte for byte with the
arena where it stood, and a port that was bound and closed again answers `-111`
and then `0`. The `net_` block of `tests/run.js` runs it under a timeout, so a
lost wake fails the run rather than hangs it.

```ts
const addr: u8[] = new Array<u8>(18);
netAddress(addr, "127.0.0.1", 8080);
const fd = tcpConnect(addr);          // the descriptor, still connecting
pollAdd(loop, fd, 2, 1);              // writable once it has finished
// ... pollWait until token 1 comes back ...
if (connectResult(fd) === 0) {
  pollModify(loop, fd, 1, 1);         // connected: now wait to read
}
```

#### UDP

| Function | Takes | Gives | Effect |
| --- | --- | --- | --- |
| `udpBind` | `string, i32, i32` | `i32` | write |
| `udpSendTo` | `i32`, a range, `to`, `segment`, `ecn` | `i32` | write |
| `udpRecvFrom` | `i32`, a range, `from`, `meta` | `i32` | write |

**`udpBind(host: string, port: i32, flags: i32): i32`** answers a datagram
socket, non-blocking and close-on-exec, bound as `tcpListen`'s is, `"::"` and
its IPv4 fallback included. Flag `1` is `SO_REUSEPORT`, flag `2` is
`UDP_GRO`, and flag `4`, with flag `1` and a group size N from 1 to 255 in
bits 8 to 15, **steers QUIC**: a classic-BPF reuseport program hands each
datagram to the port's socket number (byte 0 of the Destination Connection
ID) mod N, in bind order ([docs/h3-multicore.md](h3-multicore.md)). A refused
attach closes the socket and answers the errno. Flag `4` without `1`, with
`2` or with N `0`, N without `4`, and any other bit are `-22`; flags `2` and
`4` are `-95` on Darwin.

- *Tests:* `net_udp_calls`, `net_udp_echo`, `net_udp_offload`,
  `net_dual_stack`, `net_quic_prefork`; `reject_net_udp_wasm`,
  `reject_net_udp_parallel`.

**`udpSendTo(fd: i32, buf: readonly u8[], off: i32, len: i32, to: readonly u8[], segment: i32, ecn: i32): i32`**
sends `buf[off, off + len)` to `to`, cut by the kernel into datagrams of
`segment` bytes when that is above `0` (**GSO**), with `ecn` as the IP
header's two ECN bits. The range is [checked](#bounds).

- *Lowering:* one `sendmsg`. Not `willreturn`: on a blocking socket the
  program inherited it waits.
- *Tests:* `net_udp_calls`, `net_udp_echo`, `net_udp_offload`,
  `net_udp_bounds`; `reject_net_udp_send_element`, `reject_net_udp_arity`,
  `reject_net_udp_task`.

**`udpRecvFrom(fd: i32, buf: u8[], off: i32, len: i32, from: u8[], meta: i32[]): i32`**
receives the next datagram into `buf[off, off + len)`, cut to `len`, with its
sender in `from`, its **GRO** segment size in `meta[0]` and its ECN bits in
`meta[1]`. It answers `-11` when none is waiting. The range is
[checked](#bounds).

- *Lowering:* one `recvmsg`. Not `willreturn`, as `udpSendTo`.
- *Tests:* `net_udp_calls`, `net_udp_echo`, `net_udp_offload`,
  `net_udp_bounds`; `reject_net_udp_readonly`, `reject_net_udp_meta_readonly`,
  `reject_net_udp_meta_element`, `reject_net_udp_element`,
  `reject_net_udp_region`.

A datagram carries no stream, so an echo is `udpRecvFrom` and then `udpSendTo`
back to `from`, which is already an address; the `net_` block of
`tests/run.js` drives `net_udp_echo` from Node's `dgram`, two hundred
datagrams in a round, and requires every byte back and the arena flat. An
empty datagram is a datagram: `udpRecvFrom` answers `0` for it, which is how
`net_udp_echo` ends a round. A socket that is IPv4 — bound to an IPv4 host, or
to `"::"` on a kernel without IPv6 — sends to a mapped `::ffff:a.b.c.d`
address as IPv4 (`net_udp_calls`).

**Segmentation offload.** On Linux, one `udpSendTo` of 4,800 bytes with
`segment = 1200` leaves as four datagrams of 1,200, which a Node `dgram` socket
receives one by one. A socket bound with flag `2` receives what one such send
left as **one** datagram of up to 64 KB with `meta[0] == 1200`, while a socket
without it receives the four apart, each with `meta[0] == 0`
(`net_udp_offload`, run by the `net_` block). The kernel coalesces only
datagrams of one flow, and only those that arrive after the option is set,
which is why it is a flag of `udpBind`; on loopback it coalesces what left as
one GSO send, not datagrams sent one by one. The ECN bits a send asks for
arrive in the receiver's `meta[1]` (`net_udp_offload`). Measured on loopback,
Nish sender to Nish receiver, 1,200-byte datagrams: 459,000 a second at one
per call, and 1,760,000 a second sent with `segment = 1200` over 49,200-byte
sends.

**Darwin has none of the three.** There `udpSendTo` with a `segment` or an
`ecn` above `0`, and `udpBind` with flag `2`, answer `-95`, and `meta` is
always `0, 0`. A `meta[1]` of `0` is also what a datagram that really is not
ECN-capable reads as, so a receive on Darwin cannot say ECN is unsupported: a
program learns that from the `-95` a send with an `ecn` above `0` answers, and
on Darwin it reads every arrival as Not-ECT. CI's `runtime-net` (macos-latest)
job runs that branch: the `net_` sections there take the `-95` a GSO send and a
GRO bind answer, and fall back to one datagram a send (`net_loopback`,
`net_relay`), and `net_udp_offload` requires the `-95` of GSO, the GRO bind and
each ECN mark, with nothing sent by them while a plain send still arrives. On Linux no UDP call answers `-95`, and the code is pinned there
by `tcpAccept` on a datagram socket instead, above.

#### The readiness loop

| Function | Takes | Gives | Effect |
| --- | --- | --- | --- |
| `pollCreate` | nothing | `i32` | write |
| `pollAdd` | `i32, i32, i32, i32` | `i32` | write |
| `pollModify` | `i32, i32, i32, i32` | `i32` | write |
| `pollRemove` | `i32, i32` | `i32` | write |
| `pollWait` | `i32, i32[], i32` | `i32` | write |

**`pollCreate(): i32`** answers a loop: a descriptor, close-on-exec, that
watches others.

- *Lowering:* epoll on Linux, kqueue on Darwin.
- *Tests:* `net_loop_calls`, `net_loop_two`; `reject_net_poll_wasm`.

**`pollAdd(loop: i32, fd: i32, events: i32, token: i32): i32`** watches `fd`
for `events` (`1` readable, `2` writable) and reports it under `token`, an
`i32` of the program's choosing. It answers `-17` for a descriptor the loop
already watches.

- *Tests:* `net_loop_calls`, `net_loop_two`; `reject_net_poll_arity`,
  `reject_net_poll_parallel`.

**`pollModify(loop: i32, fd: i32, events: i32, token: i32): i32`** sets new
events or a new token for a watched descriptor. It answers `-2` for one the
loop does not watch.

- *Tests:* `net_loop_calls`, `net_loop_two`.

**`pollRemove(loop: i32, fd: i32): i32`** stops watching `fd`. It answers
`-2` for one the loop does not watch. Closing a descriptor stops the watching
too.

- *Tests:* `net_loop_calls`, `net_loop_two`.

**`pollWait(loop: i32, ready: i32[], timeoutMs: i32): i32`** waits until a
watched descriptor is ready or `timeoutMs` passes, **forever for a negative
one**, and writes a token and events pair per ready descriptor into `ready`,
**`4` added for a hang-up or an error**. It answers the count, at most 64, or
**`0` on a timeout**.

- *Lowering:* not `willreturn`, because it can wait forever.
- *Tests:* `net_loop_calls`, `net_loop_two`; `reject_net_poll_readonly`,
  `reject_net_poll_element`, `reject_net_poll_task`, `reject_net_poll_region`.

**Level-triggered.** A descriptor that is still ready when the program waits
again is reported again, so a loop that handles one pair of several, or leaves
a datagram unread, loses nothing: `net_loop_calls` sends a datagram and waits
twice, and both waits report it. The same is why the 64 a call reports at most
is a bound on a stack array rather than on the program: the rest are still
ready at the next wait. A UDP socket is always writable, and on Linux one whose
both sides are shut is readable, writable and hung up, `7` (`net_loop_calls`).
Nothing allocates; `ready` is the caller's.

**A signal wakes the loop.** The descriptor `signalFd()` answers is a
descriptor like any other, readable when SIGTERM or SIGINT arrives, so a server
adds it to its loop and shuts down when its token comes back: `readSignal`
then answers the number without waiting. A signal that interrupts the wait
itself makes `pollWait` answer **`0`**, as a timeout does, rather than wait on
past the deadline it was given; the loop comes round and the next wait finds
the signal descriptor ready (`tests/runtime-test.c`). Once the process has
opened a `NET_LISTEN_RING` listener with rings, for the rest of its life,
closed or not, the rings' own work interrupts the wait too, so an interrupted wait goes on to its deadline and only the signal
descriptor reports a signal. `net_loop_two` watches
two UDP sockets and `signalFd()` in one loop, and the `net_` block of
`tests/run.js` drives it from Node: it writes to one socket and waits for the
line that says that socket woke the loop before it writes to the other, in both
orders, and then sends SIGTERM, which wakes the loop through the signal
descriptor; the program reads `15`, prints `flat` because the arena stood
where it did at the top of every pass, and exits `0`.

```ts
const loop = pollCreate();
pollAdd(loop, server, 1, 1);
pollAdd(loop, signalFd(), 1, 2);
const ready: i32[] = new Array<i32>(32);
let running = true;
while (running) {
  const n = pollWait(loop, ready, -1);
  for (let k = 0; k < n; k++) {
    if (ready[2 * k] === 2) {
      running = false;             // SIGTERM or SIGINT
    } else {
      serve(server);               // until it answers -11
    }
  }
}
```

**Darwin** is kqueue, with a filter per direction rather than a set of events,
and the runtime builds epoll's answers from the filters: `pollAdd` of a
descriptor already watched is `-17`, `pollModify` and `pollRemove` of one not
watched are `-2`, a descriptor added watching nothing holds a disabled read
filter so the loop still knows it, and a descriptor both readable and writable
is one pair, `3`, folded from its two filters' records. Three differences
stay. The `pollAdd` that answers `-17` leaves the descriptor, both ways, under
the token it gave rather than the old one. A descriptor watching nothing is
never reported: epoll still reports its hang-up or error as `4`, but a disabled
filter reports nothing. And a peer's half-close is `1` on Linux but `5`, `1|4`,
on Darwin: kqueue marks the read filter with end-of-file as soon as the FIN
arrives, and the runtime reads end-of-file as `4`, where epoll sets its
hang-up bit only once both directions are shut. CI's
`runtime-net` (macos-latest) job runs `net_loop_calls` and `net_loop_two` on a
mac, as it runs every `net_` section.

#### Unix-domain sockets

A Unix-domain socket is named by a path rather than a host and port, and
reaches only processes on the same machine. Once made, it is a descriptor like
any other: `netRead`, `netWrite`, `netShutdown`, `netClose` and the readiness
loop take it as they take a TCP one, and a peer that has gone is `-32` here
too. There is no address form: `unixAccept` writes no peer.

- **The path.** It is bytes up to the first NUL, so a NUL inside it is `-22`,
  as an empty path is. It must fit `sun_path` with its NUL: **107 bytes on
  Linux, 103 on Darwin**, and a longer one is `-36` before a socket exists,
  rather than the kernel's cut-short name binding a file the program never
  named. A relative path is the working directory's, and the limit is on the
  string as written, not the absolute path it resolves to.
- **Abstract names.** A path that starts with `@` is Linux's abstract
  namespace: the rest, at most 107 bytes, is the name, nothing is made on the
  file system and nothing is left behind when the socket closes. A bare `@` is
  `-22`. Darwin has none, and there every `@` path is **`-95`**. A file whose
  name starts with `@` is spelled `./@name`, which is a relative path like any
  other.
- **The file's mode.** A pathname listener's file is `0600` for `unixListen`,
  so only its owner may connect, and `unixListenMode`'s `mode` otherwise. The
  runtime sets it between the bind and the listen, while every connect is
  still refused, so the umask's mode is never one a client gets in under. A
  connect needs write permission on the file, and search permission on every
  directory above it, which is the real boundary: put the socket in a
  directory only the users who may connect can reach.
- **A path that exists.** A bind never replaces a file. A path that exists is
  `-98`, whatever is there, and flag `1`, `NET_UNIX_UNLINK_STALE`, clears only
  a socket file nothing listens on, the one a server that died left: the
  runtime connects to it, and only a refusal makes it unlink the file and bind
  again. On Linux a live listener, even one whose backlog is full, stays
  `-98`; a regular file, a directory or a link is `-17` and left alone. On
  Darwin a connect to a listener whose backlog is full is refused just as one
  to a dead file is, so the probe cannot tell them apart: there a socket file
  in the way is **`-95`** and left alone, and the flag never unlinks one;
  remove a file the program knows is its own with `unlinkSync`. The probe is
  a connection the live listener sees close at once. Between the probe and the
  unlink another process can bind the path, which is why the directory must
  be the program's own ([docs/security/runtime.md](security/runtime.md),
  RT-34).
- **Cleanup.** Closing a listener does **not** unlink its file: `unlinkSync`
  it when the server stops, or let the next start's flag `1` clear it. A
  `unixListen` that fails after its bind closes the socket and unlinks the
  file it made, so no failure leaves a descriptor or a file behind
  (`net_unix_fds` counts the descriptors around every failure, a chmod made
  to fail after the bind among them, and checks that none of the paths it
  named is left on disk).
- **Pairs.** `unixSocketPair` makes two sockets already connected to each
  other. `NET_UNIX_STREAM` is a byte stream, as a connection is;
  `NET_UNIX_SEQPACKET` keeps each write one message, so a read returns one
  message, never two run together (`net_unix_calls`). Darwin has no Unix
  seqpacket, and kind `2` there is `-95`.
- **Descriptors and credentials.** The descriptor `recvFd` gets for one
  `sendFd` sent is a new descriptor for the same open file, with its offset and
  status flags shared, as `dup` gives. `recvFd` keeps the
  first descriptor of a message and closes every other one before it answers,
  so a peer cannot leave this process holding descriptors it never asked for
  ([docs/security/runtime.md](security/runtime.md), RT-37). The one it keeps
  is close-on-exec, so a later `spawn` does not hand it on, but it is not made
  non-blocking: `netRead` on a blocking one waits, so set what the program
  needs on it before it joins a loop. `peerCredentials` names the process at
  the other end as the kernel recorded it at the connect; a peer that has
  changed its uid since, or passed the socket on, still reads as it was then
  (RT-39). On a TCP socket, or any socket not `AF_UNIX`, the three are
  `-95`, and on a descriptor that is not a socket `-88`, both before anything
  is sent or asked (`net_unix_scm`).

| Constant | Value | Meaning |
| --- | --- | --- |
| `NET_UNIX_UNLINK_STALE` | `1` | `unixListen`'s flag: clear a socket file nothing listens on |
| `NET_UNIX_STREAM` | `1` | `unixSocketPair`'s byte-stream kind |
| `NET_UNIX_SEQPACKET` | `2` | `unixSocketPair`'s message kind; `-95` on Darwin |

`NET_UNIX_UNLINK_STALE` and `NET_UNIX_STREAM` are both `1`, as
`NET_TCP_NODELAY` is: the constants are plain `i32`s, so the checker cannot
tell one passed where another belongs. Name the one the call takes.

On Darwin the calls are the same C under `#if`, with seven differences: no
abstract names (`-95`), no seqpacket pair (`-95`), flag `1` meeting a socket
file is `-95` rather than a probe, a connect to a full backlog is `-111`
rather than `-11`, `fcntl` after `accept` and `socketpair` where Linux
passes `SOCK_NONBLOCK | SOCK_CLOEXEC`, `fcntl` after `recvmsg` where Linux
passes `MSG_CMSG_CLOEXEC`, so a child another thread spawns between the two
inherits the descriptor `recvFd` keeps (RT-38), and `peerCredentials` reading
`getpeereid` and `LOCAL_PEERPID`, its pid `-1` where that refuses, where
Linux reads `SO_PEERCRED`. A listener has no peer: Linux answers its own
process's credentials there, and what Darwin answers is not yet seen on a
mac. CI does not run them on a mac yet.

#### Bounds

`netRead`, `netWrite`, `netWrite2` (each of its two ranges), `udpSendTo`, `udpRecvFrom` and `fileReadAt` check `0 <= off <= off +
len <= buf.length` **in the compiled code**, before the call, the way `dst.set(src, at)` checks the range it
writes, and a range outside it panics with the same words, `slice out of range:
[4, 9) of length 8`, exit 1 (`net_tcp_bounds`, `net_udp_bounds`, `net_write2_bounds`, `file_read_at_bounds`). A negative
`off` or `len` fails it. A `peer`, `out`, `to` or `from`
array shorter than 18 bytes, or a `meta` shorter than 2, is not a panic but
`-22`, from the runtime, because the length is the argument's
property rather than the program's arithmetic. So is a `ready` shorter than 2,
and `pollWait` never writes past `ready.length`, so it has no range to check.

#### Types, threads and wasm

- **Bytes only.** Each buffer is a `u8[]`, as `crypto.getRandomValues`'s is: a
  socket carries bytes, and a wider element would make the byte order on the
  wire a fact about the machine. Anything else is `` `netRead` fills a `u8[]`,
  got i32[] `` (NL2402; `reject_net_element`) for a buffer the call writes, and
  `` `netWrite` sends from a `u8[]`, got string `` (NL2405;
  `reject_net_write_element`, `reject_net_udp_send_element`) for the one it
  reads. `udpRecvFrom`'s `meta` holds numbers rather than bytes, a segment size
  up to 65,535 among them, so it is an `i32[]`, and anything else is
  `` `udpRecvFrom` fills an `i32[]`, got u8[] `` (NL2406;
  `reject_net_udp_meta_element`), and so is `pollWait`'s `ready`, whose tokens
  are the program's own `i32`s (`` `pollWait` fills an `i32[]`, got u8[] ``,
  `reject_net_poll_element`), and so is `unixSocketPair`'s `fds`
  (`` `unixSocketPair` fills an `i32[]`, got u8[] ``,
  `reject_net_unix_pair_element`), and so are `recvFd`'s `fd` and
  `peerCredentials`'s `out` (`reject_net_unix_scm_element`,
  `reject_net_unix_peer_element`). A path is a `string`, and anything else is
  refused (`reject_net_unix_path_type`). A descriptor, an offset, a length, a port, a
  backlog, `how`, the flags, a segment size, the ECN bits, a loop, the events,
  a token, a timeout, a socket option and its value, a pair kind and a mode are `i32` in both number modes, and an
  `f64` is refused rather than converted (`reject_net_fd_type`).
- **What is written.** `netAddress`'s `out`, `tcpAccept`'s `peer`,
  `netRead`'s `buf`, `udpRecvFrom`'s `buf`, `from` and `meta`, `pollWait`'s
  `ready`, `unixSocketPair`'s `fds`, `recvFd`'s `buf` and `fd` and
  `peerCredentials`'s `out` are written, so
  a `readonly` array there is refused as a store through it is
  (`reject_net_readonly`, `reject_net_accept_readonly`,
  `reject_net_udp_readonly`, `reject_net_udp_meta_readonly`,
  `reject_net_poll_readonly`, `reject_net_unix_pair_readonly`,
  `reject_net_unix_scm_readonly`, `reject_net_unix_scm_buf_readonly`,
  `reject_net_unix_peer_readonly`), a parameter one of
  them fills is never `readonly` in the IR, and `netWrite`'s `buf`,
  `netWrite2`'s `a` and `b`, `udpSendTo`'s `buf` and `to` and `sendFd`'s `buf` may be `readonly` (`net_udp_calls`, `net_write2_bounds`).
- **Threads.** Every call changes the kernel's state of a socket, which is a
  write its caller can see, and a loop is a socket's state as much as its
  bytes, so none may be made in a `scope()` task
  (`reject_net_task`, `reject_net_udp_task`, `reject_net_poll_task`) or a
  parallel body (`reject_net_parallel`, `reject_net_udp_parallel`,
  `reject_net_poll_parallel`), and a call that writes an array is refused in a
  scope's region on one a task may read, as `fill` is (`reject_net_region`,
  `reject_net_udp_region` for `meta` and `reject_net_poll_region` for
  `ready`).
- **On wasm.** A `wasm32` target and the `wasi` profile have no sockets for these
  to reach, and `runtime-net.c` is empty there, so every call is refused by the
  checker with the host builtins' words: `` `tcpListen` reaches the operating
  system, and a wasm32 build has none to reach `` (NL2404; `reject_net_wasm`,
  `reject_net_import_wasm`, `reject_net_udp_wasm`, `reject_net_poll_wasm`,
  `reject_net_reuseport_wasm`, `reject_net_set_option_wasm`,
  `reject_net_unix_wasm`). The freestanding `--profile wasm` link, which
  takes IR compiled for the host, has no `runtime-net.c` either, so a program
  that calls one fails there at the link, on the undefined `nish_` symbol.
  The one exception is `netMss`, which compiles under a `wasm32` target and
  the `wasi` profile to the constant `-1`, its descriptor still evaluated,
  with no runtime call (`net_mss` in `tests/run.js`).
- **Not yet.** No `nish:net` call resolves a name (`reject_net_unknown_export`):
  the stub resolver is the library module `nish/net/dns`, which drives these
  calls on the program's own loop. There is no
  `sendmmsg` or `recvmmsg`, no edge-triggered mode and no timer
  but `pollWait`'s timeout. A program that does not want a loop can still wait
  for a connection, a byte or a datagram by calling again on `-11`, as
  `net_tcp_echo` and `net_udp_echo` do.

**The TypeScript reading** ([wp33-round-trip.md](wp33-round-trip.md) §2) is
**class C**, as `signalFd`'s is: Node's sockets are asynchronous only, and a
socket becomes ready only to Node's event loop, which a program that owns its
loop never returns to. `runtime/nish.d.ts` declares `nish:net` and the globals,
so `npm run check` types these programs, and under `runtime/nish.mjs` each
function throws `` `netAddress` has no synchronous reading under Node: a socket
is ready only to the event loop, which a program that owns its loop never
returns to (docs/wp33-round-trip.md) `` rather than answer `-11` forever (the
`net_` block of `tests/run.js`, for `netAddress`, `tcpConnect`, `udpBind` and
`pollCreate`). The option ids are plain numbers, so they read the same
under Node as natively, and `netSetOption` throws rather than set one
(`net_set_option` in `tests/run.js`). `netMss` throws too rather than answer `-1`: Node's
`net.Socket` has no MSS to read, and a `-1` would be a guess that the program
keeps (`net_mss` in `tests/run.js`). The same holds for the Unix-domain calls: the
`NET_UNIX_` constants read natively, and each of the five calls throws
(`net_unix` in `tests/run.js`). In a browser there are no sockets at all.
A loop has no reading either: the one a Node program has is Node's own, which
it returns to between callbacks, and `pollWait` is a program that never
returns to it.

### `nish:term`: terminal input

What a program needs to run a full-screen terminal interface: read a key the
moment it is pressed, wait for one with a timeout that doubles as a frame
clock, and ask the terminal whether it is one, how big it is, and to stop
echoing and line-editing. None of it needs the `net` capability that a
`pollAdd(0)` and `netRead(0, …)` would carry; the six functions carry
[`tty`](#capabilities) instead. They are C in `runtime/runtime-term.c`, a
translation unit of its own with its own `.text*` ceiling, which section GC
leaves out of a program that calls none of them. Each is exported by
`nish:term` and is a global too, as every `nish:` export is. Linux and Darwin
only, and WASI as below.

Reference: [`nish:term`](reference/nish-term.md).

| Function | Takes | Gives | Effect |
| --- | --- | --- | --- |
| `readStdin` | `u8[], i32, i32` | `i32` | write |
| `waitStdin` | `i32` | `boolean` | write |
| `isTerminal` | `i32` | `boolean` | write |
| `terminalSize` | nothing | `i32[]` | write |
| `setRawMode` | `boolean` | `i32` | write |
| `setTerminalRestore` | `string` | `i32` | write |

**`readStdin(buf: u8[], off: i32, len: i32): i32`** reads at most `len` bytes
of stdin into `buf[off, off + len)`, **without waiting**. It answers the
count, `0` at the end of the stream, or `-11` when nothing is waiting. The
range is [checked](#bounds), and the buffer is a writable `u8[]`.

- *Tests:* `term_calls`, `term_import`; `reject_term_read_arity`,
  `reject_term_read_i32_buffer`, `reject_term_read_readonly`.

**`waitStdin(timeoutMs: i32): boolean`** waits until stdin is readable, its
end and an error included, or `timeoutMs` passes, for ever for a negative
one. It answers `false` when the time ran out or a signal ended the wait
early, but not for a Ctrl-Z and `fg` once `setRawMode(true)` has caught
SIGTSTP, after which the wait goes on for what is left. Before raw mode Linux
goes on with what is left and Darwin ends the wait.

- *Lowering:* not `willreturn`.
- *Tests:* `term_calls`, `term_import`, `term_pty`; `reject_term_wait_string`.

**`isTerminal(fd: i32): boolean`** answers whether the descriptor is a
terminal.

- *Lowering:* `isatty`.
- *Tests:* `term_calls`, `term_pty`; `reject_term_is_terminal_arity`.

**`terminalSize(): i32[]`** answers a fresh `[columns, rows]` of the terminal
on stdout, or on stderr when stdout is not one; **`[-25, 0]` for "not a
terminal"**.

- *Tests:* `term_calls`, `term_pty`, `mem_terminal_size_scope`;
  `reject_term_size_arity`.

**`setRawMode(on: boolean): i32`** puts stdin's terminal in raw mode (`true`)
or back as it was (`false`). It answers `0`, or `-25` when stdin is not a
terminal. `setRawMode(false)` is always safe.

- *Tests:* `term_calls`, `term_pty`; `reject_term_raw_number`,
  `reject_term_unknown_export`.

**`setTerminalRestore(bytes: string): i32`** keeps a copy of `bytes` for the
runtime to write to the terminal on stdout as the program ends, **replacing**
what it kept before. It answers `0`, `-25` when stdout is not a terminal and
`-7` (E2BIG) past `NISH_TERM_RESTORE_MAX`, 4096 bytes, both keeping what was
there. When they go out is under [Raw mode](#raw-mode).

- *Tests:* `term_restore`; `reject_term_restore_arity`,
  `reject_term_restore_number`, `reject_term_restore_wasm`.

**Errors are numbers**, in `nish:net`'s shape: `>= 0` is success and a negative
number the failure's errno, negated. The two a program branches on are the
same number on every platform: `-11`, nothing is waiting, and `-25`, not a
terminal. Any other is the host's own.

**stdin is never made non-blocking.** `O_NONBLOCK` belongs to the open file
description, which a shell shares with every program it starts, so a program
that set it and then crashed would leave the shell's own stdin non-blocking.
`readStdin` asks `select` with a timeout of `0` before it reads instead, and so
does `waitStdin`: Darwin's `poll` does not support devices, and answers a
terminal at once whether a key is waiting or not.

**The loop.** `waitStdin` is the frame clock: a game waits up to one frame for a
key, reads what came, advances the world and draws, so the wait costs nothing
when a key arrives early and the frame rate holds when none does.

```ts
import { readStdin, setRawMode, waitStdin } from "nish:term";

export const main = (): number => {
  setRawMode(true);
  const keys: u8[] = new Array<u8>(16);
  let running = true;
  while (running) {
    if (waitStdin(16)) {
      const n = readStdin(keys, 0, keys.length);
      if (n === 0 || (n < 0 && n !== -11)) {
        running = false; // stdin ended, or reading it failed
      }
      for (let i = 0; i < n && i < keys.length; i++) {
        if (keys[i] === 113) {
          running = false; // q
        }
      }
    }
    // advance and draw one frame
  }
  setRawMode(false);
  return 0;
};
```

#### Raw mode

Raw mode is `cfmakeraw`'s input side without its output side. Echo, line
editing, CR-to-NL translation, flow control (Ctrl-S, Ctrl-Q) and parity
stripping are off, bytes are 8 bits wide, and a read answers as soon as one byte
is there, so a key arrives as its bytes — an arrow as the three of `ESC [ A`.
Two things stay as they were:

- **`ISIG` stays on.** Ctrl-C is still SIGINT and ends the program, Ctrl-\ is
  still SIGQUIT and Ctrl-Z still stops it; none of them arrives as a byte (3,
  28, 26). A program that wants Ctrl-C as a key asks for SIGINT through
  [`signalFd`](#the-host-the-wall-clock-entropy-file-times-and-signals) and
  handles it in its loop. Keeping it means a program that is stuck in a loop
  can always be ended from the keyboard.
- **`OPOST` stays on**, so `"\n"` still moves to the start of the next line and
  output needs no `"\r\n"`.

**The terminal is always put back.** Each `setRawMode(true)` that enters raw
mode saves the termios that was there, and it comes back on
`setRawMode(false)`; when `main` returns or `process.exit` is called (an
`atexit` handler); on every panic, a failed check included, whose path ends in
`_exit` and so is given its own hook; and on every signal whose default action
ends the program, SIGKILL aside: SIGINT, SIGTERM, SIGQUIT and SIGHUP, SIGPIPE
from a reader that went away, SIGALRM, SIGUSR1, SIGUSR2, SIGPROF, SIGVTALRM,
SIGXCPU, SIGXFSZ and SIGSYS, and the faults a program dies of, SIGILL, SIGTRAP,
SIGABRT, SIGFPE, SIGBUS and SIGSEGV (a stack overflow, or a fault in C code a
program links). For each a handler is installed only when the program left it
at its default action: it restores the terminal, puts the default back and
raises the signal again, so the program still dies of it and its parent sees
that (exit status 143 for SIGTERM in `term_pty`). The handlers run on a 64 KiB
alternate stack of the thread that entered raw mode, or on the one that thread
already had, so a stack overflow there restores the terminal too. The mode is
marked raw once the switch is made, so a signal that ends the program while
`TCSAFLUSH` drains the output, or while SIGTTOU holds it stopped in the
background, leaves the terminal as it was. A program that
took SIGTERM or SIGINT through `signalFd` keeps it, and puts the terminal back
itself, or by returning. SIGKILL leaves raw mode behind, and so does a stack
overflow on a thread other than the one that called `setRawMode(true)`; `stty
sane` undoes either. SIGTSTP, Ctrl-Z, is caught the same way when it is at its
default, because no shell can be counted on to: bash puts its own termios back
while a job is stopped but does not give the job its raw mode back on `fg`, and
a shell without that bookkeeping puts back nothing. The handler restores the
terminal, stops the program, and once `fg` or `bg` continues it puts the handler
back and enters raw mode again, so the terminal is as it was while the program
is stopped and raw after `fg`; no `setRawMode` on another thread runs between
the two. A program continued in the background stops again, by SIGTTOU, until
`fg`. A `waitStdin` the stop interrupts goes on waiting until its timeout,
measured from when it began. Any other blocking call goes on where the system
restarts it after a handler (`SA_RESTART`), and ends early where it never
does, as a `pollWait` does after any signal. A stop by SIGSTOP, which no program can catch,
leaves the terminal raw at a shell that puts nothing back.
Job control also stops a program started in the background
(`app &`) when it calls `setRawMode(true)`, by SIGTTOU, as it stops any program
that sets the terminal, and the program enters raw mode on `fg`. Two threads that call `setRawMode` at
once take turns, so the termios saved is the one from before either.

**Restore bytes go out on the same paths.** The bytes `setTerminalRestore`
kept are written to stdout once, with `write` alone, before the termios comes
back, when `main` returns or `process.exit` is called, on every panic and on
each signal above whose default ends the program, raw mode or not: setting
them installs the same handlers. Ctrl-Z and `setRawMode(false)` do not end the
program, so they write nothing. A program sets them once it has switched the
terminal (`"\u001b[?1049h"` written, say) and again with each change, last
the set that undoes them all; a signal that lands while it does writes the
old string or the new one, whole. They are written at most once, however
many of those paths race. Output is not buffered, so all the program printed
reaches the terminal before them. `term_restore` under `script(1)` checks that
what follows its last line is exactly its bytes, once, after it returns,
panics and is killed by SIGTERM and by SIGSEGV, nothing after it cleared them,
and that `stty -g` reads as before.

The `term` block of `tests/run.js` runs `term_pty` under `script(1)`, which
gives it a pseudo-terminal: it is a terminal on both descriptors with a size,
enters raw mode twice and leaves twice, each `0`, and after it returns in raw
mode, panics in raw mode, and is killed by SIGTERM, and then by SIGSEGV, while
it waits in raw mode, `stty -g` reads what it read before. Where `script` is
missing or makes no terminal, that check is a counted skip that says which.

#### Where there is no terminal

| Host | `readStdin` | `waitStdin` | `isTerminal` | `terminalSize` | `setRawMode` | `setTerminalRestore` |
| --- | --- | --- | --- | --- | --- | --- |
| Linux, Darwin | as above | as above | `isatty` | the ioctl | as above | as above |
| A pipe or a file | as above | as above | `false` | `[-25, 0]` | `-25` for `true`, `0` for `false` | `-25`, `0` for `""`, `-7` past the cap |
| `--profile wasi` | **waits** for its bytes | as above | `false` | `[-25, 0]` | `-25` for `true`, `0` for `false` | `-25`, keeping nothing; `0` for `""`, `-7` past the cap |
| `--target wasm32`, freestanding | refused | refused | refused | refused | refused | refused |
| Node ([prelude](RUN_UNDER_NODE.md)) | throws | throws | `tty.isatty` | Node's `columns` and `rows` | throws | throws |
| A browser (`nish/runtime/browser`) | throws | throws | `false` | `[-25, 0]` | throws | throws |

WASI has `read` and `poll` on stdin and no terminal interface. There
`readStdin` reads without asking `poll` first, because Node's WASI answers a
zero-timeout poll of stdin with "nothing waiting" while bytes are, so it waits
for its bytes: call `waitStdin` first, as the loop above does. For the same
reason a `waitStdin` there waits at least 10 ms: Node's WASI counts a shorter
wait from before it looks at stdin, and on a busy machine answers "nothing
waiting" before it has looked. The checker
accepts the six there, unlike `nish:net`'s, and refuses them on a
freestanding `--target wasm32` build, whose runtime has no stdin
(`reject_term_wasm`). Under Node,
stdin is read only by the event loop, which a program that owns its loop never
returns to, and Node's own raw mode turns Ctrl-C into a byte, so the four
that would need either throw, each naming itself. The `term` and `term_wasi`
blocks of `tests/run.js` feed `term_calls` and `term_import` over a pipe —
four bytes after a delay, a pipe held open and never written, and a thousand
bytes — natively and under WASI, and expect the same lines from both.

### Arrays and strings as receivers

The reference for each member, with its parameters and its answer, is its doc comment on `Array`, `ReadonlyArray` or `String` in [`runtime/nish.d.ts`](../runtime/nish.d.ts); the rules are here.

| Member | On | Gives |
| --- | --- | --- |
| `length` | arrays | `number` |
| `push(v)` | arrays | `number` |
| `pop()` | arrays | `T` |
| `indexOf(v)` | arrays | `number` |
| `join(sep?)` | arrays | `string` |
| `set(src, offset?)` | arrays | `void` |
| `fill(value, start?, end?)` | arrays | `void` |
| `sort(cmp)` | arrays | `T[]` |
| `map(f)` | arrays | `U[]` |
| `filter(pred)` | arrays | `T[]` |
| `some(pred)`, `every(pred)` | arrays | `boolean` |
| `findIndex(pred)` | arrays | `number` |
| `forEach(f)` | arrays | `void` |
| `slice(start?, end?)` | arrays | `T[]` |
| `length` | strings | `number` |
| `charCodeAt(i)` | strings | `number` |
| `substring(start, end?)` | strings | `string` |
| `slice(start, end?)` | strings | `string` |
| `indexOf(sub, from?)` | strings | `number` |
| `startsWith(sub)`, `endsWith(sub)` | strings | `boolean` |
| `String.fromCharCode(c)` | strings | `string` |
| `String.fromBytes(bytes, start, end)` | strings | `string` |

**`a.length`** is a `number`; read-only.

- *Tests:* `arr_length`, `reject_arr_length_assign`.

**`a.push(v: T): number`** appends and returns the new length. An array
never grows past 2^31 − 1 elements, in either number mode: the push that
would fails as an allocation does, `nish: out of memory` and exit 1
(`tests/link/cg_sec_push_limit`).

- *Lowering:* grows capacity by doubling (4 from 0) through
  `nish_array_grow`.
- *Tests:* `arr_push`; `reject_arr_push_type` (`Cannot push string onto i32[]`).

**`a.pop(): T`** removes and returns the last element. An empty array
**panics** and exits 1 (`index out of range: 0 >= 0`) — there is no
`undefined` to return; behind a test that the array holds an element, such
as `if (a.length > 0)`, the check is proven away (`panics_pop`). The
capacity is untouched, so the next `push` reuses the storage.

- *Tests:* `arr_pop_index`; `reject_arr_pop_arity`.

**`a.indexOf(v: T): number`** answers the first index whose element is
`=== v`, or `-1`: strings by content, classes / interfaces / arrays by
identity, floats with `fcmp oeq` (a `NaN` element is never found, as in
JavaScript).

- *Lowering:* a scan in the emitted code.
- *Tests:* `arr_pop_index`; `reject_arr_index_of_type`.

**`a.join(sep: string = ","): string`** is for **`string[]` only**
(`` `join` requires string[], got i32[] ``, `reject_arr_join_elem`). Element
conversion would allocate per element, which is the quadratic shape `join`
exists to replace ([wp14-selfhost.md](wp14-selfhost.md) §3). Like a
concatenation, its result is held to 2^31 − 1 bytes: a longer one fails as
an allocation does, `nish: out of memory` and exit 1, before anything is
allocated ([CG-3](security/codegen.md)).

- *Lowering:* one pass summing the lengths, one allocation, one `memcpy` per
  part.
- *Tests:* `arr_join`, `cg_sec_join_limit`; `reject_arr_join_elem`.

**`a.set(src: T[], offset: number = 0): void`** copies every element of
`src` into `a` from `offset` on, with `TypedArray.prototype.set`'s meaning.
**Arrays of numbers only**, of any width and ranged integers included, and
`src` has `a`'s own element type. A statement. See
[Bulk writes](#bulk-writes-set-and-fill).

- *Tests:* `bytes_set_disjoint`, `bytes_set_self`, `bytes_set_end`,
  `bytes_set_oob`, `bytes_set_overlap`, `bytes_set_float_oob`,
  `bytes_set_u64_oob`; `reject_bytes_set_string`, `reject_bytes_set_type`,
  `reject_bytes_set_arity`, `reject_bytes_set_readonly`,
  `reject_bytes_set_value`.

**`a.fill(value: T, start: number = 0, end: number = a.length): void`**
stores `value` into every slot of `[start, end)`, each end relative and
clamped as `TypedArray.prototype.fill`'s are. **Arrays of numbers only**. A
statement. See [Bulk writes](#bulk-writes-set-and-fill).

- *Tests:* `bytes_fill`, `bytes_fill_zero`, `bytes_offset_float`,
  `bytes_offset_u64`; `reject_bytes_fill_record`, `reject_bytes_fill_arity`,
  `reject_bytes_fill_value`, `reject_bytes_fill_index`,
  `reject_bytes_fill_value_position`, `reject_bytes_fill_readonly`.

**`a.sort(cmp: (a: T, b: T) => number): T[]`** sorts `a` in place,
**stably**, and answers `a` itself, as `Array.prototype.sort` does: the
order is element for element Node's for any consistent comparator. `cmp`
answers a negative number, zero or a positive number, and only "positive or
not" is read, so `-0` and `NaN` count as zero.

**The comparator is required**: `a.sort()` compares as strings in
JavaScript and is refused
(`` `sort` needs a comparator: write `xs.sort((a, b) => a - b)` ``, NL2620);
a second argument is refused too (`` `sort` takes one comparator ``,
NL2619). A `readonly T[]` is refused (`` Cannot `sort` through readonly ``),
and so is `process.argv` (`` `process.argv` is read-only ``, as `push` is).
`a - b` panics on `i32` elements a full range apart (`[2147483647, -1]`);
`(a, b) => (a > b ? 1 : a < b ? -1 : 0)` cannot overflow.

The comparator is a compile-time function argument
([Function parameters](#function-parameters)): a top-level function, or an
arrow, which may read the `const` locals and parameters of the function it
is written in; an arrow reading a `let` is refused
(`reject_arr_sort_capture_let`). See [Sorting](#sorting-with-a-comparator).

- *Lowering:* compiled to `std/sort.ts`'s `sortWith`, a merge sort over runs
  of 32 sorted by insertion, instantiated once per comparator with the
  comparator called directly; it is copied into the module that sorts.
- *Tests:* `arr_sort_cmp`, `arr_sort_cmp_f64`, `arr_sort_cmp_record`,
  `arr_sort_edge`, `arr_sort_capture`, `arr_sort_overflow`;
  `reject_arr_sort_no_comparator`, `reject_arr_sort_arity`,
  `reject_arr_sort_readonly`, `reject_arr_sort_argv`,
  `reject_arr_sort_capture_let`.

**`a.map(f: (x: T[, i: number]) => U): U[]`** answers a new array of
`f(a[i])` (or `f(a[i], i)`) for each element, in order, as
`Array.prototype.map` gives. The callback takes one or two parameters; a
third, JavaScript's array argument, is refused
(`` The callback of `map` takes 3 parameters, and Nish passes at most two … ``,
NL2698), and so is a second argument to `map` itself (JavaScript's
`thisArg`). It is a compile-time function argument under the comparator's
rule. See [Callback methods and `slice`](#callback-methods-and-slice).

- *Lowering:* compiled to `std/array.ts`'s `map` or `mapIndexed`, called
  directly.
- *Tests:* `arr_map`, `arr_map_f64`, `arr_map_template`;
  `reject_arr_map_third_param`, `reject_arr_map_this_arg`,
  `reject_arr_map_capture_let`.

**`a.filter(pred: (x: T[, i: number]) => boolean): T[]`** answers a new
array of the elements `pred` keeps, in order. `pred` answers `boolean`
(`reject_arr_filter_not_boolean`); the callback rules are `map`'s.

- *Tests:* `arr_filter`; `reject_arr_filter_not_boolean`.

**`a.some(pred)`, `a.every(pred)`: `boolean`** answer whether some (every)
element satisfies `pred`, stopping at the first that decides; an empty array
answers `false` (`true`).

- *Tests:* `arr_some_every`.

**`a.findIndex(pred): number`** answers the first index `pred` accepts, or
`-1`. There is **no `find`**: TypeScript types its answer `T | undefined`
and Nish has no `undefined`, so `xs.find(f)` is refused and points here
(`` `find` is not supported: TypeScript types its answer `T | undefined` … ``,
NL2697).

- *Tests:* `arr_find_index`; `reject_arr_find`.

**`a.slice(start: number = 0, end: number = a.length): T[]`** answers a copy
of `a[start..end)`, with `s.slice`'s rule: `0 <= start <= end <= a.length`,
or the program **panics** with
`slice out of range: [start, end) of length len` and exits 1, where
JavaScript counts a negative index from the end and clamps the rest. It
takes zero to two arguments (NL2699), each a `number`, where `s.slice` takes
any integer type. It works on a `readonly T[]`, and the copy is a mutable
`T[]`.

- *Tests:* `arr_slice`, `arr_slice_bounds`; `reject_arr_slice_args`.

**`s.length`** is a `number`, the UTF-8 byte length.

- *Tests:* `str_length`.

**`s.charCodeAt(i: number): number`** answers the **byte** at `i`,
bounds-checked against `s.length` exactly as `a[i]` is — out of range
panics and exits 1, where JavaScript answers `NaN`, which `number` cannot
hold.

- *Lowering:* no call: a `load i8`.
- *Tests:* `str_bytes`; `reject_str_char_code_arity`.

**`s.substring(start: number[, end: number]): string`** answers the bytes
of `[start, end)`, `end` defaulting to `s.length`. Both ends are clamped
into `[0, s.length]` and then swapped into order, as in JavaScript, so
`s.substring(5, 0)` is `s.substring(0, 5)` and a negative offset is `0`.

- *Lowering:* one allocation and one `memcpy` (`nish_str_new`). The clamp is
  two `llvm.smin` / `llvm.smax` calls per bound and is **not** emitted for a
  bound the compiler can place in `[0, s.length]`, because a clamp cannot
  move a value that is already inside its range: the proof is the same one
  that removes a bounds check ([Element access](#element-access)), and a
  literal `0` is proven for every string, since none has a negative length.
  Each bound is proven against the facts that hold **where that
  bound is evaluated** — the arguments run left to right and the receiver's
  length is read before either of them, so an assignment in argument 1
  cannot prove argument 0 and an argument that rebinds the receiver takes the
  proof with it (`perf_clamp_order`, `perf_clamp_rebind`). A bound it could
  not prove keeps the clamp and is reported by the performance warning
  below.
- *Tests:* `str_bytes`, `perf_clamp_quiet`, `perf_clamp_order`,
  `perf_clamp_rebind`; `reject_str_substring_arity`.

**`s.slice(start: number[, end: number]): string`** answers the same bytes,
without the clamp: `start` and `end` must satisfy
`0 <= start <= end <= s.length` and anything else **panics** with
`slice out of range: [start, end) of length len` and exits 1, where
JavaScript would count a negative offset from the end and answer `""` for a
reversed pair. `end` defaults to `s.length`, an empty range is `""`, and an
in-range non-negative pair gives exactly what JavaScript's
`String.prototype.slice` gives.

- *Lowering:* two `icmp ule` against a cold panic block, one allocation and
  one `memcpy`. Measured 1.18x over `substring` on a lexer-shaped scan
  ([wp15-performance.md](wp15-performance.md) §4).
- *Tests:* `str_slice`, `str_slice_panic`; `reject_str_slice_arity`,
  `reject_str_slice_type`.

**`s.indexOf(sub: string[, from: number]): number`** answers the first
**byte** offset at or after `from` at which `sub` occurs, or `-1`; `from`
defaults to `0`.

`from` is clamped into `[0, s.length]` first, as in JavaScript: a negative
start searches from `0`, and a start past the end finds nothing, except that
the empty needle answers the clamped start, so `s.indexOf("")` is `0`,
`s.indexOf("", 3)` is `3` and `s.indexOf("", 99)` is `s.length`. A float
start converts as JavaScript's `ToIntegerOrInfinity` does — a fraction
truncates and `NaN` is `0` — and an unsigned one is clamped from above only,
so a `u64` past 2^63 is past the end.

Under Node the program is the same call to `String.prototype.indexOf`,
whose answers differ only where every offset does, on text that is not ASCII
(NL8001, under "Portability warnings").

- *Lowering:* one `nish_str_index_of` or `nish_str_index_of_from` call and no
  allocation: the search is the runtime's, so it is the libc's vectorised
  one rather than a probe per offset (WP15 §7c), and the clamp is a
  `llvm.smin` / `llvm.smax` pair in the caller, which a literal `0` does
  without. A loop that walks every match,
  `at = s.indexOf(sub, at + sub.length)`, therefore copies nothing.
- *Tests:* `str_search`, `str_index_of_from`, `str_index_of_from_port`;
  `reject_str_index_of_type`, `reject_str_index_of_arity`,
  `reject_str_index_of_from_type`.

**`s.startsWith(sub: string): boolean`** answers whether `sub`'s bytes are a
prefix.

- *Lowering:* `nish_str_at`.
- *Tests:* `str_search`.

**`s.endsWith(sub: string): boolean`** answers whether they are a suffix; a
`sub` longer than `s` is `false`.

- *Tests:* `str_search`.

**`String.fromCharCode(c: number): string`** answers the one-byte string of
`c & 0xFF`, the inverse of `charCodeAt`. A value above 127 makes a byte that
is not valid UTF-8 on its own; nothing validates it.

- *Tests:* `str_search`.

**`String.fromBytes(bytes: u8[], start: number, end: number): string`**
answers the bytes of `bytes[start..end)` as one string, where a loop of
`String.fromCharCode` and a `join` allocates once per byte. `bytes` is a
`u8[]` reached any way an array is (a local, a field, a call, a ternary, a
literal), `readonly` or not, since the call only reads it; anything else,
a wider element or a `u8[] | null` included, is
`` `String.fromBytes` expects an argument of type u8[], got i32[] ``
(NL2268). Both ends are required (NL2060) and are numbers (NL2058).

The range is `s.slice`'s, `0 <= start <= end <= bytes.length`, checked once
after all three arguments are evaluated, so an argument that grows or
shrinks the array is checked against what it left; anything else **panics**
with `slice out of range: [start, end) of length len` and exits 1.

As with `fromCharCode`, nothing validates the bytes as UTF-8: a multi-byte
character copied whole is that character, and a range that cuts one is bytes
that are not a valid string. Natively the string's bytes are the array's, so
`write` or `writeFileSync` sends any bytes back out unchanged
([File I/O](#file-io), `io_write_bytes`). Under Node, where
`String.fromBytes` is the prelude's (`runtime/nish.mjs`), each byte is one
UTF-16 unit, as `fromCharCode` makes it, so ASCII agrees and a byte above
127 does not (a C row, [wp33-round-trip.md](wp33-round-trip.md) §3.2); under
`--emit-ts` the bytes decode as UTF-8, a sequence that is not UTF-8 to
U+FFFD. Bytes that are not text go out through `writeBytes` and
`writeFileBytesSync`, which agree on every host. `src/` does not call it
until the release that ships it (the rolling freeze).

- *Lowering:* one range check, one allocation and one `memcpy`
  (`nish_str_new`).
- *Tests:* `str_from_bytes`, `str_from_bytes_ways`, `str_from_bytes_order`,
  `str_from_bytes_lifetime`, `str_from_bytes_arrow`, `str_from_bytes_oob`;
  `reject_str_from_bytes_type`, `reject_str_from_bytes_elems`,
  `reject_str_from_bytes_start`, `reject_str_from_bytes_index`,
  `reject_str_from_bytes_arity`, `reject_str_from_bytes_arena`,
  `reject_deny_panics_from_bytes`.

Every offset above is a **byte** offset, like `s.length`: a lexer walks bytes,
and a code-point index would need a decode per access (`codePointLength` in
`nish/text` counts code points natively, and under Node for any string that is
not built from bytes). Cutting a multi-byte
character in half is therefore possible and produces bytes that are not a
valid string (docs/wp13-differential.md notes what Node then does with them).

A numeric literal argument to `push`, `indexOf` or `fill` takes the element
type, so `wide.push(3)` on an `i64[]` is an `i64` three
([Numeric literals](#numeric-literals)).

#### Sorting with a comparator

`xs.sort(cmp)` sorts with a function the program passes. The checker
rewrites the call to `sortWith(xs, cmp)` from `std/sort.ts`, which the program
does not import: a `.sort(` call is what loads it. Because `cmp` is a
compile-time function parameter, each comparator gets its own instantiation
whose inner loop calls it directly, with no function pointer and no boxing of
its answer. The sort is stable, so for a comparator that is a consistent
total preorder there is exactly one answer and it is Node's; under Node and
`--emit-ts` the call is the platform's own `Array.prototype.sort`. A 10,000
element array of records with many ties (`arr_sort_cmp_f64`) prints the same
checksum natively and under Node.

The sort costs one scratch array of `n` elements, allocated once at full size
(`new Array<T>(n)` for any `T`, which `sortWith` alone may write: the copy
after it fills every slot before one is read) from the function's arena and
released before `sortWith` returns, so a sort leaves `Arena.used()` where it was
and a loop that sorts keeps its per-pass scope (`arr_sort_edge`). The scratch is
not on the stack: its length is the array's, known only at run time. Insertion sorts
runs of 32 from the scratch into the array, then bottom-up passes merge pairs
of runs back and forth between the two. A pair already in order (the last of
the left run not after the first of the right) is copied without a comparison
per element, so a merge pass over sorted input costs one comparison per pair.
Every move is a whole slot: an array of `interface` records, which is stored
inline, moves a record as one copy of its bytes (`arr_sort_cmp_record`), and
the sort never holds an element across a write, which would read a record half
overwritten. Every index inside the sort is proven in range by a guard beside
it, so the sort keeps no bounds check, and at `-O2` the comparator is inlined
into the loops that call it.

Where JavaScript leaves the order to the implementation, so does Nish: an
array holding `NaN` under `(a, b) => a - b`, or a comparator that is not a
consistent order (one answering `1` for both `(a, b)` and `(b, a)`), comes
out a permutation of its elements, but not necessarily Node's permutation. A
program meant to agree with Node gives NaN a place of its own in the
comparator.

The idiom `(a, b) => a - b` is checked arithmetic on `i32`: two elements more
than `2^31 - 1` apart, as in `[2147483647, -1]`, panic with
`attempt to subtract with overflow`. On values that may span the whole range,
compare instead of subtracting: `(a, b) => (a > b ? 1 : a < b ? -1 : 0)`.

What differs from JavaScript is refused rather than reinterpreted: no
comparator (JavaScript would compare the elements' strings), a readonly
receiver or `process.argv`, and a comparator that reads a `let` of the
function it is written in (`reject_arr_sort_capture_let`). A comparator is an
arrow argument like any other, so it may read that function's `const` locals
and parameters (`arr_sort_capture`), under the rule in [Function parameters](#function-parameters).

#### Callback methods and `slice`

`xs.map(f)`, `xs.filter(f)`, `xs.some(f)`, `xs.every(f)`, `xs.findIndex(f)`,
`xs.forEach(f)` and `xs.slice(...)` are lowered as `sort` is: the checker
rewrites the call to a template of `std/array.ts`, which a call of one of those
names loads, and the callback is a compile-time function parameter, so each
callback gets an instantiation of its own whose loop calls it directly.
`xs.map(f)` and `map(xs, f)` with `map` imported from `nish/array` are the same
call and compile to one instance (`arr_map_template`). The template is picked by
the callback's arity: `map` for `(x) => ...`, `mapIndexed` for `(x, i) => ...`,
and `slice`, `sliceFrom` or `sliceAll` by the argument count.

`xs.forEach(f)` answers `void`, so its answer cannot be bound
(`reject_foreach_answer`), and its callback is written to answer nothing: a
concise body such as `(x) => console.log(x)` or `(x) => ys.push(x)` is a
statement, and what it computes is dropped. It compiles to a counted loop over
the array with the callback inlined into its body, as `for...of` does, but the
loop stops at the length the array had when the call began, as Node does,
where `for...of` reads the length on every pass. With a callback that does not
resize the array, `opt -O2` leaves the same instruction count for both: 18 on
the `walk` function measured in
[IR_COOKBOOK.md](IR_COOKBOOK.md#map-and-set-iteration). An arrow argument
never assigns a name of the function it is written in (NL2586), and a
`forEach` callback is no exception, so a running total is a `for...of` loop,
whose body may assign it; the refusal says so (`reject_foreach_capture_sum`):
`for (const x of xs) { sum += x }`.

The callback takes the element, or the element and its index, as TypeScript
allows. JavaScript passes a third argument, the array itself; Nish refuses a
callback that declares one (NL2698), since the array is the receiver the call
already names. A callback that declares no parameter, `xs.map(() => 0)`, is
refused too, though TypeScript accepts it: the template is picked by the
callback's arity, and there is none for zero, so write `(_x) => 0`. The
callback rule is the comparator's: a top-level function, or
an arrow that reads only the `const` locals and parameters of the function it
is written in (`reject_arr_map_capture_let`).

Each method walks the array from index 0 and calls the callback once per
element, in order, up to the length the array had when the call began, as
`Array.prototype` does; `some`, `every` and `findIndex` stop at the first
element that decides. A callback that shrinks the array ends the walk at the
new length, where JavaScript goes on and skips the missing indices. So a
`forEach` callback that pushes onto its receiver does not visit what it
pushed, one that stores ahead of the walk is handed the stored value, and one
that pops stops the walk early, as Node does (`arr_foreach`). `map` and
`filter` answer a new array, so writing into it does not touch the receiver;
an element that is an `interface` record is stored inline and copied, so
`filter(...)[0].id = 10` leaves the receiver's record as it was, as it would
under Node (`arr_filter`).

**There is no `find`.** TypeScript types `xs.find(f)` as `T | undefined`, and
Nish has no `undefined`: a program testing `r !== null` would pass `tsc` and
mean something else under Node. The call is refused with a message that
points to `findIndex` (NL2697, `reject_arr_find`):
`const i = xs.findIndex(f); if (i >= 0) { ... xs[i] ... }`.

**`slice` panics where JavaScript clamps.** The bounds rule is string
`slice`'s: `0 <= start <= end <= xs.length`, and anything else exits 1 with
`slice out of range: [start, end) of length n` (`arr_slice_bounds`). A
negative index, which JavaScript counts from the end, and an end past the
length, which it clamps, are both outside. A `number` bound under
`--number-mode f64` is made an integer before the check, as `llvm.fptosi.sat`
does: a fraction is truncated toward zero (`xs.slice(0.9, 2.5)` is
`xs.slice(0, 2)`), `NaN` is 0, and `±Infinity` or a magnitude of 2^63 or more
saturates to the `i64` limits, so it fails the check and the message prints
the limit (`slice out of range: [-9223372036854775808, 9223372036854775807) of
length 3`; `arr_map_f64`, `arr_slice_saturate`). The bounds are `number`
only, where string `slice` takes any integer type: an `i64` or `u32` bound is
refused (`` Argument 2 of `slice`: expected i32, got i64 ``;
`reject_arr_slice_i64_bound`), so convert it first: with `toI32(n)` in the
default i32 mode, and with `Number(n)` under `--number-mode f64`, where the
message reads `expected f64`. Neither conversion works in the other mode. An array's `slice` is not a
`slice` [panic site](#panic-sites): its check is `std/array.ts`'s own
`panic(...)`, so a call to it is a `call` site that reaches `panic`, which no
proof at the call removes, and `--deny-panics` refuses it
(`reject_deny_panics_arr_slice`). Under Node and `--emit-ts` the call
is the runtime's `sliceArray`, which applies the same check with the same
words, so the two agree on every input; `map`, `filter`, `some`, `every`,
`findIndex` and `forEach` are the platform's own `Array.prototype` methods
there, and an answer that holds records inline is copied with the runtime's
`copyRecords`, as the native `push` copies.

### Bulk writes: `set` and `fill`

The reference for `set` and `fill`, with their parameters and their answers, is their doc comments on `Array` in [`runtime/nish.d.ts`](../runtime/nish.d.ts); the rules are here.

A packet is copied, cleared and filled through `u8[]` without a loop per byte
(WP34 N2). Both methods take their meaning from `TypedArray.prototype`, and both
are admitted **on an array of numbers only** — `u8[]` above all, but any width,
`f64[]` and a ranged `integer<Lo, Hi>[]` included — because an element there is
a fixed-size value, so the lowering is one copy or one store of bytes. On any
other array each is `` `set` copies bytes, so it needs an array whose elements
are numbers (`u8[]`, `i32[]`, `f64[]`, ...), got string[] `` (NL2395,
`reject_bytes_set_string`, `reject_bytes_fill_record`): a `string` or a `class`
element is a pointer a byte copy would share, and a record is a struct stored
whole.

- **`a.set(src, offset)`** copies all of `src` into `a` starting at `offset`,
  which defaults to `0`. `src` has `a`'s own element type — a `readonly` array
  may be the source, since it is only read — and anything else is
  `` `set` copies from an array of the receiver's element type, so it expects u8[], got i32[] ``
  (NL2396, `reject_bytes_set_type`), because a conversion per element is not a
  byte copy. One or two arguments (NL2397, `reject_bytes_set_arity`).
- **The range written is checked.** `0 <= offset` and
  `offset + src.length <= a.length`, or the program **panics** with
  `slice out of range: [offset, offset + src.length) of length a.length` and
  exits 1 — the same check and the same message as `s.slice`, since it asks
  the same question of a range (`bytes_set_oob`). A range that ends exactly at
  `a.length`, and an empty `src` at `a.length`, are in range
  (`bytes_set_end`). JavaScript throws a `RangeError` for exactly these
  offsets.
- **An overlapping copy behaves as if `src` were read first**, which is
  `TypedArray.prototype.set`'s promise, so `set` lowers to `llvm.memmove`.
  Nish itself can overlap an array only with itself (`a.set(a)`), but a C host
  may hand in two headers over one buffer, and then the copy is right in either
  direction (`bytes_set_overlap`). It lowers to `llvm.memcpy` only where the
  checker **proves** the two buffers distinct, and records the proof for the
  emitter: when either operand is an array literal or a `new` written at the
  call, or when both are different `const` locals each initialised with a
  fresh allocation — a literal, a `new` or a `readFileBytesSync` — since a
  second name for either buffer would not be such a local
  (`bytes_set_disjoint`). A parameter, a field, a `let` and a self-copy are
  "not proven", which is the `memmove` and never wrong (`bytes_set_self`).
- **`a.fill(value, start, end)`** stores `value` into every slot of
  `[start, end)`. `value` is the element type (`` `fill` expects u8 (the element
  type of u8[]), got string ``, `reject_bytes_fill_value`), and a ranged
  element checks it once, before the fill. `start` defaults to `0` and `end` to
  `a.length`; **a negative end counts back from `a.length`, and each is then
  clamped into `[0, a.length]`**, so no range is out of range, a reversed range
  fills nothing, and `fill` never panics (`bytes_fill`). One to three
  arguments (NL2398, `reject_bytes_fill_arity`), each end a number
  (`reject_bytes_fill_index`).
- **A float offset is converted as JavaScript's `ToIntegerOrInfinity`
  converts it**, for `set`'s offset and for both of `fill`'s ends: an `f64`
  (every `number` in f64 mode) or `f32` goes through `llvm.fptosi.sat`, never a
  bare `fptosi`, whose answer for NaN or an infinity is poison. **NaN is `0`,
  a fraction truncates toward zero** (`2.7` is `2`, `-0.5` is `0`), and **an
  infinity or a value past the `i64` range saturates** to the `i64` bound on
  its side. `fill` then clamps that bound to an end of the array, so in f64
  mode `a.fill(v, 0, 1 / 0)` fills all of it, as `Uint8Array.prototype.fill`
  does (`bytes_offset_float`); `Infinity` itself is not a name in Nish. `set`
  fails its range check with the saturated offset in the message —
  `slice out of range: [9223372036854775807, -9223372036854775808) of length 4`
  for `1e300` or an infinity, where the end has wrapped — and exits 1 where
  JavaScript throws a `RangeError` (`bytes_set_float_oob`,
  `bytes_set_float_panic`).
- **An unsigned offset is never negative**, whatever its width. A `u64` of
  2^63 or more has the `i64` sign bit set, and `fill` still reads it as past
  the end: as a start it fills nothing, and as an end it fills to the length
  (`llvm.umin`, where a signed clamp would count it back from the end).
  `set`'s range check compares unsigned, so the same offset panics, printed
  signed as every range panic prints (`bytes_offset_u64`, `bytes_set_u64_oob`).
  An `i64` at `INT64_MIN` or `INT64_MAX` keeps the signed clamp above. The
  TypeScript reading of a 64-bit offset is class C: `i64` and `u64` are
  `bigint` under `runtime/nish.mjs`, and `fill` or `set` with a `bigint`
  offset throws a `TypeError` there, as all 64-bit arithmetic does
  ([RUN_UNDER_NODE.md](RUN_UNDER_NODE.md)).
- **`fill` on a `u8[]` is one `llvm.memset`.** On a wider element it is a
  counted store loop of the one value, the shape LLVM vectorises; `opt -O2`'s
  loop-idiom pass makes a `memset` of that loop by itself when the value is a
  repeated byte, zero above all, which `tests/run.js` checks on
  `bytes_fill_zero`.
- **Both are statements**, as `writeFileSync` is: `` `set` returns void and
  can only be used as a statement `` (`reject_bytes_set_value`,
  `reject_bytes_fill_value_position`). `set` answers
  `undefined` in JavaScript and `fill` answers the array the program already
  holds, so refusing the value costs nothing and keeps the two readings the
  same.
- **Both write their receiver**, so a `readonly` array refuses them under their
  own names (`` Cannot `set` through readonly u8[] (declare it u8[] to write
  through it) ``, `reject_bytes_set_readonly`, `reject_bytes_fill_readonly`), a scope's region refuses them
  on memory a task may read (`reject_thread_region_fill`,
  `reject_thread_region_set_call`), and a parameter they write is never
  `readonly`. Neither moves `length`, so neither disturbs a hoisted header or a
  length the bounds proof holds.
- **A window into a buffer is `(buf, offset, length)` by convention**, not a
  view type: a second array layout would be one every array path in the emitter
  has to handle ([wp34-network-stack.md](wp34-network-stack.md) §4 N2).

The TypeScript reading ([wp33-round-trip.md](wp33-round-trip.md) §2): `fill` is
**class A** — a `u8[]` is a plain `Array` under Node, and `Array.prototype.fill`
has `TypedArray.prototype.fill`'s meaning for every argument Nish admits. `set`
is **class A under `runtime/nish.mjs`**, which adds the one method `Array` lacks
to `Array.prototype` with the copy-first semantics and the native panic, and
**class C** in a TypeScript host without it, where a plain array has no `set`
([wp33-round-trip.md](wp33-round-trip.md) §3.3). Every `bytes_*` program with
a `main` runs under both and agrees byte for byte.

### Readonly arrays

The reference for the members a `readonly T[]` has is their doc comments on `ReadonlyArray` in [`runtime/nish.d.ts`](../runtime/nish.d.ts); the rules are here.

`readonly T[]` — or `ReadonlyArray<T>`, the same type under the other spelling
— is a `T[]` that may not be written through. It is the same header, the same
pointer and the same LLVM type; the golden
(`tests/cases/arr_readonly_param`) is the IR the mutable spelling emits,
instruction for instruction, because the annotation is a promise to the checker
and not a value.

- **Everything that reads still works**: `a.length`, `a[i]`, `for...of`,
  `indexOf`, `join`, `map`, `filter`, `some`, `every`, `findIndex`,
  `forEach`, `slice`, passing it on to another `readonly T[]`.
- **Everything that writes is refused**: `a[i] = v` and `a[i] op= v` are
  `` Cannot assign to an element of readonly i32[] (declare it i32[] to write through it) ``
  (`reject_arr_readonly_store`), and `push` / `pop` are
  `` Cannot `push` through readonly i32[] (...) `` under their own names
  (`reject_arr_readonly_push`, `reject_arr_readonly_pop`), and so are `set`
  and `fill` (`reject_bytes_set_readonly`). `a.length = n` was
  already refused for every array.
- **A `T[]` widens into a `readonly T[]`, and never back.** The conversion
  emits nothing, because the two are the same pointer; the reverse is
  `` Argument 1 of `fill`: expected i32[], got readonly i32[] ``
  (`reject_arr_readonly_widen`), since laundering the promise away one call
  deeper would make it worth nothing.
- **It is shallow**, as TypeScript's is: the element of a `readonly T[][]` is a
  mutable `T[]`.
- **It is a type, not a parameter modifier**, so it is legal wherever an array
  type is — a class field, a return type, a `const`'s annotation — and the rule
  travels with it (`arr_readonly_field`, `reject_arr_readonly_field`). That is
  why the message says "declare it" rather than naming a parameter.
- **`readonly` goes on an array type and nothing else.** TypeScript allows the
  modifier on array and tuple types only (TS1354), so `readonly i32` is
  `` `readonly` is only permitted on an array type, got i32 ``
  (`reject_arr_readonly_scalar`) rather than a construct waiting to be
  supported — a program that used it would not be TypeScript either.

The reason to write one is the C ABI. `--emit-header` already spells an array
parameter `const nish_array *` when the whole-program fixpoint proves nothing
stores through it, which makes `const` a *consequence* that can quietly
disappear when a callee three levels down starts writing. On a `readonly T[]`
it is the signature keeping a promise instead, and the comment above the
prototype shows the annotation that earned it
(`tests/cases/arr_readonly_header`, checked in the WP8 block of
`tests/run.js`):

```c
/* sum(xs: readonly number[]): number -- xs: int32_t elements */
int32_t sum(const nish_array *xs);
/* fill(xs: number[], v: number): void -- xs: int32_t elements */
void fill(nish_array *xs, int32_t v);
```

The fixpoint is not consulted for a `readonly T[]` at all, and that is
deliberate rather than a shortcut. `writesThrough` is a conservative
*may-write*: every escape sets it, on the grounds that an alias might be
written through later, so a `readonly` parameter that is merely returned or
stored in a field would land in the written set and lose the `const` its
annotation promised (`tests/cases/arr_readonly_escape`). The checker is what
makes the promise true — no store, no `push`, no `pop`, and no widening back to
a mutable `T[]` — and it is exact where the fixpoint is not
(`writtenArrayParams`, `src/interop-abi.ts`).

`process.argv` is read-only under a rule of its own rather than this type
(`` `process.argv` is read-only ``), because it is a value and not an
annotation.

There are no other array or string methods (`shift`, `find`, `reduce`,
`toUpperCase`, `charAt`, ...) and no
`toString` (template literals and `console.log` convert numbers);
string-to-number parsing is the bare
`Number(s)` / `parseInt(s)` / `parseFloat(s)` under
[Numeric conversions](#numeric-conversions). An unknown name is
`` Unknown method `codePointAt` on string `` or
`` Unknown method `shift` on i32[] ``, each with the supported list
(`tests/cases/reject_str_method_unknown`, `reject_arr_method_unknown`).

### Typed-array names have no `push` or `pop`

The reference for the four names is the doc comment on `Array` in [`runtime/nish.d.ts`](../runtime/nish.d.ts); the rules are here.

`Int32Array`, `Float32Array`, `Float64Array` and `BigInt64Array` are the same
type as `i32[]`, `f32[]`, `f64[]` and `i64[]`, but in TypeScript a typed array
has a fixed length and no `push` or `pop`, so a call to either is a
`TypeError` there. A receiver **spelled** with one of the four names refuses
both (NL2415):

```
`push` is not a method of `Float64Array`, whose length is fixed: declare it `f64[]` to push and pop
```

(`tests/cases/reject_typed_push_i32`, `reject_typed_push_f32`,
`reject_typed_push_f64`, `reject_typed_push_i64` and their `reject_typed_pop_*`
twins). The rewrite is the one the message names: a binding that grows is
declared `f64[]`, which is what it meant. Every other array operation is
unchanged, and so is the type: `sameType` still holds, a `Float64Array` is an
`f64[]` wherever one is expected, and no IR moves.

The spelling is a fact about the program text, not a type. A receiver carries
it when it is:

- **`new X(n)` itself**, for the four names;
- **an identifier** whose `let`, `const` or parameter is annotated with one of
  the names — directly, in parentheses, as the one member of `X | null`, or
  through a `type` alias declared or imported in the module
  (`reject_typed_push_param`) — or is unannotated and initialised with a
  receiver that carries it: `const t = new Float64Array(n)`, which TypeScript
  infers as the typed array (`reject_typed_push_inferred`), or `const u = t`;
- **a field read** `o.f` whose field is declared with one of the names;
- **a call** whose callee declares one of the names as its return type
  (`reject_typed_pop_receivers` has one of each). A field or a return type
  written through a `type` alias carries it in every module that reads it,
  including one that does not import the alias, because the declaring module
  reads the spelling where its aliases are (`tests/link/reject_typed_push_alias`);
- **a call of a generic function** whose return type is a type parameter —
  or an array of one — that an argument binds to a receiver carrying it:
  `first(rows)` with `first<T>(xs: T[]): T` and `rows: Float64Array[]`,
  `same(new Int32Array(n))` with `same<T>(x: T): T`. The spelling is the
  call's, not the instantiation's: `first(plain)` over an `f64[][]` is the
  same instantiation and is not refused (`reject_typed_push_generic`);
- **a value read out of a `Map`** whose value type is spelled with a name,
  whether the `Map` is annotated `Map<string, Float64Array>`, made with
  `new Map<string, Float64Array>()` or is a field so declared: `m.get(k)`
  once narrowed, `m.get(k) ?? d`, and the variable of a `for...of` over
  `m.values()` (`reject_typed_push_map`). A `Set` holds no arrays and a
  `Map`'s keys are none, since an array is not a key;
- **an element of an array spelled with a name**: `rows[i]` or a `for...of`
  variable over `rows`, where `rows` is any of the above spelled
  `Float64Array[]` or `Array<Float64Array>`, or is an array literal of
  receivers that carry it, `[new Float64Array(n)]`
  (`reject_typed_push_element`). The array itself is an ordinary array, and
  `rows.push(new Float64Array(n))` compiles;
- **a ternary or a `??`** either of whose operands carries it: `c ? xs : t`
  is `number[] | Float64Array` to TypeScript, which has no `pop` either
  (`reject_typed_push_ternary`).

What does not carry it is a member of a generic **class** instantiated at
one of the names: `new Box<Float64Array>(t).value` and a method of it that
returns `T` still push natively where the same source throws a `TypeError`
under Node, because a binding records one spelling and not one per type
argument. Declare such a value `f64[]` where it is bound, which is what
TypeScript needs to accept the push as well.

**A typed array that flows into a binding spelled `T[]` may be pushed there**:
`const a: f64[] = t; a.push(v)`, or a `Float64Array` passed to a parameter
`xs: f64[]` that pushes (`tests/cases/arr_typed_push_pop`, whose IR is the
`f64[]` program's). The refusal follows the spelling the program wrote, and
TypeScript itself refuses `const a: number[] = new Float64Array(n)`, so no
program `tsc` accepts reaches that push.

### `Arena`

The reference for `Arena.used`, `Arena.mark` and `arena()`, with their answers and their capabilities, is their doc comments in [`runtime/nish.d.ts`](../runtime/nish.d.ts); the rules are here.

Reading the arena the runtime allocates from
([wp6-memory.md](wp6-memory.md#3-explicit-control)). The automatic placement
described under [Memory model](#memory-model) frees what a program allocates;
[`using a = arena()`](#using-a--arena) below frees a batch by hand, with the
proof done by the compiler. These two read the arena's position, and the
memory tests watch it through them. Both are available in both number modes.
`Arena.release` and `Arena.reset`, which freed to a mark with no proof, were
removed before 1.0: a call to either is an unknown builtin (NL2244, the
`arena_removed` block of `tests/run.js`).

| Signature | Semantics | Effect | Test |
| --- | --- | --- | --- |
| `Arena.mark(): i64` | the current bump address (`nish_arena_mark`; `0` while the arena is empty) | write | `mem_callee_scope_control`, `mem_reclaim_guards` |
| `Arena.used(): i64` | bytes bumped in the current chunk (`nish_arena_used`); the number the memory tests watch | write | `mem_loop_scope_control`, `mem_scope_dynamic_array` |

`mark` and `used` only read the arena, but they are recorded as writes so
that a caller is never hoisted across an allocation, and a function that calls
either — itself or through a callee — is never the callee of a tail call whose
scope release moved ahead of it, so the position it reports is the one it would
have reported before ([Memory model](#memory-model), item 2). A function that
calls `Arena.mark` in its own body (`managesArena`) never gets an automatic
arena scope, for the function or for a loop's pass, so the position it reads
is never moved under it by a scope it did not write.

#### `using a = arena()`

A block that declares `using a = arena()` takes the arena's mark where the
declaration stands and releases to it on every exit of the block, and the
compiler refuses the block if anything allocated after the declaration could
still be reachable once it has released. It is the
[per-pass scope](#memory-model) of item 2 written by the program, held to the
same rule with the block as the pass, and refused rather than quietly dropped
when the rule fails.

```typescript
const tally = (rows: string[]): i32 => {
  let total = 0;
  for (const row of rows) {
    using a = arena();                // the mark
    const line = `${row}: ${row.length}`;
    total = total + line.length;      // a number leaves the block; the string does not
  }                                   // released here, and on every other exit
  return total;
};
```

- **`arena()` is a global builtin** declared in `runtime/nish.d.ts` as
  `declare function arena(): Disposable`, so a program stays TypeScript; under
  Node its disposal does nothing. It is only the initialiser of a `using`
  declaration, which is a statement of a block (the
  [`using` placement rule](#scoped-tasks-using-s--scope)); anywhere else it is
  `` `arena()` must be the initialiser of a `using` declaration, `using a = arena()`: the arena releases what was allocated after it when the block that declares it ends, and an `arena()` written anywhere else has no block to end ``
  (NL2416, `tests/cases/reject_using_arena_not_using`). The binding holds the
  mark and is never read:
  `` `a` is the binding of a `using` declaration of `arena()` and cannot be read: it holds the mark its block releases to when it ends, and nothing but that release may see or move the mark ``
  (NL2417, `reject_using_arena_binding`).
- **The release is emitted at every exit of the block**: its end, a `return`
  (after the returned value is computed, so the value may read what the block
  allocated), a `break` or `continue` that leaves it, and an `orReturn()`
  (`tests/link/arena_using_exit_paths`, `tests/cases/mem_using_arena`,
  `mem_using_arena_or_return`). It nests with everything else on the same
  stack, innermost first: a `using s = scope()` inside the block joins before
  the block releases, and a block inside a scoped loop pass or a function's
  automatic scope releases before they do; a `return` releases only the
  outermost of them, whose mark is the lowest. A `return g(n)` whose
  arguments are all numbers is a tail call with the release moved ahead of
  it, unless `g` reads the arena (`mem_using_arena_tail`). A panic ends
  the process. Statements of the block before the declaration are
  outside it.
- **Nothing allocated inside may outlive the block.** From the declaration to
  the end of the block, each of these is refused, naming the value and where
  it would go:

  | Route | Refused when | Code | Test |
  | --- | --- | --- | --- |
  | assigned to a local declared outside the block | the value is not older than the block (a literal, a parameter or outer local, a field or element read, a call that allocates nothing) | NL2418 | `reject_using_arena_outer_local` |
  | stored into a field, `o.f = v` | `v` is not older than the block, unless the field is a number, a `boolean` or an `enum` | NL2419 | `reject_using_arena_field` |
  | stored into an element, `xs[i] = v` | likewise | NL2420 | `reject_using_arena_element` |
  | stored into memory any other way: handed to a callee that keeps it, held by an object or array literal | always: the escape analysis stops following a stored value | NL2421 | `reject_using_arena_stored` |
  | `push` onto an array | the array is not a `const` the block binds to a fresh array, whatever is pushed: a `push` moves the array's storage into the arena | NL2422 | `reject_using_arena_push` |
  | `return v`, `r.orReturn()` | `v` is not older than the block; `orReturn()` unless the function returns a `Result` packed into a register, whose payloads are numbers | NL2423 | `reject_using_arena_return`, `reject_using_arena_or_return`, `reject_using_arena_declarator_or_return` |
  | a call to a function that stores an allocation into memory | always | NL2424 | `reject_using_arena_callee_stores` |
  | a call the analysis has no facts for | always; every callee has facts today | NL2425 | — |
  | `s.spawn(...)` on a scope declared outside the block | always: the task runs, and stores, when that scope joins, after the release | NL2427 | `reject_using_arena_spawn` |
  | `s.spawn(...)` on a scope the same `using` declares ahead of `arena()`, `using s = scope(), a = arena()` | an argument is not older than the block: `s` is disposed after the arena, so it joins after the release | NL2427 | `reject_using_arena_spawn_declarator` |
  | the same, ahead of the statement's last `arena()`, `using a = arena(), s = scope(), b = arena()` | an argument is not older than the block: `b` releases before `s` joins | NL2427 | `reject_using_arena_spawn_last` |

  A number, a `boolean` or an `enum` leaves the block freely, and so does a
  value older than it. The rule is the escape analysis's, so it is
  conservative: a block that stores a fresh string into an object it also
  allocated, or builds a `Map`, is refused even though nothing escapes, and
  what has to outlive the block is allocated before it opens. The first route
  reads ``` `` `item ${i}` `` may be allocated inside the `using arena()` block at 6:5 and is assigned to `last`, which is declared outside the block: the block releases what it allocated when it ends, and the local would outlive it pointing into freed memory ```
  (`reject_using_arena_outer_local`).
- **A parallel body or a task may not open one**, for the reason it may not
  call `Arena.*` (`reject_using_arena_parallel`, NL2351).
- **A map that answers numbers or strings may run inside one.** The map's
  region joins before the call returns, so its result array is the block's
  alone, and the blocks of strings it adopts from its workers are the block's
  newest memory; the release frees both (`tests/link/mem_using_arena_map`).
  What the map answers may not outlive the block, as anything else allocated
  in it may not (`tests/cases/reject_using_arena_map_escapes`). A map whose
  body answers an array stores each one into its result, which the analysis
  stops following, as it does for a loop that pushes arrays into an array, so
  the block refuses it as NL2424 and says what to write instead: run that map
  outside the block (`tests/cases/reject_using_arena_map_arrays`).
- **A task filed on a scope the block declares may read what it allocated.**
  That scope joins before the block releases, inner `using s = scope()` or
  `using a = arena(), s = scope()` alike, so the block may hand its task an
  array or an object it made (`tests/link/thread_scope_reclaim`). A scope
  declared ahead of the statement's last `arena()` is not one: that arena
  releases first (`reject_using_arena_spawn_last`). The task
  is followed as any callee is: one that answers its argument into an older
  destination stores it (NL2424, `tests/cases/reject_using_arena_spawn_relay`,
  as `reject_using_arena_spawn_stores` for any array answer), and a
  constructor that makes the argument and hands `this` out stores it too
  (`reject_using_arena_spawn_constructor`).
- **It costs no scope.** A function that declares one keeps its automatic
  scope and its loops' pass scopes, because the block's mark is checked like
  theirs; only `Arena.mark` gives those up. And the arena-loop warning, NL9011, says
  nothing about a call inside the block, whose leftovers the block releases
  (`tests/cases/perf_arena_using`).

### `Map` and `Set`

The reference for each member of `Map` and `Set`, with its parameters and its answer, is its doc comment in [`runtime/nish.d.ts`](../runtime/nish.d.ts); the rules are here.

The global `Map<K, V>` and `Set<T>` are JavaScript's: insertion-ordered, with
keys compared by SameValueZero, so `-0` is `+0` and `NaN` is `NaN`. They need
no import. They are generic classes written in Nish in
[`std/collections.ts`](../std/collections.ts), which a module loads by naming
`Map` or `Set` in a type or after `new`, and the layout and every decision
below are [wp32-map.md](wp32-map.md)'s.

```typescript
export const main = (): i32 => {
  const seen = new Set<string>();
  const counts: Map<string, i32> = new Map();
  seen.add("a").add("b").add("a");
  counts.set("a", 1).set("b", 2);
  counts.delete("b");
  return seen.size + counts.size;   // 3
};
```

- **The members are JavaScript's, less what this version defers.** A `Map` has
  `size`, `get`, `set`, `has`, `delete`, `clear` and `forEach`; a `Set` has
  `size`, `add`, `has`, `delete`, `clear` and `forEach`. `set` and `add`
  answer the receiver, so they chain, and `delete` answers whether the key was
  there (`tests/cases/map_key_str`, `set_str`). `size` is a read-only
  `number`: `` `size` of `Map<string, i32>` is read-only ``
  (`reject_map_size_assign`).
  `get` answers `V | undefined`, which has rules of its own, below.
  `keys()` and `values()` are iterators, and an iterator is only ever the
  iterable of a `for...of`, below. There is no `entries`, because a `[key, value]`
  pair is a two-type tuple (`reject_map_entries`,
  `reject_map_iter_entries_call`):
  `m.forEach((value, key) => ...)` visits each key with its value.
- **`forEach` is the `for...of` walk with the callback inlined.**
  `m.forEach(f)` on a `Map` calls `f` with each value, and with its key too
  when `f` is written with two parameters, value first, as JavaScript does;
  `s.forEach(f)` on a `Set` calls `f` with each element. The checker rewrites
  the call to a template of `std/collections.ts` (`forEachEntry`,
  `forEachValue`, `forEachElement`), whose body is the same walk as
  `for...of` over the table, below: the same insertion order, an entry set
  during the walk visited and one deleted before the walk reaches it not, and
  `clear` ending it (`map_foreach`, `set_foreach`). It allocates nothing and
  looks no key up, where `for (const k of m.keys())` with `m.get(k) ?? 0`
  calls `Map.probe` and takes the nullish branch once per key, and rewinds
  the arena on every pass: under `opt -O2`, 92 instructions against 112 for
  a `Map` and 78 against 89 for a `Set`
  ([IR_COOKBOOK.md](IR_COOKBOOK.md#map-and-set-iteration)). JavaScript passes
  a `Map`'s callback the map as a third argument, and a `Set`'s callback the
  element twice and the set third; Nish refuses a callback written with more
  than two parameters on a `Map` (NL2771, `reject_map_foreach_third_param`)
  or more than one on a `Set` (NL2772, `reject_set_foreach_second_param`),
  since the receiver is the one the call already names. The callback follows the array callbacks' rules
  above: a top-level function or an arrow written at the call
  (`reject_map_foreach`), at least one parameter, an answer of `void`, no
  assignment to a name of the function around it (NL2586), and `m.forEach`
  named without a call is refused (`reject_map_foreach_uncalled`). An arrow
  inside another arrow reads only its own parameters, so a nested walk goes
  through a top-level function (`set_foreach`). Everything else in the
  class is the table's own and is refused as if it did not exist:
  `` Unknown member `mask` on `Map<string, i32>` `` (`reject_map_internal_field`,
  `reject_map_internal_method`, `reject_set_set`).
- **`new` takes no arguments**, because a class of this language has one
  constructor and no optional parameter:
  `` `new Map<string, i32>` takes no arguments in this version `` (`reject_map_new_args`,
  `reject_set_new_args`). The type arguments are written out, except that a
  declaration annotated with the type takes them from the annotation, as `tsc`
  infers them there — `const m: Map<string, i32> = new Map()` and the same with
  `let` (`tests/cases/map_annotated_new`); a bare `new Map()` is
  `` `Map` is generic: it must be written with its type arguments `` (`reject_map_new_no_type_args`).
- **A key is a string, a number of any width in either mode, `f32`, `f64`, a
  `boolean`, an enum or a class instance**, the last by identity
  (`tests/cases/map_key_str`, `map_key_i32`, `map_key_i64`, `map_key_u8`,
  `map_key_u16`, `map_key_u32`, `map_key_u64`, `map_key_f64`, `map_key_f32`,
  `map_key_bool`, `map_key_enum`, `map_key_class`). An interface, an array, a
  nullable type and a `Result` are not keys:
  `` `Point` cannot be the key type of `Map<Point, i32>`: a key is hashed and compared by value, or by identity for a class instance ``
  (`reject_map_key_interface`, `reject_map_key_array`, `reject_map_key_nullable`,
  `reject_map_key_result`, and for a `Set` element, `reject_set_key_interface`).
  A float key is SameValueZero, and so is its hash: `-0` and `+0` are one key
  and every `NaN` is one key, and `map_key_f64` prints under Node's own `Map`
  what it prints compiled (`tests/differential/unmodified.js`). A `-0` key is
  stored as `+0`, as JavaScript stores it, so a walk over `keys()` or a `Set`
  yields `+0` whichever zero was inserted, by every insert path: `set`, `add`,
  a fused update or guarded insert, and `getOrInsert` (`map_key_negzero`, which
  Node runs unmodified too, and `map_key_f32_negzero` for an `f32` key).
- **A value is anything but `void` and an interface**, whose record would be
  copied into the table rather than shared:
  `` `Point` cannot be the value type of `Map<string, Point>` ``
  (`reject_map_value_interface`, `reject_map_value_void`).
- **A string key is hashed under a per-process random key**: SipHash-1-3 of
  its UTF-8 bytes, keyed with 128 bits drawn from the system's entropy source
  before `main`, so a program's input cannot choose keys that share a bucket.
  4096 keys that collide under an unkeyed FNV-1a insert with no key compare
  (`tests/cases/map_hash_collide`, counted the same way as below), and two runs
  of one program hash under two keys. Iteration is still insertion order, so
  nothing a program prints depends on the key. When the entropy source fails
  the program panics before `main`: `` Map: the system's entropy source
  failed ``. On wasm32 the key comes from WASI's `random_get`, and a reactor
  module is keyed only once its host calls `_initialize`
  (docs/security/json.md, JSON-13).
- **An integer, `boolean` or enum key is hashed under a per-process random
  key too**, drawn the same way: a key of 32 bits or fewer by
  multiply-add-shift, `(a * x + b) >> 32`, and an `i64` or `u64` key by a
  folded 128-bit multiply. 8192 `i32` keys built to collide under 0.28's
  unkeyed `fmix32` run within 8 times of as many ordinary keys, where 0.28
  ran them about 215 times slower (`tests/cases/map_key_int_collide`). The
  `i64` hash is keyed but not provably universal, and before `_initialize` a
  wasm32 reactor hashes every key of 32 bits or fewer to one bucket
  (docs/security/json.md, JSON-15). **A float key and a class instance key
  are not keyed**: a float hashes its canonical bits with `fmix64` and an
  instance its address, so a program keying a table by floats a peer chose
  converts them to a string or a scaled integer first (JSON-16).
- **A pair of `i32`s is one `i64` key**, packed exactly for every pair:
  `(toI64(hi) << toI64(32)) | toI64(toU32(lo))`. `toU32` takes `lo`
  unsigned, so it stays in the low half, so nothing is added and nothing overflows; with `+` in
  place of `|` the key leaves the `i64` range at `hi = -2^31` with a negative
  `lo`. Every operand is an `i64` so the same line runs under Node, where an
  `i64` is a `BigInt` (`tests/cases/map_key_composite`, both extremes
  included).
- **Every `set`, `add`, `has` and `delete` is one probe.** A bucket holds eight
  bits of the key's hash beside the entry's index, and each entry keeps its
  full hash, so a probe reads a key only when both match: 10000 lookups of
  absent string keys make no key compare at all, and 10000 hits make exactly
  10000 (`tests/cases/map_fingerprint_miss`, counted by `tests/run.js` through
  `-Wl,--wrap=nish_str_eq`). A table grows by doubling at three quarters full
  and never hashes a key again (`map_growth`); a deleted key leaves a
  tombstone that later probes walk past, and setting it again appends a new
  entry (`map_delete_reinsert`); and a table whose entries are mostly dead
  compacts in place instead of growing (`map_compaction`). A table holds at
  most 2^24 - 1 entries, which is what a 24-bit index field holds and one fewer
  than Node's 2^24: an insert at the cap first compacts
  away dead entries, and when there are none it panics with
  `Map maximum size exceeded` (or `Set …`) *(CLI only: the case takes 16 million
  inserts)*.
- **Asking about one key twice is one probe** ([wp32-map.md](wp32-map.md)
  §9.1). Three patterns keep the first probe's answer — the entry it found, or
  the empty bucket it stopped at and the key's hash — and write through it:
  `setValueAt` of the entry where the key was found, and `insertAt` the bucket
  with the hash already computed where it was not. The second hash and the
  second search are never made:

  | Pattern | Written | Case |
  | --- | --- | --- |
  | update | `counts.set(w, (counts.get(w) ?? 0) + 1)`: the value asks about the key exactly once, with `get` or `has` | `map_fused_wordcount`, `map_fused_update_has` |
  | guarded write | `if (m.has(k)) { m.set(k, E); … }` or `if (!m.has(k)) { m.set(k, E); … }`, the `set` first in the branch | `map_fused_guard_has`, `map_fused_guard_not_has` |
  | insert if absent | `if (!s.has(x)) { s.add(x); … }`, the `add` first in the branch; the rest of the branch runs only where it inserted | `map_fused_set_insert` |

  The receiver and the key are spelled the same way in both calls, and each is
  a local, a parameter or a `this.<field>` path; the key may also be a literal
  (`map_fused_this_field`, `map_fused_literal_key`). Between the probe and the
  write — inside the value, and between the `has` and the branch's first
  statement — there is no call of any kind, no `new`, array or object literal,
  template literal or string `+`, and no assignment, `++`, `--` or compound
  assignment; `&&`, `||`, `??` and the ternary may stay, and a `??` default
  still runs only where the key is missing. A pattern outside these rules is
  not an error: it compiles as the separate calls it is, one probe each, and
  prints what they print (`map_fused_no_call`, `map_fused_no_assign`,
  `map_fused_no_key_spelling`, `map_fused_no_element_receiver`,
  `map_fused_no_template`, `map_fused_no_statement_before`). The places are
  compared, not what they hold, so an alias of the receiver is not fused
  (`map_fused_no_alias`), and neither is a value that reads the key twice or
  reads another map (`map_fused_no_two_gets`, `map_fused_no_other_map`); a
  guard fuses the write that starts its then-branch, and a `set` in its `else`
  is an ordinary call (`map_fused_no_else_branch`). A pattern in a
  generic function or method is fused in every instantiation
  (`map_fused_generic`), and one inside a walk of the table it writes does
  what the separate calls do: a key it inserts is appended past the cursor and
  visited (`map_fused_walk`). `tests/run.js` counts one call of `probe`, no
  hash of its own and no `get`, `set` or `has` in the loop of
  `map_fused_wordcount`'s golden
  ([IR_COOKBOOK.md](IR_COOKBOOK.md#fused-lookups-one-probe-for-a-key-asked-about-twice)).
- **`nish/map` adds `reserve(m, n)` and `getOrInsert(m, k, v)`**, the two
  things a program asks of a table that JavaScript's `Map` has no call for
  ([wp32-map.md](wp32-map.md) §9.2). Their bodies in
  [`std/map.ts`](../std/map.ts) are what runs under Node — `reserve` does
  nothing, and `getOrInsert` is a `get`, and a `set` of `v` when the key was
  missing, answering the value either way — so a program that uses them runs
  unmodified there (`examples/wordcount.ts`). Natively neither body is called:
  every call is lowered in place, so `std/map.ts` writes no `.ll` of its own
  and a one-file program importing it is still one module.

  ```typescript
  import { getOrInsert, reserve } from "nish/map";

  export const main = (): i32 => {
    const first = new Map<string, i32>();
    reserve(first, 64);                        // no rebuild until 64 entries
    const a = getOrInsert(first, "a", 1);      // 1, inserted
    const b = getOrInsert(first, "a", 2);      // 1, found: 2 is not stored
    return a + b + first.size;                 // 3
  };
  ```

  - **`getOrInsert` is one probe**: the value of the entry found, or `insertAt`
    of `v` through the bucket the probe stopped at. `v` is evaluated either way,
    as every argument is (`tests/cases/map_extras_get_or_insert`, whose loop
    `tests/run.js` counts as one `probe` and no `getOrInsert` call).
  - **`reserve` is the table's `reserveSlots`**, which doubles the bucket table
    until `n` entries, dead ones included, fit under the three-quarters bound,
    and re-files the buckets from the stored hashes. It never shrinks a table,
    a count that is not positive does nothing, and one past the 2^24 - 1 entry
    cap is the cap (`map_extras_reserve`). It moves no entry, so like
    `getOrInsert` it may be called during a walk of the table
    (`map_extras_walk`), and both are lowered in each instantiation of a
    generic caller (`map_extras_generic`) and in each module that calls them
    (`tests/link/map_extras_two_modules`). Only speed depends on it: each case
    prints under Node what it prints compiled
    (`tests/differential/unmodified.js`).
  - **They are generic functions, checked as one**: a first argument that is
    not a `Map`, or a key or value of the wrong type, is
    `` Argument 1 of `getOrInsert<i32, i32>`: expected Map<i32, i32>, got i32[] ``
    (`reject_map_extras_not_map`, `reject_map_extras_key_type`,
    `reject_map_extras_value_type`, and `reject_map_extras_reserve_count` for a
    count that is not a `number`); a missing argument is
    `` `getOrInsert` expects 3 argument(s), got 2 `` (`reject_map_extras_arity`);
    and a `Set` is not a table `reserve` takes:
    `` Cannot infer `K` for `reserve`: argument 1 is Set<string>, which does not match the declared `Map<K, V>` ``
    (`reject_map_extras_reserve_set`). The module has those two and nothing
    else: `` Module `nish/map` has no exported function `peek` ``
    (`reject_map_extras_unknown_export`, NL2376, the code any module's missing export now carries).
  - **The lowering belongs to `nish/map`'s two functions**, found by the module
    that declares them and not by their names: a program's own `reserve`, or a
    `getOrInsert` from its own module `./map`, is an ordinary function whose
    body runs (`tests/link/map_extras_user_names`).
- **`std/collections.ts` writes no `.ll` of its own.** What a module uses of it
  is emitted into that module, `internal`, after the module's own functions,
  so a one-file program that names `Map` is still one module for
  `-o <file.ll>` and every instance is inlined, specialised or dropped with
  the rest of the module. Two modules that share one `Map<string, i32>` each
  call their own copy of its methods (`tests/link/map_two_modules`). Under
  `-g` each copy's subprogram names `std/collections.ts`
  (`tests/cases/map_dbg`). The symbols are the package's
  (`@nish.Map$str$i32.set`), and a map is filled and grown through a callee
  and across loop arena scopes like any other object
  (`tests/cases/map_arena_callee`).
- **`m.get(k)` answers `V | undefined`**, as it does under `tsc`: a *maybe*.
  It is one probe, and a maybe is read in one of three ways, the three a
  program that type-checks under `tsc --strict` has
  ([wp32-map.md](wp32-map.md) §3):

  ```typescript
  export const main = (): i32 => {
    const counts = new Map<string, i32>();
    for (const w of ["a", "b", "a"]) {
      counts.set(w, (counts.get(w) ?? 0) + 1);      // a default
    }
    const a = counts.get("a");                      // a `const`, tested
    if (a !== undefined) {
      console.log(`${a}`);                          // 2: `a` is an i32 here
    }
    return counts.get("z") === undefined ? 0 : 1;   // a test
  };
  ```

  - **Where a maybe may stand**: the initialiser of a `const`, unannotated or
    annotated with the maybe type; the left operand of `??`; and an operand of
    `=== undefined` or `!== undefined`, either way round
    (`tests/cases/map_get_nullish`, `map_get_narrow`). The type is spelled
    `V | undefined` or `undefined | V`, and `Node | null | undefined` for a
    nullable `V` (a scalar is no more nullable here than anywhere,
    `reject_map_get_nullable_scalar`), and only as the annotation of a `const`
    initialised from a call of `get`. On a `let` initialised from `get` it is
    refused as the unannotated `let` is (NL2361, `reject_map_get_let_annotated`),
    and anywhere else it is the union it looks like (`reject_union_undefined`), and
    `undefined` as a value is refused as it always was
    (`reject_undefined_value`, and in a module constant, which never holds a
    `get` result, `reject_map_get_undefined_module_const`).
  - **A `const` bound to `get` is narrowed** by the rules of
    [Nullable types](#nullable-types), with `undefined` in place of `null`:
    it reads as `V` in the region a test proves it present, `if (a === undefined) return`
    included, and nowhere else (`map_get_narrow`,
    `reject_map_get_narrowing_leaks`). A `const` is never assigned, so its
    narrowing never ends early; a `let` would need that rule, and is refused.
    Narrowed, it is still the maybe it was bound to, as under `tsc`: testing it
    again, or defaulting it with `??`, reads the same found bit
    (`map_get_narrowed_again`).
    Compared with `undefined`, anything that is not a maybe is
    `` `undefined` is forbidden in Nish; use `null` with a `T | null` type ``
    (`reject_map_get_undefined_compare`).
  - **`a ?? d` has TypeScript's precedence**: the level of `||`, with operands
    that bind as tightly as `|`, left associative (`tests/parser/nullish`). It
    does not mix with `||` or `&&` without parentheses, as `tsc` reports
    TS5076: `` `||` and `??` cannot be mixed without parentheses `` is a
    syntax error (`reject_nullish_mixed_or`, `reject_nullish_mixed_and`),
    reported once however often an expression mixes them
    (`reject_nullish_mixed_chain_or`, `reject_nullish_mixed_chain_and`). `d`
    runs only when the value is missing, and it has type `V`, as does the
    whole expression:
    `` The right operand of `??` stands in for a missing value, so it must be `i32` ``
    (`reject_nullish_default_type`). When `V` is nullable, `??` replaces a
    stored `null` as well, as JavaScript's does, and the result is still `V`;
    `!== undefined` narrows to `V`, keeping the `null`
    (`map_get_pointer_value`). A `??` whose left operand is a `T | null`
    rather than a maybe is [Nullable types](#nullable-types)' default, and
    one whose left operand is neither is refused in the words Phase 0 always
    used,
    `` Nullish coalescing `??` is forbidden in Nish (narrow with `!== null` instead) ``
    (`reject_nullish`, `reject_nullish_nullable`), which the `nullish`
    feature of [the compatibility dialect](#the-compatibility-dialect) admits.
  - **Everywhere else a maybe is refused**, and the message names the place,
    because the rewrite differs by place. Some fail under `tsc` too (an
    operand, a `const` annotated `V`); the rest are legal TypeScript that this
    version does not take, because a maybe never crosses a call, never reaches
    memory, and is narrowed only in a `const` ([wp32-map.md](wp32-map.md) §3.2):

    | Place | Message after `` `m.get("a")` is `i32 \| undefined` `` | Case |
    | --- | --- | --- |
    | a `let`, or an assignment to one | `` and cannot be held in a `let` `` | `reject_map_get_let`, `reject_map_get_assign_let`, `reject_map_get_let_annotated` (NL2361) |
    | an argument of a function, method, constructor or builtin | `and cannot be passed as an argument` | `reject_map_get_argument`, `_argument_method`, `_argument_constructor`, `_argument_builtin` (NL2362) |
    | a `return`, or a concise arrow body | `and cannot be returned` | `reject_map_get_return`, `reject_map_get_const_read` (NL2363) |
    | a field, or an object literal's | `and cannot be stored in a field` | `reject_map_get_field`, `reject_map_get_object_field` (NL2364) |
    | an array element, or an array literal's | `and cannot be stored in an array element` | `reject_map_get_element`, `reject_map_get_array_literal` (NL2365) |
    | a template literal hole | `and cannot be a template literal hole` | `reject_map_get_template` (NL2366) |
    | an operand of any other operator | `and cannot be the operand of an operator other than` | `reject_map_get_arithmetic`, `reject_map_get_compare`, `reject_map_get_unary` (NL2367) |
    | the default of another `??` (`m.get(a) ?? m.get(b) ?? 0`) | `` and cannot be the default of another `??` `` | `reject_nullish_default_maybe` (NL2371); write `m.get(a) ?? (m.get(b) ?? 0)` |
    | a `const` annotated `V` | `` and cannot initialise a `const` annotated with its value type `` | `reject_map_get_annotated` (NL2368) |
    | anywhere else, a dropped result included | `` , which can only initialise a `const`, be the left operand of `??`, or be compared with `undefined` `` | `reject_map_get_statement` (NL2369) |

    `get` is called, never read as a value
    (`` Unknown field `get` on class `Map<string, i32>` (it is a method; call it) ``,
    `reject_map_get_property`), and its key is checked against `K`
    (`reject_map_get_key_type`, `reject_map_get_arity`).
  - **A maybe is two SSA values**: the found bit, which is the probe's packed
    answer compared with 0, and the value, which `valueAt` reads only on the
    edge where the bit is set. There is no struct and no store. Each `get` in
    the `map_get_*` goldens is exactly one call of the instance's `probe`, and
    `get` never probes twice nor calls `has`. `??` on a `get` is a branch to
    the value or the default and a `phi`; on a `const`, whose value is loaded
    already, with a literal or a name as its default, it is one `select`
    (`map_get_narrow`). Where the `??` is wanted as an interface its class
    implements, the two class pointers are joined and the result converted
    once (`map_get_interface`). A `const` holds a `phi` of the value and `V`'s zero,
    which no narrowed read can reach. A value built in the default goes
    wherever the `??` goes, as a ternary's arm does, so an object made there
    and stored in the map is allocated in the arena (`map_get_default_escapes`).
    Each value width is a golden: `map_get_value_i32`, `map_get_value_f64`,
    `map_get_value_bool`, `map_get_value_string`, an enum, `i64`, `u64` and
    `f32` in `map_get_value_widths`, and a class in `map_get_pointer_value`.
    Under `-g` a `const` bound to `get` is described by `llvm.dbg.value` of
    its payload, since it has no slot (`dbg_map_get`). The `number`-mode cases print under Node's own
    `Map` what they print compiled (`tests/differential/unmodified.js`).
- **`for...of` walks a table in insertion order**: `for (const k of m.keys())`,
  `for (const v of m.values())`, and for a `Set`, `for (const x of s)`,
  `s.keys()` and `s.values()`, which are one walk, as JavaScript's
  `Set.prototype.keys` *is* `values` ([wp32-map.md](wp32-map.md) §6.2, §6.3;
  `tests/cases/map_iter_keys`, `map_iter_values`, `set_iter`, `set_iter_keys`,
  `set_iter_values`). The variable takes `K` or `V`, and a deleted key is not
  visited. A walk in a generic function or method is checked per
  instantiation like the rest of its body (`map_iter_generic`).

  ```typescript
  export const main = (): i32 => {
    const ages = new Map<string, i32>();
    ages.set("ada", 36).set("alan", 41).set("grace", 85);
    ages.delete("alan");
    let total: i32 = 0;
    for (const name of ages.keys()) {
      console.log(name);                  // ada, then grace
    }
    for (const age of ages.values()) {
      total += age;
    }
    return total === 121 ? 0 : 1;
  };
  ```

  - **The table may change during the walk, with JavaScript's effect**, because
    the walk re-reads the entry count every pass and no entry moves while a
    loop walks the table. Each row is a golden whose output Node's own `Map`
    prints too (`tests/differential/unmodified.js`):

    | During the walk | Effect | Case |
    | --- | --- | --- |
    | `set` of a new key | visited later in the same walk | `map_iter_set_new`, `set_iter_values` |
    | `set` of a key already there | the new value is seen if the walk has not reached the key yet, and the key keeps its place | `map_iter_set_existing` |
    | `delete` of a key not yet visited | it is skipped | `map_iter_delete_ahead` |
    | `delete`, then `set`, of one key | it is visited again, at the end | `map_iter_delete_reset` |
    | `clear` | nothing more is visited, then whatever is set after it is | `map_iter_clear` |
    | enough inserts to grow the table | invisible: the buckets move, the entries do not | `map_iter_growth` |

  - **A walk defers compaction.** Compacting is the one thing that moves
    entries, so each table counts the loops walking it: the count goes up where
    a loop is entered and down on every edge that leaves it — the
    fall-through, `break`, a `return` or an `orReturn()` out of any number of
    walks around it — and not on `continue`. A rebuild while it is above zero
    doubles the table instead, and the first rebuild after the walk compacts.
    Churn during a walk moves nothing under it (`map_iter_compaction_deferred`),
    and churn after a walk left by each kind of edge allocates nothing once
    warm, which is a compacting table (`map_iter_break`, `map_iter_return`,
    `map_iter_or_return`). Walks are lexical loops, so nested walks of one
    table and a walk in a function called from a walk are counted exactly
    (`map_iter_nested`, `map_iter_callee`). A `break` out of a `switch` inside
    a walk leaves the switch and not the walk, a `return` from inside it closes
    the walk, and a receiver reassigned mid-loop does not change the table the
    walk closes, which is the one it opened (`map_iter_exit_edges`). It costs two stores a loop and
    none an entry. A walk never counts as a bounded loop: a body that sets a
    new key every pass never ends, as in JavaScript. An insert that would pass
    the 2^24 - 1 entry cap while a loop walks the table panics rather than
    compacting.
  - **The walk is four calls of the table's own code**: `walkOpen` where the
    loop is entered, `walkNext` for the first live entry and after each pass,
    `keyAt` or `valueAt` for the variable, and `walkClose` on each edge out,
    all emitted `internal` into each module that walks, like the rest of the
    table (`tests/link/map_walk_two_modules`)
    ([IR_COOKBOOK.md](IR_COOKBOOK.md#map-and-set-iteration)). Under `-g` the
    variable is described in its slot like any `for...of` variable
    (`dbg_map_iter`).
  - **An iterator is not a value**, so `keys()` and `values()` anywhere but as
    the iterable of a `for...of` are refused, naming the place:

    | Place | Message after `` `keys()` of `Map<string, i32>` `` | Case |
    | --- | --- | --- |
    | a `const`, a `let`, or an assignment | ` cannot be stored` | `reject_map_iter_const`, `reject_map_iter_assign`, `reject_map_keys` (NL2372) |
    | an argument | ` cannot be passed as an argument` | `reject_map_iter_argument` (NL2373) |
    | a `return`, or a concise arrow body | ` cannot be returned` | `reject_map_iter_returned` (NL2374) |
    | anywhere else, a dropped result or an uncalled `m.keys` included | `` can only be the iterable of a `for...of` `` | `reject_map_iter_statement`, `reject_map_iter_uncalled`, `reject_map_values` (NL2358) |

    `for (const e of m)` over a `Map` itself would walk `entries()`, whose
    `[key, value]` pairs are two-type tuples:
    `` `for...of` over `Map<string, i32>` needs `entries()` ``, with the
    rewrite, `for (const k of m.keys())` (`reject_map_iter_entries`, NL2375).
    It reports once: the variable is an error that its body reads without a
    second report (`reject_map_iter_recovery`). A spread is refused as it is
    in any array literal (`reject_map_iter_spread`, NL2237), `for...in` is Phase 0's NL1056 as it is over
    anything (`reject_map_iter_for_in`), `keys()` takes
    no argument (`reject_map_iter_arity`), and the variable has the type it
    walks (`reject_map_iter_variable_type`).
- **A module's own `Map` or `Set` wins in that module.** A module that
  declares or imports a class, interface, alias or enum of either name gets no
  implicit import, as the declaration shadows the global under `tsc`
  (`tests/link/map_own_class`), and its `get` is its own method, answering
  what its signature says (`tests/cases/map_get_user_class`). A type parameter called `Map` or `Set` is not a
  use of the global either, so a module whose only `Map` or `Set` is a type
  parameter loads nothing and compiles as it did before `Map` existed
  (`tests/cases/map_type_param_shadow`). It does not shadow the global,
  though: as for any class name in scope, a module that also uses the global
  `Map` refuses a type parameter of that name with
  `` `Map` is generic: it must be written with its type arguments ``
  (`tests/cases/reject_map_type_param_beside_global`), where `tsc` would
  shadow it. A class name is program-wide, though, so a
  program in which one module declares `Map` and another names the global is
  refused at the declaration:
  `` `Map` is declared here and main.ts uses the global `Map`; a class or interface name is program-wide, so one program cannot have both ``
  (`tests/link/map_clash`, NL3030).
- **Interop**: `--emit-header` declares an instance as an opaque struct,
  `typedef struct nish_gen_Map_str_i32 nish_gen_Map_str_i32;`, so a C host can
  hold one it was given and pass it back; `--emit-dts` and `--emit-napi` leave
  a function that takes or returns one unbridged, with the comment they write
  for a class.

### Typed JSON: `nish/json-typed`

The reference for each export, with its parameters, its answer and the codes it records, is its doc comment in [`std/json-typed.ts`](../std/json-typed.ts); the rules are here.

`jsonDecode(d, out)` reads one JSON object into a class and `jsonEncode(w,
value)` writes one back, and the code that does it is written by the compiler
from the class's fields. They are generic functions in
[`std/json-typed.ts`](../std/json-typed.ts), and every call of one is lowered
in place, in the module that makes it, so nothing is looked up by name at run
time and no class carries anything it would not otherwise have.

```typescript
import { JsonWriter } from "nish/json";
import { JsonLimits } from "nish/json-tokenizer";
import { JsonDecoder, jsonDecode, jsonEncode } from "nish/json-typed";

class Player {
  name: string = "";
  score: i32 = 0;
}

class Team {
  players: Player[];
  captain: Player | null = null;
  constructor() {
    this.players = [];
  }
}

export const main = (): i32 => {
  const d = new JsonDecoder(body, 0, toI32(body.length), new JsonLimits());
  const t = new Team();
  const code = jsonDecode(d, t);     // 0, or the first error's code
  const w = new JsonWriter(out, 0);
  jsonEncode(w, t);                  // {"players":[...],"captain":...}
  return code;
};
```

- **The decoder is `JsonDecoder`**, a [`JsonTokenizer`](../std/json-tokenizer.ts)
  over the input and a sticky error, and the encoder is the
  [`JsonWriter`](../std/json.ts) the call is given. The code written for a
  class is straight-line calls of their methods, one per field: for decoding,
  a loop over the object's keys that sends each key to the field it names
  and reads the value with the method of the field's type; for encoding,
  `w.key(name)` and the value's method per field, in declaration order. A
  nested class, an array's element class, a `| null` field's class and a
  `Map`'s values each get the same code of their own, so it recurses as the
  data does (`tests/link/std_json_typed`, whose `main.ll` is the golden of the
  code written for a one-field class and `tag.ll` of the code for a `u64`, an
  enum and arrays of each; [IR_COOKBOOK.md](IR_COOKBOOK.md#typed-json)).
  Because the encoding is calls of the writer's methods, it is written in the
  writer's modes: a writer set with `setIndent(2)` encodes what
  `JSON.stringify(v, null, 2)` writes, and a `setStrict(true)` writer fails a
  NaN or infinite `f64` field with `JSON_WRITE_NON_FINITE`
  (`tests/link/std_json_writer`).
- **A key is sent to its field by its length, then by one byte.** The code
  written for a class of three or more fields switches on the key's length in
  bytes, so a key is compared only with the names of that length. Where three
  or more names share a length, it switches once more, on the key's byte at
  the one position where those names differ most, and calls `keyIs` for each
  name that has that byte there, in declaration order; a byte none of them has
  is an unknown key at once. One or two names, of a class or of one length,
  are compared in turn with `keyIs`, which is no more calls. A key with an escape has no byte to switch on there, and is compared
  with every name of its length, so `"\u0069d"` is the field `id`
  (`tests/link/std_json_typed`, "wide: every key escaped"). A key is
  therefore compared with the names of its length that share its byte at that
  position, usually one, rather than with every name in turn, and a field
  name that is not ASCII is dispatched by its UTF-8 bytes like any other
  ("names: escaped field names decode").
- **What a field may be.** `T` is a declared class, and every field of every
  class the call reaches is one of these; anything else is refused at the
  call's argument, naming the class and the field:

  | Field type | JSON | Decoded with | Encoded with |
  | --- | --- | --- | --- |
  | `i32`, `u32`, `i64` | an integer written without a fraction or an exponent, in the type's range | `d.i32()`, `d.u32()`, `d.i64()` | `w.i32`, `w.u32`, `w.i64` |
  | `u64` | an integer written in digits alone, with no sign, fraction or exponent, up to 2^64 - 1 | `d.u64()`, through the tokenizer's `numberU64` | `jsonEncodeU64` |
  | a numeric `enum` `E` | the number of one of `E`'s members | `d.i32()`, then a `switch` over the members' values | `w.i32` |
  | a [string `enum`](#string-enums) `E` | the string of one of `E`'s members | `d.enumString()`, then the string's bytes against the members' strings | `w.string` of the member's string |
  | `f64` (and `number` under `--number-mode f64`) | any number; past the double range an infinity, which the writer writes as `null` | `d.f64()` | `w.f64` |
  | `boolean` | `true`, `false` | `d.boolean()` | `w.boolean` |
  | `string`, `string \| null` | a string, and `null` for the second | `d.string(cur)` | `w.string`, `jsonEncodeStringOrNull` |
  | a declared class `C`, `C \| null` | an object, and `null` for the second | `C`'s own decoding, into the object the field holds | `C`'s own encoding |
  | `T[]`, `T[] \| null` for any of the above | an array, and `null` for the second | `d.i32Array(cur)` and its kin, or `C`'s or `E`'s decoding per element | `jsonEncodeI32Array` and its kin, or `C`'s or `E`'s encoding per element |
  | `Map<string, V>`, `Map<string, V> \| null`, for any `V` in this table, `\| null` or not, a `Map` included | an object whose keys are the map's, each value a `V`, and `null` for the second | the object's keys in order, each value decoded as a `V` and `set` | the map's entries in its order, each value encoded as a `V` |
  | a [tagged union](#discriminated-unions) `U` of declared classes, `U \| null`, `U[]` | an object whose tag key names its variant, and `null` for the second | the tag's string, then that variant's decoding, into the object the field holds when its tag matches | the tag first, then the variant's own encoding |
  | `JsonNumber` from `nish/json-typed`, alone, `\| null`, in an array or as a `Map`'s value | any number, kept as the text it is written in | `d.number(n)`, which copies the number's bytes into `n` | `jsonEncodeNumber`, which writes them back |

  `` `jsonEncode` cannot handle `Sample.ratio`, which is `f32`: a field read or written as JSON is an `i32`, `u32`, `i64`, `f64`, `boolean`, `string` or a declared class, an array of one of those, or a `string`, a class or an array with `| null` ``
  (NL2485, `tests/cases/json_reject_field_type`; two classes down through an
  array's element, `json_reject_nested_field`; in a `| null` field's class,
  `json_reject_nullable_field`; in a class a `Map` holds,
  `json_reject_map_value_class`; `i32[][]`, `json_reject_nested_array`, and
  `Level[][]`, `json_reject_enum_nested_array`; a generic class of the
  program's own, `json_reject_generic_field`). The message goes on to name the
  kinds added since: `` a `u64` and an enum are too, alone or in an array, and so is a `Map` whose keys are `string` and whose values are any of these, with `| null` or not ``.
  A JSON object's keys are strings, so a `Map` keyed by anything else is
  refused, an enum included (`json_reject_map_key`, `json_reject_map_key_enum`),
  and so is a map whose values typed JSON cannot write, at any depth
  (`json_reject_map_value`, `json_reject_map_value_nested`). A `Set` and an
  array of maps are refused as well (`json_reject_set_field`,
  `json_reject_map_array`). A `Map` keyed by a string enum is refused with
  the rest (`json_reject_map_key_enum_string`): a map's keys are read and written as `string`s, and a string
  enum is not one. An enum that mixes strings and numbers is not one the
  language declares at all (NL1043, `json_reject_enum_mixed`), an enum is
  never `| null`, numeric or string, so a `Role | null` field is refused where
  it is written (NL2010, `json_reject_enum_nullable`) while a `Role[] | null`
  is a field like any other, and a
  `const enum` is refused where it is declared (NL2285,
  `json_reject_const_enum`). A value that is not a declared class is
  `` `jsonEncode`'s value is `Point`, which is not a class: typed JSON reads and writes an object through the fields of a declared class, and an interface, a generic class or any other type is not one in this version ``
  (NL2486, `json_reject_interface`, `json_reject_not_class`). An interface is
  a record stored inline wherever it is held, and decoding into one is left
  for a later version. A call inside a generic function is checked for each
  class an instantiation binds (`json_reject_through_generic`).
- **Decoding is strict, and every outcome is a code.** The keys are the field
  names, byte for byte, or the names the class's options give them. Every
  field is required unless its class's options make it optional, each key may
  appear once, and
  a key that names no field is an error unless `d.ignoreUnknown` is set, when
  the key's value is stepped over, checked but not kept. The first error sets
  `d.failed` and `d.errorAt`, the byte offset of the token it was found at,
  and every later call does nothing, as the tokenizer's and the writer's
  errors do; `jsonDecode` answers `d.failed`, and `d.reset` starts over:

  | Outcome | Code | `errorAt` |
  | --- | --- | --- |
  | a value of the wrong JSON type: a string for an `i32`, an array for a class, `null` for a field that is not `\| null`, a top-level value that is not an object, an integer that is no member's value for a numeric enum, a string that is no member's value, or a value that is not a string, for a string enum | `JSON_DECODE_TYPE` (-20) | the value |
  | a number its field cannot hold: a fraction or an exponent for an integer, or out of range, a negative number (`-0` included) for a `u64` | `JSON_DECODE_RANGE` (-21) | the number |
  | a key that names no field | `JSON_DECODE_UNKNOWN` (-22) | the key |
  | a key given twice, a field's or a `Map`'s, however it is escaped | `JSON_DECODE_DUPLICATE` (-23) | the second |
  | a field the object does not give | `JSON_DECODE_MISSING` (-24) | the object's `}` |
  | more keys, over every `Map` field of the decoding, than `d.maxMapKeys` (4,096 unless set) | `JSON_DECODE_MAP_LIMIT` (-25) | the first key past it |
  | a union's tag missing, not a string, or a string no variant writes | `JSON_DECODE_TAG` (-26) | the tag's value, or the object's `{` when it has none |
  | text that is not JSON, or that crosses a `JsonLimits` limit | the tokenizer's `JSON_TOK_ERR_*` (-1 to -13) | the tokenizer's |

  Nothing an input holds panics: the recursion is the data's, so the
  tokenizer's depth limit bounds it. That bound is the caller's
  `JsonLimits.maxDepth`, 128 by default: each level is one native frame, so a
  limit raised into the hundreds of thousands can run off the stack, and one
  kept to a few thousand cannot. The writer refuses a 65th open container
  (`JSON_WRITER_MAX_DEPTH`), so a value decoded from deeper than 64 levels
  encodes as `JSON_WRITE_TOO_DEEP` (`tests/link/std_json_typed`, which
  reaches each row at each depth, the limits included). A duplicate of a key
  `ignoreUnknown` steps over is not detected, because its value is never
  read. After an error every field of `out` holds a value of its type, some
  decoded and some as they were: an enum field or element never holds a
  number that is no member's, because such a number is not stored.
- **A numeric enum is its number.** It is read with `d.i32()`, so a
  number that is not an `i32` integer is that field's `JSON_DECODE_RANGE`, and
  an integer that is not the value of one of its members is
  `JSON_DECODE_TYPE`; a member's name, `"High"`, is a string and a type error
  too. Two members of one value are one number (`tests/link/std_json_typed`,
  "enum: two members of one value both read 1"). It is written as `w.i32` of
  its value, as `JSON.stringify` writes a TypeScript numeric enum.
- **A string enum is its member's string.** It is read with
  `d.enumString()`, which takes the value as a string without copying it,
  and its bytes are matched against the members' strings the way a key is
  sent to its field: by length, then by one byte, then with `keyIs`, so the
  read allocates nothing, and an escaped string, `"\u0061dmin"`, is the
  member its unescaped bytes spell. A string that is no member's, a prefix of
  one included, and a value that is not a string are `JSON_DECODE_TYPE`, and
  the field or element keeps the member it held. It is written as `w.string`
  of the member's string, which is what `JSON.stringify` writes for a
  TypeScript string enum (`tests/link/json_enum_string`;
  [IR_COOKBOOK.md](IR_COOKBOOK.md#typed-json)). A field, an array, a
  `| null` array and a `Map<string, Role>`'s values are read and written so.
- **A `u64` is exact to 2^64 - 1.** It is read through the tokenizer's
  `numberU64`, so `18446744073709551615` decodes and `18446744073709551616`,
  `-1`, `-0` and `1.5` are `JSON_DECODE_RANGE`. It is written as its digits,
  which `JSON.stringify` cannot do for a number past 2^53: `tests/run.js`
  holds `round-trip-kinds.txt` to `JSON.stringify(JSON.parse(line))` with each
  integer past 2^53 kept as its own digits (`JSON.rawJSON`).
- **A class's options are one `static readonly json` literal.** A class
  gives a field another key on the wire, and lets a key be left out, in an
  object literal written in the class, which the compiler reads when it writes
  the class's code:

  ```typescript
  class Account {
    static readonly json = { rename: { userId: "user_id" }, optional: ["tags"] };
    userId: i32 = 0;
    tags: string[] | null = null;
  }
  ```

  `rename` maps a field to its key, a string literal of any bytes, so
  `{"user_id":7}` is decoded into `userId` and `userId` is encoded as
  `"user_id"`; the field's own name is then a key no field has. The key is
  dispatched by its length and bytes like any other, escapes and non-ASCII
  included (`tests/link/std_json_typed/options.ts`, "rename: escaped wire
  names decode"). `optional` lists fields whose key may be missing: a missing
  one sets the field to its initializer, on a fresh object and on one decoded
  into again, so a reused object does not keep what an earlier input gave it
  ("optional: sets the missing fields back to their initializers"), and
  allocates nothing to do it. Every other missing key is still
  `JSON_DECODE_MISSING`, and an optional key that is given is read like any
  other: once, and of its field's type. The member is not a field: it has no
  slot, the class's layout is what it would be without it, the program
  cannot read it, and a class without it is decoded exactly as before. It is
  the one `static` member a class may declare, and its options are checked
  where the class is declared, whether or not any call decodes the class,
  each misuse with its own code:

  | Misuse | Code | Case |
  | --- | --- | --- |
  | `static json` without `readonly` but with a type, `static readonly json` with a type annotation, or on a generic class | NL2492 | `json_reject_options_mutable_typed`, `json_reject_options_annotated`, `json_reject_options_generic`, and on a generic class nothing instantiates, `json_reject_options_generic_unused` |
  | options, `rename`, a key or an `optional` entry not written as the literal it must be: a module constant, an array for the object, a string for `optional`'s array | NL2493 | `json_reject_options_alias`, `json_reject_options_alias_whole`, `json_reject_options_not_object`, `json_reject_options_optional_not_array` |
  | an option other than `rename`, `optional` and `presence` | NL2494 | `json_reject_options_unknown` |
  | a name that is not one of the class's fields | NL2495 | `json_reject_options_misspelt_rename`, `json_reject_options_misspelt_optional` |
  | a rename to a value that is not a string | NL2496 | `json_reject_options_rename_number` |
  | two fields with one key, a rename to another field's own name included, or a field renamed or made optional twice | NL2497 | `json_reject_options_wire_collides`, `json_reject_options_wire_twice`, `json_reject_options_optional_twice` |
  | an optional field with no initializer | NL2498 | `json_reject_options_no_initializer` |
  | a rename to a key that is not valid UTF-8, a lone surrogate such as `"\ud800"` included, which no input could give | NL2499 | `json_reject_options_surrogate` |
  | `presence` or one of its entries not written as an object literal of string literals | NL2493 | `json_reject_presence_not_object`, `json_reject_presence_not_literal` |
  | `presence` naming a field, or a presence field, the class does not declare | NL2495 | `json_reject_presence_misspelt_field`, `json_reject_presence_misspelt_flag` |
  | a presence field that is not a `boolean`, is `readonly`, is the field it records, records two fields, is recorded by a presence field of its own or is renamed or made optional; a field recorded twice | NL2592 | `json_reject_presence_not_boolean`, `json_reject_presence_readonly`, `json_reject_presence_itself`, `json_reject_presence_shared`, `json_reject_presence_of_presence`, `json_reject_presence_recorded`, `json_reject_presence_renamed`, `json_reject_presence_optional`, `reject_json_presence_twice` |

  A spread in the literal is
  `` `User.json` spreads another value into the typed JSON options: … ``,
  because the options are read from the class's text, where a spread names
  nothing (NL2711, `reject_json_options_spread`), and a computed key is
  refused by Phase 0 as it is anywhere (NL1041,
  `json_reject_options_computed`), a subclass by `extends`
  (`json_reject_options_subclass`), and a second `static readonly json` is a
  duplicate member (`reject_json_options_twice`). The options are not a
  value: `User.json` names a class where a value is due, and is refused as
  any class name there is (`json_reject_options_read`). Only `static readonly json`
  may leave out its type: written `static json = { ... }`, or as an instance
  field, it is an ordinary field to the parser and needs one
  (`a type annotation is required`, `json_reject_options_mutable`,
  `json_reject_options_instance`), and an instance field called `json` with a
  type is an ordinary field, read and written under its own name
  (`tests/link/std_json_typed/options.ts`, "instance json: an ordinary field
  decodes"). The options are not a member, so a field or a method called
  `json` may come before or after them, as in TypeScript, whose statics have
  a namespace of their own ("order: a json field before the options
  decodes", "order: a json method before the options decodes"). Under Node the literal is a
  static property of the class that nothing reads.
- **`presence` records which keys were given.** A third option names, for a
  field, a `boolean` field of the same class that every decoding sets to
  whether the input gave that field's key; a key given `null` is given:

  ```typescript
  class UserPatch {
    static readonly json = { optional: ["email"], presence: { email: "hasEmail" } };
    email: string | null = null;
    hasEmail: boolean = false;
  }
  ```

  So `{}` leaves `hasEmail` false, and `{"email":null}` and `{"email":"a"}`
  set it true, which `optional` alone cannot tell apart from a key given the
  initializer. Any field may be recorded, of any kind the decoder takes and
  optional or not (`tests/link/json_presence`). The presence field is off the
  wire: no key decodes into it, `jsonEncode` leaves it out, it takes no part
  in the key-uniqueness rule, and no option renames it, makes it optional or
  records it. It is set when the object closes, from the per-field flag the
  decoder already keeps to report a duplicate or a missing key: one `store i1`
  per recorded field, no allocation, and a class that records nothing compiles
  to the code it did before. Each object decoded sets its own, so a nested
  class, an array element and a map's value answer for their own keys, and a
  second decoding into one object answers for its own input. A decoding that
  fails may have set some presence fields and not others (none, when the input
  is not an object), so they are read only after `JSON_DECODE_OK`. A JSON Merge Patch (RFC 7396) is applied with it: the patch
  is a class whose fields are all optional and recorded, and `null` on a field
  that is not `| null` is `JSON_DECODE_TYPE`, so the patch is refused before
  any of it is applied (`examples/merge-patch.ts`,
  `tests/link/json_merge_patch`).
- **A `JsonNumber` is a number's text.** `JsonNumber`, from `nish/json-typed`,
  holds a number as the bytes it was written in, so a field of it decodes and
  encodes any number byte for byte: an integer wider than a `u64`, a fraction
  with more digits than an `f64` holds, `1E+400` and `-0` alike
  (`tests/run.js` holds each line of `round-trip-options.txt` to
  `JSON.stringify(JSON.parse(line))` with every number kept as its source).
  It is read as a number whole, not as an object, so anything but a number is
  `JSON_DECODE_TYPE`, and its length is bounded by `JsonLimits.maxNumberBytes`
  like any number's. Decoding into one reuses its bytes, so `Arena.used()`
  stays flat over decodes into one object. It reads its text as
  `nish/json-value` reads a number: `text()`, `isI64()` and `i64()`,
  `isU64()` and `u64()`, and `f64()`, the nearest double; `setText(t)` sets it
  when `t` is one JSON number and answers whether it was. A new one holds
  `0`. Its methods run under Node, and `tests/run.js` holds them to the
  native lines (`readers.ts`).
- **A `Map<string, V>` is an object.** Decoding empties the map the field
  holds once the object opens, then reads each key as a new string and its
  value as a `V`, made fresh for the key (a zero, `""`, the enum's first member,
  `null`, or a new object, array or map, which a `Map`'s value class is made
  with `new C()` for, so its constructor takes no parameters, NL2488,
  `json_reject_map_value_constructor`), and `set`s it, so the map's entries
  are the input's, in the input's order. A key the object gave already is
  `JSON_DECODE_DUPLICATE` before its value is read, whether it is spelled
  the same way or through an escape (docs/security/json.md, JSON-3). Encoding
  writes the entries in the map's own order, which is insertion order. That
  differs from a JavaScript object in one case: a key that reads as an array
  index (`"1"`) keeps its place, where `JSON.parse` would move it first
  ("map: a key like an index keeps the input's order"). Unlike the rest of a
  decode, a map's entries are made anew each time, so decoding into a map
  allocates its keys and values. A value whose read fails is not `set`, so a
  map never holds a value the input did not give ("map: and the map holds
  only the entry read before it"). The maps of one decoding take at most
  `d.maxMapKeys` keys between them, 4,096 unless set, the keys of a map inside
  another map included, and the key past it is `JSON_DECODE_MAP_LIMIT` before
  it is read ("map limit: one key past it: code", "map limit: 820 small maps,
  4,100 keys, are refused"); `d.reset` starts the count again. At `0` or below
  no map may take a key, and `{}` is the one map value accepted. The global
  `Map` hashes a string under a per-process random key, so a body cannot
  choose keys that collide, and this limit bounds what all the maps of one
  decoding hold together (docs/security/json.md, JSON-13).
- **A tagged union is an object with its tag.** A field, an array's element
  or the value of `jsonEncode` may be a [discriminated union](#discriminated-unions)
  whose variants are all declared classes, and the union is written as the
  variant's object with its tag key first, the tag's value the name of its
  enum member, or for a [string enum](#string-enums) the member's string:

  ```typescript
  enum Kind { Num, Neg }
  class Num {
    readonly kind: Kind.Num = Kind.Num;
    value: f64 = 0;
  }
  class Neg {
    static readonly json = { tag: "negate" };
    readonly kind: Kind.Neg = Kind.Neg;
    arg: Expr;
    constructor() { this.arg = zero(); }
  }
  type Expr = Num | Neg;
  const zero = (): Expr => new Num();

  const e = jsonDecodeUnion(d, zero());  // {"kind":"negate","arg":{"kind":"Num","value":2}}
  jsonEncode(w, e);                      // the same text back
  ```

  With `enum Kind { Num = "num", Neg = "neg" }` the same union writes
  `"kind":"num"`, and `Neg`'s `tag` still writes `"negate"`
  (`tests/link/json_enum_string`). A variant's `tag` option replaces its
  member's name or string on the wire, and
  `rename` renames the tag key as it renames any field. Every variant writes
  its tag under one key and as a different string, or the union is refused
  where a call reaches it (NL2721, `json_reject_union_tag_key`; NL2720,
  `json_reject_union_same_tag`); a `tag` that is not a string literal is
  NL2722 (`json_reject_union_tag_literal`), one on a class with no field whose
  type is one enum member is NL2724 (`json_reject_union_tag_no_field`), and
  `tag: ""` is the same as no `tag`: the variant writes its member's name,
  or string. A
  `tag` on a class that has such a field but that no union holds is not
  refused and does nothing: the class compiles while no JSON call reaches it,
  and one that does refuses the field (below). A variant
  that is not a class, an interface, is NL2486
  (`json_reject_union_interface`), the code of any typed JSON type that is not
  a declared class. A field typed with an enum member that no
  union tags a variant with is no tag, and is refused as any other field type
  is (`json_reject_enum_member`). `jsonDecode` decodes into the object it is
  given and a union's variant is known only from the input, so a union is
  decoded with `jsonDecodeUnion(d, prev)`, which answers the object it decoded
  into: `prev` itself when the input's tag is `prev`'s, reused as any nested
  object is, and otherwise a new variant made with `new V()`. On a failure it
  answers `prev`, with the code in `d.failed`, at the top only: a union field,
  element or `Map` value already holds the new variant when the failure comes,
  decoded up to it, as any failed decode leaves what it read. Its type argument is inferred
  from `prev` and never written; `jsonDecode` with a union is
  `` `jsonDecode`'s value is `A | B`, a tagged union: … ``
  (NL2719, `json_reject_union_decode`), and `jsonDecodeUnion` with a class is
  NL2723 (`json_reject_union_not_union`). A union field decodes into the
  object it holds the same way, and an array's element past its end is made
  fresh. The tag may come anywhere in the object: when it is the first key
  the variant is known at once, and otherwise the decoder reads ahead to it,
  stepping over the values before it, and rewinds, so each byte is read at
  most `maxDepth` + 1 times (docs/security/json.md, JSON-17). A tag that is
  missing, not a string or no variant's is `JSON_DECODE_TAG`. A variant used
  alone, as a class, decodes and encodes its tag too, and a tag that is not
  its own is `JSON_DECODE_TAG`. Each union gets one decoding and one
  encoding function, `.json.decode.union.<U>` and `.json.encode.union.<U>`,
  which every place it appears calls, so a recursive union such as `Expr`
  above recurses through them (`tests/link/json_tagged_union`). A
  `Map<string, Expr>` field decodes each value through that same function
  and encodes it through the other.
- **Decoding reuses what `out` holds.** A nested object is decoded into the
  object its field holds, an array's elements into the elements it has, with
  new ones made past its end and the rest dropped, and a string field keeps
  its string when the input's is equal. So decoding one shape into one object
  again and again allocates nothing: `Arena.used()` is flat over 1,000 decodes
  of a three-level object (`tests/link/std_json_typed`). A string that changes
  is a new string, since strings are immutable, and only that: it is made by
  one `String.fromBytes`, straight from the input when the string has no
  escape and from its unescaped bytes when it has one, and those bytes are
  reclaimed at the call. A class the decoder has to make itself
  — an array's element past the end, or the object of a `| null` field that
  holds `null` — is made with `new C()`, so its constructor takes no
  parameters:
  `` `jsonDecode` makes a `Pet` with `new Pet()`, and its constructor takes 1 parameter(s): an array's element and a `| null` field's object are made by the decoder with no arguments, so their class's constructor takes none ``
  (NL2488, `json_reject_constructor`, `json_reject_constructor_nullable`).
  Decoding assigns every field, so a `readonly` one is refused:
  `` `Key.id` is `readonly`, and `jsonDecode` assigns every field of the class it decodes into ``
  (NL2487, `json_reject_readonly`). A decode stores what it makes into the
  object it fills, so a call inside a `using a = arena()` block is the NL2424
  of [that block](#using-a--arena) (`json_reject_arena_block`). An encoding only reads the object and keeps nothing, so it may run inside one (`tests/link/std_json_typed`). Two fields
  holding one object are decoded into it twice, the second winning.
- **Encoding is `JSON.stringify`'s text** for the same object, its keys in
  declaration order, which is also the order an object's keys come back in
  when it is decoded from text whose keys are in that order:
  `tests/run.js` holds each line of `tests/link/std_json_typed/round-trip.txt`,
  decoded and encoded natively, to `JSON.stringify(JSON.parse(line))`. A full
  buffer is the writer's `JSON_WRITE_FULL`, and an object that holds itself
  ends at the writer's depth limit with `JSON_WRITE_TOO_DEEP`, because the
  encoding stops at the first failure rather than recursing on.
- **The TypeScript reading is class C**
  ([wp33-round-trip.md](wp33-round-trip.md) §2). Under Node the type
  arguments are erased, so there is no layout to write the code from, and the
  bodies in `std/json-typed.ts` that Node runs end the program with
  `panic("nish/json-typed: jsonDecode and jsonEncode are written by the compiler from the class's fields, and under Node the types are erased")`
  rather than guess a field's type from the value it holds
  (`tests/run.js`, "under Node, jsonDecode panics"). The translation is the
  code the compiler writes, written as TypeScript for each class: a function
  per class of the same calls into `JsonDecoder` and `JsonWriter`, which
  everything else in the module already runs under Node: `tests/run.js` runs
  the decoder's readers there and natively and holds both to the same lines
  (`tests/link/std_json_typed/readers.ts`). A program that
  imports `std/json-typed.ts` by path rather than as `nish/json-typed` is
  compiled as written and gets those bodies natively too.

### Capabilities

Each builtin's label is the `Capability:` line of its doc comment in [`runtime/nish.d.ts`](../runtime/nish.d.ts); the rules are here.

Every builtin carries exactly one **capability** label, or a deliberate none,
and the compiler works out which capabilities every function, module and
package can reach — directly, through any chain of calls, across packages — with
one witness call chain for each ([wp35-capabilities.md](wp35-capabilities.md)).
A program is refused for what it reaches only under a [capability
policy](#the-capability-policy); without one, the set is a report.

| Capability | Builtins |
| --- | --- |
| `clock` | `Date.now`, `monotonicNanos`, `wallClockNanos`, `statMtimeSync` (`tests/cases/caps_clock`) |
| `entropy` | `crypto.getRandomValues`, `Math.random` (`caps_entropy`) |
| `env` | `getenv`, `geteuid` (`caps_env`) |
| `exit` | `process.exit`, and `exit` from `nish:process` (`caps_exit`) |
| `ffi` | any call to a `declare function` (`caps_ffi`) |
| `fs.read` | `readFileSync`, `readFileSyncOrNull`, `readFileBytesSync`, `readdirSync`, `realpathSync`, `isDirectorySync`, `lstatOwnerModeSync`, `isExecutableSync`, `fileOpen`, `fileReadAt`, `fileSize`, `fileClose` (`caps_fs_read`, `caps_file_read`) |
| `fs.write` | `writeFileSync`, `appendFileSync`, `mkdirSync` (`caps_fs_write`), `writeFileBytesSync`, `renameSync`, `unlinkSync` (`caps_fs_replace`), `writeFileSyncMode`, `createFileExclusiveSync`, `mkdirSyncMode` (`caps_fs_mode`) |
| `net` | every `nish:net` export (`caps_net`) |
| `process.spawn` | `spawnSync`, `spawnSyncTo` (`caps_process_spawn`), `spawnPiped` (`caps_process_spawn_piped`), `spawnPipedWithin` (`caps_process_spawn_piped_within`), `spawn`, `kill`, `waitPid` (`caps_process_wait`), `setNice`, `setIdlePriority`, `setCpuAffinity` (`caps_process_nice`) |
| `signal` | `signalFd`, `readSignal` (`caps_signal`) |
| `tty` | every `nish:term` export (`caps_tty`) |
| `unsafe` | the eight `nish:unsafe` exports: `uncheckedGet`, `uncheckedSet`, `wrappingAdd`, `wrappingSub`, `wrappingMul`, `readCString`, `readStruct`, `cErrno` (`tests/link/caps_policy_deny_unsafe`; "capabilities: each of the eight `nish:unsafe` exports carries `unsafe` at its call") |

Everything else is none: printing (`console.*`, `write`, `writeError`, `writeBytes`),
`process.argv`, `process.platform` and `process.arch`, `availableParallelism` and `totalMemory` (`caps_host`), `panic`, `Arena.*` and `arena()`,
`Math.*` other than `random`, the conversions, the constant-time builtins, `secureZero`, the
string, array, `Map` and `Set` surface, and `nish/threads` (`caps_pure`). A
`nish:` import carries the label of the builtin it renames.

- A function is judged **per instantiation**: `pick<i32, double>` and
  `pick<string, firstLine>`, or `apply<lengthOf>` and `apply<(name) => ...>`,
  are separate entries with separate sets (`caps_generic`, `caps_fnarg`). A
  module's set is the union over its functions, a package's over its modules,
  and the program's is `main`'s closure (`tests/link/caps_package`). A
  parallel body cannot reach a capability at all: every builtin that carries one
  writes memory the runtime shares (`tests/link/caps_parallel`,
  `reject_caps_parallel_clock`).
- A program is **deterministic** when it reaches none of `clock`, `entropy`,
  `env`, `ffi`, `fs.read`, `fs.write`, `net`, `process.spawn` and `tty`: the
  same argv and stdin then give the same output. `tty` is among them although
  stdin is an input a deterministic program may read, because `nish:term` reads
  it against the clock (`waitStdin`'s timeout, `readStdin`'s "nothing yet")
  and asks the terminal itself. `exit` and `signal` keep a program
  deterministic (`caps_exit`, `caps_signal`).
- `--emit-capabilities <file.json>` writes the report: version, entry,
  `deterministic`, the program's set, then each package, module and exported
  function (and every instantiation of one) with its set and a witness chain
  per capability, `{ "function", "at": "path:line:col", "calls" }` per call,
  and then its `"panics"`: every [panic site](#panic-sites) the function has,
  `{ "kind", "at": "path:line:col" }` followed by the keys `--emit-panics`
  writes after its position (`"proven"`, `"callee"`, `"via"`, `"allowed"`).
  Keys are in a fixed order, sets in the order of the table above, packages,
  modules and functions sorted, and every path relative to the entry's
  directory, so the file is byte-stable and diffable (`.caps.json` beside each
  `caps_*` case). `nish run --capabilities` — or `--capabilities` on a compile —
  prints one line on stderr, `capabilities: fs.read (not deterministic)` or
  `capabilities: none (deterministic)`, before the program runs, and leaves its
  stdout alone. `--emit-capabilities` without a file is a usage error, exit 2,
  and so is either flag with `--emit-ast`, which stops before the checker;
  with `--emit-checked` both are answered beside the dump, and
  `--fix`, which answers before the program is analysed, takes neither. `nish run` refuses
  `--emit-capabilities` as it refuses every product it keeps to itself.

#### The capability policy

`--allow <cap>[,<cap>...]` and `--deny <cap>[,<cap>...]`, each repeatable,
and `"nish": { "capabilities": { "allow": [...], "deny": [...] } }` in the
root `package.json` (the one nearest above the entry, where `noPanic` is read)
are a **capability policy**, and a program whose entry reaches a capability
the policy does not grant is refused
([wp36-capability-policy.md](wp36-capability-policy.md)). The same object's
`dependencies` key grants a dependency its gated capabilities, as [a
dependency's capabilities](#a-dependencys-capabilities) says (NL3041, NL3042):

```text
main.ts:6:36: error: `main` reaches `net`, which the capability policy does not grant (the root package's `deny`); the chain that reaches it: main.ts:6:36 calls dial, client.ts:5:10 calls netAddress
```

- A denied capability is refused when it is reached. Giving `--allow` or an
  `allow` list makes the policy an allowlist: a reached capability it does not
  list is refused, `exit` and `signal` included. The command line can only
  narrow the manifest: denials union and allowlists intersect.
- What is judged is every function outside code can call: `main` alone in a
  closed `--link` build or under `nish run`, and in an open one (`-o` alone, a
  sidecar, a `declare function`, wasm) `main` and every exported function of
  every module, or every function at all under `--no-strict-exports`
  (`tests/wordings/nl2459_policy_library`, `nl2459_policy_unexported`). Each
  refused capability is one error (NL2459), reported in source order, spanned
  at the first call of the witness chain and naming every hop of it as
  `--emit-capabilities` writes them (`tests/wordings/nl2459_policy_deny`,
  `nl2459_policy_allowlist`; `tests/link/caps_policy_manifest`,
  `caps_policy_two_denied`). The command line can only narrow
  (`caps_policy_cli_cannot_widen`, `caps_policy_allow_intersect`,
  `caps_policy_allow_narrowed`, `caps_policy_manifest_allow_cli_deny`).
- `unsafe` can be denied — `--deny unsafe` refuses a program that reaches a
  `nish:unsafe` export anywhere in its closure
  (`tests/link/caps_policy_deny_unsafe`) — and never allowed: the import is
  the opt-in, so an allowlist does not refuse it and `--allow unsafe` is a
  usage error.
- `unsafe` travels like every other capability — to each caller, however far
  up, and to the module and package above it, including a dependency that
  imports `nish:unsafe` when the entry package does not — and keeps a program
  deterministic ("capabilities: `unsafe` reaches a caller two frames up, with
  the whole chain as its witness", "capabilities: a dependency that imports
  `nish:unsafe` gives `unsafe` to its package and to the entry that calls
  it"). No flag turns a check off for a whole program, so `nish:unsafe` is
  the only way to one and `--deny unsafe` sees every unchecked site.
- A name that is no capability, `--allow unsafe`, a capability both allowed
  and denied, and a directory scope (`fs.read=<dir>`) without `--sandbox`,
  which alone enforces one (**Directory scopes** under
  [The sandbox](#the-sandbox)), are usage errors, exit 2. In `package.json` they are errors where the
  manifest writes them: the wrong shape of `capabilities`, `allow` or `deny`
  written twice included (NL3032, `tests/link/caps_policy_manifest_shape`,
  `caps_policy_manifest_repeated`), a name that is no capability (NL3033,
  `caps_policy_manifest_unknown`), `unsafe` under `allow` (NL3034,
  `caps_policy_manifest_unsafe`) and a capability under both (NL3035,
  `caps_policy_manifest_both`).
- **The `"nish"` field is read strictly**, as [the no-panic scope](#the-no-panic-scope) says:
  a key is decoded as `JSON.parse` decodes it, so a policy written with an
  escape is honoured (`caps_policy_manifest_escaped_policy`,
  `caps_policy_manifest_escaped_entry`), and anything the reader could
  otherwise not vouch for — a second `"nish"` or `capabilities`, a key other
  than `noPanic`, `capabilities`, `host`, `compat` and `netRings` — is NL3036
  (`caps_policy_manifest_repeated_nish`, `caps_policy_manifest_repeated_policy`,
  `caps_policy_manifest_nish_unknown_key`).
- A policy changes no byte of the IR: a program inside it compiles and runs as
  it does with none (`tests/link/caps_policy_granted`,
  `caps_policy_manifest_granted`). `nish run` takes both flags and refuses
  before it links; `--fix` and `--emit-ast` refuse them.

##### A dependency's capabilities

A dependency — a package loaded from `node_modules` — may reach `ffi`,
`fs.read`, `fs.write`, `net`, `process.spawn` and `unsafe`, the **gated**
capabilities, only when the root
`package.json` grants them to it by name; it reaches every other capability
without one ([wp40-dependency-capabilities.md](wp40-dependency-capabilities.md)):

```json
{ "nish": { "capabilities": { "dependencies": { "pkg_http": ["net"] } } } }
```

A dependency that reaches one it is not granted is refused (NL2576), in the
dependency, naming the package, the capability and the function:

```text
node_modules/pkg_http/src/index.ts:6:10: error: the dependency `pkg_http` reaches `net` through `dial`, which the root package does not grant it; grant it with "nish": { "capabilities": { "dependencies": { "pkg_http": ["net"] } } } — the chain that reaches it: node_modules/pkg_http/src/index.ts:6:10 calls netAddress
```

- A dependency's capabilities are the union over **every** function its
  modules define, exported or not, called or not
  (`tests/link/caps_dep_unexported`), and what it reaches through another
  dependency is its own: granting the package that dials refuses the one that
  calls it (`caps_dep_transitive`). One error per package and capability,
  spanned at the first call of the witness chain from the package's first
  function, in source order, that reaches it (`caps_dep_order`; one refused and
  one granted program per capability, `caps_dep_net_refused` …
  `caps_dep_unsafe_granted`).
- The standard library is never refused, and what decides is where a module
  was resolved, not its package's name: a dependency that calls itself `nish`
  is judged like any other (`caps_dep_std_not_refused`, `caps_dep_named_nish`).
  The ungated capabilities need no grant (`caps_dep_ungated`).
- A function argument counts where it is instantiated: the root's function
  passed to a dependency's template makes the instantiation, which is the
  dependency's, reach what that function reaches, so the dependency is
  refused for it (`caps_dep_fnarg_callback`).
- Only the root manifest grants: no flag does (`--allow net` leaves the
  dependency refused, `caps_dep_cli_cannot_grant`), nor the dependency's own
  manifest (`caps_dep_self_grant`), and a grant never widens the root's own
  policy — a capability the root denies is refused by NL2459 whoever is
  granted it (`caps_dep_root_deny_wins`).
- `dependencies` is read as strictly as the rest of the field: a value that is
  not an object, a package named twice, a grant that is not an array and an
  entry that is not a string are NL3041 (`caps_dep_manifest_not_object`,
  `_repeated`, `_not_array`, `_non_string`), a name that is no capability is
  NL3033 (`caps_dep_manifest_unknown`) and one that is not gated NL3042
  (`caps_dep_manifest_ungated`). `unsafe` may be granted, keys are decoded as
  JSON, and a grant to a package the program does not load is no error
  (`caps_dep_manifest_unsafe`, `_escaped_name`, `_unloaded`).
- `fs.read` and `fs.write` are gated: a dependency that reads or writes a file
  needs its grant like one that dials (`caps_dep_fs_read_refused`,
  `caps_dep_fs_write_refused`).

A grant entry may carry an **argument**, `capability=argument`, which narrows
it: a directory for `fs.read` and `fs.write`, a program for `process.spawn`,
a numeric host, or a Unix socket's absolute path, for `net`. An entry
without one grants the capability whole, as before:

```json
{ "nish": { "capabilities": { "dependencies": {
  "pkg_tool": ["fs.read=./data", "process.spawn=git", "net=127.0.0.1"]
} } } }
```

- A directory is resolved from the root package's directory and must exist
  when the program is built (NL3047); a program is found on `PATH`, or as a
  path from that directory (NL3046); a host is an IPv4 or IPv6 address, the
  form `nish:net` takes (NL3045). `ffi`, `unsafe` and the ungated
  capabilities take no argument (NL3048; all four in
  `caps_dep_manifest_arg_refused`). A capability may be named more than once,
  one argument each.
- What the compiler can see it checks: a string literal a dependency hands
  `readFileSync`, `writeFileSync`, `spawnSync` or `netAddress` outside its
  grant is refused (NL2594), at the literal:

  ```text
  node_modules/pkg_conf/src/index.ts:2:38: error: the dependency `pkg_conf` hands `readFileSync` "/etc/passwd", which its `fs.read` grant does not cover: it is granted fs.read=data; name it in the grant, or grant `fs.read` whole
  ```

  (`caps_dep_arg_fs_too_narrow`, `_spawn_too_narrow`, `_net_too_narrow`; the
  grant that covers each, `caps_dep_arg_granted`).
- What it cannot see — a computed path, program or host — the build leaves to
  `--sandbox`, which scopes Landlock to the granted directories and
  programs ([The sandbox](#the-sandbox), `tests/link/sandbox_dep_*`).
  Hosts have no run-time check: seccomp cannot read the address a socket is
  given, so a `net=<host>` grant binds only the literals the build sees.
- The lockfile records the arguments (`"pkg_conf": ["fs.read=data"]`). A
  grant past them — a new directory, program or host for a capability the
  row records narrowed — is NL2593 until the lock is updated; a row that
  records the capability whole accepts any argument (`caps_lock_args`).
- `@nish_sandbox` takes a fifth operand for the programs a
  `process.spawn=<program>` grant allows, null when none is named, and a
  sixth, the number of restricted rings to make before the filter (WP63 S3;
  0 unless `main` reaches `net` with `NET_LISTEN_RING` and not
  `process.spawn`):
  `call void @nish_sandbox(i32 32, i32 1, i8* null, i8* null, i8* null, i32 0)`.
- `process.spawn=exec:<program>` grants the program as `process.spawn=<program>`
  does, and lets it start others: under `--sandbox` a granted program is held
  to its own start (no program it starts may exec again), and an `exec:` one
  is not, so its subtree may run anything the allowlist's EXECUTE reaches, its
  loaders included. The prefix is read before the program is resolved:
  `process.spawn=exec:` with no program is NL3046
  (`caps_dep_manifest_spawn_exec_refused`); the literal check treats
  `exec:<program>` as `<program>` (`caps_dep_arg_spawn_exec_too_narrow`,
  `caps_dep_spawn_exec_granted`); a program granted both ways is `exec:`; and
  the lockfile records the prefix, so adding it is NL2593
  (`caps_dep_lock_spawn_exec_widened`). The program is
  listed with three leading slashes, the same file to the kernel. For
  `tests/link/sandbox_dep_exec_optin`, granted `exec:env` and `true`, on an
  x86_64 glibc machine (illustrative: the paths, the loader and the length
  are the machine's; `tests/run.js` pins only the `///` entry for `env`):

  ```llvm
  @.sandbox.exec = private unnamed_addr constant [78 x i8] c"///usr/bin/env\00/usr/bin/true\00//usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2\00\00"
  ```

##### The capability lockfile

`--update-capability-lock` writes `nish-capabilities.lock.json` beside the
nearest `package.json` above the entry (beside the entry when there is none),
recording every capability each dependency reaches, gated or not. While the
file exists, every build is held to it:

```json
{
  "version": 1,
  "packages": {
    "pkg_http": ["net"]
  }
}
```

A dependency that reaches a capability its row does not record is refused
(NL2577), in the dependency, with the same witness chain as NL2576:

```text
node_modules/pkg_http/src/index.ts:6:10: error: the dependency `pkg_http` reaches `net` through `dial`, which `nish-capabilities.lock.json` does not record for it; review the chain, then record it with `--update-capability-lock` — the chain that reaches it: node_modules/pkg_http/src/index.ts:6:10 calls netAddress
```

- Only growth is an error. A row that records more than the dependency
  reaches, or a row for a package the program no longer loads, is accepted
  (`tests/link/caps_lock_shrink`, `caps_lock_stale`); a dependency with no row
  is held to an empty one (`caps_lock_no_row`, `caps_lock_no_row_pure`). One
  error per package and capability, in NL2576's order (`caps_lock_growth`).
- The comparison runs after both policies: a build the root's policy or the
  dependency grants refuse is refused by them, and `--update-capability-lock`
  on it writes nothing (`caps_lock_refused`). The flag skips the comparison and
  rewrites the file, even a malformed one.
- The file is byte-stable: packages sorted, capabilities in the fixed order of
  the report, two-space indentation, one trailing newline, `[]` for a package
  that reaches nothing. Neither the standard library nor the root package has
  a row.
- It is read strictly: text that is not JSON, a `version` other than `1`, a key
  other than `version` and `packages`, a name that is no capability, and a key
  or capability written twice are NL3043, spanned in the lockfile
  (`caps_lock_bad_json`, `_version`, `_key`, `_capability`, `_repeated`).
- The lockfile changes no byte of the IR. `nish run` takes the flag, and checks
  the program against the file before it looks in its cache, so the file is not
  part of the cache key and a cache hit is held to it too. `--fix` and
  `--emit-ast` refuse the flag.

#### `--deterministic`

`--deterministic`, on a compile or `nish run`, promises that the program's
`f64` and `f32` results are the same bits natively on x86-64 and AArch64, on
wasm32 and in the `--emit-ts` reading under Node
([wp50-wasm-host.md §9](wp50-wasm-host.md#9-w7-the-same-bits-on-every-target)):

- `Math.sin`, `cos`, `exp`, `log` and `pow` lower to `std/math.ts`'s
  `sinF64`, `cosF64`, `expF64`, `logF64` and `powF64` on every target, as on a
  page module, and a float `%` to `fmodF64` (an `f32` widened and the exact
  result narrowed back). The `--emit-ts` reading imports those functions, and
  `tanF64`, `atan2F64` and `hypotF64`, from `./nish/math.ts` in place of
  `Math`. `+ - * /`, `sqrt` and the exact builtins need nothing: they are
  correctly rounded everywhere, and every C unit and the program's IR are
  compiled with `-ffp-contract=off` with or without the flag.
- `f64ToBits` and `f32ToBits` give the canonical quiet NaN,
  `0x7ff8000000000000` and `0x7fc00000`, for every NaN (`quietBitsF64` and
  `quietBitsF32`); targets differ in the sign and payload of a NaN an
  operation makes.
- A program that reaches a nondeterministic capability — `clock`, `entropy`,
  `env`, `ffi`, `fs.read`, `fs.write`, `net`, `process.spawn` or `tty` — is
  refused with the chain that reaches it, as the capability policy refuses
  one: NL3052 the file system, NL3053 another machine or program (`net`,
  `process.spawn`), NL3054 C code or a host import (`ffi`), NL2700 the clock
  and the random source, NL2701 the environment and the terminal.
- `Number(s)`, `parseFloat(s)` and `parseInt(s)` read a string with one
  grammar on every target, the one `--emit-ts` reads: a `0x` integer, read by
  `std/math.ts`'s `numberExact` and `parseFloatExact` (which the flag calls
  in their place) and correctly rounded on any libc, and no hex float, so
  `Number("0x1p3")` is NaN and `parseFloat("0x1p3")` is 1 where a native build
  without the flag lets `strtod` read 8 (`deterministic_parse`). Every decimal
  spelling already agreed: glibc, musl and Node round them all correctly.

```text
main.ts:2:15: error: `main` reaches `clock`, which `--deterministic` refuses: the clock and the random source answer differently on every run; the chain that reaches it: main.ts:2:15 calls Date.now
```

The float corpus, `tests/differential/corpus/float/`, holds every operation
and `Math` builtin over ±0, subnormals, the normal extremes, ±Infinity, NaN,
integers near 2^53, multiples of π/4, NaN payloads read through
`f64ToBits` and `f32ToBits`, and 94 strings through `Number`, `parseFloat` and
`parseInt` to one `expected.txt` on each target
(`tests/run.js`, sections `deterministic` and `float-corpus`; the
`reject_deterministic_*` cases).

#### The sandbox

`--sandbox` holds a running native program to the capabilities its `main`
reaches. The policy above refuses at compile time a program that reaches more
than it grants; the sandbox makes the kernel refuse, at run time, what the
program's code does not reach, `ffi` callees and constructors included
([wp37-os-sandbox.md](wp37-os-sandbox.md),
[security/sandbox.md](security/sandbox.md)):

```llvm
@.sandbox.preinit = internal constant void ()* @.sandbox.apply, section ".preinit_array", align 8
@llvm.used = appending global [1 x i8*] [i8* bitcast (void ()** @.sandbox.preinit to i8*)], section "llvm.metadata"

define internal void @.sandbox.apply() {
entry:
  call void @nish_sandbox(i32 0, i32 1, i8* null, i8* null, i8* null, i32 0)
  ret void
}

define noundef i32 @main(i32 noundef %argc, i8** noundef %argv) #1 {
entry:
  call void @nish_sandbox_check()
```

- **The flag.** `--sandbox` is strict; `--sandbox=best-effort` runs on a
  kernel that lacks part of the confinement and says in one line on stderr
  what it could not withhold. Any other mode is a usage error, exit 2. It is
  accepted by `--link`, by `nish run` (before the file) and on the IR-only
  route, alone or beside the flags that write a file next to the IR; the
  `.ll` then carries the call, and linking it by hand keeps the confinement
  (`tests/cases/sandbox_hello`). `--emit-ast`, `--emit-checked`, `--emit-ts`,
  `--fix`, `--emit-napi` and `--emit-napi-async` refuse it, exit 2, since none
  writes a program with a `main` to confine, and so does an entry module that
  declares no `main` and holds no [top-level code](#top-level-code) to run
  as one (`--sandbox` on a script confines the `main` its code becomes). `--sandbox` and `--sandbox=best-effort` on one command
  line are refused, exit 2; the same one twice is one.
- **The call.** The first operand is `main`'s capability mask, numbered as
  `--emit-capabilities` numbers the bits (`clock` 0 … `tty` 10, `unsafe` 11), the
  second `1` for strict and `2` for best-effort; the two `i8*` operands are
  the `fs.read` and `fs.write` directory scopes below, `null` when there are
  none. `nish_sandbox` runs from `.preinit_array`, after the loader and
  before any constructor of the executable, an `ffi` object or a shared
  library, and applies, in order: `PR_SET_NO_NEW_PRIVS`, a drop of every
  Linux capability (each set read back), a Landlock ruleset masked to the ABI
  the kernel answers, and a seccomp filter. `main` calls
  `nish_sandbox_check` first, which refuses to run a program whose C library
  never ran `.preinit_array` (musl), with exit 126 and one line: `nish:
  --sandbox: the C library did not run .preinit_array, so the program was
  not confined`.
- **What each capability's absence withholds.** Without `fs.read`, Landlock
  withholds reading files and directories; without `fs.write`, writing,
  making, removing, renaming and linking (within one directory too) and
  truncating, and seccomp
  answers `EPERM` to `chmod`, `chown`, `utimensat`, `setxattr` and their
  siblings, which Landlock does not decide. Without `process.spawn`,
  `execve`, `execveat`, `fork`, `vfork` and a `clone` without
  `CLONE_THREAD` kill the process, `clone3` answers `ENOSYS`, and Landlock
  withholds executing files and device `ioctl`s (ABI 5); with it, executing
  and reading files and device `ioctl`s are granted beneath `/`, since a
  child must load its binary and libraries, so a program that reaches
  `process.spawn` can read any file the user can whether or not it reaches
  `fs.read`. Without `net`, `socket`, `socketpair`, `connect`,
  `bind`, `listen`, `accept` and `accept4` kill it. With `net` but without
  `fs.write`, a pathname `unixListen` or `unixListenMode` is **`-13`**:
  Landlock counts making the socket file as a write (`MAKE_SOCK`), while an
  abstract name binds. The sandbox uses no Landlock right that covers
  connecting to a pathname socket, so `net` alone still lets `unixConnect`
  reach any pathname listener whose file and directories the user may
  reach; only abstract
  names outside the sandbox are scoped, from ABI 6. `ffi`, `unsafe`, `tty`,
  `clock`, `entropy`, `env`, `exit` and `signal` withhold nothing of their
  own; the ABI 6 scopes under **Always** apply whatever `main` reaches.
- **Directory scopes.** Under `--sandbox`, `--allow fs.read=<dir>` and
  `--allow fs.write=<dir>` grant the capability beneath `<dir>` alone. The
  directory is resolved, symlinks and all, when the program is built, and
  must exist then, or it is a usage error, exit 2: `` compile:
  `fs.read=<dir>` names no directory; a scope is a directory that exists when
  the program is built ``. Any other capability scoped, or a scope in
  `--deny`, is refused, exit 2, and so is a scope without `--sandbox`, as
  before. A scope narrows the policy like any `--allow` list, so the same
  list names every other capability the program reaches. A capability also
  granted whole is granted whole. The scopes are emitted as one constant per
  capability, each directory ended by a NUL and the list by a second:
  `@.sandbox.read = private unnamed_addr constant [N x i8] c"/srv/data\00\00"`,
  passed as `nish_sandbox`'s third (`fs.read`) and fourth (`fs.write`)
  operand, `null` when `main` does not reach the capability. Landlock grants
  the scoped access beneath each directory and nothing else, except that a
  `main` reaching `process.spawn` keeps reading every file beneath `/`
  (`READ_FILE`, so that `exec` can load a program), scope or not; `chmod`,
  `chown`, `utimensat`, `setxattr` and their siblings still answer `EPERM`
  inside an `fs.write` scope, since seccomp cannot read a path. A main that
  reaches `ffi` is widened by the policy's `net`, `fs.read`, `fs.write` and
  `process.spawn` grants, a scope included, since foreign code reaches them
  without the checker seeing it. A directory cannot hold a comma.
- **The CPU count.** Before it confines anything, `nish_sandbox` reads the
  CPU count (the affinity mask and the cgroup quota) and keeps it as the
  thread pool's ceiling, since without `fs.read` the quota under
  `/sys/fs/cgroup` cannot be read afterwards. `NISH_NUM_THREADS` still lowers
  the pool. `availableParallelism()` reads the count again on each call and
  is not bounded by that ceiling, so in such a program it no longer sees the
  quota.
- **Always.** `ptrace`, `process_vm_readv`, `process_vm_writev` and
  `pidfd_getfd` kill; io_uring kills without `net`, and with `net` but not
  `process.spawn` only `io_uring_enter` is let through, on the premade
  rings' descriptors, matched by descriptor number (see the premade rings
  below); on x86-64 a system call numbered with bit 30 (x32) kills, and
  a call from any other architecture's entry kills. A killed process ends by
  `SIGSYS`, exit status 159 from a shell. From Landlock ABI 6 a sandboxed
  process cannot signal or reach the abstract sockets of a process outside
  it.
- **The premade rings.** With `net` granted and `process.spawn` not, a
  program whose `main` reaches `tcpListenFlags` with `NET_LISTEN_RING` gets
  its rings before the filter loads: `nish.netRings` in the root
  `package.json` (an integer from 1 to 64, default 1; anything else is
  NL3058) restricted rings, each taking only `ACCEPT`, `RECV`, `SEND`,
  `CLOSE`, `ASYNC_CANCEL` and `NOP`, with the submission flags
  `FIXED_FILE`, `BUFFER_SELECT` and `CQE_SKIP_SUCCESS`; any other
  submission completes with `-13`. Ring listeners take them as they fill:
  once every ring made is in use, a listener whose rings are full answers
  `-23` from `tcpAccept` until a connection closes, a ring listener opened
  after that serves descriptors, and a kernel or limit that refuses them
  leaves the process on descriptors for good, which `netRingState()`
  reports. One more ring, the keeper, takes only `NOP` and is entered by
  nothing; a ring a closed listener held has the keeper put at its
  descriptor number, so no premade ring's number is ever free. `close`,
  `dup2` and `dup3` naming a ring's or the keeper's number as the descriptor
  they close or replace kill, except a `dup3` from the keeper, which is how
  the runtime puts the keeper at a freed ring's number, and `close_range`
  fails with `ENOSYS`, as on
  a kernel older than 5.9; on every other
  descriptor they work as before (NURING-36 in `docs/security/net-uring.md`).
- **Refusals.** A program whose sandbox cannot be applied prints one line,
  `nish: --sandbox: ...`, and exits 126 before `main` runs. Strict refuses a
  kernel without Landlock, and one below ABI 3 when `fs.write` is not
  granted, since `TRUNCATE` cannot be withheld there, or when it is granted
  only beneath a directory, since below ABI 3 that grants nothing beneath
  `/`; best-effort runs on
  both, naming what it could not withhold (without Landlock, files are not
  confined at all). A scope directory missing at run time is refused by
  strict, `nish: --sandbox: cannot open the directory <dir> (ENOENT)`;
  best-effort leaves its rule out, so nothing beneath it is granted, and
  names it once. Neither mode refuses a kernel without `IOCTL_DEV` (ABI 5)
  or the signal and socket scopes (ABI 6); best-effort names them.
- **Targets.** A darwin target, given or the host's, is refused (NL3044,
  `tests/wordings/nl3044_sandbox_darwin`). The wasm and WASI targets
  (`wasm32`, `wasm32-wasi`) accept the flag
  and emit no call, since the host already holds a module to its imports;
  `--profile wasm` refuses IR built with `--sandbox` for the host. A `.ll`
  built with `--sandbox` and linked on a platform other than Linux refuses to
  run, exit 126.
- **No byte of a program's IR moves without the flag**: the entry, its
  `@llvm.used` slot and the two declarations are emitted only under
  `--sandbox` ("sandbox: without the flag the IR is the sandboxed IR less the
  sandbox's lines"). `--runtime-decls`, which lists every declaration the
  runtime answers, lists the two whatever the flag.
- **Reserved names.** The runtime calls `prctl` and `syscall` from C, so in
  every build, sandboxed or not, a `declare function` of either name is
  refused as a reserved C symbol (NL3037).

## Semantics decisions

- **Signed integer overflow is a checked panic; `wrappingAdd`,
  `wrappingSub` and `wrappingMul` from `nish:unsafe` wrap.** Every user-level `i32`/`i64` `add`/`sub`/
  `mul` — the binary operators, unary minus, `op=` on locals, fields and
  elements, `++`/`--` — either fits its type or stops the program with Rust's
  words, `attempt to add with overflow` (`subtract`, `multiply`, `negate`
  likewise), exit 1, the way [checked integer division](#checked-integer-division)
  does. It is never undefined: `x + 1 > x` cannot be folded to `true` while
  `x + 1` prints `-2147483648` (`tests/cases/ovf_repro`, built at
  `--profile speed`; `ovf_matrix` for every operator at both widths, on
  locals, elements and fields).

  An operation the compiler **proves** fits is the plain instruction with
  `nsw`, and that flag is then a fact rather than an assumption: it is what
  lets LLVM widen an induction variable. The proof reads what the bounds
  analysis knows ([Element access](#element-access)) and the declared ranges,
  as interval arithmetic: a literal, a folded constant, `w.length`, `toI32` of
  a `u8` or `u16`, an `integer<Lo, Hi>`, a mask `x & c`, a shift or a division
  by a literal, and a local narrowed by the facts in force. The shapes it
  proves (`tests/cases/ovf_proven_*`, one golden each):

  - `i + 1`, `i++`, `i += 1` under `i < n` for any `i32` `n`, or
    `i < xs.length` — `i` is below `INT_MAX` (`ovf_proven_below`);
  - `i - 1`, `i--` under `i > 0`, or `n - 1` past `if (n < 2) return`
    (`ovf_proven_floor`);
  - arithmetic on declared ranges whose interval fits: `integer<0, 100>`
    operands, `toI32(hi) * 256 + toI32(lo)` on bytes (`ovf_proven_range`);
  - a local only ever assigned `(...) & c`, at every pass of a loop
    (`ovf_proven_mask`);
  - a bounded accumulation: a local that each pass of a counted `for` loop
    moves by a bounded step stays within the steps the loop can take —
    `sum += toI32(buf[i])` over 256 bytes, `count++` under `i <= n`
    (`ovf_proven_accumulate`);
  - what every caller passes: a parameter every call site bounds is bounded in
    the callee, recursion included (`ovf_proven_callsite`);
  - what a function returns: a call to a plain function is the join of its
    returns' ranges, a `Result`'s `Ok` payload included, and a
    `return r.value` hands on the range of the payload the caller passed —
    `clamp(a) + clamp(b)`, `acc + orMinus(half(i & 0xff))`
    (`ovf_proven_return`; `ovf_return_unproven` keeps the checks when a
    return, or an argument, is unbounded);
  - `i * i <= n` bounds `i` by the square root of `n`'s bound
    (`ovf_proven_square`).

  Anything else is `llvm.s{add,sub,mul}.with.overflow` and a branch on its
  flag to one cold block per function (per source location under `-g`) that
  calls `nish_panic_overflow`
  (`ovf_checked`). The check is not free where nothing proves the operation:
  a sum folded over a whole array, a recursive `fib(n - 1) + fib(n - 2)`, a
  counter in a field. Such a loop is not vectorised, and a sum the optimiser
  used to re-associate keeps its order (`docs/BENCHMARKS.md` has the cost
  measured).

  A program that overflows a signed integer **on purpose** — a hash, an LCG,
  a wrap-around counter — says so at the operation. Write the arithmetic in
  `u32` or `u64`, which are defined to wrap and never checked (the
  conversions back are free), or write it as a `wrappingAdd`, `wrappingSub`
  or `wrappingMul` call from
  [`nish:unsafe`](#nishunsafe-unchecked-access-and-defined-wrapping), the
  plain instruction with no check, like Rust's `wrapping_add`
  (`tests/cases/unsafe_wrapping`; `tests/cases/opt_nsw` for the default).
  There is no flag that changes the rule for a whole program: `--nsw`, which
  made overflow undefined, and `--wrapping`, which made every operator wrap,
  are both refused with exit 2 and a line naming the `wrapping*` functions
  (`tests/nish/cli.ts`).
- **Unsigned integers never carry a no-wrap flag**, in either mode. `u8`,
  `u16`, `u32` and `u64` are *defined* to wrap, so `(255: u8) + 1` is `0`
  (`tests/cases/u_arith_wrap`): `nuw` would be a claim the language does not
  make, and `nsw` on a value that has merely passed 2^31 would poison an
  ordinary result. Write the deliberately-overflowing arithmetic in an unsigned
  type and it needs no flag at all.
- **What is never flagged or checked**, whatever the mode: division and
  remainder (which have [checks of their own](#checked-integer-division)),
  shifts, `Math.abs(-2147483648)`, which still answers itself because
  `llvm.abs` is emitted with its poison flag off, the conversions, which
  `trunc` and therefore wrap by definition, and every piece of the compiler's
  own index, length and allocator arithmetic (`tests/cases/opt_nsw` pins
  exactly which operations are proven, which are checked, and which are
  neither).
- **`f32` is a distinct type, not a rounding mode.** It never mixes with
  `f64` and is never what `number` means; every `f32` result is a real 32-bit
  float, so `0.1 + 0.1` is `0.20000000298023224` there and
  `0.2` in `f64` ([`f32`](#f32), `tests/differential/corpus/f32_round`).
- **Shift counts are masked**, never undefined. `a << b` uses `b & 31` on a
  32-bit type and `b & 63` on a 64-bit one, so `x << 33` is `x << 1` and
  `x << -1` is `x << 31`, exactly as in JavaScript, rather than the poison
  LLVM produces for a shift at or beyond the operand's width. The narrow
  unsigned widths mask to their own width (`b & 7` on a `u8`, `b & 15` on a
  `u16`): JavaScript has no `u8` to be compatible with, and masking to the
  width is the rule the other types already follow. A constant count is masked
  at compile time and emits no `and` at all; a variable one costs one
  instruction, which is the price of a language whose premise is that if it
  compiles, the behaviour is known (`tests/cases/bit_shifts`,
  `bit_shift_const`, `bit_shift_fill`, `bit_shift_narrow`;
  `tests/differential/corpus/bit_shifts`).
- **`>>>` on `i32` keeps the signed reading**, and this is a deliberate
  divergence. `lshr` fills with zeros and the result is read back as the
  signed `i32` it is, so `-1 >>> 0` is `-1` here and `4294967295` in
  JavaScript, which promotes the unsigned 32-bit value into a double. It is
  the same honest choice the language already makes when integer arithmetic
  wraps instead of promoting, and it is the wart `u32` exists to avoid: on an
  unsigned type `>>` and `>>>` are both `lshr` and both read back unsigned.
  `i64` has no divergence to report, because JavaScript has no `>>>` for
  BigInt at all (`tests/cases/bit_shift_fill`, `u_shift_logical`; the
  differential rewrite adds `| 0` around an `i32` `>>>` so Node and the
  native binary agree, [wp13-differential.md](wp13-differential.md)).
- **Bitwise operators cannot fail.** They have no divisor check and no panic
  path, unlike `/` and `%`, so a function whose arithmetic is all bitwise
  keeps `readnone` and `willreturn` (`tests/cases/bit_attributes`).
- **Integer division is checked**: `sdiv`/`srem` truncating toward zero
  (`-7 / 2` is `-3`, `-7 % 2` is `-1`; `tests/cases/cf_collatz`,
  `cf_do_while`), preceded by a divisor check that exits with status 1 on a
  zero divisor (`attempt to divide by zero`) or `MIN / -1`
  (`attempt to divide with overflow`), like Rust and unlike JavaScript's
  `0` (`tests/cases/div_checked`, `div_zero_panic`, `div_overflow_panic`;
  [Checked integer division](#checked-integer-division)).
- **`Math.pow`** follows ECMAScript where C99 `pow` differs
  (`pow(x, NaN)`, `pow(±1, ±Infinity)` are `NaN`; see the `Math` table).
- **`f64`** follows IEEE-754: `x / 0` is `Infinity`, `x !== x` detects NaN
  (`fcmp une`), `%` is `frem` (`tests/cases/f64_mode`, `conversions`).
- **Strings** are immutable UTF-8 byte sequences; `.length` is the byte
  length (`"héllo".length` is `6`, not JavaScript's `5`); `===` compares
  content; there is no implicit conversion (`"a" + 1` is an error; write
  `` `a${1}` ``); no ordering (`<`) is defined (`tests/cases/str_length`,
  `str_eq`, `reject_str_plus_number`, `reject_str_lt_str`).
- **Number formatting** matches `String(x)` in JavaScript (see `console`).
  For an `f64` that means the *fewest* digits that read back as the same
  double, which is not the same as the correctly-rounded string of that length:
  `7.120236347223045e-307` prints those sixteen digits and not the seventeen a
  round-and-check search settles for (`tests/cases/f64_shortest_digits`).
- **`Math.round`** rounds half toward +infinity like JavaScript, and
  `Math.round(-0.3)` is `-0` in both. **`Math.min`/`Math.max`** on a float
  answer NaN when either operand is NaN and order `-0` below `+0`, as
  JavaScript does (`tests/cases/math_minmax_nan`, `math_round_negzero`).
  Both take exactly two arguments, and so does `Math.hypot`.
- **`toI32`/`toI64` from `f64` saturate** (NaN -> 0, `toI32(5e10)` ->
  `2147483647`) like a Rust `as` cast, not JavaScript's modulo-2^32
  `ToInt32`. Integer-to-integer conversions wrap (`toI32(5000000000)` ->
  `705032704`) (`tests/cases/conversions`).
- **A program can be run under Node** as the TypeScript it is, in f64 mode and
  within a stated overlap, with `runtime/nish.mjs` supplying the globals
  Node lacks and nothing rewritten
  ([RUN_UNDER_NODE.md](RUN_UNDER_NODE.md)). Every decision on this page is a
  reason it is an overlap and not an equivalence.
- **No exceptions.** Functions are `nounwind`, there is no `throw` and no
  unwinding, and a failure a caller should handle is a `Result<T, E>`
  (`tests/cases/res_basic`); runtime failures (bounds check, integer
  division, file errors, out of memory) print a message to stderr and exit
  with status 1 (`tests/cases/arr_bounds_panic`:
  `index out of range: <i> >= <len>`; `str_slice_panic`:
  `slice out of range: [<start>, <end>) of length <len>`; `div_zero_panic`:
  `attempt to divide by zero`).
- **Bounds checks** on every `a[i]` read and write, unsigned, so `-1` fails
  (`tests/cases/arr_bounds_panic`), and the same unsigned compare guards
  `s.charCodeAt(i)` and the two ends of `s.slice(a, b)`
  (`tests/cases/str_slice_panic`). `uncheckedGet` and `uncheckedSet` from
  `nish:unsafe` remove the one at their own site (`tests/cases/unsafe_get_set`),
  and past one, out-of-range is undefined behaviour.
- **`new Array<T>(n)` zero-fills** (`0` / `false`), no holes; pointer element
  types are rejected because a zeroed pointer would be null
  (`tests/cases/arr_new_zeroed`, `reject_arr_new_string`).
- **Typed-array names are aliases, not views.** `Int32Array` is `i32[]` with
  every array operation but `push` and `pop`, which a receiver spelled with
  the name refuses as TypeScript does
  ([Typed-array names have no `push` or `pop`](#typed-array-names-have-no-push-or-pop));
  there is no separate buffer type and no `subarray`. The alias names are exactly four — `Int32Array`,
  `Float32Array`, `Float64Array`, `BigInt64Array` — and an *unsigned* array has
  none: a program writes `u8[]`, and `Uint8Array` is not a type it can spell.
  That asymmetry is only a spelling. `u8[]`, `u16[]`, `u32[]` and `u64[]` cross
  a host boundary as the matching typed array
  ([wp30-bytes-interop.md](wp30-bytes-interop.md)), and an element of one needs
  **none** of the masking its scalar twin needs: a scalar `u32` result travels
  in an i32 value type and reaches JavaScript negative above 2^31 unless the
  loader restores it, while an element is a byte in `data` that `Uint32Array`
  reads unsigned. `boolean[]` still has no flat view at all, because an `i1`
  must be 0 or 1 and that is a per-element check rather than a reinterpretation.
  At a host boundary the name is the JS typed array that crosses
  ([wp8-interop.md](wp8-interop.md)).
- **Evaluation order** follows JavaScript: `x op= e` reads `x` before
  evaluating `e` (`tests/cases/cf_compound_assign`); `a[i] = v` evaluates
  `a`, `i`, `v`, then checks and stores; `a[i] op= v` evaluates `a`, `i`,
  checks, loads, evaluates `v`, stores (`tests/cases/arr_index_read_write`),
  and when `v` can push to or pop from `a` the store goes into `a` as `v`
  left it, its index checked again against the length then: `xs[0] +=
  grow(xs)` writes the block `grow` moved the elements to, and an index `v`
  shrank past panics (`tests/cases/cg_sec_compound_element_order`);
  `p.f op= v` reads the field before `v` (`tests/cases/cls_compound_field`);
  the target expression is evaluated **once** whichever `op=` it is, so
  `a[next()] |= 1` calls `next()` a single time and pays for a single bounds
  check (`tests/cases/arr_element_bitwise_assign`);
  array literal elements are evaluated before the allocation
  (`tests/cases/arr_literal`); `push`'s argument is evaluated before the
  length is read (`tests/cases/arr_push`).
- **Arrays and objects are references**: `===` is identity; `const b = a;
  b.push(2)` is visible through `a` *(CLI only)*; assignment never copies.
- **Method dispatch is static.** `x.m()` calls the `m` declared by `x`'s
  type, decided at compile time. There is no vtable and no virtual dispatch,
  and since WP25 there is no inheritance either, so there is no override for
  one to disagree about: every method call in a program names one symbol
  (see [Classes](#classes)).
- **Memory** is one global bump arena plus the stack, decided at compile
  time (see [Memory model](#memory-model)); nothing is freed individually;
  `main`'s wrapper releases everything on exit. Objects, arrays, and strings
  are never null unless typed `T | null`.
- **Parameters are immutable** and used as SSA values; locals use
  `alloca`/`load`/`store` and are promoted by `mem2reg`.
- **Only an `export`ed function is an external C symbol**; the rest are
  `internal` unless `--no-strict-exports`.

### Memory model

There is no garbage collector. Every object, array, and runtime string is
placed by one of four mechanisms, all decided at compile time
([wp6-memory.md](wp6-memory.md)); none changes what a program computes, only
where its memory lives and when it is reused.

1. **Stack allocation.** A `new C(...)`, object literal, array literal, or
   `new Array<T>(<non-negative integer literal>)` whose value provably does
   not outlive its function becomes an `alloca` in the entry block
   (`tests/cases/mem_stack_struct`, `mem_stack_array_literal`). "Provably"
   means the value only ever flows into uses that consume it on the spot
   (operands, conditions, field and element access, `.length`, `for...of`,
   arguments to callees that do not capture the parameter, runtime
   builtins) or into `const`-like locals that are never reassigned; it
   stays in the arena when it is returned, stored into a field or element,
   pushed, assigned to another variable (`let q = p` included), held by a
   reassigned `let`, or passed to a callee that captures it
   (`tests/cases/mem_stack_escape`). A site inside a loop gets one slot,
   reused every iteration (`tests/cases/mem_stack_loop`). A `Result` is the
   exception to "held by a reassigned `let`": an `Ok`/`Err`, or a call
   returning a by-value `Result`, assigned to a `let` of the same function
   goes where that `let` goes, so a `let r = Ok(n)` assigned again keeps its
   function's arena scope. Outside a loop each such site is its own alloca;
   inside one it is arena memory the scope gives back. A `let` assigned from
   itself (`r = c ? r : Ok(0)`) keeps the arena answer
   (`tests/cases/res_let_reassign`, whose 100000 calls leave `Arena.used()`
   unchanged). Stack arrays are
   capped at 4096 bytes of data; a later `push` moves the elements to the
   arena and the header stays valid. The slot's type spells the length out,
   and the length is read from the literal that made the site stackable in the
   first place, so `--number-mode f64` — where the same literal reaches the
   emitter as a converted register — allocates the same `[n x T]`
   (`tests/cases/arr_stack_f64`). `--no-stack-alloc` turns this off.
2. **Automatic arena scopes.** A function whose arena temporaries all die
   with it (a dynamic `new Array<T>(n)`, `push` growth on its own array, a
   string concatenation or template, a number printed by `console.log`, a
   callee's returned allocation), that neither returns nor leaks an
   allocation, and has no callee that leaks one, calls `nish_arena_mark` on
   entry and `nish_arena_release` before every `ret` (`tests/cases/mem_scope_dynamic_array`,
   `mem_scope_string_temp`: 100000 calls leave `Arena.used()` unchanged).

   **A loop's pass gets a scope of its own.** A loop whose body allocates,
   itself or through a callee that leaves memory behind, reads the bump
   position at the top of every pass and rewinds to it on every edge that
   leaves the pass: the back-edge, `continue`, `break`, and a `return`, which
   releases the outermost scope open. A `switch`'s `break` stays in the pass.
   It needs nothing allocated during the pass to be reachable afterwards
   except through a number, a `boolean` or an `enum`, which holds when every
   one of these does:

   - no allocation of the pass is stored into memory — a field, an element,
     an array or object literal, a capturing parameter — by the body or by
     any callee (the escape analysis above);
   - a local declared outside the body (a parameter, a `for` initialiser, the
     variable of the `for...of` being scoped) of a type that can hold a
     pointer is assigned only a value older than the pass: a literal, `this`,
     another outer local, a field or element read, the `const` variable of a
     nested `for...of` over such a value, a call to a function that allocates
     nothing, or a choice between two of those. `s = s + x` and
     every `+=` on a `string` are refused;
   - `push` grows only an array the pass itself declared with a fresh literal
     or `new Array`;
   - a `return` in the body answers a scalar or a value older than the pass,
     and `orReturn` is refused;
   - the function does not call `Arena.mark` itself.

   A string pushed onto an array that is only joined is not stored into
   memory. When a function binds a `string[]` local to its own fresh literal
   or `new Array` and then uses it only as `parts.push(...)`,
   `parts.join(...)` and `parts.length`, what it pushes is reachable only
   through `parts`. `join` copies every part into a new string, so the
   pushed values die with the frame, and a loop that calls the function keeps
   its scope (`tests/cases/mem_join_parts_scope`: 1000 calls leave
   `Arena.used()` where one call left it). Any other use of `parts` keeps the
   pushed value stored, because it could hand a part back out: an element
   read (`mem_join_parts_readback`), a `for...of` (`mem_join_parts_forof`),
   passing `parts` to a function (`mem_join_parts_passed`), another method on
   it, such as `parts.pop()` (`mem_join_parts_method`), or a `parts` that
   names another local's array (`mem_join_parts_alias`). Assigning or
   returning `parts`, and an array the function did not build itself, count
   the same way. The same holds for a `string` *parameter* the function
   pushes onto such a `parts` directly (`parts.push(word)`, parentheses
   seen through): `join` reads it before the call returns and nothing can
   reach it afterwards, so the callee does not keep it, the parameter is
   `nocapture`, and a loop that builds the argument in the same pass and
   passes it keeps its scope (`tests/cases/mem_join_parts_same_pass`: 1000
   passes leave `Arena.used()` where one pass left it). Every negative above
   keeps the parameter kept as well (`mem_join_parts_same_pass_kept` reads a
   part back into an object). The rule stops at the push: a parameter that
   is first copied into a local (`let rest = text`), returned, or handed to
   another user function still counts as kept, since a `string` passed on is
   not followed into its callee. So `jsonField(line, ...)` and `replaceAll`
   on a line built in the pass still have no scope, and passing them a
   string older than the pass is what keeps it.

   A value stored into an array that is returned with it is returned, not
   stored. When a function binds a local `xs` to its own fresh literal or
   `new Array` and uses it only as `xs[i] = v`, `xs.push(v)`, `xs.length`,
   an element read that is only tested (`xs[i] === null`), and `return xs`
   itself, what it stores is reachable only through `xs`, so it goes to the
   caller with the array and the function lets nothing else out. Only a
   string, or a `string | null`, is carried this way: an array or an object
   holds pointers of its own, which no caller follows a level further down
   (`mem_return_array_nested`). So a loop that calls it keeps its scope
   (`tests/cases/mem_return_array_scope`: 1000 calls leave `Arena.used()`
   where one call left it). Any other use of `xs` keeps
   the stored value stored, because it could hand an element on: storing
   `xs` into a field, passing it to a function, reading an element back and
   keeping it, naming `xs` through another local, or returning it through a
   choice (`mem_return_array_callee`). An arrow argument that reads `xs` as a
   capture is a use too, since it may read `xs` when the call runs, after a
   join could have released it (`mem_join_parts_captured`). Inside the function the value is in memory all the
   same, so a loop whose pass stores into an `xs` declared outside it keeps
   no pass scope, and a `using a = arena()` block that stores into an `xs`
   declared before it is refused as any store into older memory is. Only a
   store that stands as its own statement is carried: an assignment's value is
   its right-hand side, so `h.f = (xs[0] = v)` keeps `v` stored.

   The caller is what makes this sound. Such a call answers an array whose
   elements are as new as the call, so the caller follows them as the call
   itself, as it follows a `readdirSync` listing's: an element read out of
   it and a `for...of` variable over it are that call's, and a function that
   returns the array on answers such an array in turn. Passing the array to a function, `pop`, and every method but
   `length`, `join`, `indexOf` and `push` count as storing it, because each
   could hand an element back where the analysis does not follow
   (`mem_return_array_caller`). The same rules close four ways a listing's
   name used to outlive a scope that released it: returned through a
   function and kept by a pass, passed to a function that answers it,
   assigned to a local that is returned, and stored into a field
   (`mem_return_array_readdir`).

   An element of an array whose elements are inline is the address of a slot
   in that array, so keeping one keeps the array: it is followed as the array
   in every rule above, and in the function rule too
   (`tests/cases/mem_loop_scope_interior`). A pointer-returning function gets
   no function scope, so a pass scope is what reclaims its loop
   (`tests/cases/mem_loop_scope`: `Arena.used()` moves as far after 4000
   rounds as after one). `mem_loop_scope_control` covers every exit edge,
   nested loops and a `switch`; `mem_loop_scope_forof` the `for...of` rules;
   `mem_loop_scope_escape` a pass value kept in an outer local, pushed into
   an outer array, stored into a field, stored by a callee, built up across
   passes and returned, each read back after the arena is reused; and
   `mem_loop_scope_threads` the same round trip under `--threads`, where the
   arena, and so the scope, is per thread. A `for` loop's condition and
   update run outside the bracket. Like the function scope it is invisible to
   a program except through `Arena.used()`. A program that wants the same
   bracket around a block of its own writes
   [`using a = arena()`](#using-a--arena), which this rule checks and refuses
   rather than declines.

   **A function whose callees are what allocate gets a scope too.** One that
   allocates nothing of its own, returns a number, a `boolean`, an `enum` or
   nothing, and calls a function that leaves arena memory behind, brackets
   itself the same way when nothing it or its callees allocate can outlive
   the call except through the return value. That holds when no allocation
   is stored into memory anywhere in the call (the escape analysis above), or
   when nothing the function was handed can hold a pointer at all: every
   parameter, `this` included, is a number, a `boolean`, an `enum`, a
   `string`, or an object whose fields are all numbers, booleans and enums.
   The one mutable global is [module storage](#module-storage), whose
   elements are pointer-free, so memory older than the call that has a slot
   a pointer fits in is reachable only through those parameters, and none
   of it has one (`tests/cases/mem_callee_scope`, the Are We Fast Yet
   `List` benchmark; `mem_callee_scope_tree`, its `Storage` benchmark, where
   10000 runs leave `Arena.used()` where one left it). A callee that stores
   what it allocates into `this` or a parameter, a function that returns a
   pointer, and one that manages the arena itself get none
   (`mem_callee_scope_escape`, `mem_callee_scope_return`,
   `mem_callee_scope_control`), and neither does a function that reads an
   allocation back out of what a callee returned and stores it
   (`mem_callee_scope_nested`). A callee that already has a scope of its own
   leaves nothing behind, so it earns its caller no second one.

   **A tail call is marked `tail`, and the release moves ahead of it.** A
   `return g(...)` whose arguments are every one a scalar — a number, a
   `boolean` or an `enum` — is the last thing its function does, and is
   emitted as `tail call`. The marker says the callee cannot reach this
   frame's stack slots, so the frame may be popped before the jump: the
   recursion it may be part of then costs one frame however deep it goes, in
   *every* build profile, `--profile debug` included, where no optimiser runs
   at all (`tests/link/tail_call_depth_debug` recurses a million levels at
   `-O0` and segfaults without the marker, and `tests/cases/cf_gcd` is a
   golden small enough to read the marker out of). In a function with an
   automatic scope the same proof also moves `nish_arena_release` ahead of the call, because
   a release between the call and the `ret` is work after the call and would
   leave it not last after all (`tests/cases/mem_scope_tail_call` pins that
   order, and `tests/link/tail_call_depth` runs a million levels of it, which
   segfaults without the move).

   Refused when an argument is a `string`, an array, an object or a `Result`,
   because that argument may be memory this frame owns; when the callee is a
   method, whose receiver is an argument the argument list does not carry and
   is a pointer by construction; when the callee reads the bump position
   (`Arena.mark`, `Arena.used`), which a release moved ahead of it would make
   answer a smaller number; and when the call is not the whole of the `return`
   (`tests/cases/mem_scope_tail_call_guards`). Like the reclaim below it is
   invisible to a program: it changes how much stack a recursion costs and
   when memory is reused, never what a value holds. Turning the recursion into
   an actual loop, rather than a jump back to the top of the frame, is then
   the optimiser's job, which every build profile but `debug` runs
   ([wp6-memory.md](wp6-memory.md) §2b).

3. **A reclaim at the call site.** A function that *returns* a string can have
   no scope of its own — the string has to outlive it — so its caller takes the
   mark instead: `nish_arena_mark` after the arguments, then
   `nish_arena_keep(mark, s)`, which moves the returned string down onto the
   mark and releases every temporary the callee bumped underneath it. Emitted
   only when the callee returns a plain `string`, allocates, and never lets an allocation out of its
   frame other than through its return value — so a callee that stores what it
   built into an object its caller holds gets no bracket, and neither does one
   returning an array, a struct or a `Result`, whose values name memory outside
   themselves (`tests/cases/mem_reclaim_call`, `mem_reclaim_argument`,
   `mem_reclaim_guards`). Independent of `--no-stack-alloc`
   (`tests/cases/mem_reclaim_no_stack_alloc`), and invisible to a program: it
   changes when memory is reused, never what it holds
   ([wp6-memory.md](wp6-memory.md) §2a).
4. **Explicit control** with the [`Arena`](#arena) builtins, and
   `nish_reset_arena()` / `nish_arena_mark()` / `nish_arena_release()` for a C
   or Node host ([wp8-interop.md](wp8-interop.md)).

Everything else is bumped from the arena by the inlined fast path, and the
arena is released when `main` returns. Objects stored into fields or arrays
never move to the stack, and a returned object is always arena memory owned
by the caller.

### Target, overflow and linkage flags

- **`--target <triple>`** / **`--target host`** writes `target datalayout`
  and `target triple` (the strings clang 18 emits for that triple) into every
  module: `x86_64-unknown-linux-gnu`, `aarch64-unknown-linux-gnu`,
  `x86_64-apple-darwin`, `aarch64-apple-darwin`, `wasm32-unknown-unknown`,
  `wasm32-wasi`, plus common aliases (`x86_64-linux`, `arm64-apple-darwin`,
  `wasm32`, ...); anything else, and `host` on an unsupported machine, is a
  usage error (exit 2) listing the supported triples
  (`tests/cases/opt_target_triple`). The default emits neither line, so
  clang supplies them at link time; the flag matters when running `opt` or
  `llc` by hand, which otherwise assume a generic layout and never vectorise
  ([wp9-optimisation.md](wp9-optimisation.md#--target-triple-and---target-host)).
  It shapes what a compile emits and links, and `--fix`, which rewrites the
  sources and emits and links nothing, refuses it with a usage error (exit 2)
  rather than dropping it, as it refuses `-o` and `--link`: fix first, then
  compile for the target. It refuses `-g`, `--threads`, `--runtime-decls` and
  `--plain` the same way, for the same reason.
- **`--no-strict-exports`**: see *Linkage* above
  (`tests/cases/export_no_strict`).
- **`--strict-exports`** is still accepted and now says explicitly what the
  compiler does anyway; it exists so a build script written before the default
  changed still runs (`tests/cases/export_strict`).
- **`--nsw`**, **`--wrapping`** and **`--unchecked-indexing`** are refused, a
  usage error with exit 2. The first said that signed overflow was undefined
  behaviour the optimiser could assume away, the second made it a defined
  wrap, and the third dropped every bounds check in the entry package; the
  rule is a checked panic now, and no flag changes it. Each refusal names the
  [`nish:unsafe`](#nishunsafe-unchecked-access-and-defined-wrapping) calls
  that skip one check at their own site: `wrappingAdd`, `wrappingSub` and
  `wrappingMul`, or `uncheckedGet` and `uncheckedSet` (`tests/nish/cli.ts`).
- **`--no-stack-alloc`**: see *Memory model* above.

### The CPU level

- **`--cpu x86-64-v3`** links the program for one CPU level above the
  baseline: the module and the runtime are both compiled, and linked, with
  `-march=x86-64-v3 -ffp-contract=off`, so the code generator may use AVX2,
  BMI2 and FMA. It is the **one** level: `native`, `x86-64-v4`, `armv8.2-a`
  and every other value are a usage error (exit 2, one line), and so is the
  flag with `--profile wasi` or with a `--target` that is not x86-64. Without
  `--target` the host's triple is the one checked, so a host that is not
  x86-64 refuses it the same way; an x86-64 `--target` on such a host is not
  refused, and fails at the link as a toolchain error. `scripts/build.sh --cpu
  x86-64-v3` is the same build, and refuses the `wasm` and `wasi` profiles.
- **It changes the link and nothing else.** The IR is byte for byte the IR
  without it, so the flag changes no operation's meaning; and
  `-ffp-contract=off` keeps the code generator from contracting a multiply and
  an add into one fused, once-rounded instruction the source did not write, so
  a float prints the same at either level. `nish run` takes it too, and both
  caches key on it: a run or a link at the level never reuses the baseline's
  binary or runtime objects. `--emit-capabilities` adds a `"cpu"` key after
  `"entry"`; a baseline report has none.
- **A release binary stays baseline.** A binary linked with the flag stops
  with `SIGILL` on a CPU without AVX2, so it is for programs that run on
  machines whose CPU is known. The `nish` the project releases is built
  without it. The constant-time check reads the runtime and the
  `nish:crypto-ct` fixtures at this level as well as at the baseline
  ([CT-16](security/ct-verification.md)); a level it does not read is not
  offered (`tests/run.js`, the `cpu level` section).

### Profile-guided builds

- **`--pgo-generate`** links an instrumented binary: the module, every
  runtime unit and, when the program calls it, SQLite are compiled, and
  linked, with `-fprofile-generate`, so each run writes a raw profile
  (`LLVM_PROFILE_FILE` names it). **`--pgo-use <file.profdata>`** compiles
  and links the same units with `-fprofile-use=<file>`, the file's real
  path, so a relative path means the same file whichever unit compiles from
  which directory. `scripts/build.sh --pgo-generate` and `--pgo-use` are the
  same build.
- **Each needs `--link` and the `speed` or `size` profile, and the host.**
  Both flags at once, either without `--link`, with `--profile debug` or
  `wasi`, with a `--target` that is not the host's, or in `nish run` is a
  usage error (exit 2, one line, nothing written). The `--pgo-use` file must
  exist and begin with the indexed profile's magic bytes, which
  `llvm-profdata merge` writes: a directory, a raw `.profraw` (named, with
  the `merge` that fixes it) or any other file is refused the same way, and
  so is one `llvm-profdata show` cannot read. `llvm-profdata` missing from
  `PATH` is a toolchain failure (exit 3).
- **It changes the link and nothing else.** The IR is byte for byte the IR
  without it. A profile-guided link compiles every runtime and SQLite unit
  itself: it reads no entry of the runtime cache and writes none, so a plain
  link after an instrumented one is byte for byte the plain link before it
  (`tests/run.js`, the `pgo` section).

### The debug arena

- **`--debug-arena`** links the program against a runtime compiled with
  `-DNISH_ARENA_DEBUG` (`scripts/build.sh --debug-arena`). The IR is byte for
  byte the IR without it. Under it every arena block is a chunk of its own,
  on pages no earlier block had, with `cap` exact, so the inline bump never
  fits again and every allocation and every scope's release reaches the
  runtime. A release or reset retires each chunk it frees: its pages become
  `PROT_NONE` and go back to the system, but their addresses stay reserved,
  so a read or write through a reference that outlived its scope faults at
  that access. The runtime writes `nish: --debug-arena: stale arena reference
  at 0x…` to stderr, and the program dies of `SIGSEGV`. A fault elsewhere
  goes to the handler that was installed before.
- **It needs a link and a native profile.** Without `--link` and outside
  `nish run` it is a usage error (exit 2), and so is `--profile wasi`;
  `scripts/build.sh` refuses it with the `wasm`, `wasm-host`, `wasi` and
  `napi` profiles. `nish run` takes it, and the run and runtime caches key on
  it, so a debug-arena build never reuses a normal binary or runtime.
- **It is for tests, never a release.** Each block takes at least a page and
  no address is reused, so memory only grows; a process at its limit of
  mappings fills a retired chunk with `0xDB` instead of unmapping it. The
  rules in *Memory model* mean no correct program reads released memory, so a
  trap under the mode is a compiler or runtime bug
  ([security/runtime.md](security/runtime.md#the-debug-arena)).

### Diagnostics and debugging flags

- **Errors are collected, not thrown on the first.** Phase 0 reports every
  forbidden construct in a file; pass 1 recovers per declaration (a rejected
  class, interface, import or function signature is skipped); pass 2 recovers
  per statement (the enclosing function is marked poisoned and the next
  statement is checked). A phase that found anything stops the pipeline
  before the next one, so pass 2 never sees a broken signature and the
  emitter never sees a poisoned function. Errors print in source order
  (files in load order), at most 20 before `...and N more errors`, followed
  by an `N errors` line; a lone error prints exactly as before
  (`tests/cases/reject_multi_error`, `reject_multi_forbidden`,
  `reject_multi_decl`). A `let x: T = <rejected>` still declares `x` as `T`
  so later uses do not cascade.
- **Performance warnings are the one diagnostic that is not an error**
  (WP15 §8). The compiler reports one whenever it had to take a slow path and a
  faster one was available, or whenever it can prove that a piece of arithmetic
  does not compute what it was written to compute, in the same anchored,
  excerpted shape an error has but with `performance` where `error` would be:
  `file:line:col: performance: <text>`. They are **on by default**, print on
  stderr, and **never change the exit code**: a program that trips one still
  compiles and still exits 0. `--no-warn-performance` silences the class and
  changes nothing else — the IR is byte-identical either way. The standard
  library and the examples compile with **none**, in both number modes where
  they compile, and `npm test` fails the day one of them warns; the compiler's
  own source is held to a per-code count that may only fall
  (`.claude/testing.md`, "The performance gate"). A compilation
  that *failed* prints its errors and none of its warnings; a report of more
  than one warning is capped at 20, like the error report, with
  `...and N more performance warnings` and an `N performance warnings` line.
  They print in the order a reader reads a file — by file, in the order files
  are first warned about, then by position in that file, then by diagnostic code
  where two rules report at one position — which is also the order of the
  `--json` stream and is a contract rather than a presentation detail. Within a
  file it is **not** the order the analysis finds them in: a generic's body is
  checked when one of its instantiations is finished, and the padding rule below
  is decided a whole pass earlier than the others
  (`tests/cases/diag_order`, `tests/cases/diag_order_pass1`).
  The fourteen below each name the rewrite; the class also holds NL9012, a
  `parallelMapInto` body that allocates per element
  ([Data parallelism](#data-parallelism-nishthreads)), and the retired NL9014
  and NL9015, which noted the removed `--unchecked-indexing` and `--wrapping`:
  - **quadratic string building** — `s = <something built from s>` where `s`
    is a string local declared outside the loop the assignment sits in, so
    every pass copies the whole accumulator. The hint is a `string[]` and one
    `join` (`tests/cases/perf_str_concat_loop`). Not reported when the result
    does not include the target (`line = part + "!"`), when the accumulator is
    declared inside the loop and therefore reset every pass, or outside any
    loop (`tests/cases/perf_str_concat_quiet`).
  - **allocation in a loop** — a `new Array<T>(n)` with a non-constant `n`
    declared inside a loop whose value never leaves the iteration. A
    dynamically sized array cannot be a stack slot, so the arena grows once per
    pass; the hint is to hoist it above the loop or to open the loop body
    with [`using a = arena()`](#using-a--arena)
    (`tests/cases/perf_alloc_loop`). Not reported for a `new C(...)`, an object
    or array literal, or a `new Array<T>(<literal>)`, all of which the escape
    analysis already turns into one entry-block alloca whose slot is reused
    every pass, and not when the value is pushed, stored, returned or passed
    on, because then the program asked for one object per iteration
    (`tests/cases/perf_alloc_quiet`).
  - **an allocation dropped by an assignment** — `p = new Point(n)` where `p`
    was declared holding an allocation of its own. The value it held is
    unreachable from there and nothing frees it, and assigning a local is also
    what takes away the proof the automatic arena scope needs
    ([Memory model](#memory-model)), so the whole body's allocations live until
    the program exits. The hints are a `const` per value and, where the
    assignment is the point, a block around the body that opens with
    [`using a = arena()`](#using-a--arena) (`tests/cases/perf_arena_drop`). Not reported when the local was
    declared holding a literal and is then given its one value in a branch
    (`let what = "unbound"; if (...) what = \`long ${s}\`;`), which drops
    nothing and has no rewrite — that function still loses its arena scope and
    still retains its memory, silently, unless it earns the scope through its
    callees ([Memory model](#memory-model), item 2), which is a known gap
    rather than a guarantee ([wp6-memory.md](wp6-memory.md), "Left out") —
    a `let` holding a `Result` is no longer in it ([Memory model](#memory-model),
    item 1); when the assigned
    value is not an allocation;
    when the function returns a pointer, because then its caller owns the
    memory; when the value being dropped may already be reachable from
    somewhere else, which is a question of order — a capture anywhere in the
    enclosing loop, or one that finishes before the assignment starts, leaves
    the old value reachable and the `const` rewrite inapplicable (a capture is
    the value passed to a call or a constructor, either arm of a conditional
    included, a method called on it unless it is a string, an array or a
    `Result`, whose methods hand back a flag or the payload and never the box, a
    `return`, an element of an array or object literal, or the right-hand side
    of an assignment or a declaration); or when the
    quadratic-string rule is already reporting the same line
    (`tests/cases/perf_arena_quiet`).
  - **an allocation dropped on every pass** (NL9016) — `x = <allocation>` as a
    statement of its own at the top of a loop's body, where `x` is a local
    declared outside that loop. Each pass drops the value the pass before gave
    `x`, and nothing frees it while the loop runs: the pass cannot take a scope,
    because its fresh value outlives it in `x`, and a
    [`using a = arena()`](#using-a--arena) block refuses the same assignment
    (NL2418). So memory grows with the number of passes; 10,000,000 passes of
    `last = \`item ${i}\`` peaked at 392 MB where the rewrite peaks at 11 MB.
    The hints are a `const` inside the loop when only the pass reads the value,
    or numbers kept across passes and the value built once after the loop
    (`tests/cases/perf_arena_pass_drop`). An `Ok(...)` or `Err(...)` inside
    a loop is such an allocation unless its `Result` is passed by value, so a
    `let r` given a new one on every pass is reported, and so is one assigned
    over another inside the pass (NL9003). Reported whatever the local was
    declared holding and whatever the function returns, since the dropped
    values are this assignment's own; a line the rule above already reports is
    its alone. Not reported for an assignment inside a branch, which may run
    once, as a search loop's `found = ...` before its `break` does; in a body
    whose top level ends the loop with `break`, `return` or `throw`, or in a
    `do ... while (false)`, either of which runs at most once; for a local
    declared inside the loop; when the assigned value is not an allocation; or
    when a capture anywhere in the loop, as the rule above counts one, may keep
    the old value reachable, as `head = new Node(i, head)`,
    `picks.push(i > 0 ? tag : "none")` and `cur.attach(reg)` do
    (`tests/cases/perf_arena_pass_quiet`).
  - **a loop that leaves a callee's memory behind** — a call inside a loop to
    a function that leaves arena memory behind (it allocates, lets none of it
    escape, and has no scope of its own) whose result dies with the pass,
    where neither a scope around the pass nor one around the function
    reclaims it ([Memory model](#memory-model), item 2), in a function of any
    return type. Every pass adds memory that nothing releases before the
    function returns, and the function does not release it then either. The
    warning names what refused the pass its scope — the line of an allocation
    stored into memory, a callee that stores one, the line that keeps what
    the pass allocated in a local declared outside the loop or grows an array
    older than the pass, or a callee that releases or resets the arena — and
    what refused the function its own, and the hints are to keep what a pass
    allocates out of outer locals and older memory, or to open the loop body
    with [`using a = arena()`](#using-a--arena)
    (`tests/cases/perf_arena_loop`). A call in a `for` loop's condition or
    update is outside the pass's bracket and is reported as such. It is found
    after the whole-program analysis rather than by the checker, because
    every half of it is that analysis's facts. Not reported in a function
    that calls `Arena.mark` itself, whose author is already managing the
    memory, whatever it returns (`tests/cases/mem_callee_scope_control`); when the
    callee stores what it allocates, because then the program is keeping it;
    when the result is returned, stored, pushed or passed on; or in a loop
    whose pass can `return` what it allocated, which no bracket could
    release, so there is no rewrite to name.
  - **a pass of an unbounded loop that keeps what it allocates** (NL9018) —
    an allocation that `--emit-arena` marks `"accumulates":true`, where some
    loop between it and its release has nothing bounding how many passes it
    runs. `"accumulates"` means the allocation runs on every pass of a loop
    that releases nothing per pass, and nothing reaches it once the pass ends.

    That is the shape of a request loop on `Http1Server`. Its pass calls
    `accept` or `respond`, which store into the server's memory, so the pass
    is refused its scope. A reply string built in the handler then stays
    allocated for as long as the server runs:
    `tests/link/nl9018_server/leaky.ts` grew 1,252 kB over 20,000 requests,
    and the rewrite grew none.

    What a pass keeps counts at any depth of calls. A function the pass calls
    leaves memory behind in the loop when all of these hold:
    - it answers no memory (a number, a `boolean`, an enum or nothing);
    - it has no scope of its own and manages no arena;
    - it builds a temporary that it drops, or calls a function that leaves
      one behind by this same rule, on every call that returns.

    "Every call" admits one kind of branch: an `if (p === K)`, `if (p !== K)`
    or `switch (p)` on a parameter `p` against a constant. `K` is a literal,
    a name that is neither a parameter nor a `let`, or a member of a name
    that is not a local, such as an enum's. A handler that dispatches on the event it is handed therefore
    counts. The warning names the call in the pass and the site, as in "what
    `readPost` leaves behind on line 102 (the string built on line 69, in
    `readPost`) piles up". Its rewrite puts the block inside the function that
    builds the temporary. When that function is in `std/` or a dependency, the
    rewrite puts the block in the loop body instead.

    `tests/link/nl9018_server/helper_leaky.ts` builds its reply in a
    `readPost` helper that also answers, so `readPost` is refused a scope of
    its own. `method_leaky.ts` reaches the same helper from the loop through
    `App.ready` and `App.onEnd`. Each grew 1,252 kB over 20,000 requests,
    and each rewrite (`helper_flat.ts`, `method_flat.ts`) grew none.

    These are not charged to the loop:
    - what a function that answers memory builds, which goes to its caller
      with the result;
    - a temporary under any other branch, or after a statement that can
      return, such as an error message, a table built on first use or one
      step of a handshake;
    - a temporary whose every path ends the program (`panic`,
      `process.exit`), whether it is built in the call's arguments or in a
      statement before it, as in `const msg = ...; panic(msg)`.

    A loop is bounded, and NL9018 stays silent for it, when one of these
    holds:

    - It is a `while`, `do` or `for` whose condition has an order comparison
      (`<`, `<=`, `>`, `>=`) as a conjunct of its top-level `&&` chain. The
      condition must call nothing but the numeric conversions (`toI32` and
      its kin), and read nothing but locals, fields (`.length` among them)
      and constants. A call to any function of the program or of `std/`
      anywhere in the condition makes the loop unbounded.
    - It is a `for...of` whose body cannot extend the collection it walks:
      an array or a map, named by a local or a field path such as
      `log.items`. The body extends it only through the same walked
      expression, by one of these:
      - adding to it: `push`, `unshift`, `splice`, `set` or `add` on it, or
        a write through `walked[k]`;
      - `++` or `--` on it, or spreading it;
      - passing it to a call or a `new` whose callee may resize an array,
        or that goes through a function reference;
      - assigning it, or storing it in a variable, field, array or object.

      Any other use leaves the walk bounded, and so does a call in the body
      that resizes some other array.

    Every other loop is unbounded:
    - `while (true)` and `for (;;)`;
    - a flag with no comparison (`while (running)`);
    - equalities only (`while (a !== X && a !== Y)`);
    - a top-level `||` (`while (next >= 0 || next === FULL)`);
    - a call in the condition (`while (more(log))`,
      `while (k < n && poll())`);
    - a `for...of` whose body extends what it walks, as above;
    - a bounded loop inside an unbounded one that releases nothing.

    The rule has known blind spots. A comparison loop whose body never
    moves toward its bound still counts as bounded. So does a `for...of`
    whose collection grows by a way the rule does not follow: through an
    alias (`const a = q; for (const x of q) a.push(x)`), through a method
    that grows `this.items` while it is walked, or when the walked
    expression is not a local, `this` or a field path (a call result or an
    index expression).

    There is at most one warning per loop, at the innermost loop whose pass
    releases nothing. It names:
    - the first site and its kind, and how many more there are;
    - where the memory goes back;
    - why the pass has no scope;
    - the rewrite.

    The rewrite moves the per-pass work that builds the temporary into a
    block inside the loop body that opens with
    [`using a = arena()`](#using-a--arena). The compiler refuses that block
    (NL2416 and its family) if anything allocated there could outlive it
    (`tests/cases/perf_arena_unbounded_pass`).

    Only a temporary the pass drops counts. These do not: an array a `push`
    grows, a value stored or passed on, and a call to a function that stores
    what it allocates. A temporary handed to a callee that keeps it is passed
    on, so it is not counted. A temporary from which every path leaves the
    loop, by `return`, `throw` or a `break` out of it, is built at most once
    each time the loop runs, so it is not counted either. Inside nested
    loops it has to leave every unbounded loop out to where its memory is
    released, not only the innermost: an unlabelled `break` ends only its
    own loop, so a temporary that breaks out of a `for...of` inside a
    `while (poll())` still counts, while a `return` or a `break` to a label
    on the outer loop leaves both. The walk that proves it gives up at a
    `switch`, a `try` or a nested loop, so a temporary that a `return`
    inside a `switch` leaves with still counts.

    Not reported for:
    - a bounded loop;
    - the same temporary inside the block;
    - a loop whose pass takes its scope;
    - a site NL9002, NL9003, NL9011 or NL9016 already reports, as the value
      of the assignment or the call that warning sits on
      (`tests/cases/perf_arena_unbounded_quiet`).

    It reads the `"accumulates"` fact `--emit-arena` prints, then keeps only
    the temporaries a pass drops, and changes no byte of the IR.
  - **a function that keeps memory on every call** (NL9019) — a function
    that keeps an allocation of its own past the call (a local assigned more
    than once, or an array of its own; a value it only hands to a function's
    parameter does not count, nor does one it only places in an array or
    object literal that is itself handed to a parameter or to `spawnSync`, or
    only reads in place, as in `[a, b].join(",")`), so that it has no arena
    scope of its own, and that a loop pass which releases nothing calls
    directly. Every pass adds the allocation the call kept, and nothing
    releases it while the loop runs. Reported once, at the function's
    declaration, naming the line of the first allocation it holds; the hints
    are a `const` per value, a block that opens with
    [`using a = arena()`](#using-a--arena) around the work, or a region for
    what must outlive the call (`tests/cases/perf_kept_memory`). The rule
    counts passes, not their number: a short fixed loop such as
    `for (let i = 0; i < 3; i++)` warns as an unbounded one does. Not reported
    when the function returns a value that is not a number, a boolean, an enum
    or nothing, because then its caller owns the memory; when it manages the
    arena itself, feeds tasks, or fills a parameter; when it is a
    constructor reached by `new`; or when every loop that calls it releases
    what it kept — a pass with a scope of its own, or a call inside a
    `using a = arena()` block. A loop nested in such a block, or in a pass of
    an outer loop that has a scope of its own, counts as released, because
    the memory goes back when that block or pass ends: a block around a loop
    that never ends silences the warning without bounding the growth. Only a loop's direct callees are
    judged, each on its own allocations: memory kept deeper in the chain,
    behind a direct callee that answers memory, is not this warning's, and
    [`--explain-memory`](#explaining-kept-memory) lists it
    (`tests/cases/perf_kept_memory_quiet`). No call is excused for the object
    it receives: a function that does its work once, behind a guard on a
    field (`if (s.ready) return; s.ready = true`), still warns when it keeps
    an array of its own, because the rule does not prove which object reaches
    it on each pass; open a block with `using a = arena()` around that work
    (`tests/cases/perf_kept_memory_direct`). A value handed to a callee's
    parameter is not counted as kept even when the callee stores it into
    something older (`add(list, makeItem())`): this rule does not report
    that retention.
  - **a constant computed with overflow** — a `+`, `-` or `*` over decimal
    literals whose exact value does not fit the `i32` it is computed in. By
    default that operation panics when it runs, so the hint is to widen the
    operands with `toI64` or to write it as a `wrapping*` call from
    `nish:unsafe` (`tests/cases/perf_overflow_const`). Reported on the
    innermost expression that overflows, so `100000 * 100000 + 1` warns once.
    Silent for a `wrapping*` call, where the wrap is the defined answer,
    silent for the unsigned widths,
    which are defined to wrap in both modes, and silent for anything the
    folder does not evaluate — a named `const`, a hexadecimal literal, or a
    value large enough that the fold itself would have to overflow to find out
    (`tests/cases/perf_overflow_quiet`). A *module-level* `const` needs no
    warning: its fold is eager and an overflow there is a hard error.
  - **a product widened after it has already overflowed** — `toI64(a * b)` or
    `toF64(a * b)` where the operand expression is `i32`. The multiplication
    happens in `i32`, where a product past its range panics before the conversion sees it, so the wider type never holds
    the value the reader expects; the hint is to
    convert the operands first (`tests/cases/perf_overflow`). Not reported when
    the arithmetic is already done in the wider type (`toI64(a) * toI64(b)`),
    which is the rewrite itself, and not for `+` or `-`, which can overflow
    too but whose shape is usually innocent: `toI64(intBits(t) - 1)` has
    nothing wrong with it, and a warning there would be the un-actionable kind.
  - **a shift count at or beyond the operand width** — `x << 32` on an `i32`.
    The count is masked to the width, so the shift that runs is not the shift
    that was written; the hint is to mask deliberately or to shift a wider
    value (`tests/cases/perf_overflow`). A count inside the width is silent.
  - **a bounds check that was not eliminated** — `a[i]` or `s.charCodeAt(i)`
    inside a loop where the proof above did not come off, so the length is
    loaded and compared on every iteration. The hint is the guard that always
    works — `if (i >= 0 && i < a.length)` reaching the access proves both ends,
    whatever took the proof away — with an unsigned index named beside it,
    since half the proof then comes off the declaration; for a `u8`, `u16`
    or `u32` index, which that `i32` test does not type-check against, the
    hint is the other half alone, `if (toU32(i) < toU32(a.length))`
    (`tests/cases/perf_bounds_loop`, `arr_bounds_unsigned_guard`,
    `reject_deny_panics_index_unsigned`). Under `--number-mode f64`, where a
    length is an `f64`, the bound is spelled `toI32(a.length)`
    (`tests/wordings/nl9007_guard_f64_mode`, and NL2457's
    `nl2457_deny_panics_index_f64_i32` and `_f64_ranged`). The hint names
    only a guard that compiles and that the proof credits, so it names none
    for an `i64`, a
    `u64` or a float index, which no spelling compares with the length in a
    credited way, nor where the module declares its own `toU32` (or, under
    f64, `toI32`), which the guard would call instead of the builtin; it says
    so instead (`tests/wordings/nl9007_guard_*`, and NL2457's
    `nl2457_deny_panics_index_*`). Reported on the index, once per
    access. Where the index is an `i32`, an `i32`-based ranged integer or a
    `u8`, `u16` or `u32`, and nothing between the start of its statement and
    the access branches, loops, calls, allocates or assigns (the README below
    lists the rest of the conditions), the warning carries a fix: `nish --fix`
    inserts `if (!(i >= 0 && i < toI32(xs.length))) { panic("index out of range") }`,
    or `if (!(toU32(i) < toU32(xs.length))) { panic("index out of range") }`
    for an unsigned index, at the start of that statement, a guard the proof
    credits, so an index in range runs as before and one out of range still
    exits 1, at the guard
    (`tests/fix/guard-*`, [`tests/fix/README.md`](../tests/fix/README.md)).
    Silent outside a loop, where one check is not a cost anybody is paying,
    and silent unless the receiver is a plain local and the index a plain
    local or an offset from one, `i + c`, which are the shapes the analysis
    knows how to prove — a field receiver
    (`this.source.charCodeAt(this.pos)`) or any other computed index was
    never a candidate, and the rewrite there is to bind them to locals first
    (`tests/cases/perf_bounds_quiet`). An offset index is named as written
    and the guard offered is one on the sum,
    `` `if (i >= 0 && i + 1 < ys.length)` proves both ends, and so does a loop condition `i + 1 < ys.length` on a counter that starts at 0 ``,
    with `toI32(ys.length)` under f64 (`tests/cases/perf_bounds_offset`,
    `tests/wordings/nl9007_offset`, `nl9007_offset_f64_mode`). It carries no
    fix: an inserted guard would stop at `i === -1`, whose index `i + 1` is
    in range, so it could change what a program that works today does.
  - **a range entry that was not proven** — a value entering an
    `integer<Lo, Hi>` inside a loop where the proof above did not place it in
    the range, so the compare and its cold panic run on every iteration. A
    local is named with the guard that proves it —
    `if (k >= 0 && k <= 99)`, or `if (k <= 99)` for a range with no lower end
    — and anything computed is told to be bound to an `i32` local and guarded
    there, or, when it is a counter or a cursor written back into its own
    range, to be declared `i32` with the range on the value that is used
    (`tests/cases/perf_rng_loop`, `perf_rng_counter`). Reported on the value,
    or on the target of a compound assignment or an increment, once per
    entry. Silent outside a loop; silent for a proven entry
    (`tests/cases/perf_rng_quiet`); and silent for a range whose lower end is
    neither 0 nor `-2147483648`, where no guard proves the entry.
  - **a `substring` bound whose clamp could not be folded off** —
    `s.substring(a, b)` inside a loop where the proof above could not place `a`
    or `b` in `[0, s.length]`, so that bound keeps the `llvm.smin` /
    `llvm.smax` pair JavaScript's clamp needs and pays for it on every pass.
    Two hints, because they are not the same trade: a test that reaches the
    call (`if (a >= 0 && a <= s.length)`) keeps the semantics exactly and lets
    the compiler write the bound through, and `slice` has no clamp at all but
    **panics** where `substring` would have clamped — it was measured 1.18x
    over an unfolded `substring` on a lexer-shaped scan
    ([wp15-performance.md](wp15-performance.md) §4), and the fold is what
    closes most of that gap for a bound the guard proves
    (`tests/cases/perf_clamp`). Reported on the bound, once per bound, so
    `s.substring(from, to)` with neither end proven warns twice. Silent
    outside a loop, where the clamp runs once; silent for a bound the proof
    came off, including the literal `0` that every string proves; and silent
    unless the receiver and the bound are both plain locals, which is the
    shape a guard could prove (`tests/cases/perf_clamp_quiet`).
  - **a function kept external by `--no-strict-exports`** — a call, inside a
    loop, to a function the module does not export, while that flag is in
    effect. The default gives such a function `internal` linkage, which is what
    lets the whole-program passes treat the call sites they can see as all of
    them: specialise the body to those arguments, and drop the out-of-line copy
    once the calls are inlined. The hint is to stop passing the flag
    (`tests/cases/perf_inline`). What it costs is measured as a **size**: 240
    bytes on `bench/sieve`, where `opt -O3` deletes the out-of-line copy under
    the default and keeps it under the flag, and nothing at all on
    `bench/spectral`, whose binary is in fact 64 bytes *smaller* with it. The
    wall clock does not move on either
    ([wp15-performance.md](wp15-performance.md) §9), so the message names the
    missed specialisation and no speed figure. It is reported at a call in a
    loop rather than per function. Reported once per
    call site. Silent for an exported function, where the ABI is the point;
    silent outside a loop; silent for a `declare function`, which is external
    because C defines it and so has neither rewrite available — `export
    declare function` is refused, and the flag has no linkage to withdraw from
    a declaration with no body; and silent altogether under the default, so a
    build that did not ask for the flag never sees it
    (`tests/cases/perf_inline_quiet`, `perf_inline_foreign`).
  - **wasteful struct padding** — a `class` or `interface` whose declared field
    order costs it bytes of padding that a different order would not spend.
    Fields are laid out in declaration order at natural alignment, exactly as
    clang lays out the equivalent C struct ([Classes](#classes)), so a
    `boolean` in front of an `f64` throws seven bytes of every value away. The
    message names the current size, the size the same fields reach in their best
    order, and that order — the fields widest first, same-width fields left
    where they were written (`tests/cases/perf_padding`). On an `interface` it
    names the second half of the rewrite as well, because the interface's fields
    are the first fields of every class that `implements` it and reordering it
    alone is what stops those classes compiling. It is the rule the report order
    above was written for, being the only one of the ten decided in pass 1
    (`tests/cases/diag_order_pass1`). Silent wherever the
    two sizes are equal — fields already widest first, one alignment
    throughout, a single field, or trailing padding that belongs to the
    alignment rather than to the order; and silent for a generic
    instantiation, which shares one declaration with every other instantiation
    of the same class, so the caret would land on that declaration once per type
    argument and the order that suits one need not suit another
    (`tests/cases/perf_padding_quiet`). A class that `implements` an interface
    is held to the part of its order that is its own: the fields of the longest
    interface it implements are its first fields, in that interface's order, so
    they stay put, and the rule warns when reordering only the fields after them
    would shrink the class. The message names the whole order and says the
    first fields stay where `implements` puts them
    (`tests/cases/perf_padding_suffix`). The fields after them are laid out
    from where the prefix ends, which is not always widest first. A prefix
    that ends off alignment leaves a gap, and the order the message names
    fills that gap with the narrow fields first
    (`tests/cases/perf_padding_suffix_gap`). Padding inside that prefix is the
    interface's, and the class says nothing about it
    (`tests/cases/perf_padding_suffix_quiet`).
- **Portability warnings are the second diagnostic that is not an error**
  ([wp33-round-trip.md](wp33-round-trip.md) §5.2). A program here can also be
  read as TypeScript and run under Node with `runtime/nish.mjs`, and at a few
  kinds of site the two readings both run to the end and quietly answer
  differently; `--warn-portability` reports those sites, in the shape a
  performance warning has, with `portability` where `performance` would be:
  `file:line:col: portability: <text>`, and `"severity":"portability"` under
  `--json`. They are **off by default** — the pass that finds them does not run
  without the flag — and **never change the exit code** or a byte of the IR.
  They print only for a compilation that checked cleanly, after the performance
  warnings and on the same streams, capped at 20 with
  `...and N more portability warnings` and an `N portability warnings` line, in
  the same order as the performance report. `--no-warn-performance` does not
  silence them, and `--warn-portability` does not change the performance
  report. The standard library is not walked: its sites are not the reader's
  to change, and a program that uses `Map` never runs `std/collections.ts` as
  TypeScript at all. A difference TypeScript reports loudly (`orReturn`, `Ok`
  and `Err`, a host global, a `nish:` specifier, `export const main`, `enum`)
  is not one of them, because the TypeScript tests already notice it. The
  rows, one code each in band NL8xxx:

  | Code | Row ([wp33](wp33-round-trip.md) §3) | Where it is reported | What the TypeScript reading does instead |
  | --- | --- | --- | --- |
  | NL8001 | UTF-8 offsets (3.2) | an offset (`s.length`, `s.indexOf(t)`, `s.lastIndexOf(t)`) or a code unit (`s.charCodeAt(i)`) of a string that is not provably ASCII, where it meets a fact not counted in bytes: printed, returned by `main`, stored (a data-parallel body's answer included), compared or combined with a number literal, taken from a width (`width - s.length`), used as an array index, a loop bound or `parallelFrom`'s count — directly, through a function it is passed to, or through a helper that returns it; the exact predicate is below the table | counts UTF-16 code units, so the number differs wherever the text is not ASCII |
  | NL8002 | checked `slice` (3.2) | a `slice(a)` or `slice(a, b)` on a string with a bound that is a negative literal, or that is placed inside `[0, length]` neither by the bounds proof which folds a `substring` clamp nor by the receiver's own text: an ASCII string literal, a `const` bound to one, a `const` copied from such a `const`, or a module constant that folds to one has a known length, and a bound no larger than it is quiet when it is a non-negative literal, or a local the same bounds proof holds between 0 and that length — a `const` or a `let` its initialiser bounds, or one a guard bounds — and, when the receiver's length is what proves either of two bounds, the first is known to be no larger than the second, from the largest the first can be and the smallest the second can be (`tests/cases/port_str_slice_literal_quiet`; past the end, a reversed pair such as `slice(5, 2)`, a pair nothing orders, a `let` receiver and a non-ASCII literal still warn, `port_str_slice_literal_past`); one warning per call, at the first such bound | clamps the bounds and counts a negative one from the end, where this panics |
  | NL8003 | a record copied in (3.3) | a local record `p` copied into a record array `ps` (`ps.push(p)`, an element of an array literal, `ps[i] = p`), when a field of one copy is written after the copy and the other copy is read after that write; the exact predicate is below the table | stores the same object, so a write through one is seen through the other |
  | NL8004 | a store over a live element (3.3) | a whole-slot store `ps[i] = v` into a record array while an element reference into the same array (`const r = ps[j]`, or `r` of `for (const r of ps)`) is still read afterwards; `i` and `j` are not compared, and a field store `ps[i].x = v` is not a whole-slot store | puts a new object in the slot and leaves `r` holding the old one |
  | NL8005 | zero-fill (3.3) | `new Array<T>(n)` of a number or a boolean, unless `n`'s value is zero, however it is spelled: `0x0`, `-0`, `0.0` or a `const` that folds to 0 (`tests/cases/port_array_zero_fill`; `[]`, a zero length and the typed arrays are silent, `port_array_quiet`, `port_array_quiet_f64`) | fills it with holes, which read back as `undefined` |
  | NL8006 | integer `/` (3.1) | `/` or `/=` on an integer type, not already the argument of its own type's conversion (`toI32(a / b)` does not warn) | divides exactly and keeps the fraction. **`review`:** the division wrapped in its type's own conversion, `toI32(a / b)`, `toU8`, `toU16` or `toU32` (`q /= d` becomes `q = toI32(q / d)`), which emits no instruction here and truncates the quotient under Node; none in a generic body, whose one rewrite would serve every instantiation, for `/=` on anything but a name (`p.x /= 2`), which the rewrite would evaluate twice, for a `/=` on a ranged target, whose type is the range and not the conversion's, for a `/=` whose divisor holds a `/` (`q /= a / b`), whose own edit would land inside this one, or with a comment before its `/=`, which the rewrite would drop, where the quotient's type or an operand's is not exactly the conversion's (a `u8` divided into an `i32`), whose conversion would change a value, in a module that binds the conversion's name as anything but the builtin (a `const`, function, parameter, loop variable, member or import named `toI32`, renamed imports included), where the edit would call that binding, or for `i64` and `u64`, which no conversion leaves alone here and truncates there. A ranged operand's `/` takes the edit: its quotient is the base type, and a quotient's conversion to its own type keeps the quotient's proven range, so `toI32(a / 4) + 1` skips the overflow check `a / 4 + 1` skips. The edits compose: `a / b / c` warns twice, both edits insert `toI32(` at one offset, and applied together from the end they nest, `toI32(toI32(a / b) / c)` (`tests/fix/port-div-*`, `port-nofix-div-*`) |
  | NL8007 | wrapping (3.1) | `+ - *`, their `op=` forms, `++` and `--` on `u8`/`u16`/`u32`; a ranged integer is left out, because every write into its range is checked | keeps counting past the range. **No `review`:** a mask (`(a + b) & 0xff`) or `>>> 0` still warns and adds an `and` or `lshr` here, and `toU8` and its kin saturate under Node where the native value wraps (`tests/fix/port-nofix-wrap`) |
  | NL8008 | `i32 >>>` (3.1) | `>>>` or `>>>=` whose result is `i32`, unless the count is a constant `k` — a literal, or a `const` that folds to one — with `k & 31` not 0: such a shift is at most 2^31 − 1, so it reads back the same both ways (`-16 >>> 2` is `1073741820` in each), and `x >>> 0` or a count that is not a constant is reported | reads the result back unsigned. **No `review`:** `(x >>> k) \| 0` still warns and adds an `or` here, and `toI32` saturates under Node where the native bits read back signed (`tests/fix/port-nofix-shift`) |
  | NL8009 | 64-bit integers (3.1) | a binding, parameter, field or return type declared `i64` or `u64` | holds a double, which rounds past 2^53 |
  | NL8010 | *retired* | nothing: the row was `Math.min`, `Math.max` or `Math.round` of an `f64` or `f32`, when `min` and `max` dropped a NaN operand and `round` answered `0` for a negative number that rounds to zero. They lower to a NaN test and a sign-bit pick (`llvm.minimum`/`llvm.maximum` on wasm) and a `llvm.copysign.f64` now, which answer NaN and `-0` as JavaScript does, so no site diverges (`tests/cases/port_num_libm` is quiet). The code stays reserved and is never reused | — |
  | NL8011 | *retired* | nothing: the row was `console.log` or `console.error` of a float printing `-0`, and it marks no divergence in the reading the class is defined against. `runtime/nish.mjs` replaces both with shims that print `String(x)`, and `String(-0)` is `0`, which is what the native build prints. The code stays reserved and is never reused | — |
  | NL8012 | a stubbed generic (`--emit-ts` only) | a generic function or method of the program's own modules that no instance reaches, whose body needs the checker's types to translate (a 64-bit integer or a builtin call) | throws when called, where the native build has no body to call at all |

  **NL8001, exactly.** A *source* is `s.length`, `s.indexOf(t)`,
  `s.indexOf(t, i)` or `s.lastIndexOf(t)` (an offset) or `s.charCodeAt(i)` (a code unit) on a
  `string` — an array's `.length` is not one — whose receiver is not
  *provably ASCII*: a literal of bytes below 128, a module constant that folds
  to one, a template, `+` or `?:` built only of ASCII parts and number or
  boolean holes, or a local declared in the same body whose initialiser and
  every `=` to it are one of those (`s = s + "x"` keeps `s` proven). A
  parameter proves nothing. From a source the value is followed outward
  through parentheses, `toI32` / `toI64` / `toF64`, either arm of a `?:` and
  arithmetic (`+ - * / %` and the bitwise operators) with an operand that is
  not a literal, and into a local and every read of it. It is reported where
  it meets an outside fact:

  - it is **printed**: an argument of `console.log` or `console.error`, or a
    template literal's hole;
  - it is **the exit code**: the value `main` returns, or its concise body;
  - it is **stored**: into a field or an element, as an object literal's
    property or an array literal's element, or pushed on to an array;
  - it is **compared or combined with a number** — a literal, a signed one or
    a module constant — whose value is, for an offset, anything but `0` and
    `-1` (every string answers those two in both units: `s.length === 0`,
    `s.indexOf(t) < 0`), and for a code unit, 128 or more (a code below 128
    names the same character in both units);
  - it is **taken from a width**: the right operand of a `-` whose left
    operand does not itself hold an offset, as in `width - s.length`, the
    room left in a column that was not counted in bytes;
  - it **indexes an array** (`a[s.indexOf(t)]` picks another element) or
    **counts the elements** `parallelFrom(n, f)` makes — an offset or a code
    unit alike (`table[s.charCodeAt(i) % n]` reads another slot where the
    byte and the unit differ);
  - it **bounds a loop**: either operand of a comparison in a `while`, `do`
    or `for` condition, unless the other operand also holds an offset or is
    the loop's *cursor* into the string it counted — a local the loop hands
    to that string's method, alone or in arithmetic — which counts in the
    string's own unit (`for (let i = 0; i < s.length; i++)` over
    `s.charCodeAt(i)` is quiet, and so is a bound that moves the cursor by a
    constant to look ahead, `i + 1 < s.length`; the same loop over
    `other.charCodeAt(i)` alone is reported);
  - it is **a data-parallel body's answer**: stored in the array
    `parallelMap`, `parallelMapInto` or `parallelFrom` fills, or folded by
    `parallelReduce` (with its identity) into the value the call answers,
    which is followed on from the call.

  The walk crosses functions of the same module that are not generic or
  methods of a generic class, up to four calls deep. An offset passed as an
  argument — to a function, a method or a constructor — is followed through
  the parameter in the callee and reported at the argument, quoting the
  callee's reason (`` `s.length` … and it is passed to `show`, where it is
  printed ``). An offset a function returns, or an arrow answers, is followed
  from every call of it in the module, and from the parallel call that runs
  the arrow as its body; a call whose string argument is provably ASCII is
  skipped. A name an arrow captures is provably ASCII when the function that
  hosts the arrow writes only ASCII to it.

  The walk is a lint, not a proof, and it is silent where it stops: past the
  fourth call (a recursive call ends there), into a generic function, a
  method of a generic class or a function of another module, at a parameter
  the callee never reads, or one it reads only inside an arrow it passes on,
  and at the answer of a `spawn` body, whose task is not followed into the
  value its scope hands back. A recursive helper that answers its parameter
  is still reported at the call that prints its answer. Once an offset has
  crossed into another function, the string it counted is out of reach, so a
  loop it bounds there takes any string's method as its cursor
  (`tests/link/port_utf8_offset_walk_limits`).

  One `+ k` on the offset an `indexOf` (with or without a start) or
  `lastIndexOf` of a provably ASCII needle answers, with `0 < k <= needle.length`, steps inside the match and is not itself a
  fact from outside: `line.substring(line.indexOf(":") + 1)` is quiet, and
  the stepped offset is followed on like any other, so printing it is
  reported. Everything else is quiet: an offset handed to a string method,
  compared with another offset or with a cursor, or kept inside a function
  the walk does not cross, stays inside the program's own counting, so
  `const width = name.length;` alone is not reported
  (`tests/cases/port_str_length_printed`, `port_str_nonascii_charcode`,
  `port_str_needle_step_printed`, `port_utf8_offset_index`,
  `port_utf8_offset_argument`, `port_utf8_offset_loop_bound`,
  `port_utf8_offset_helper_return`; `tests/link/port_utf8_offset_parallel_body`,
  `port_utf8_offset_parallel_from`, `port_utf8_offset_parallel_reduce`,
  `port_utf8_offset_walk_limits`; quiet:
  `port_str_ascii_literal_quiet`, `port_str_offset_roundtrip_quiet`,
  `tests/link/port_utf8_offset_quiet`; the form with a start:
  `str_index_of_from_port`).

  **NL8003 and NL8004, exactly.** A *record array* holds its records inline:
  its element type is an `interface` no class `implements`, and not
  `T | null`. The two rows tell arrays apart by name — a local, or a member
  chain such as `this.ps` — except for an element type the body *aliases*:
  when a record array is declared or assigned from anything but a literal or
  a `new`, or used other than as an index or member receiver, a `for … of`
  iterable, a call argument or such an assignment's target (`const qs = ps`,
  `this.f = ps`, `return ps`), every array of that element type is taken to
  be the same array. An arrow argument's body is its own.

  - NL8003's *copy site* is a local `p`, as written, passed to `ps.push`, put
    in an array literal that initialises or is assigned to a binding, or
    stored by `ps[i] = p`. It is reported at `p` when a field write
    (`x.f = e`, `x.f op= e`, `x.f++`, `x.f--`) through `p`, or through
    `ps[k]` for any `k`, runs after the copy, and the other side is read after
    that write: any use of `ps` after a write through `p`; any use of `p` after
    a write through `ps[k]`, and any use of `ps` too when `p` was copied in at
    two sites (`[p, p]`). "Runs after" is later in the source, or inside a
    loop that encloses the earlier node and does not declare `p`. A write
    through a nested record (`p.inner.x`) is not one: that field is a pointer
    in both readings.
  - NL8004 tracks the element references `reject_arr_element_across_push`
    tracks, less `pop()`'s, whose slot no in-bounds store reaches; each is
    live until its block ends, and inside a loop the loop's stores reach a
    reference that was live on entry. It is reported at the store, naming the
    reference and the line it is next read on.

  Neither row sees an array that reaches a second name through a call, two
  parameters or fields that already hold one array on entry, a write done in a
  callee (`bump(p)`), a write through an element reference or a `for … of`
  variable (for NL8003), or a copy whose source is not a local
  (`ps.push(this.p)`). They warn where nothing diverges at a self-copy
  (`r = ps[0]; ps[0] = r`), at a `let p` rebound between the copy and the
  write, across `if`/`else` arms (which are ordered by source position), at a
  read of `ps` that is only `ps.length`, and at any two arrays of an aliased
  element type (`tests/cases/port_rec_push_then_write`,
  `port_rec_literal_twice`, `port_rec_slot_store_live_ref`,
  `port_rec_alias_copy`, `port_rec_alias_store`; quiet:
  `port_rec_push_never_written_quiet`, `port_rec_slot_store_dead_ref_quiet`,
  `port_rec_pop_ref_quiet`, `port_rec_alias_arrow_quiet`).

  Every row but the retired NL8010 and NL8011 is live, each with a warning case and a
  quiet counterpart among `tests/cases/port_*` and a wording pin in
  `tests/wordings/`, but NL8012, which only `--emit-ts` reports: its cases are
  `tests/emit-ts/records/generic-uncalled.ts` (warned) and
  `tests/emit-ts/identity/maps.ts` (a standard-library stub, quiet), checked
  by `tests/run.js`'s emit-ts section, and its pin is
  `tests/wordings/nl8012_generic_stub`.
- **Deprecation warnings are the third diagnostic that is not an error.** One
  marks a call the language still compiles, to exactly the IR it always did,
  and is going to take away in a later breaking release, naming what replaces
  it: `file:line:col: deprecation: <text>`, with the excerpt, and
  `"severity":"deprecation"` under `--json`. They are **on by default** with
  no flag to silence them — `--no-warn-performance` does not, and `nish run`
  prints them too — and **never change the exit code**. They print only for a
  compilation that checked cleanly, **before** the performance warnings and on
  the same streams, capped at 20 with `...and N more deprecation warnings` and
  an `N deprecation warnings` line, in the order the other two reports use. A
  call in a generic body warns once, however many instantiations check it. The
  standard library and the examples call nothing deprecated, and `npm test`
  fails the day one of them does. **Nothing is deprecated today**: band NL7xxx
  holds only the retired NL7001 (`Arena.release` and `Arena.reset`) and NL7002
  (`--unchecked-indexing`'s sites), whose constructs were removed before 1.0
  rather than kept behind a warning (`tests/wordings/unreachable.txt`).
- **`--json`** prints every diagnostic as one JSON object per line on stdout,
  `{"file","line","column","endLine","endColumn","severity","code","message"}`
  (1-based, end exclusive; syntax errors carry a `syntax error: ` prefix in
  `message`), nothing else on stdout and nothing on stderr, with the same exit
  code. `severity` is `"error"` for every error, `"performance"` for a
  WP15 §8 warning, `"portability"` for a WP33 one and `"deprecation"` for a
  deprecated call, which is the field a tool filters on; `code` is the stable
  identifier for the rule (`NL1013`, `NL2231`, ...) and is the field to key on,
  because the prose may improve between releases and the code may not. A
  diagnostic in a dependency's source — a module resolved into a package
  other than the root and the standard library — adds `"package"`, the
  package's name, after `message` (and before a `fix`), and its human report
  adds a line under the excerpt, `` = note: this is in the dependency
  `pkg_broken` 0.3.1, not in this program's own source `` (WP21 S3,
  `tests/link/package_dependency_error`). A
  failure with no source position — an unusable C toolchain, an internal
  compiler error, a bad `-o` layout — is `{"severity","code","message"}`. Two
  optional keys follow `message`, each a list of edits
  `[{"line","column","endLine","endColumn","text"}]` placed as the diagnostic
  is, and each absent rather than empty: `fix`, the rewrite that removes the
  diagnostic and keeps the program's meaning, which `nish --fix` applies; and
  then `review`, printed after `fix` (WP33 R5), on a portability warning whose
  rewrite makes the site read the same under Node and compiles to the same IR
  byte for byte, but changes what the source says, so a person or an agent
  decides: `nish --fix` never applies it. Which rows carry one is the
  portability table's last column. The
  bands and the registry are in
  [wp10-ci.md](wp10-ci.md#code). A clean compile with no warnings prints
  nothing.
- **`--emit-ast`** prints the syntax tree of every module after Phase 0 as an
  indented `<KIND> <start> <end>` tree — the node kinds of `src/nodes.ts` and
  each node's span as byte offsets, identifier and literal text appended — and
  writes no IR (`tests/cases/dump_ast`).
- **`--emit-checked`** checks the program and prints the side tables the
  emitter would consume: per module its structs (fields with index and byte
  offset, size, align, constructor and methods), imports, and functions
  (resolved signature, LLVM symbol, attribute facts, pointer-parameter facts,
  locals with types, callees) (`tests/cases/dump_checked`).
- **`--emit-panics <file.json>`** writes every panic site of the program,
  function by function, beside the IR, and changes no byte of it; see
  [Panic sites](#panic-sites) below.
- **`--deny-retention`** refuses a program whose own code keeps arena memory
  that nothing can reach, for a long-running program that cannot afford it; see
  [Retention as an error](#retention-as-an-error) below.
- **`--compat`** selects the compatibility dialect, and
  **`--compat=<feature>,...`** selects it with only the features it names. It
  is a dialect flag, not a diagnostic one; the rules are
  [The compatibility dialect](#the-compatibility-dialect) below.
- **`--emit-arena <file.json>`** writes every allocation site of the program
  with where its memory goes, beside the IR, and changes no byte of it; see
  [Arena placement](#arena-placement) below.
- **`--explain-memory`** prints, beside the warnings, every loop and function
  of the program's own modules that keeps the memory it allocates past its
  scope, and why, and changes no byte of the IR; see
  [Explaining kept memory](#explaining-kept-memory) below.
- **`-g`** emits DWARF metadata: a `DICompileUnit` (`DW_LANG_C99`) and a
  `DIFile` per source file a declaration comes from — the name as it was given
  on the command line, with `.` for the directory, so the metadata depends only
  on the command line and not on where the build ran — a `DISubprogram` per
  function, a `DILocation` on every instruction (each statement's and
  expression's start; the function's own position for the prologue),
  `llvm.dbg.value` for parameters and
  `llvm.dbg.declare` for `let`/`const` slots. `number` is `int`, `i64`
  `long`, `f64` `double`, `boolean` `bool`, `string` `char*`, a class or
  interface a pointer to a `DICompositeType` with the checker's layout, `T[]`
  a pointer to `{ long len; long cap; T* data; }`. A function's own position —
  its `DISubprogram`'s `line` and `scopeLine`, its parameters'
  `DILocalVariable`s and the `DILocation` the prologue carries — is where its
  **declaration** starts, which is the `export` or the `const` and never the
  arrow's parameter list, so the two spellings of one function describe it
  identically (`tests/cases/dbg_arrow`). A `DILocation` column is a 1-based
  **byte** offset into its line, as `clang -g` writes it, so a position after a
  multi-byte character is counted in bytes and not in UTF-16 code units
  (`tests/cases/dbg_utf8`). Without `-g` the IR is
  byte-identical. `--link -g` passes `-g` to `scripts/build.sh`, which
  compiles `runtime.c` with `-g` and skips the strip step of every profile
  (`tests/cases/dbg_locals`; the `-g` block of `tests/run.js` checks the
  linked binary's line table with `llvm-dwarfdump`).

### Writing the program out as TypeScript

- **`--emit-ts <dir>` writes the checked program back out as TypeScript**
  that Node runs with its type stripping ([wp33](wp33-round-trip.md) §3),
  one file per module, and emits no IR (`src/emit-ts.ts`). Each module of the
  root package keeps its path relative to the directory they all share; each
  standard-library module the program reaches is written under `nish/` beside
  them (`std/pair.ts` as `nish/pair.ts`); a dependency package's module is not
  written. Last comes `entry.ts`, which imports `nish/runtime/node`, calls
  `main` and exits with what it answered. Imports are rewritten to match: a
  `nish:` specifier becomes `nish/runtime`, the one package the output names,
  `nish:secret` included (its `std/secret.ts` is not written: the runtime's
  `wipe` answers it, a zero-fill that cannot reach a copy the engine made, so
  erasure is the native build's alone: `docs/security/secret.md`, SECRET-6),
  save `nish:async`, which becomes `nish/runtime/async.mjs` because
  `nish:process` has a `spawn` of its own in `nish/runtime`; a `nish/x` or relative one becomes the relative path, with its `.ts`; and an
  imported name that is only a type (an interface, a generic interface, an
  alias) is written `type X`, because Node's type stripping does not know
  which names are types. A module that needs none of that and none of the rows
  below is written byte for byte (`tests/emit-ts/identity/`; the layout is
  `tests/emit-ts/layout/`); one row that touches an otherwise untouched module
  is the `: string` on an unannotated `const` bound to a string literal.
- **The flag turns `--warn-portability` on**: those warnings name the sites
  where the TypeScript reading answers differently.
- **Seven kinds of module are refused, and then nothing is written** (exit 1):
  one that declares C functions, whose bodies are not in the program
  (NL4010, `tests/cases/reject_emit_ts_ffi`), and one that imports `nish:net`
  or calls a `nish:net` function, `signalFd` or `readSignal`, imported or by
  its global name, whose translation is not local to its statement (NL4011,
  `reject_emit_ts_net`, `reject_emit_ts_net_global`, `reject_emit_ts_signal`),
  and one with an `x op= e` the TypeScript writes as `x = x op e` (a width
  that wraps, a checked i32 operation, an integer `/`) whose target's index
  holds a call, a step or an element read, which would then run twice
  (NL4012, `reject_emit_ts_compound`). An index of names, their fields
  (`seen.length`), literals and their arithmetic is repeated, and `pts[i + 1].n += 10` is translated.
  The fourth is a generic whose instances would be written as different
  TypeScript, which is written once for them all: an element held inline in
  one instance and by reference in another (`P` and `P | null`), or element
  types with different zeros in `new Array<T>(n)` (`i32` and `i64`) (NL4013,
  `reject_emit_ts_instances`). Write a function per element type.
  A generic no instance reaches (a function, a method, or the methods and
  constructor of a class no type argument list names) has no types and no
  native body. Where no type would change its text it is written as it is,
  through the rewrites that need no type (`a[i]` is still checked); where a
  type would (a 64-bit integer, which is a `bigint` there, `f32`, a builtin
  call, arithmetic whose width wraps, a string's `.length` or methods, a
  `Result`'s), it is written with a body that throws. Such a stub in the
  program's own modules is a portability warning naming it at its
  declaration (NL8012, `tests/emit-ts/records/generic-uncalled.ts`); the
  standard library's (`insertAt` of `nish/collections`) are written without
  one. The fifth refusal is such a generic in the program's own modules whose
  body copies an element into an array slot, in a module that holds records
  inline, or fills `new Array<T>(n)` with `T`'s zero, which only an instance
  would decide, whatever else in it needs a type, a 64-bit integer or a
  builtin call included (NL4014, `tests/emit-ts/refused/uncalled-zero.ts`,
  `uncalled-copy.ts`, `uncalled-ctor-zero.ts`, `uncalled-field-zero.ts`,
  `uncalled-wide-zero.ts`); in the standard library the same body is a stub,
  without a warning, and the program is written. The sixth is a module that
  imports `nish:region`, whose regions the runtime the output imports
  (`nish/runtime`) does not answer yet, though a program run under Node as it
  is written does (NL4015, `reject_emit_ts_region`); keep it native.
  Every refusal in the program is reported before it exits.
- **It answers in place of the other outputs.** `--link`, `--emit-ast`,
  `--emit-checked` and the `--emit-header`/`--emit-dts`/`--emit-napi`/
  `--emit-napi-async` sidecars are refused beside it with exit 2, and so is
  `-o`, once the program is known to be writable. `--emit-ts` without a
  directory is exit 2 as well, and so is a program that cannot be laid out
  under one directory: a module above the directory of the others, or two
  modules (or one and `entry.ts`) that would be written to one path, and so
  is a directory where a file it would write is one of the program's own
  modules (`--emit-ts .` beside the sources), checked before anything is
  written.

### Panic sites

A compiled program can stop with exit 1 in more places than the `panic` calls
its author wrote: a bounds check the checker could not prove away, an integer
division, a value entering a range, `r.expect`, a `readFileSync` of a file that
is not there. Each such place is a **panic site**, and
`--emit-panics <file.json>` lists them all, per function, after the checker's
whole-program proofs have run. A site is listed exactly where the emitter
writes a check that can fail or calls into the runtime where it exits; it is
`"proven": true` where a proof table lets the emitter leave the check out, and
a function whose sites are all proven (or `oom`) has no panic path in its IR
— `npm test` holds every golden in `tests/cases/` and `tests/link/` to that
(`tests/panics-oracle.js`). The kinds:

**`index`**: `a[i]`, read or written, and `s.charCodeAt(i)`: `i` outside
`[0, length)`; and the second check of a compound store `a[i] += f()` whose
right side may resize the array

- *What proves it away:* the bounds proof of [Element
  access](#element-access): a dominating guard, a loop bounded by the length,
  or every call site proving the argument (`tests/cases/panics_index`);
  nothing removes the second check of a compound store, which is made after
  the call however the first was proved (`tests/cases/panics_index_recheck`)

**`pop`**: `a.pop()` on an empty array

- *What proves it away:* a dominating `if (a.length > 0)`, the length fact the
  bounds proof already keeps (`tests/cases/panics_pop`)

**`slice`**: `s.slice(a, b)`, `dst.set(src, at)`,
`String.fromBytes(bytes, start, end)` and the buffer range of `netRead`,
`netWrite`, `netWrite2`, `writeBytes`, `udpSendTo` and `udpRecvFrom`: the
range outside the receiver

- *What proves it away:* nothing yet: `substring` clamps instead, and is not a
  site; an array's `xs.slice` is not a `slice` site but a `call` reaching
  `std/array.ts`'s `panic` ([Callback methods and
  `slice`](#callback-methods-and-slice)) (`tests/cases/panics_slice`,
  `str_from_bytes_oob`, `reject_deny_panics_from_bytes`,
  `io_write_bytes_bounds`, `net_write2_bounds`)

**`divide`**: integer `/`, `%`, `/=` and `%=`: a zero divisor, or `MIN / -1`
when signed

- *What proves it away:* a divisor that is not 0, and not -1 unless the
  dividend is known non-negative: a constant (`a / 2`, `a % -3`, a folded
  module constant), a ranged or unsigned divisor whose declared range leaves
  those values out, or a guard on a local divisor —
  `if (d !== 0 && d !== -1)`, `if (d > 0)`, or `if (d !== 0)` on an unsigned
  one. A float division is not a site (`tests/cases/panics_divide`)

**`overflow`**: a signed `i32`/`i64` `+`, `-`, `*`, unary `-`, `++`, `--` or
`op=` whose result does not fit: `attempt to add with overflow` and its
siblings

- *What proves it away:* the overflow proof of [Semantics
  decisions](#semantics-decisions): an operation the bounds walk proves fits
  is `nsw` with no check (`tests/cases/panics_overflow_proven`); every other
  one is checked (`tests/cases/panics_overflow`). A `nish:unsafe`
  `wrappingAdd`, `wrappingSub` or `wrappingMul` is checked nowhere and is not
  a site

**`range`**: a value entering `integer<Lo, Hi>`, the store of `+=` or `++`
into a ranged place, and an exported function's check of a ranged parameter on
entry

- *What proves it away:* the range proof of
  [wp31-ranged-integers.md](wp31-ranged-integers.md) §8 ([Types](#types)): a
  dominating guard such as `if (n >= 0 && n <= 9)`, or every call site proving
  the argument (`tests/cases/panics_range`)

**`array-length`**: `new Array<T>(n)` whose length type could make a bad
header or a negative byte count (an `i64`, a float, an `i32` or a ranged
integer, a `u32` under `--number-mode i32`)

- *What proves it away:* a narrower unsigned length or a literal up to 2^31 -
  1, which is not checked and not a site (`tests/cases/panics_array_length`)

**`panic`**: `panic(message)`

- *What proves it away:* nothing: a path the program never takes is still a
  site (`tests/cases/panics_panic`)

**`expect`**: `r.expect(message)` on an `Err`

- *What proves it away:* nothing; `unwrapOr` and `orReturn` are not sites
  (`tests/cases/panics_expect`)

**`io-exit`**: `readFileSync`, `writeFileSync`, `appendFileSync` and
`crypto.getRandomValues`, which exit inside the runtime on failure

- *What proves it away:* nothing; `readFileSyncOrNull` is the twin that
  answers `null` instead (`tests/cases/panics_io_exit`)

**`parallel-length`**: a `parallelMapInto` call whose `dst` is shorter than
its `src`

- *What proves it away:* nothing yet: the check is `std/threads.ts`'s own
  (`tests/link/panics_parallel_length`)

**`ffi-nul`**: a `string` argument to a [`declare function`](#calling-c) that
holds a NUL byte, which C would read as the end of the string:
`` `name`: argument N (param) holds a NUL byte, which C would read as the end of the string ``

- *What proves it away:* a literal with no NUL in it, which is not checked and
  not a site; every other string is checked, and `string | null` checks only
  the string (`tests/cases/panics_ffi_nul`)

**`ffi-null`**: a `string` result of a [`declare function`](#calling-c) that
is `NULL`:
`` `name` returned NULL for a `string` result; declare it `string | null` ``;
or the pointer of a [`readStruct`](#readstruct-a-struct-out-of-memory-c-owns)
call that is `NULL`: `` `readStruct` read a NULL pointer into a `Lconv` ``;
or the pointer of a
[`readCString`](#readcstring-a-string-out-of-a-buffer-c-owns) call that is
`NULL`: `` `readCString` read a NULL pointer ``

- *What proves it away:* nothing: a result declared `string | null` reads
  `NULL` as `null` and is not a site (`tests/cases/panics_ffi_null`); the
  `readStruct` and `readCString` tests stay at every call
  (`tests/cases/panics_ffi_read_struct_null`,
  `tests/cases/panics_ffi_read_cstring_null`)

**`ffi-length`**: a call to a
[`declare function`](#a-u8-parameter-a-buffer-and-its-count) whose count is
larger than a `u8[]` buffer of its run:
`` `name`: argument N (count) counts more bytes than argument M (buf) holds ``,
compared unsigned, so a count that wrapped below zero fails too

- *What proves it away:* a count of `toU64(b.length)` where `b` is that buffer
  itself, a `const` local or a parameter named alone, and no later argument
  may resize an array (`tests/cases/ffi_buffer_count_proved`,
  `ffi_buffer_late_load`); every other count is checked
  (`tests/cases/panics_ffi_length`, `panics_ffi_length_wrapped`,
  `panics_ffi_length_shrink`).

**`region`**: a call to `nish:region`'s `region`, `regionWith`, `enter`,
`enterWith` or `free`: a handle that is 0, freed, another thread's or entered
already, a `free` of an entered region, or more live regions than the table
holds

- *What proves it away:* nothing: the handle is a number the checker does not
  follow, so every call checks it (`tests/cases/reject_deny_panics_region`)

**`call`**: a call into a function that has a site that can panic, directly or
through further calls

- *What proves it away:* the callee having none (`tests/cases/panics_call`)

**`unchecked`**: `uncheckedGet` and `uncheckedSet` from `nish:unsafe`: no
check at all, so nothing panics, but an index out of range is undefined
behaviour (`readCString` and `readStruct` test their pointer for `NULL`, so
each is an `ffi-null` site above)

- *What proves it away:* nothing, and nothing needs to: the call is the
  author's word that the index is in range, not a
  proof, and the `nish:unsafe` import its module must write is the opt-in to
  that word, so it is listed with `"allowed": true` and, like `oom`, never
  makes a function one that may panic (`tests/cases/deny_panics_unsafe`)

**`oom`**: an arena allocation: the out-of-memory exit

- *What proves it away:* nothing, and nothing needs to: it is listed with
  `"allowed": true` and never makes a function one that may panic
  (`tests/cases/panics_oom`)

- **A `call` names its callee and the kind it reaches** (`"via"`), and is
  decided over the whole program, the standard library and dependencies
  included. The kind is the one the callee reaches first at run time, its own
  checks and its calls taken together: an operation checks its operands once
  they are evaluated, so `pick(xs, i) + 1`, `1 + pick(xs, i)`,
  `x += pick(xs, i)` and `100 / pick(xs, i)` reach `pick`'s `index` before
  their own `overflow` or `divide`, while `pick(xs, i - 1)` reaches its
  argument's `overflow` before the call (`tests/cases/panics_overflow_via`).
  In a cycle of calls made before any check, the cycle's first function in
  declaration order with a site of its own or a call out of the cycle passes
  over its calls back into it, and the rest of the cycle reaches what it
  reaches (`tests/cases/panics_call_cycle`). The list itself stays in source
  order, by where each site starts. A generic function's sites are its instantiations', each under its
  own symbol and decided over its own side tables
  (`tests/cases/panics_generic`).
- **Two ways a program can stop are not sites**, because no proof the checker
  makes could remove them. Out of memory is listed, as `oom`, but excluded: every
  allocation can fail and no guard in the source prevents it. Stack overflow is
  a fault the operating system raises, with no handler in the runtime and no
  check in the IR. Signed overflow is a site, `overflow`, because it is checked
  (see *Signed integer overflow is a checked panic* above). Neither are
  `process.exit(n)`, which is a deliberate exit, or a call into a `declare
  function`, whose body is C the compiler does not see.
- **The file is a contract**, like `--json`: one `{"functions":[...]}` object,
  one function per line in module and declaration order, each
  `{"name","symbol","module","line","panics"}`, where `symbol` is the
  function's LLVM name; per site `{"kind","line","column"}` and then
  `"proven"` for a check, `"proven","callee"` for `parallel-length`,
  `"callee","via"` for `call` and `"allowed": true` for `oom` and `unchecked`. Lines and
  columns are 1-based, in the units a diagnostic uses. The `wrote <file>` line
  is on stderr, like the IR's. It is written once the program is checked: a
  program that does not compile writes none, and `--emit-checked` writes it
  beside its dump. `--emit-ast`, which stops before the check, refuses it with
  a usage error (exit 2) rather than leaving the file unwritten, and so do
  `nish run`, which keeps its build to itself, and `--fix`, which writes no IR.

### The no-panic scope

A module can be **required** to have no panic site left. `--deny-panics` puts
every module of the program's own package in the scope; the root package's
`package.json` — the one nearest above the entry file — puts the modules it
lists there, by their path relative to that file:

```json
{ "nish": { "noPanic": ["src/parser.ts", "src/lexer.ts"] } }
```

Both together put the union in scope; with neither, nothing changes. In a
module of the scope, every site of a kind above that is not proven is an
error, NL2457, which names the kind and, where a proof the checker makes would
remove the check, the guard that gives it — the same sentence the performance
warnings use for an index (NL9007) and a range entry (NL9013), so one way of
writing each is taught (`tests/cases/reject_deny_panics_<kind>`, one per kind;
`tests/cases/deny_panics_clean` is the module that passes, and its IR has no
`nish_panic_` call and no panic tail). Where a refused site sits in a loop, the
performance warning about the same check is not printed beside the error.

- **A call out of the scope is refused at the call** (NL2458): the standard
  library and a dependency are not in the scope — their author, not this one,
  proves them — but a call from the scope into one of their functions that may
  panic names the callee and the site it reaches (`reject_deny_panics_call`,
  `tests/link/no_panic_transitive`). A call into a function that is itself in
  the scope is not refused again: its own sites are.
- **A module the list does not name keeps its checks**: the same unproven index
  is refused in a listed module and compiles in an unlisted one
  (`tests/link/no_panic_module`, `tests/link/no_panic_unlisted`).
- **An entry that names no module of the program is an error** (NL3031),
  reported in `package.json` where the entry is written: a typo would
  otherwise leave the module it meant outside the scope without a word
  (`tests/link/no_panic_unknown_entry`).
- **The root package's `"nish"` field is one object, written once, whose
  keys are `noPanic`, `capabilities`, `host`, `compat` and `netRings`, each written once**, and anything
  else is an error (NL3036) where `package.json` writes it: a second `"nish"`
  even when neither holds a policy (`caps_policy_manifest_repeated_nish_no_panic`),
  a `"nish"` that is not an object (`caps_policy_manifest_nish_not_object`), a
  key it does not know, a misspelt `capabilites` included
  (`caps_policy_manifest_nish_unknown_key`), a `noPanic` that is not an array
  (`caps_policy_manifest_no_panic_not_array`), and a manifest that mentions
  `nish` or carries a `\u` escape and stops being JSON
  (`caps_policy_manifest_broken_json`). Each would otherwise leave part of
  what the package says about itself unread. A key is decoded as `JSON.parse`
  decodes it, so `"ni\u0073h"` is `"nish"`; an escape outside ASCII decodes
  to a byte no name contains, so it never matches one.
- **A `nish:unsafe` import is the opt-in.** `uncheckedGet` and `uncheckedSet`
  are reached only through `import { … } from "nish:unsafe"` at the top of the
  module that calls them, which is the module's word, visible where a reader
  looks first, that its indexes are in range. So the scope allows them, as
  `unchecked` sites with `"allowed": true`, and a call into a function whose
  only unproven sites are `unchecked` is not a `call` site at all, from inside
  the scope or out of it (`tests/cases/deny_panics_unsafe`,
  `tests/link/no_panic_unsafe_callee`). The global spelling `tsc` accepts has
  no import to show and is refused, scope or not (NL2456,
  `reject_deny_panics_unsafe_no_import`).
- **Signed overflow is refused where it is not proven.** Every signed `+`, `-`,
  `*`, unary `-`, `++`, `--` and `op=` the bounds walk has not proven to fit is
  an `overflow` site, refused like an index or a divisor, with a hint to bound
  its operands, compute in `u32`/`u64` (the width's unsigned type), or write
  the operator's drop-in `nish:unsafe` form: `wrappingAdd(x, y)`,
  `wrappingSub(x, y)`, `wrappingMul(x, y)`, `x = wrappingAdd(x, y)` for an
  `op=`, `wrappingSub(0, x)` for a negation and `x = wrappingAdd(x, 1)` or
  `x = wrappingSub(x, 1)` for `++` and `--`. A proven one is accepted, and so is
  every `wrapping*` call, which is defined to wrap and is not a site
  (`tests/cases/reject_deny_panics_overflow`, `tests/cases/reject_deny_panics_overflow_ops`, `tests/cases/deny_panics_overflow_proven`,
  `tests/cases/deny_panics_overflow_wrapping_add`,
  `tests/link/no_panic_overflow`).
- **What the scope does not cover.** Out of memory is listed but never
  refused: every allocation can fail and no guard prevents it. Stack overflow
  is a fault the operating system raises, with no check in the IR to refuse.
  So a module in the scope cannot *panic* except by running out of memory,
  and that is the whole claim. Nor can it reach undefined behaviour through a
  check the compiler left out, except where a `nish:unsafe` import says so.
- `--deny-panics` changes no byte of the IR: a program it accepts is the one the
  build compiles without it. With `--emit-ast`, which stops before the checker,
  it is a usage error (exit 2).

### The compatibility dialect

Nish has two dialects. The strict one is this document. The compatibility
dialect accepts more of TypeScript, feature by feature: it differs from the
strict dialect in the number a bare `number` is, and in what each feature it
allows admits. This compiler has built six features, `nullish`,
`optional-chaining`, `string-switch`, `for-of-string`, `optional-params` and
`overloads`.

- **`--compat` selects the dialect with every feature this compiler has
  built; `--compat=<feature>,...` selects it with only the features named.**
  A name that is no feature is a usage error (exit 2) that names it and
  writes no IR, and so is an empty list (`--compat=`). `nish run` and `--fix`
  take the flag too.
- **`"compat"` in the root package's `"nish"` field selects it without the
  flag**: `true` for every built feature, or an array of feature names for
  exactly those (`[]` for the dialect with no feature). The root package is
  the one whose `package.json` is nearest above the entry module. A value that
  is neither is NL3036 (`tests/link/compat_manifest_not_a_list`), and a name
  in the array that is no feature is NL3056, where `package.json` writes it
  (`compat_manifest_unknown_feature`). `--compat` on the command line decides
  the dialect alone when it is given: the manifest's list is still checked,
  and not otherwise consulted.
- **The root package's dialect is the program's ceiling.** Every module of a
  program is compiled in one dialect, the root's. A dependency whose own
  `package.json` asks for the compatibility dialect is refused under a strict
  root (NL3057, at the import that brings it in,
  `tests/link/compat_ceiling_dialect`), and one that lists a feature the
  root's dialect does not have is refused the same way
  (`compat_ceiling_feature`). A dependency that asks for no more than the root
  allows compiles (`compat_manifest_program`), and so does the first under a
  build that passes `--compat`. A dependency's `"nish"` field is read for this
  key alone.
- **The dialect implies `--number-mode f64`**: a bare `number` is the double,
  as a JavaScript engine computes it, and every rule of
  `--number-mode f64` applies unchanged — its diagnostics
  included, so a `main` that returns a bare `number` is refused with NL2140
  under `--compat` exactly as it is under `--number-mode f64`. A
  `--number-mode` on the command line wins, on either side of `--compat`.
  `--number-mode i32` beside the dialect is honoured and priced: one
  `performance` warning, NL9020, at the entry module's first character,
  because arithmetic that leaves 32 bits panics there where the double would
  carry on (`tests/cases/perf_compat_number_i32`). `--no-warn-performance`
  silences it, as it does the rest of its class.
- **Every module of a compat build says so.** Its IR ends with the named
  metadata `!nish.compat`, one node whose first operand is the number mode
  (`!"f64"` or `!"i32"`) and whose others are the allowed features in the
  compiler's order:

  ```llvm
  !nish.compat = !{!0}
  !0 = !{!"f64", !"nullish", !"optional-chaining", !"string-switch", !"for-of-string", !"optional-params", !"overloads"}
  ```

  A strict build carries no `!nish.compat`. `--emit-checked` opens with the
  same facts on one line, `compat number=f64 features=[nullish,optional-chaining,string-switch,for-of-string,optional-params,overloads]`, and prints no such
  line for a strict build.
- **A strict refusal of a construct a feature admits names the feature.** It
  closes with the note ``add `<feature>` to `nish.compat` in package.json to
  accept it``, and under a compat build whose list leaves the feature out it
  also names that build's dialect (`this program's dialect is
  `compat=<list>``).
- **`optional-chaining` admits a `?.` chain with no `??` default** where the
  strict dialect has none to give it. A chain that is a statement of its own,
  `a?.b`, `a?.m()` or `a?.b.m(x)`, runs to its end when every link is there
  and does nothing from the first one that is `null` or `undefined`, as in
  Node: the arguments of a call it skips are not evaluated
  (`tests/cases/compat_optional_chain_statement`, refused in the strict
  dialect as `reject_optional_chain_statement`), so an enum value one of them
  assigns is, after the call, one the variable may or may not hold, as
  `?:` has it (`tests/link/compat_optional_skipped_enum`). `?.[i]` is admitted inside a
  chain that a member, a method call or a `??` default follows: the element is
  read, and bounds-checked, only when the array is there
  (`compat_optional_chain_element`, strict `reject_optional_chain_element_inner`).
  An index read inside a link the chain skips is not counted as checked for
  the reads after it. Two forms stay refused in the compatibility dialect
  too, because Node's answer and the build's would part. An element read the
  chain carries on past is NL1067, since past the end of the array Node
  answers `undefined` and goes on where the bounds check panics: in a `??`
  chain or a statement chain, a `?.[i]` that ends it
  (`tests/link/compat_optional_element_last`); and in a statement chain any
  element read that ends it, `a?.xs[i];`
  (`tests/link/compat_optional_element_statement`), or an element read,
  plain or `?.`, that a `?.` link tests, `xs[i]?.m();`
  (`tests/link/compat_optional_element_before`). In a `??` chain a plain
  element read a `?.` tests, `xs[i]?.m() ?? d`, is the strict dialect's own
  and keeps its meaning in both: the `?.` tests a nullable element, and the
  read is bounds-checked as every element read is. A
  `?.[i]` that ends a chain in any other place, `const x = xs?.[0]`, is the
  `?.` refusal of a chain with no default, NL1049. And an optional call
  `f?.()` is NL1068 (`compat_optional_call`).
- **`nullish` admits a `??` whose left operand is never missing**: a value
  whose type is not nullable, or a nullable one narrowed past `null` (the
  strict dialect refuses both, as a default with nothing to replace), when the
  left operand is one of the forms JavaScript can be seen not to answer
  `undefined` for: a literal (number, string, `true`, `false`, template, array
  or object), a name, `this`, a `new`, a unary or binary operation, or a
  plain member read of one of these, in parentheses or not. Any other left
  operand keeps the strict refusal in the same words whatever its type: a
  call, `f(x) ?? 1`, and a ternary, `(c ? a : b) ?? d`, are not on the list
  yet (`tests/link/compat_nullish_call_left`), nor is an element read, below. Node's
  answer is always the left operand, so the build keeps the left operand alone
  and says so: one `performance` warning, NL9021, at the `??`, naming the
  default to drop (`tests/cases/compat_nullish_never_missing`,
  `compat_nullish_narrowed`; strict `reject_nullish`,
  `reject_nullish_nullable`). The default is never run, but it is still
  checked as the left operand's type, as TypeScript checks it (NL2370,
  `tests/link/compat_nullish_never_missing`). A `??` on a nullable left
  operand is the strict dialect's own and unchanged. An element read is not
  never missing, whatever its element type: past the end of the array Node
  reads `undefined` and answers the default, where the bounds check panics,
  so `xs[i] ?? d` keeps strict's refusal in the same words, naming no feature
  (`reject_nullish_element_never_missing`).
- **`string-switch` admits a `switch` whose discriminant is a `string`**
  (`tests/cases/compat_string_switch`, strict `reject_switch_string`). Each
  `case` label is a string literal, a template with no substitution, or a
  module constant of type `string`, parenthesised or not, because a label is compared without being
  run; any other label is NL2799
  (`tests/link/compat_string_switch_label_not_constant`), a label of another
  type is the strict `` `case` label is f64 but the discriminant is string ``
  (`compat_string_switch_label_type`), and two labels with the same text, a
  constant's included, are `` Duplicate `case` label `` as in an integer
  switch (`compat_string_switch_duplicate`): the text is what the label
  spells once its escapes are read, so `"\u00e9"` and `"é"`, or a template
  and the literal it spells, are the same label
  (`compat_string_switch_duplicate_spelling`,
  `compat_string_switch_duplicate_template`). Fallthrough, into and out of a
  `default` in any place, an empty case group, `return` from a case, `break`
  and a labelled `break` out of an enclosing loop, and `continue` of an
  enclosing loop mean what they mean in Node, and the discriminant is run
  once, before the first comparison (`tests/cases/compat_string_switch_flow`).
  A nullable discriminant, `string | null`, is no `string` and keeps the
  strict refusal, naming no feature. The switch compares the discriminant with each label in
  source order, one `nish_str_eq` call each, and jumps to the first that
  matches, or to `default`: a chain, not a tree bucketed by length, because
  `nish_str_eq` already answers on a length mismatch before it reads a byte.
- **`for-of-string` admits `for (const c of s)` over a `string`**
  (`tests/cases/compat_for_of_string`, strict `reject_arr_forof_non_array`).
  Each pass binds `c` to the next code point, as Node walks a string: a
  character outside the Basic Multilingual Plane is one pass, not two. `c` is
  a new `string` holding that code point's UTF-8 bytes. `break`, `continue`
  and labels work as they do over an array. A destructuring head,
  `for (const [a] of s)`, keeps the array walk's refusal
  (`tests/link/compat_for_of_string_destructure`), and so does a nullable
  iterable, `string | null`, naming no feature. A string that is not valid
  UTF-8 (`String.fromCharCode(200)`, `String.fromBytes`) is walked a lead
  byte at a time: a pass takes the lead and only the continuation bytes
  (`10xxxxxx`) after it, up to the width the lead names, so a lead with none
  is a pass of one byte and the byte after it starts the next pass, a stray
  continuation byte is a pass alone, and a sequence cut short by the end is
  one pass of what is left. The number of passes is then Node's for the same
  characters (`tests/cases/compat_for_of_string_invalid`), though `c`'s bytes
  are nish's, not Node's UTF-16. `c` is fresh each pass, and the walk opens
  no arena pass of its own: each `c` stays until the scope around the loop
  releases its arena, so a code point kept past the loop, in a variable or
  returned, is still there (`tests/cases/compat_for_of_string_fresh`), and a
  walk of `n` code points holds `n` small strings until then.
- **`optional-params` admits an `x?: T` parameter and a default that is not
  a constant** (`tests/cases/compat_optional_params`, strict
  `reject_param_default_expression`, `reject_param_default_array`,
  `reject_param_default_object`). An `x?: T` parameter of a function, an
  arrow or a method is `T | null` inside, and a call may leave it out. It is
  read only as the left operand of `??`, parenthesised or not, because a call
  that leaves it out passes `undefined` in Node and `null` here, and
  `x ?? <default>` is the one read that gives both the same value; any other
  read is NL2803 (`tests/link/compat_optional_params_read`,
  `compat_optional_params_read_paren`). An `x?` whose `T` has no `null`, a
  bare `number` or a `boolean`, is NL2804
  (`compat_optional_params_value`): give it a default instead. A default of a
  top-level function, an arrow `const` included, that is not one the strict
  dialect accepts as a constant, a call, an array, an object or an
  arithmetic on earlier parameters, runs in the callee, once per call that
  leaves its argument out, after the arguments and left to right, as Node
  runs it: a call that writes the argument does not run it. The build gives
  the function one wrapper per argument count a call may stop at, and each
  call goes to the wrapper for the count it writes. Only a function every
  call to which the module sees and routes takes wrappers: an exported
  function (`compat_optional_params_exported`), whose callers in another
  module would pass the default themselves, an overloaded one
  (`compat_optional_params_overloaded`), whose signatures name the
  implementation, and one with a required parameter between two such
  defaults (`compat_optional_params_required_between`) keep the strict
  refusal, with a note that names the rule. So do a method's or a
  constructor's default, and a function whose earlier parameter is an `x?`.
  `--emit-ts` writes no wrapper: the TypeScript keeps each default where it
  was written. Without the feature, the refusal of such a
  default names it (`compat_optional_params_default_feature`), and an
  `x?` stays refused as before (`compat_optional_params_feature`).
- **`overloads` admits overload signatures**: a function, a method or a
  constructor written as bodiless signatures of one name followed by its
  implementation (`tests/cases/compat_overloads`; strict, the signatures are
  `Functions must have a body`, `tests/link/compat_overloads_feature`). The
  signatures are checked and then dropped, so the build is the
  implementation's alone. Each signature is held to the implementation, as
  `tsc` holds it: it takes no rest parameter, every argument list it takes
  the implementation takes too, each parameter type is one the
  implementation's takes, and it writes the return type, which is the
  implementation's exactly, which is stricter than `tsc`, where a return
  type the implementation's is assignable to will do; otherwise NL2800
  (`compat_overloads_incompatible`, `compat_overloads_return`). A call the
  implementation accepts is then held
  to the signatures: one that no signature takes is NL2801, because the
  implementation's own signature is not one a caller may call
  (`compat_overloads_no_match`, `compat_overloads_method_no_match`,
  `compat_overloads_constructor_no_match`). Only a call that names the
  function, the method or the class is held to the signatures: a call
  through a function value is held to the implementation alone. A
  function with signatures is refused by `--emit-header`, `--emit-napi` and
  `--emit-dts`, NL2802, since the file would spell only the implementation
  (`compat_overloads_emit_header`, `compat_overloads_emit_dts`). A generic function or class keeps the
  strict refusal.
- **The dialect only adds.** A strict build of a program the strict dialect
  accepts is unchanged by all of the above, byte for byte; what changed for a
  program it refuses is the refusal's words. A compat build is `--number-mode f64` for every program the
  strict dialect accepts: the same IR but for the mark, the same refusals in
  the same words. And under one number mode a compat build and a strict build
  of such a program differ in the mark alone. `tests/compat-erasure.js` checks
  both over every program in `tests/cases`. A feature may accept a program the
  strict dialect refuses, and that runner compiles each such case with the
  feature, links it and runs it beside Node, which must print and exit the
  same; it may never change the answer for a program the strict dialect
  accepts.

### Retention as an error

A program that runs for a long time, a server above all, cannot afford memory
that stays allocated after nothing can reach it: in a command-line tool it is
returned when `main` does, and in a server it grows until the process is
killed. Six performance warnings are exactly that finding, and
**`--deny-retention`** makes each of them an error (NL2462) in the program's own
modules:

| Warning | What stays allocated |
| --- | --- |
| NL9002, quadratic string building | every intermediate string of `s = s + t` in a loop |
| NL9003, an allocation dropped by an assignment | the value the local held |
| NL9011, a loop that leaves a callee's memory behind | what the callee left on every pass |
| NL9016, an allocation dropped on every pass | the value each pass replaced |
| NL9018, a pass of an unbounded loop that keeps what it allocates | the temporary each pass built, for as long as the loop runs |
| NL9019, a function that keeps memory on every call | what each call a loop makes keeps |

- **The error keeps the warning.** Its text is the warning's, after the code of
  the rule that found it, so it names the same rewrite:
  `` `--deny-retention` refuses this NL9016 finding, because the arena memory it describes stays allocated after nothing in the program can reach it any more: `last` is given a new allocation on every pass of this loop … ``
  (`tests/cases/reject_deny_retention_pass_drop`, `reject_deny_retention_drop`,
  `reject_deny_retention_loop`, `reject_deny_retention_concat`,
  `reject_deny_retention_unbounded_pass`, `reject_deny_retention_kept`, and for
  a `Result` assigned over another, `reject_deny_retention_result_drop` and
  `reject_deny_retention_result_reassign`). The warning it
  restates is not printed as well, and `--no-warn-performance` does not
  silence the error.
- **The program's own modules only.** A module of the root package is held to
  it; a dependency's warnings stay warnings, as its panic sites stay outside
  the [no-panic scope](#the-no-panic-scope), because the program's author
  cannot change that code (`tests/link/deny_retention_dependency`).
- **What it does not promise.** The five warnings are conservative in the
  direction of silence: each fires only where the compiler can name the memory
  and the rewrite, so a program it accepts can still retain memory in a shape
  no rule recognises ([wp6-memory.md](wp6-memory.md), "Left out"). Nor does it
  cover memory a program keeps on purpose: an array it pushes onto for its
  whole run is reachable, and so not retention.
- `--deny-retention` changes no byte of the IR: a program it accepts is the one
  the build compiles without it (`tests/cases/deny_retention_clean`). `nish run`
  and `--fix` accept it; with `--emit-ast`, which stops before the checker, it
  is a usage error (exit 2).

### Arena placement

**`--emit-arena <file.json>`** writes where the memory of every allocation site
goes: the decisions the [memory model](#memory-model) made, read back in the
order the emitter applies them, so the file and the IR cannot disagree. It is
the audit for the cases no warning names: a site a rule stays silent about is
still in the file, with its placement.

The file is one JSON object, one function per line, in module order and, in
each module, in declaration order followed by the instantiations of its
generic functions, and its sites in source order. The keys and their order are
a contract, like `--emit-panics`':

```
{"functions":[
{"name":"main","symbol":"nish_main","module":"tests/cases/arena_placement.ts","line":32,"sites":[{"kind":"new","line":34,"column":13,"placement":"stack"},…,{"kind":"string","line":52,"column":12,"placement":"function","accumulates":true}]}
]}
```

Per function `{"name","symbol","module","line","sites"}`, as `--emit-panics`
writes them, and a generic function once per instantiation. Per site
`{"kind","line","column","placement"}`, then `"callee"` for a `call` and a
`builtin`, then `"accumulates":true` where it applies. A site's **kind** is
`new`, `object`, `array`, `string` (a concatenation or a template), `push`,
`print` (a number `console.log` formats), `builtin` (a runtime function that
allocates, such as `join`) or `call` (a user function whose memory the result
is). Its **placement** is the first of these that holds:

| Placement | Where the memory goes |
| --- | --- |
| `stack` | an entry-block `alloca`, reused on every pass of a loop |
| `pass` | released at the end of each pass of the innermost scoped loop around it |
| `block` | released when the block of the `using a = arena()` before it ends |
| `function` | released when the function returns: its arena scope |
| `returned` | handed to the caller with the return value, whose placement decides |
| `caller` | released when the function returns, by every caller's reclaim of the returned string |
| `kept` | stored into memory older than the function, and as long-lived as it |
| `unscoped` | released by nothing in this function: it lives as long as the caller's memory, which in `main` is the rest of the run |

**`accumulates`** marks a site that runs on every pass of a loop that releases
nothing per pass — or in that loop's condition or update, which run outside
the bracket a pass takes — and whose memory is unreachable before its
release: `pass`, `block`, `function`, `caller` or `unscoped`. Its memory piles up pass
after pass until then. `` last = `item ${i}` `` in a loop over ten million
passes is a `function` site that accumulates in a `main` that earns a scope
through its callees, and an `unscoped` one in a function that has none
(`tests/cases/arena_placement`, `arena_placement_loops`). A `returned` or `kept`
site is memory the program holds on purpose, so it is never marked.
An `unscoped` site in another function is marked too when that function is
reached from such a pass and leaves the site behind in it, by NL9018's rule for
callees: what the function leaves in its caller's memory piles up in the loop's.

- **The answer is about the site's own function.** A scope in a caller can
  still release an `unscoped` site's memory: a loop whose pass is scoped takes
  back what its callees leave behind. Only in `main` is `unscoped` the end of
  the run.
- `--emit-arena` changes no byte of the IR, and it is a product, as
  `--emit-panics` is: `nish run` and `--fix` refuse it, and so does
  `--emit-ast`, which stops before the facts exist (exit 2).

### Explaining kept memory

**`--explain-memory`** answers, before the program is deployed, the question a
memory budget turns on: which loops hand back what each pass allocated, and
which do not. The [memory model](#memory-model) gives a pass of a loop, and a
function, an arena scope of its own when it can prove what they allocated is
unreachable at the end; one stored allocation, in the loop or in any callee,
refuses the scope, and the memory the pass allocated then stays until the next
bracket out. The warnings name such a refusal only where they can also name a
rewrite; this report names every one, on stderr, after the warnings (an
excerpt of `tests/cases/explain_memory`):

```
tests/cases/explain_memory.ts:21:1: memory: `remember` keeps what it allocates until the memory of its caller is released, because the allocation on line 22 is stored into memory, where this analysis stops following it
tests/cases/explain_memory.ts:43:20: memory: this loop's condition allocates on every pass, outside the scope a pass takes, and keeps it until `extra` returns
tests/cases/explain_memory.ts:43:40: memory: this loop's update allocates on every pass, outside the scope a pass takes, and keeps it until `extra` returns
tests/cases/explain_memory.ts:60:3: memory: this loop keeps what each pass allocates until `main` returns, because line 61 keeps what the pass allocated in `last`, which is declared outside the loop
tests/cases/explain_memory.ts:76:10: memory: this loop's condition allocates on every pass, outside the scope a pass takes, and keeps it until `main` returns
explain-memory: 7 of 9 allocating loops keep what a pass allocates past the pass; 1 of 4 allocating functions with a scalar result keep what they allocate past the call
```

- **A loop** is listed when its passes allocate — themselves, or through a
  callee that leaves memory behind — and no scope releases it at the end of
  each pass. The line says where it does go back: at the end of the pass of the
  scoped loop around it, at the end of the `using a = arena()` block around it,
  when the function returns, or, in a function with no scope, when its caller's
  memory is (in `main`, never: "for the rest of the run"). The reason is the
  first refusal the analysis met, the one NL9011 names. A loop whose every
  allocation goes back with a `using a = arena()` block or a scoped loop
  inside its body keeps nothing past the pass and is not listed. A condition or `for` update that allocates is
  listed on its own line — both, when both do — because it runs outside the
  bracket a pass takes whether or not the body has one; a `do...while`
  condition's line follows the lines of the loops in its body.
- **A listed loop with no bound** — one that is not bounded, by NL9018's rule — is
  the loop NL9018 warns about when what its pass keeps is a temporary the
  pass drops, or one a function it calls leaves behind; the report lists it
  either way.
- **A function** is listed when it answers a number, a `boolean`, an enum or
  nothing, leaves memory behind, and has no scope of its own. A function that
  answers memory (a string, an array, an object) is not, nor is a constructor,
  which answers the object it builds: what it allocates goes to its caller with
  the result, and whether the caller gives it back is the
  caller's line.
- **The summary** counts the loops whose passes allocate and the functions that
  answer no memory and allocate, and how many of each keep it. A budget in CI
  can hold that count, or the listed lines, against a golden, as
  `tests/run.js` does with a case's `<name>.memory`
  (`tests/cases/explain_memory`).
- **The program's own modules only**, as `--deny-retention` judges them. A
  generic function, or one that takes a function parameter, is explained once
  per instantiation, under its instantiated name (`` `each<twice>` ``), after
  the functions declared outright (`tests/cases/explain_memory_calls`).
- **A callee the analysis cannot see counts as allocating.** In a function
  that allocates, a loop with no scope that calls one is listed, since nothing
  proves its passes leave no memory behind. A function that allocates nothing
  the analysis can see is not examined.
- **A callee's leak is its caller's.** A function whose kept allocation is a
  call names that callee. One whose own allocation is held where the analysis
  does not prove it dead names that first, whatever its callees do. One that
  keeps memory only because a function down its calls holds an allocation the
  analysis does not prove dead names that function, the one the doubt starts
  in, even when that function's own scope gives its memory back: the doubt
  passes up every call.
- **A function is judged by what it still holds when it returns.** One with
  no scope of its own keeps nothing when every allocation it leaves is inside
  a scoped pass or a `using a = arena()` block, so it is counted and not
  listed; one that is listed names the line of the first allocation it holds.
- **Under `--no-elision`** no automatic scope is taken, so every allocating
  loop and function is listed except the passes and blocks the program
  brackets itself with `using a = arena()`.
- **What it does not promise.** It reports the scopes the compiler takes, not
  the bytes: a listed loop over three passes costs nothing, and memory the
  program keeps on purpose — an array it pushes onto for its whole run — is
  listed with the line that keeps it. It does not measure memory at run time.
- `--explain-memory` changes no byte of the IR. `nish run` accepts it. A build
  refused after the analysis has run (by `--deny-retention`, or a check that
  follows it) still prints the report after the errors, since it says why each
  refused loop keeps its memory; one refused earlier prints none. With
  `--emit-ast`, which stops before the facts exist, with `--json`, whose
  stderr is diagnostic objects only, and with `--fix`, which compiles nothing,
  it is a usage error (exit 2).

## Forbidden constructs (Phase 0 validator)

`src/validator.ts` walks the whole syntax tree before the checker and rejects
everything below on the first hit, regardless of where it appears (even in
dead code or nested type arguments). Each row gives the exact message
fragment `tests/run.js` matches and the case that proves it.

### Types

| Construct | Message | Test |
| --- | --- | --- |
| `any` anywhere, including nested type arguments | `` `any` is forbidden in Nish `` | `reject_any_param`, `reject_any_nested` |
| `unknown` | `` `unknown` is forbidden in Nish `` | `reject_unknown_param`, `reject_unknown_nested` |
| `symbol` type | `` `symbol` type is forbidden in Nish (no symbol type) `` | `reject_symbol_type` |
| `bigint` type | `` `bigint` type is forbidden in Nish (use number, i32, or f64) `` | `reject_bigint_type` |
| `undefined` type | `` `undefined` is forbidden in Nish; use `null` with a `T \| null` type `` | `reject_union_undefined` (via the union rule) |
| union types other than `T \| null` / `null \| T` and [discriminated unions](#discriminated-unions) | `` Union types other than `T \| null` are forbidden in Nish (values have one fixed layout) `` | `reject_union_type`, `reject_union_undefined`, `reject_union_untagged_scalar` |
| `Function`, `Symbol`, `Proxy` as type names | `` `Function` type is forbidden in Nish (no dynamic function values) `` (and analogous) | `reject_function_type` |
| `import("x").T` | `` Dynamic `import()` is forbidden in Nish (modules are resolved at compile time) `` | `reject_dynamic_import` |
| `x as any`, `<any>x` | `` Type assertion to `any` is forbidden in Nish `` | `reject_as_any`, `reject_as_any_angle` |
| `x as unknown`, `<unknown>x` | `` Type assertion to `unknown` is forbidden in Nish `` | `reject_as_unknown` |

### Declarations

- **type parameters on a type alias**:
  `` Generic type parameters are forbidden on a type alias in Nish; a generic function, class or interface is monomorphised, and an alias only renames a type that already exists ``
  (`reject_type_alias_generic`)
- **type parameters on a constructor**:
  `` a constructor cannot have type parameters: it takes its class's, which are written after `new` (`new Box<i32>(v)`) ``
  (a syntax error; a *method* may declare its own, see [Generic
  methods](#generic-methods)) (`reject_generic_method_constructor`)
- **a generic class or interface named without its type arguments**:
  `` `Holder` is generic: it must be written with its type arguments, e.g. `Holder<number>` ``
  (`reject_generic_class`)
- **type *arguments* on `new` of a class that is not generic**:
  `` `Point` is not generic, so `new Point` takes no type arguments ``
  (`reject_cls_new_generic`)
- **generators (`function*`, `*m()`)**:
  `` Generators are forbidden in Nish (no coroutine runtime) ``
  (`reject_generator`, `reject_generator_method`)
- **an `async` method, field or constructor ([Async
  functions](#async-functions-async-and-await) has the rest)**:
  `` Only a top-level function or an arrow may be `async` `` (NL1063)
  (`reject_async_method`)
- **`var`**: `` `var` is forbidden; use `let` or `const` ``
  (`reject_var_keyword`, `reject_var_in_for`)
- **enum members that are neither all numeric nor all string literals**:
  `` Enum members must be numeric literals in Nish, or every member a string literal (an enum lowers to a plain integer, and one numbering cannot mix with strings) ``
  (NL1043, `reject_enum_string_mixed`, `reject_enum_computed`; the numeric
  and the [string](#string-enums) forms compile ([Enums](#enums)))
- **`namespace` / `module` blocks, `declare module "m"`**:
  `` `namespace` and `module` blocks are forbidden in Nish (use ES module files) ``
  (`reject_namespace`, `reject_module_declared`)
- **`declare global`**:
  `` `declare global` is forbidden in Nish (no global object to augment) ``
  (`reject_declare_global`)
- **decorators, on a class, a member or a parameter**:
  `` Decorators are forbidden in Nish (no runtime metadata or class rewriting) ``
  (`reject_decorator`, `reject_decorator_member`, `reject_decl_shapes`)
- **computed property names, in an object literal (`{ [k]: 1 }`,
  `{ [k]() { } }`), a class (`[k]: i32`, `[Symbol.iterator]() { }`) or an
  interface (`[k]: i32`)**:
  `Computed property names are forbidden in Nish (member names are fixed at compile time)`
  (NL1041, Phase 0; before a method in an object literal is refused)
  (`reject_computed_property`, `reject_computed_method`,
  `reject_cls_computed_field`, `reject_cls_computed_method`,
  `reject_iface_computed_member`)

### Imports

| Construct | Message | Test |
| --- | --- | --- |
| import attributes, `with { type: "json" }` or `assert { ... }` | `` Import attributes (`with { ... }`) are forbidden in Nish (an import names source this compiler reads, never a resource loaded at run time) `` | `reject_import_attributes`, `nl1057_import_attributes` |
| a module export name written as a string, `import { "a-b" as b }` | `` A module export name written as a string is forbidden in Nish (an export is a declaration, and a declaration has a name; import it by that name) `` | `reject_import_string_name`, `nl1058_string_export_name` |
| `import defer` | `` `import defer` is forbidden in Nish (a module has no top-level code, so there is nothing to defer) `` | `reject_import_defer`, `nl1059_import_defer` |

### Statements

- **`with`**: `` `with` is forbidden in Nish (no dynamic scope) ``
  (`reject_with_statement`)
- **`try` / `catch` / `finally`**:
  `` `try`/`catch`/`finally` is forbidden in Nish (no unwinding; use `Result<T, E>`) ``
  (`reject_try_catch`)
- **`throw`**:
  `` `throw` is forbidden in Nish (it aborts rather than unwinding): return a `Result<T, E>` for a failure a caller should handle, or `panic(message)` to end the process ``
  (`reject_throw`)
- **`debugger`**: `` `debugger` is forbidden in Nish (no debugger hook) ``
  (`reject_debugger`)
- **a label on another statement**:
  `` Labeled statements are forbidden in Nish except on a loop, a block or a `switch` ``
  (`reject_label_if`)
- **`for...in`**:
  `` `for...in` is forbidden in Nish (it enumerates property names, and object layout is fixed at compile time); use `for...of` ``
  (`reject_for_in`, `reject_map_iter_for_in`)

### Expressions

| Construct | Message | Test |
| --- | --- | --- |
| `eval(...)`, `eval` as a value | `` `eval` is forbidden in Nish (no interpreter at runtime) `` | `reject_eval` |
| `Function(...)` | `` `Function` constructor is forbidden in Nish (no interpreter at runtime) `` | (validator; no case) |
| `new Function(...)` | `` `new Function` is forbidden in Nish (no interpreter at runtime) `` | `reject_new_function` |
| `Function` as a value | `` `Function` is forbidden in Nish (no interpreter at runtime) `` | (validator; no case) |
| `new Proxy(...)` | `` `new Proxy` is forbidden in Nish (no dynamic property interception) `` | `reject_proxy` |
| `Proxy` as a value | `` `Proxy` is forbidden in Nish (no dynamic property interception) `` | (validator; no case) |
| `Reflect` | `` `Reflect` is forbidden in Nish (no runtime reflection) `` | `reject_reflect` |
| `Symbol(...)`, `Symbol` as a value | `` `Symbol` is forbidden in Nish (no symbol type) `` | `reject_symbol_value` |
| `globalThis` | `` `globalThis` is forbidden in Nish (no global object) `` | `reject_globalthis` |
| `arguments` | `` `arguments` is forbidden in Nish (functions have fixed arity) `` | `reject_arguments` |
| `undefined` as a value, except compared with a `Map.get` result ([`Map` and `Set`](#map-and-set)) | `` `undefined` is forbidden in Nish; use `null` with a `T \| null` type `` | `reject_undefined_value`, `reject_map_get_undefined_compare` |
| `void expr` | `` `void` expressions are forbidden in Nish (no `undefined` value) `` | `reject_void_expression` |
| `==`, `!=` | `Loose equality is forbidden; use === / !==` | `reject_loose_equality`, `reject_loose_inequality` |
| `in` | `` `in` operator is forbidden in Nish (no dynamic property lookup) `` | `reject_in_operator`, `reject_in_newline` |
| `a?.[i]` inside a chain ([the compatibility dialect](#the-compatibility-dialect) admits it) | `` Optional chaining `?.` is forbidden in Nish (narrow with `!== null` instead) `` | `reject_optional_chain_element_inner` |
| `a?.[i]` ending a chain, `f?.()` (in both dialects) | `` An element read cannot end a `?.` chain or be what a `?.` tests: past the end of the array JavaScript answers `undefined` and carries on, and the bounds check panics (test the index against `length`, or narrow the array with `!== null` and read the element into a `const`) ``; `` An optional call `f?.()` is not supported, with or without `--compat`: call `f()` directly, or narrow `f` with `!== null` first `` | `reject_optional_chain_element`, `reject_optional_call` |
| `a?.b` outside a chain that is the left operand of `??` ([Nullable types](#nullable-types); [the compatibility dialect](#the-compatibility-dialect) admits a chain that is a statement) | `` `?.` is allowed only in a chain that ends in `??`, whose default stands in when a link is `null`: write `a?.b ?? d`, or narrow with `!== null` `` | `reject_optional_chain`, `reject_optional_chain_paren`, `reject_optional_chain_argument` |
| `a ?? b`, unless `a` is a `T \| null` ([Nullable types](#nullable-types)) or a `Map.get` result ([`Map` and `Set`](#map-and-set)); [the compatibility dialect](#the-compatibility-dialect) admits it | `` Nullish coalescing `??` is forbidden in Nish (narrow with `!== null` instead) `` | `reject_nullish` |
| `instanceof` | `` `instanceof` is forbidden in Nish (no prototype chain) `` | `reject_instanceof` |
| comma expressions | `Comma expressions are forbidden in Nish (write separate statements)` | `reject_comma_expression` |
| `typeof x` | `` `typeof` is forbidden in Nish (no runtime type tags) `` | `reject_typeof_operator` |
| `delete x.y` | `` `delete` is forbidden in Nish (object layout is fixed) `` | `reject_delete` |
| `yield` | `` `yield` is forbidden in Nish (no coroutine runtime) `` | `reject_yield` |
| regex literals | `Regular expression literals are forbidden in Nish (no regex engine in the runtime)` | `reject_regex`, `reject_regex_class` |
| `bigint` literals (`10n`) | `` `bigint` literals are forbidden in Nish (use number, i32, or f64) `` | `reject_bigint_literal` |
| `{ __proto__: x }` | `` `__proto__` is forbidden in Nish (no prototype chain) `` | `reject_proto_literal` |
| `x.__proto__` | `` `__proto__` access is forbidden in Nish (no prototype chain) `` | `reject_proto_access` |
| `x.prototype` | `` `.prototype` access is forbidden in Nish (no prototype chain) `` | `reject_prototype_access` |
| `Object.assign/create/defineProperty/defineProperties/setPrototypeOf/getPrototypeOf` | `` `Object.assign` is forbidden in Nish (object layout is fixed at compile time) `` (and analogous) | `reject_object_assign`, `reject_object_define_property`, `reject_object_set_prototype` |
| `o["x"]`, `` o[`x`] `` | `` String-keyed element access is forbidden in Nish; use `obj.name` (no dynamic property lookup) `` | `reject_string_key_access` |
| `o[true]`, `o[{}]`, ... (non-numeric-shaped key) | `Element access requires a numeric index in Nish (no dynamic property lookup)` | `reject_non_numeric_index` |
| dynamic `import(...)` | `` Dynamic `import()` is forbidden in Nish (modules are resolved at compile time) `` | `reject_dynamic_import` |
| `import.meta`, and a member access or a call through it (`import.foo` stays a syntax error, and `meta` is a name everywhere else: `tests/parser/names-meta.ts`) | `` `import.meta` is forbidden in Nish (a module has no runtime object; resolve paths at compile time) `` | `reject_import_meta`, `reject_import_meta_call` |

"Numeric-shaped" index keys pass the validator (identifiers, numeric
literals, parentheses, unary `+`/`-`, `+ - * / %` over those, calls,
property and element access); the checker then requires a numeric type.

Each of these is parsed and refused by its rule, once: a module with several
reports the first in source order (`reject_expr_forms_together`). `typeof`,
`void`, `delete`, `await`, `yield`, `in`, `instanceof`, `as` and `satisfies`
are not reserved, and a variable, a parameter, a field or a function may be
called one (`tests/parser/names-operators.ts`, `names-operator-calls.ts`). A
word is the operator only where the name could not stand:

- `typeof`, `void`, `delete`, `await` and `yield` when an operand follows on
  the same line — a name, a literal, `this`, `super`, `new`, `!` or `~`. After
  a line break, or before `(`, `[`, `+`, `-`, `++`, `--`, `/` or `<`, the word
  is a name as it always was: `typeof(x)` and `void (0)` call a function of
  that name, `typeof -x` subtracts, and each is refused as the name it is when
  nothing declares it, where TypeScript reads the operator.
- `in` and `instanceof` after an operand on its line, or at the start of the
  next line when an operand follows them there (`reject_in_newline`). `in` in
  a `for` head's initialiser is the loop's, except inside a bracket that
  ECMAScript's grammar reads it in again — a parenthesis, an array or object
  literal, an argument list, an element access, a template substitution, a
  block, or the branch between a conditional's `?` and `:`
  (`reject_in_for_head_array`, `_call`, `_arrow`, `_element`, `_template`,
  `_object`, `_block`, `_conditional`). TypeScript's parser differs on the array
  literal, which it reports as a syntax error; Node follows the grammar.
- `as` and `satisfies` after an operand on its line, which is TypeScript's own
  rule for them.

A regular expression literal is read where an operand is due, which is where
TypeScript reads one; anywhere else a `/` divides.

## Rejected by the checker

Everything the validator lets through but the checker cannot compile. The
messages are exact for the cases cited; other entries quote the checker
(`src/checker.ts` and the modules beside it) and `src/types.ts`.

- **top-level statement other than
  function/class/interface/const/type/enum/import, outside an entry without
  `main`**:
  `Only top-level function declarations are supported in Phase 1 (found <Kind>)`
  (`reject_top_level_stmt`)
- **a function naming a variable of the entry's top-level code**:
  `` `count` is a variable of the entry module's top-level code, which runs as `main`, so a function cannot read it; pass it as a parameter, or declare it as an annotated module `const` above the code ``
  (`reject_script_local_in_function`)
- **a declaration below top-level code that reaches it**:
  `` `twice` is declared below the top-level code on line 5 that reaches it: under Node a top-level statement runs where it stands, before the declarations after it exist, so declare it above that line ``
  (`reject_script_declared_below`)
- **a variable of top-level code named like a declaration or import**:
  `` `go` is a variable of the top-level code and also a name the module declares or imports: under Node both live in the one module scope, so rename one ``
  (`reject_script_name_collision`)
- **type alias cycle**: `` Type alias `Feet` is defined in terms of itself ``
  (`reject_type_alias_cycle`)
- **a member of an unconstrained type parameter**:
  `` Cannot read `x` of `T`: an unconstrained type parameter has no members; say which ones it has with `<T extends Point>` ``
  (`reject_generic_member_unconstrained`)
- **a member the constraint does not declare**:
  `` Unknown field `radius` on interface `Shape`, the constraint of `T`: a constrained type parameter has only the members its constraint declares ``
  (`reject_generic_member_not_in_constraint`)
- **a constraint that is not a class or interface**:
  `` `T extends i32` is not supported: a constraint must be a declared class or interface, because the members a type parameter has are its constraint's ``
  (`reject_generic_constraint`)
- **a constraint that mentions a type parameter**:
  `` `U extends T` is not supported: a constraint cannot mention a type parameter, because it is resolved once for the template rather than once per instantiation; name a class or interface, with any type arguments written out ``
  (`reject_generic_constraint`)
- **a type parameter list that names one parameter twice**:
  `` Duplicate type parameter `T` ``, on the first repeat alone
  (`reject_generic_duplicate_type_parameter`, `…_arrow`, `…_method`,
  `…_class`, `…_interface`, `…_template`, `…_triple`)
- **a type argument that does not satisfy its constraint**:
  `` `T` of `areaOf` requires `T extends Shape`, and `i32` does not implement it; pass a class or interface that declares `implements Shape` ``
  (`reject_generic_unsatisfied_constraint`)
- **a function parameter used as a value**:
  `` `f` is a function parameter and can only be called or passed on as a function argument: ... ``
  (`reject_fnarg_store`, `reject_fnarg_return`)
- **an arrow argument that reads a `let`, `this`, or a function parameter of
  its function, or assigns to a capture**:
  `` The arrow reads `k`, a `let` of the function it is written in: ... `` /
  `` The arrow reads `this`: ... `` /
  `` The arrow assigns to `total`, which belongs to the function it is written in: ... ``
  (`reject_fnarg_capture_let`, `_this`, `_function_param`, `_write`)
- **an arrow inside another arrow that reads the function's locals**:
  `` The arrow reads `k` from outside the arrow it is written in: ... ``
  (`reject_fnarg_capture_nested`)
- **an arrow anywhere but as a function argument or a top-level `const`**:
  `` an arrow in value position is not yet a function reference: declare it as a top-level function and name it ``
  (`reject_fnarg_arrow_value`), or, when it captures,
  `` this arrow captures `k`: a function reference names a top-level function and carries no environment ``
  (`reject_arrow_as_value`, `reject_fnref_capture`)
- **a function type written inline on a parameter of a method, a constructor
  or a function type**:
  `` `f` cannot have a function type here: ... `` (`reject_fnarg_method`,
  `reject_fnarg_nested`)
- **a function reference to a function it cannot hold, or used other than
  called, compared, stored or passed**: NL2725, NL2726, NL2727, NL2728,
  NL2729, NL2730, NL2732, NL2733, NL2734, NL2735, NL2736, NL2737, NL2739,
  NL2758, NL2759, NL2760, NL2761 and NL2762 (`reject_fnref_generic`, `_async`, `_ffi`,
  `_rest`, `_zero_fill`, `_host`, `_host_field`, `_no_strict`, `_escape_join`,
  `_escape_join_transitive`, `_print`, `_json`, `_map_key`, `_nullable_call`,
  `_arg_effect`, `_arg_field`, `_arg_element_nullable`, `_result`, `_result_generic`, `reject_fnarg_alias`,
  `reject_fnarg_ref_assigned_later`, `reject_mutex_guard_helper_*`; [Function references](#function-references))
- **a function argument that is not a function's name, an arrow or a local
  holding a reference, or does not match**:
  `` Argument 1 of `apply` must be the name of a top-level function or an arrow written at the call, ... ``
  / `` ...; a function argument must have exactly its parameter's type ``
  (`reject_fnarg_not_name`, `reject_fnarg_generic_name`,
  `reject_fnarg_mismatch`, `reject_fnarg_arity`)
- **an arrow argument whose types cannot be inferred**:
  `` Cannot infer the type of `x` in the arrow passed to `run`: ... `` /
  `` The arrow passed to `map` needs a return type annotation: ... ``
  (`reject_fnarg_infer`, `reject_fnarg_block_return`)
- **a method type parameter named like one of its class's**:
  `` Type parameter `T` of `Box.map` shadows `Box`'s own `T`: a class's type parameters are in scope in its methods, and a diagnostic that names `T` has to mean one of them; give the method's another name ``
  (`reject_generic_method_shadow`)
- **type arguments written at a method call**:
  `` Type arguments are not written at a call site in Nish: `T` is inferred from the arguments, so write `h.get(...)` ``
  (`reject_generic_method`)
- **a `Secret` where a value would leave it, or a `Secret` the function made
  and did not return or wipe on some path**: NL2428 to NL2453 and NL2540 to
  NL2548, worded in [Secrets](#secrets-nishsecret) (`reject_secret_*`)
- **type alias named after a built-in type**:
  `` `string` is a built-in type name and cannot be used for a type alias ``
  (`reject_type_alias_builtin`)
- **enum named after a built-in type**:
  `` `i32` is a built-in type name and cannot be used for an enum ``
  (`reject_enum_builtin_name`)
- **importing an enum or a type alias its module does not export**:
  `` `Kind` is declared in `./kinds` but not exported (add `export`) ``
  (`tests/link/enum_import_not_exported`, `alias_import_not_exported`)
- **a declaration named like an imported enum or alias, or a second import of
  its name**: `` `Kind` is already declared in this module `` /
  `` `Kind` is already imported from `./kinds` ``
  (`tests/link/enum_import_clash`, `enum_import_clash_function`,
  `enum_import_duplicate`, `enum_import_duplicate_function`,
  `alias_import_clash`, `alias_import_duplicate`)
- **`const enum`**:
  `` `const enum` is not supported: an enum member is already folded to its integer, so `const` would ask for nothing ``
  (`reject_enum_const_enum`)
- **`declare enum`**: `` `declare enum` is not supported ``
  (`reject_enum_declare`, `nl2286_declare_enum`)
- **enum with no members**: `` Enum `Kind` must declare at least one member ``
  (`reject_enum_empty`)
- **two enum members of one name**: `` Duplicate member `If` in enum `Kind` ``
  (`reject_enum_duplicate_member`)
- **enum member that is not an integer**:
  `` Enum member `Kind.Half` must be an integer literal ``
  (`reject_enum_float`)
- **enum member outside `i32`**:
  `` Enum member `Kind.Big` does not fit in i32 `` (`reject_enum_overflow`)
- **name that is not a member of the enum**:
  `` Enum `Kind` has no member `Nope` `` (`reject_enum_unknown_member`)
- **top-level `let`, outside an entry without `main`**:
  `` Top-level `let` is not supported; a module has no top-level code, so only `const` is available ``
  (`reject_const_top_level_let`)
- **`for await`, in any body, a template nothing instantiates included**:
  `` `for await` is not supported `` (`nl2133_for_await`,
  `reject_for_await_template`)
- **`for (x of a)`, assigning rather than declaring**:
  `` `for...of` needs a `const` or `let` declaration, e.g. `for (const x of xs)` ``
  (`reject_arr_forof_expression`, `reject_arr_forof_expression_template`,
  `nl2135_for_of_without_declaration`)
- **`a ** b`, in any body, a template nothing instantiates included**:
  `` Unsupported binary operator `**` `` (`reject_op_exponent`,
  `reject_op_exponent_template`, `nl2254_unsupported_binary`)
- **`x **= e`, to a local, a field or an element**:
  `` Unsupported assignment operator `**=` `` (`reject_exponent_assign_local`,
  `reject_cls_compound_operator`, `nl2253_field_compound_operator`)
- **a hole in an array literal, `[1, , 2]`**:
  `Holes in array literals are not supported` (`reject_arr_hole`,
  `nl2210_array_hole`)
- **a spread in an array literal, `[...a]`**:
  `Spread in array literals is not supported` (`reject_arr_spread`,
  `reject_map_iter_spread`, `nl2237_array_spread`)
- **`new` of anything but a class name, `new a.B()`, `new cs[0]()`**:
  `` `new` requires a class name `` (`reject_cls_new_not_identifier`,
  `reject_new_parenthesized`, `nl2144_new_non_identifier`)
- **`x as T`, `<T>x`, `x satisfies T`, to anything but `any` and `unknown`
  ([Phase 0's](#types-1))**: `Unsupported expression in Phase 1: AsExpression`
  / `TypeAssertionExpression` / `SatisfiesExpression` (`reject_as_type`,
  `reject_angle_assertion`, `reject_satisfies`, `nl2256_satisfies_expression`)
- **more than one of these in one declaration**: the first, alone: the refusal
  comes before the declaration is collected (`reject_expr_sweep_together`)
- **constant initialiser that is not constant**:
  `A module constant's initialiser must be a literal, another constant, or arithmetic over them`
  (`reject_const_not_constant`)
- **constant cycle**: `` Module constant `A` is defined in terms of itself ``
  (`reject_const_cycle`)
- **assignment to a module constant**:
  `` Cannot assign to `LIMIT` because it is a module constant ``
  (`reject_const_assign`, `reject_const_incdec`)
- **missing return type, a function's or a method's, in a template nothing
  instantiates too**:
  `` Function `f` needs an explicit return type annotation `` /
  `` Method `m` of class `Box` needs an explicit return type annotation ``
  (`reject_missing_return_type`, `reject_arrow_return_type`,
  `reject_method_return_template`, `reject_method_return_generic`)
- **a function with no body (an overload signature)**:
  `Functions must have a body` (`nl2204_function_without_body`)
- **`export default function ()`**: `Functions must be named`
  (`reject_fn_anonymous`)
- **a destructuring pattern as a parameter or a module constant, over
  `await` but for `const [a, b] = await awaitAll(…)`, or with a default, a
  rest, a nested pattern or a computed key**:
  `Destructured constants are not supported` /
  `Destructured parameters are not supported` /
  ``A pattern may destructure an `await` only of `awaitAll(...)` …`` /
  NL2773 to NL2785
  (`reject_const_destructured`, `reject_param_destructured`,
  `reject_destructure_*`; [Destructuring declarations](#destructuring-declarations))
- **an optional parameter; a default or rest outside a function, method,
  constructor or `const` arrow; a spread argument**:
  `Optional parameters are not supported` /
  `Optional/default parameters are not supported here` /
  `Rest parameters are not supported here` /
  `Spread arguments are not supported` (`reject_param_optional`,
  `reject_param_default`, `nl2233_optional_parameter`, `reject_param_rest`,
  `reject_param_spread_call`)
- **an arrow bound with `let`, annotated, or beside a second name**:
  `` Function `f` must be declared `const`, not `let` `` /
  `` Function `f` takes its signature from the arrow; drop the annotation on `f` ``
  / `A function declaration binds one name` (`reject_arrow_let`,
  `reject_arrow_annotated`, `reject_fn_two_names`)
- **a getter or setter; a method in an interface**:
  `` Getters and setters are not supported in class `Box` (use a method) `` /
  `` Interface `Shape` cannot declare methods (interfaces describe layout only) ``
  (`reject_cls_accessor`, `reject_iface_method`, `reject_iface_accessor`)
- **more than one function or binding form in one declaration**: the first in
  source order, alone (`reject_fn_sweep_together`)
- **a class with no name: `export default class { }`, a class expression**:
  `Classes must be named` (a named class expression:
  `Unsupported expression in Phase 1: ClassExpression`)
  (`reject_cls_anonymous`, `nl2018_anonymous_class`)
- **a `declare class` that is not a C struct layout, a generic one, `declare
  interface`; `abstract` on a class or a member**: the refusals the
  [`declare class` section](#a-declare-class-a-c-struct-lent-by-pointer) lists /
  `` A generic `declare class` is not supported `` /
  `Abstract classes are not supported` (`reject_cls_declare`,
  `reject_generic_declare_class`, `reject_generic_abstract`)
- **a method or a constructor with no body, a constructor's return type**:
  `` Method `m` of class `Point` must have a body `` /
  `` Constructor of class `Point` must have a body (no overload signatures) ``
  / `Constructors cannot declare a return type` (`reject_cls_method_no_body`,
  `reject_cls_ctor_no_body`, `reject_cls_ctor_return_type`)
- **a member named by a string or a number, a parameter property**:
  `` Members of `Point` must have plain identifier names `` /
  ``Parameter properties (`constructor(public x: number)`) are not supported; declare the field and assign it``
  (`reject_cls_field_string_name`, `reject_cls_param_property`)
- **an index signature, a `static { }` block, a construct or call signature,
  `interface … extends`**:
  `` Index signatures are not supported in class `Point` (object layout is fixed) ``
  (or `interface`) /
  `` Unsupported class member in `Point`: ClassStaticBlockDeclaration `` /
  `` Unsupported interface member in `Point`: ConstructSignature `` /
  ``Interface inheritance (`extends`) is not supported; list every field``
  (`reject_cls_index_signature`, `reject_iface_index_signature`,
  `reject_cls_static_block`, `reject_iface_member_unsupported`,
  `reject_iface_extends`)
- **an object literal key that is not a name, a method in an object literal**:
  `Object literal keys must be plain identifiers` /
  ``Unsupported object literal member: MethodDeclaration (only `key: value`)``
  (`reject_cls_literal_key`, `reject_cls_literal_member`)
- **an object literal typed as a class with methods**:
  `` `Counter` has methods, so it is made only by `new`: ... Write `new Counter(...)` ``
  (`reject_class_literal_*`, `nl2556_class_literal`)
- **more than one class, interface or enum form in one declaration**: the
  first in source order, alone; a `static` or `readonly` header before one is
  the member's own refusal (`reject_cls_sweep_together`)
- **a side-effect import, `import "./m"`**:
  `` Side-effect imports (`import "./locals"`) are not supported; modules have no top-level code ``
  (`reject_side_effect_import`)
- **`import type`, `{ type A }`**: `Type-only imports are not supported`
  (`reject_import_type_only`, `nl2243_type_only_import`)
- **a default import: `import d from`, `import d, { a } from`,
  `{ default as d }`**:
  `` Default imports are not supported; use `import { math } from "./locals"` ``
  (`reject_default_import`)
- **a namespace import**:
  `` Namespace imports (`import * as math`) are not supported; import functions by name ``
  (`reject_namespace_import`)
- **a specifier that is not a string literal**:
  `Import specifier must be a string literal`
  (`reject_import_template_specifier`, `nl2212_template_specifier`)
- **`export { a }`, `export { a } from`, `export * from`,
  `export * as ns from`, `export type { A }`**:
  `` `export { ... }` / `export * from` are not supported; put `export` on the function declaration itself ``
  (`reject_export_list`, `nl2128_export_list`)
- **`export default <value>`, `export =`**:
  `` `export default` / `export =` are not supported; use a named `export function` ``
  (`reject_export_assignment`, `nl2129_export_default_value`)
- **`export default function f`**:
  `` `export default` is not supported; use a named `export function` ``
  (`reject_export_default`)
- **`export default class C`, `export default interface I`**:
  `` `export default` is not supported; use a named `export` ``
  (`reject_cls_export_default`, `reject_generic_export_default`,
  `nl2131_export_default_class`)
- **`export import`**:
  `` Only functions can be exported for now, plus classes and interfaces (found `export` on ImportEqualsDeclaration) ``
  (or `ImportDeclaration`) (`reject_export_import_equals`,
  `nl2226_export_import_equals`)
- **`import x = require("./m")`, `import x = A.B`, `export as namespace X`**:
  `Only top-level function declarations are supported in Phase 1 (found ImportEqualsDeclaration)`
  (or `NamespaceExportDeclaration`) (`reject_module_sweep_together`)
- **a function or an import declared inside a body**:
  `Unsupported statement in Phase 1: FunctionDeclaration` (or
  `ImportDeclaration`) (`reject_fn_nested`, `reject_fn_nested_template`)
- **the empty statement `;` in a body**:
  `Unsupported statement in Phase 1: EmptyStatement` (`reject_stmt_empty`)
- **more than one import or export form in one module**: the checker's
  refusals one each, since each is its own declaration; a Phase 0 one
  (NL1057–NL1059) alone, as every Phase 0 rule is, because Phase 0 halts the
  module before the checker runs (`reject_module_sweep_together`)
- **unknown identifier**: `` Unknown identifier `x` ``
  (`reject_unknown_ident`)
- **wrong arity**: `` `f` expects 1 argument(s), got 2 `` (`reject_arity`)
- **mixed operand types**:
  `` Operator `+` requires two operands of the same numeric type, got i32 and boolean ``
  (`reject_type_mismatch`, `reject_i64_mixed`)
- **string `+` number**:
  `` ... got string and i32 (no implicit string conversion; use a template literal) ``
  (`reject_str_plus_number`)
- **arithmetic compound assignment**:
  `` Operator `+=` requires two operands of the same numeric type, got string and string ``
  — one rule, naming the token that was written, for a local, a field and an
  element alike: the target must be numeric (so `+=` never concatenates) and
  the value must be exactly its type (`reject_cf_compound_string`,
  `reject_cf_compound_widths`)
- **object literal field of the wrong type**:
  `` Field `code` of `IoError` expects a value of type i32, got f64 ``
  (`reject_struct_field_f64`, `reject_struct_field_u8`)
- **a dotted call that is not a builtin**:
  `` Unknown builtin `foo.bar` (supported: console.log, console.error, String.fromCharCode, String.fromBytes, Math.sqrt, ...) ``
  — the callee is named, not its receiver, whether the receiver is a namespace
  or not (`reject_unknown_builtin`, `reject_arch_call`)
- **bitwise operator on a non-integer**:
  `` Operator `&` requires two operands of the same integer type, got f64 and f64 ``
  (with
  `` (`number` is f64 under --number-mode f64; convert with toI32/toI64) ``
  appended in that mode) /
  `` Operator `~` requires an integer operand, got f64 ``; a compound form
  names itself,
  `` Operator `&=` requires two operands of the same integer type, got f64 and f64 ``,
  for a local, a field and an element alike (`reject_bit_f64`,
  `reject_bit_width`, `reject_bit_number_mode`, `reject_bit_not`,
  `reject_arr_element_bitwise_f64`)
- **bitwise operator on booleans**:
  `` Operator `&` is not available on boolean (use `&&`) `` (`|` names `||`,
  `^` names `!==`, `~` names `!`) (`reject_bit_boolean`)
- **ordering on booleans / strings / structs**:
  `` Operator `<` requires two numeric operands, got string and i32 ``
  (`reject_bool_ordering`, `reject_str_lt`, `reject_str_lt_str`,
  `reject_cls_ordering`)
- **`T | null` misuse**: see [Nullable types](#nullable-types)
  (`reject_nullable_scalar`, `reject_null_to_nonnull`,
  `reject_null_field_access`, `reject_null_compare_two`,
  `reject_null_narrowing_leaks`, `reject_null_narrowing_assigned`,
  `reject_null_narrowing_assigned_in_chain`,
  `reject_readfile_or_null_unchecked`, `reject_readdir_unchecked`)
- **non-integer literal in i32 mode**:
  `` Non-integer literal `1.5` in i32 number mode (use --number-mode f64) ``
  (`reject_float_in_i32`)
- **non-boolean condition**:
  `Condition must be boolean, got i32 (Nish has no truthiness)`
  (`reject_cf_nonbool_cond`)
- **`&&`/`||` on numbers**:
  `` Operator `&&` requires boolean operands, got i32 and i32 ``
  (`reject_cf_logical_numbers`)
- **ternary arm mismatch**:
  `Ternary branches must have the same type, got i32 and boolean`
  (`reject_cf_ternary_mismatch`)
- **assignment to `const` / parameter**:
  `` Cannot assign to `x` because it is a const `` / `... a parameter`
  (`reject_assign_const`, `reject_assign_param`, `reject_cf_compound_const`,
  `reject_cf_incdec_param`)
- **missing return**:
  `` Function `f` must return a value of type i32 on every path ``
  (`reject_missing_return`, `reject_cf_missing_return_loop`)
- **unreachable code**: `Unreachable code after return` / `break` /
  `process.exit` / ... (`reject_unreachable`,
  `reject_cf_unreachable_after_break`, `reject_exit_unreachable`)
- **`break`/`continue` outside a loop**: `` `break` outside of a loop ``
  (`reject_cf_break_outside`, `reject_cf_continue_outside`)
- **`console.log` misuse**:
  `` `console.log` expects exactly 1 argument, got 0 `` /
  `returns void and can only be used as a statement`
  (`reject_console_log_noargs`, `reject_console_log_two_args`,
  `reject_console_log_as_value`)
- **unknown property / method / builtin**:
  `` Unknown property `foo` on string `` /
  `` Unknown property `length` on i32 `` /
  `` Unknown builtin `Math.foo` (supported: ...) ``
  (`reject_unknown_property`, `reject_length_on_number`,
  `reject_unknown_builtin`)
- **`Math.*` on an integer**:
  `` `Math.sqrt` requires an f64 argument, got i32 (use --number-mode f64 or toF64(x)) ``
  (`reject_math_i32`)
- **conversion of a non-number**:
  `` `toI32` expects a number (i32, i64, or f64), got string ``
  (`reject_toi32_string`)
- **I/O with the wrong type**:
  `` `readFileSync` expects an argument of type string, got i32 ``
  (`reject_readfile_number`, `reject_readdir_type`, `reject_spawn_to_type`)
- **I/O with the wrong arity**:
  `` `readdirSync` expects exactly 1 argument, got 2 ``;
  `` `spawnSyncTo` expects exactly 3 arguments, got 2 ``;
  `` `spawnPiped` expects exactly 4 arguments, got 3 ``;
  `` `spawnPipedWithin` expects exactly 5 arguments, got 4 ``;
  `` `monotonicNanos` expects exactly 0 arguments, got 1 ``
  (`reject_readdir_arity`, `reject_spawn_to_arity`,
  `reject_spawn_piped_arity`, `reject_spawn_piped_within_arity`,
  `reject_monotonic_arity`)
- **array errors**: see [Arrays](#array-literals), [Element
  access](#element-access), [`for...of`](#for-const-x-of-a) (`reject_arr_*`)
- **element reference held across a `push` or `pop`**:
  `` `p` refers to an element of `ps`, and `ps.push(...)` may move or reuse that storage; index `ps` again afterwards rather than holding the element across it ``
  — see [Arrays of records are contiguous](#arrays-of-records-are-contiguous)
  (`reject_arr_element_across_push`, `reject_arr_element_loop_push`,
  `reject_arr_element_push_self`)
- **`push` or `pop` on a receiver spelled `Int32Array`, `Float32Array`,
  `Float64Array` or `BigInt64Array` (NL2415)**:
  `` `push` is not a method of `Float64Array`, whose length is fixed: declare it `f64[]` to push and pop ``
  (`reject_typed_push_f64`, `reject_typed_pop_receivers` ([Typed-array names
  have no `push` or `pop`](#typed-array-names-have-no-push-or-pop)))
- **class and interface errors**: see [Classes](#classes),
  [Interfaces](#interfaces-and-object-literals) (`reject_cls_*`)
- **`extends` or `super` on a class (WP25: there is no inheritance)**:
  `` `extends` is not supported: Nish has no inheritance. Declare the base's fields as the first fields of `Derived` and `implements` an interface to convert between them ``
  /
  `` `super` is not supported: Nish has no inheritance, so a class has no base class to reach ``
  (`reject_cls_extends`, `reject_cls_super`)
- **a class does not cover the interface it `implements`**:
  `` Class `Point2` does not implement `Point3`: it lacks field `z: i32` (the interface's fields must be the class's first fields, in order) ``
  (`reject_cls_implements_short`, `reject_cls_implements_mismatch`)
- **module errors**: see [`export` and `import`](#export-and-import),
  [`main`](#main) (`reject_bare_import`, `reject_default_import`,
  `reject_namespace_import`, `reject_side_effect_import`,
  `reject_missing_module`, `reject_std_escaping_module`, `reject_export_*`,
  `reject_main_params`, `tests/link/*`)
- **unsupported syntax the validator allows**:
  `Unsupported statement in Phase 1: <Kind>` /
  `Unsupported expression in Phase 1: <Kind>` /
  `` Unsupported binary operator `**` `` /
  `` Unsupported unary operator `+` `` / `` Unsupported type `...` `` (*(CLI
  only)*)

## Known inconsistencies

Behaviour observed with the current compiler that disagrees with the design
notes, the runtime header, or JavaScript beyond the documented semantics
decisions. Listed here so the reference stays truthful; each is a candidate
fix, not a feature. (Found by the first audit and fixed since, so no longer
listed: inverted boolean ordering, silently accepted `?.`, the rejected
`-2147483648` literal, undefined `x / 0` and `INT_MIN / -1`, and
`Math.pow(1, NaN)`.)

All four discrepancies found by the documentation audit (the `main`
parameter message, the `%.17g` comment in `nish.h`, the exclusive
`i64` literal bound, and the generic message for comparing `T | null` with
`T`) are fixed; `2^53` is accepted as an `i64` literal and the nullable
comparison names the nullable side.
