@amritk/nish-aarch64-linux 0.38.0 → 0.40.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/INSTALL.md +74 -129
- package/bin/nish +0 -0
- package/docs/AI.md +455 -65
- package/package.json +1 -1
- package/runtime/core/host.d.ts +11 -0
- package/runtime/core/host.mjs +35 -0
- package/runtime/nish.d.ts +320 -33
- package/runtime/nish.h +84 -10
- package/runtime/nish.mjs +69 -6
- package/runtime/node.mjs +117 -0
- package/runtime/page-frame.d.ts +123 -0
- package/runtime/page-frame.mjs +736 -0
- package/runtime/page-game.d.ts +132 -0
- package/runtime/page-game.mjs +738 -0
- package/runtime/runtime-aes.c +97 -12
- package/runtime/runtime-async.c +43 -10
- package/runtime/runtime-bytes.c +88 -4
- package/runtime/runtime-checksum.c +207 -15
- package/runtime/runtime-net.c +64 -3
- package/runtime/runtime-os.c +174 -27
- package/runtime/runtime-region.c +94 -10
- package/runtime/runtime-sandbox.c +404 -17
- package/runtime/runtime-sha256.c +11 -4
- package/runtime/runtime-wasm.c +437 -0
- package/runtime/runtime.c +5 -0
- package/runtime/vite.mjs +1 -1
- package/scripts/build.sh +42 -8
- package/std/README.md +78 -91
- package/std/array.ts +36 -3
- package/std/collections.ts +51 -0
- package/std/compress/checksum.ts +13 -0
- package/std/compress/deflate.ts +0 -2
- package/std/crypto/hmac.ts +37 -10
- package/std/crypto/p256.ts +1629 -2732
- package/std/crypto/p384.ts +3 -1
- package/std/crypto/pki.ts +151 -13
- package/std/crypto/sha256.ts +34 -6
- package/std/crypto/x25519.ts +153 -64
- package/std/crypto/x509.ts +120 -10
- package/std/host/game.ts +273 -0
- package/std/input.ts +56 -0
- package/std/json-tokenizer.ts +344 -111
- package/std/json-typed.ts +256 -12
- package/std/json-value.ts +144 -3
- package/std/json.ts +63 -8
- package/std/net/fetch.ts +22 -4
- package/std/net/handler.ts +130 -16
- package/std/net/http-server.ts +3382 -0
- package/std/net/http1-client-codec.ts +6 -2
- package/std/net/http1-codec.ts +636 -162
- package/std/net/http1-server.ts +569 -42
- package/std/net/http2-cleartext.ts +526 -0
- package/std/net/http2-tls.ts +48 -0
- package/std/net/http2.ts +131 -14
- package/std/net/http3-server.ts +29 -3
- package/std/net/http3.ts +180 -7
- package/std/net/postgres-async.ts +1304 -86
- package/std/net/postgres-carrier.ts +343 -10
- package/std/net/postgres.ts +122 -7
- package/std/net/prefork.ts +195 -11
- package/std/net/quic-datagram.ts +30 -0
- package/std/net/quic-listener.ts +38 -12
- package/std/net/quic-packet.ts +19 -6
- package/std/net/quic-recovery.ts +373 -27
- package/std/net/quic-stream.ts +195 -37
- package/std/net/quic.ts +516 -22
- package/std/net/router.ts +407 -38
- package/std/net/serve.ts +1022 -110
- package/std/net/tls/codec.ts +110 -32
- package/std/net/tls/record-server.ts +37 -7
- package/std/net/tls/verify.ts +19 -1
- package/std/net/tls-tcp.ts +56 -1
- package/std/net/tls.ts +196 -50
- package/std/net/url.ts +83 -35
- package/std/net/websocket.ts +129 -19
- package/std/net/webtransport.ts +185 -1
- package/std/raster.ts +837 -0
- package/std/regex.ts +69 -47
- package/std/region.ts +62 -11
- package/std/release.ts +593 -0
- package/std/secret.ts +26 -59
- package/std/synth.ts +143 -0
- package/std/text.ts +233 -0
- package/std/threads.ts +298 -0
- package/std/yaml-json.ts +368 -28
- package/std/yaml.ts +122 -27
package/docs/AI.md
CHANGED
|
@@ -7,6 +7,10 @@ Nish and get it accepted on the first try**. It is a digest, not the authority:
|
|
|
7
7
|
This page exists because LANGUAGE.md is 2,300 lines written to be *read*, and
|
|
8
8
|
what an author needs is the rules in one pass with the traps first.
|
|
9
9
|
|
|
10
|
+
> Its short form, published to agents by the docs site, is the
|
|
11
|
+
> [`writing-nish` skill](../skills/writing-nish/SKILL.md): a change here to the
|
|
12
|
+
> loop, the unlearn table or the checklist below moves it too.
|
|
13
|
+
|
|
10
14
|
> Working **on the compiler** rather than **in the language**? That is a
|
|
11
15
|
> different document: [`AGENTS.md`](../AGENTS.md) and [`.claude/`](../.claude/).
|
|
12
16
|
|
|
@@ -49,7 +53,7 @@ stdout, nothing on stderr, every field 1-based with `endLine`/`endColumn`
|
|
|
49
53
|
exclusive:
|
|
50
54
|
|
|
51
55
|
```json
|
|
52
|
-
{"file":"p.ts","line":3,"column":17,"endLine":3,"endColumn":23,"severity":"error","code":"NL2249","message":"Unknown method `reduce` on i32[] (supported: push, pop, indexOf, join, set, fill, sort, map, filter, some, every, findIndex, slice)"}
|
|
56
|
+
{"file":"p.ts","line":3,"column":17,"endLine":3,"endColumn":23,"severity":"error","code":"NL2249","message":"Unknown method `reduce` on i32[] (supported: push, pop, indexOf, join, set, fill, sort, map, filter, some, every, findIndex, forEach, slice)"}
|
|
53
57
|
```
|
|
54
58
|
|
|
55
59
|
- **Key on `code`, never on `message`.** A code is a promise: `NL2249` means
|
|
@@ -92,6 +96,14 @@ what remains. A warning can carry a fix too, and `--fix` applies it only when th
|
|
|
92
96
|
compiles and the warning would be printed: `NL9007`'s inserts the guard that
|
|
93
97
|
proves an index in range (not under `--no-warn-performance`).
|
|
94
98
|
|
|
99
|
+
Under `--warn-portability`, a portability warning can carry a **`review`**
|
|
100
|
+
after `fix`, in the same edit shape: a rewrite that makes the line read the
|
|
101
|
+
same under Node and compiles to byte-identical IR, but changes the source's
|
|
102
|
+
words, so `--fix` never applies it. Today that is `NL8006`, an integer
|
|
103
|
+
division, which `review` wraps in its type's conversion (`toI32(a / b)`).
|
|
104
|
+
The loop: run `--fix`, compile with `--warn-portability --json`, apply each
|
|
105
|
+
`review` you agree with, compile again and check the warning is gone.
|
|
106
|
+
|
|
95
107
|
When it compiles, **check the native build against the program's TypeScript
|
|
96
108
|
reading**. Run the project's tests natively; where it has none, write the
|
|
97
109
|
program back out and run both:
|
|
@@ -141,7 +153,7 @@ everywhere, a template literal instead of `String(n)`.
|
|
|
141
153
|
|
|
142
154
|
- A module is one `.ts` file. At the top level it may hold **only**
|
|
143
155
|
declarations: `const` arrows (functions), `class`, `interface`, module
|
|
144
|
-
`const`s, `type` aliases,
|
|
156
|
+
`const`s, `type` aliases, `enum`s (numeric or string), and `import`s. There is no
|
|
145
157
|
top-level code, so there is no initialisation order to think about. The
|
|
146
158
|
one exception is an entry module with no `main`: its top-level statements
|
|
147
159
|
run as `main` (`docs/LANGUAGE.md` → "Top-level code"). Declare every
|
|
@@ -165,9 +177,10 @@ rejects. This table is the highest-value part of the page.
|
|
|
165
177
|
| `x == y` | `Loose equality is forbidden` | `x === y` |
|
|
166
178
|
| `throw new Error(m)` | `` `throw` is forbidden `` | `return Err(m)`, or `panic(m)` to end the process |
|
|
167
179
|
| `try { … } catch { … }` | `` `try`/`catch`/`finally` is forbidden `` | `Result<T, E>` and `isErr()` |
|
|
168
|
-
| `xs.reduce(f)`, `.
|
|
180
|
+
| `xs.reduce(f)`, `.shift` | `` Unknown method `reduce` on i32[] (supported: push, pop, indexOf, join, set, fill, sort, map, filter, some, every, findIndex, forEach, slice) `` | a `for` loop; `map`, `filter`, `forEach`, `some`, `every`, `findIndex` and `slice` work, with a one- or two-parameter callback |
|
|
169
181
|
| `xs.find(f)` | `` `find` is not supported: TypeScript types its answer `T \| undefined` … `` (NL2697) | `const i = xs.findIndex(f); if (i >= 0) { ... xs[i] ... }` |
|
|
170
182
|
| `s.toUpperCase()`, `s.split()`, `s.trim()`, `s.replace()` | `` Unknown method … on string `` | index bytes with `charCodeAt` / `substring` |
|
|
183
|
+
| `x.toFixed(2)`, `s.split(sep, limit)` | `` Unknown method `toFixed` on f64 `` | `toFixed(x, 2)` and `splitLimit(s, sep, limit)` from `nish/text` |
|
|
171
184
|
| `a?.b`, `a ?? b` | `?.` only in a chain that ends in `??`; `??` only on a `T \| null`, a chain or `m.get(k)` | `a?.b ?? d`, `a ?? d`, or `if (a !== null)` first |
|
|
172
185
|
| `x as T`, `<T>x`, `x satisfies T` | `Unsupported expression in Phase 1: AsExpression` (to `any` or `unknown`: `` Type assertion to `any` is forbidden ``); `x!` is a syntax error | there are no casts; `implements` is the only widening |
|
|
173
186
|
| `typeof x`, `x instanceof C`, `"k" in o`, `delete o.k`, `void 0`, `a, b` | each refused by name (`` `typeof` is forbidden ``, …) | there is no runtime type information: a value's type is its declared one |
|
|
@@ -176,7 +189,7 @@ rejects. This table is the highest-value part of the page.
|
|
|
176
189
|
| `undefined` | forbidden, except `x === undefined` on a `Map.get` result | `null`, with a `T \| null` type |
|
|
177
190
|
| `let total = 0` at the top level | `` Top-level `let` is not supported `` | a module `const`, or a local |
|
|
178
191
|
| `for (const k in o)` | `` `for...in` is forbidden `` | `for (const x of xs)` over an array, or `for (const k of m.keys())` over a `Map` |
|
|
179
|
-
| a
|
|
192
|
+
| a closure stored or returned: `const cb = (n: i32) => n + k` inside a function | `` this arrow captures `k`: a function reference names a top-level function and carries no environment `` / `an arrow in value position is not yet a function reference: declare it as a top-level function and name it` | a [function reference](#function-references) names a capture-free top-level function: declare the function at the top level and store its name, or pass the arrow straight to a [function parameter](#function-parameters) |
|
|
180
193
|
| `type Pair<T>` (a generic alias) | `Generic type parameters are forbidden on a type alias` | a generic **function**, **class**, **interface** and **method** all work — see below; an alias renames a type that already exists, so it has nothing to specialise |
|
|
181
194
|
| `constructor<T>(x: T)` | a syntax error: `a constructor cannot have type parameters` | put the parameter on the class (`class Box<T>`), or on a method |
|
|
182
195
|
| `h.get<i32>(7)` (type argument at a method call) | `Type arguments are not written at a call site in Nish` | `h.get(7)` — a generic method infers like a generic function |
|
|
@@ -187,12 +200,14 @@ rejects. This table is the highest-value part of the page.
|
|
|
187
200
|
| `keyof T`, `<T = i32>` (a default type argument) | `` Unsupported type `keyof T` (Phase 1 supports …) `` / `a default type argument … is not supported` | name the type; a type argument is always inferred |
|
|
188
201
|
| `class B extends A` | `` `extends` is not supported: Nish has no inheritance `` | repeat the fields and `implements` an interface |
|
|
189
202
|
| `static` members, `get x()` / `set x(v)` | `` … `static` members are not supported `` / `` Getters and setters are not supported in class `C` (use a method) `` | module `const`s and plain methods |
|
|
190
|
-
| `
|
|
203
|
+
| `[a, b] = [b, a]`, `const { x = 0 } = p`, `({ x }: Point) =>`, `(n?: i32)`, `(n = 1)`, `f(...xs)` | `Destructuring assignment is not supported` / `A default in a destructuring pattern is not supported` / `Destructured parameters are not supported` / `Optional parameters are not supported` / `` Parameter `n` has a default and no type annotation `` / `Spread arguments are not supported` | one name per binding; `n: i32 = 1` (a constant or an earlier parameter) for a default, `o: Opts | null = null` for an options argument; `...ns: i32[]` as the last parameter, or pass the array itself |
|
|
204
|
+
| `const { a, b } = config` at module level | `Destructured constants are not supported` | one module `const` per name (a module constant is a compile-time value folded into each use, with nothing at run time for a pattern to read), or destructure inside a function |
|
|
191
205
|
| `function f(): void;` (an overload), `export default function ()` | `Functions must have a body` / `Functions must be named` | one named function, with its body |
|
|
192
206
|
| a method in an `interface` | `` Interface `I` cannot declare methods (interfaces describe layout only) `` | fields only; a top-level function over the interface |
|
|
193
|
-
| `abstract class`, `declare class
|
|
207
|
+
| `abstract class`, a `declare class` with methods, `constructor(public x: i32)`, `interface B extends A`, `[k: string]: T` | `Abstract classes are not supported` / `` `declare class Point` cannot have a method or accessor `` (a `declare class` is a C struct: fields only) / `Parameter properties … are not supported; declare the field and assign it` / ``Interface inheritance (`extends`) is not supported; list every field`` / `Index signatures are not supported …` | a plain class with its fields declared and assigned in the constructor; every field listed; a `Map` for a keyed table |
|
|
194
208
|
| `{ m() { … } }`, `{ "a": 1 }`, `const C = class { }` | ``Unsupported object literal member: MethodDeclaration (only `key: value`)`` / `Object literal keys must be plain identifiers` / `Classes must be named` | fields with identifier keys, a top-level function over the interface, a named top-level class |
|
|
195
|
-
| `{ ...base
|
|
209
|
+
| `const o = { ...base }` with no annotation; `{ ...maybe }` for a `T \| null`; `{ ...base }` copying a field the target lacks | ``An object literal with a spread needs a contextual class or interface type…`` / ``Spread of `T \| null` into `T` may spread `null`…`` / ``Spread of `Point3` into `Point` copies field `z`, which `Point` does not declare…`` | annotate the literal's type (`const p: Point = { ...base, x: 1 }`); narrow the source first; spread a value whose fields the target declares, or set the fields by name |
|
|
210
|
+
| `{ [k]: v }`, `[k]: i32` in a class or interface | `Computed property names are forbidden in Nish (member names are fixed at compile time)` | a `Map` for a keyed table |
|
|
196
211
|
| `type Pair = { a: i32 }` (inline object type) | `` Unsupported type `{ a: i32 }` `` | declare an `interface` |
|
|
197
212
|
| `A \| B` unions of anything but tagged classes and interfaces | `` Union types other than `T \| null` are forbidden `` | a [discriminated union](#discriminated-unions): a tag field first in each variant |
|
|
198
213
|
| `String(n)`, `n.toString()` | `` Unknown function `String` `` / `` Unknown method `toString` on i32 `` | `` `${n}` `` |
|
|
@@ -204,7 +219,7 @@ rejects. This table is the highest-value part of the page.
|
|
|
204
219
|
| `total += xs[i]` in a loop, with `i` from somewhere the compiler cannot bound | it compiles, with an `NL9007` performance warning: `` `i` is not proven to be in range for `xs` here, so this access keeps its bounds check `` | a guard before the statement, `if (!(i >= 0 && i < toI32(xs.length))) { panic("index out of range") }`, which proves both ends in either number mode; `nish --fix` inserts it where it changes nothing the program does |
|
|
205
220
|
| `new Date()` | `` `new Date()` is refused: Nish has no `Date` object; the one `Date` member is `Date.now()`, the wall clock in milliseconds `` | `Date.now()` for the wall clock, `monotonicNanos()` for elapsed time; there is no calendar |
|
|
206
221
|
| `JSON.parse`, `RegExp`, `/re/` literals, `Promise` | unknown / forbidden | none of these are built in: `regexCompile(pattern, flags)` from `nish/regex` for a pattern, `jsonDecode` from `nish/json-typed` for JSON; restructure around `Promise` |
|
|
207
|
-
| `for (const [k, v] of m)`, `m.
|
|
222
|
+
| `for (const [k, v] of m)`, `m.entries()`, `new Map(entries)` | each refused by name | `Map` and `Set` exist, with `size`, `get`, `set` / `add`, `has`, `delete`, `clear`, `forEach`, and `keys()` / `values()` in a `for...of` — see [Map and Set](#map-and-set) |
|
|
208
223
|
| `let v = m.get(k)`, `f(m.get(k))`, `m.get(k) + 1` | `` `m.get(k)` is `i32 \| undefined` and cannot be held in a `let` `` (and one message per place) | `m.get(k) ?? 0`, or `const v = m.get(k); if (v !== undefined) { … }` |
|
|
209
224
|
| `let x = 5; x = "s"` | `Cannot initialize …` | types never change and never convert implicitly |
|
|
210
225
|
|
|
@@ -224,6 +239,43 @@ if (xs.length !== 0) {
|
|
|
224
239
|
}
|
|
225
240
|
```
|
|
226
241
|
|
|
242
|
+
### Lines that type-check and are still refused
|
|
243
|
+
|
|
244
|
+
Some mistakes have nothing wrong with their types. rustc warns about them and
|
|
245
|
+
Clippy denies some. Nish refuses all of them, because each is a bug far more
|
|
246
|
+
often than a choice
|
|
247
|
+
([LANGUAGE.md](LANGUAGE.md#mistakes-every-type-accepts)). They are reported
|
|
248
|
+
only once the program has no other error, so they show up last.
|
|
249
|
+
|
|
250
|
+
| You wrote | Code | Write instead |
|
|
251
|
+
| --- | --- | --- |
|
|
252
|
+
| a local nothing reads, or only stores into (`n++` that nothing reports) | NL2712 | use it, delete it, or name it `_n`; a loop that only counts is `for (const _x of xs)` |
|
|
253
|
+
| a statement with no call, store or `await` in it: `a === b;`, `p.x + 1;` | NL2713 | `a = b`, or delete the line |
|
|
254
|
+
| `x = x`, `p.x = p.x` | NL2714 | the value you meant to store |
|
|
255
|
+
| the same operand on both sides: `a.w === a.w`, `xs[i] - xs[i]`, `ok && ok` | NL2715 | the other operand you meant; to compare a value with itself, copy it to a second `const` first. On a float, `x !== x` (NaN) and `x - x` are allowed |
|
|
256
|
+
| `if (c) … else if (c) …`, the same condition again | NL2716 | the condition you meant for the second branch |
|
|
257
|
+
| `u < 0` or `u >= 0` on a `u8`, `u16`, `u32`, `u64` | NL2717 | test before the subtraction that would wrap, or use a signed type |
|
|
258
|
+
|
|
259
|
+
```ts nish:err-body NL2712
|
|
260
|
+
const xs = [3, 4];
|
|
261
|
+
let total = 0;
|
|
262
|
+
for (const x of xs) {
|
|
263
|
+
total = total + x;
|
|
264
|
+
}
|
|
265
|
+
const average = total / 2;
|
|
266
|
+
console.log(`${total}`);
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
```ts nish:ok-body
|
|
270
|
+
const xs = [3, 4];
|
|
271
|
+
let total = 0;
|
|
272
|
+
for (const x of xs) {
|
|
273
|
+
total = total + x;
|
|
274
|
+
}
|
|
275
|
+
const average = total / 2;
|
|
276
|
+
console.log(`${average}`);
|
|
277
|
+
```
|
|
278
|
+
|
|
227
279
|
## Types
|
|
228
280
|
|
|
229
281
|
Every type is exactly one LLVM first-class type. No boxing, no runtime tag, no
|
|
@@ -242,8 +294,9 @@ compatible only when their types are identical.
|
|
|
242
294
|
| `Int32Array`, `Float32Array`, `Float64Array`, `BigInt64Array` | aliases of `i32[]`, `f32[]`, `f64[]`, `i64[]` | not distinct types; fixed length, so no `push` or `pop` (NL2415): declare `f64[]` to grow one |
|
|
243
295
|
| `class C`, `interface I` | a struct, fields in declaration order | no header, no vtable |
|
|
244
296
|
| `enum K` | a **distinct** type represented as `i32` | never interchangeable with `i32` |
|
|
297
|
+
| `enum K { A = "a" }` | a string enum: a distinct type, its member's ordinal as `i32` | never interchangeable with `string`; `String(k)` reads the member's string |
|
|
245
298
|
| `K.M` | an enum member type: the one member `K.M`, as `i32` | holds only that member; a read is a `K` |
|
|
246
|
-
| `T \| null` | `T` a class, interface, array, or
|
|
299
|
+
| `T \| null` | `T` a class, interface, array, string or function reference | a scalar can never be nullable |
|
|
247
300
|
| `A \| B` of tagged variants | a pointer to the variant; its first field is the tag | [Discriminated unions](#discriminated-unions); only the tag is read until a test of it narrows |
|
|
248
301
|
| `Result<T, E>` | the only way to report failure | `E` may not be `void` |
|
|
249
302
|
| `void` | return type only | |
|
|
@@ -252,8 +305,9 @@ compatible only when their types are identical.
|
|
|
252
305
|
the site: `uncheckedGet(xs, i)` and `uncheckedSet(xs, i, v)` on an array of
|
|
253
306
|
numbers with an `i32` index (out of range is undefined behaviour), and
|
|
254
307
|
`wrappingAdd` / `wrappingSub` / `wrappingMul` on two `i32`s or two `i64`s.
|
|
255
|
-
|
|
256
|
-
|
|
308
|
+
Two more, `readCString` and `readStruct`, copy a C string or a C struct
|
|
309
|
+
out of a `CPtr`, and the eighth, `cErrno()`, reads the errno the last C call
|
|
310
|
+
left ([Calling C](#calling-c)). Calling one without the import is NL2456. No flag turns the checks off for a
|
|
257
311
|
whole program: `--unchecked-indexing` and `--wrapping` were removed before 1.0
|
|
258
312
|
and are refused with exit 2.
|
|
259
313
|
|
|
@@ -419,7 +473,8 @@ export const main = (): i32 => {
|
|
|
419
473
|
The surface: `Ok(v)` / `Ok()`, `Err(e)`, `r.isOk()`, `r.isErr()`, `r.ok`,
|
|
420
474
|
`r.value`, `r.error`, `r.orReturn()`, `r.unwrapOr(d)`, `r.expect(msg)`. There
|
|
421
475
|
is deliberately no `unwrap()` — `expect` insists on a reason — and no
|
|
422
|
-
`map`/`andThen`, which
|
|
476
|
+
`map`/`andThen`, whose callbacks are usually closures, which a function
|
|
477
|
+
reference cannot hold.
|
|
423
478
|
|
|
424
479
|
**Three rules, and they are the ones that catch you out:**
|
|
425
480
|
|
|
@@ -460,9 +515,10 @@ terminates control flow, so a non-`void` function may end with it.
|
|
|
460
515
|
|
|
461
516
|
## Absence: nullable types
|
|
462
517
|
|
|
463
|
-
`T | null` is available for `T` a class, interface, array,
|
|
464
|
-
scalar, which has no null value. It is the same pointer
|
|
465
|
-
|
|
518
|
+
`T | null` is available for `T` a class, interface, array, string or function
|
|
519
|
+
reference — never a scalar, which has no null value. It is the same pointer
|
|
520
|
+
(or, for a function reference, the same tag) with `null` as one more value, so
|
|
521
|
+
nothing is boxed.
|
|
466
522
|
|
|
467
523
|
```ts nish:ok
|
|
468
524
|
class Node {
|
|
@@ -578,15 +634,15 @@ const double = (n: i32): i32 => n * 2; // a concise body is that one `return`
|
|
|
578
634
|
```
|
|
579
635
|
|
|
580
636
|
- A function is a **module-level `const` bound to an arrow**. `let` is
|
|
581
|
-
rejected; annotating the `const` is rejected (the
|
|
582
|
-
|
|
637
|
+
rejected; annotating the `const` is rejected (the signature is written once,
|
|
638
|
+
on the arrow). The `function` keyword is
|
|
583
639
|
accepted as the legacy spelling and compiles to identical IR.
|
|
584
640
|
- **Every parameter and the return type must be annotated.**
|
|
585
|
-
- **A function is
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
641
|
+
- **A capture-free top-level function is a value** — a
|
|
642
|
+
[function reference](#function-references): `const h: Op = double`, a field
|
|
643
|
+
`op: Op`, an `Op[]`, a returned `Op`, where `type Op = (n: i32) => i32`. An
|
|
644
|
+
arrow written inside a function is not one: declare it at the top level and
|
|
645
|
+
name it.
|
|
590
646
|
- **Parameters are immutable**: `p = 1`, `p++`, `p += 1` are all rejected. Copy
|
|
591
647
|
into a `let` first.
|
|
592
648
|
- A non-`void` function must return on every path.
|
|
@@ -750,10 +806,11 @@ export const main = (): i32 => {
|
|
|
750
806
|
- **A type parameter takes no type arguments of its own.** `T` is whatever the
|
|
751
807
|
instantiation bound it to, so `const y: T<i32>` is
|
|
752
808
|
`` Unsupported type reference `T<i32>` ``.
|
|
753
|
-
- **A template obeys every rule a declared class obeys**: `
|
|
754
|
-
Box<T>`, `
|
|
755
|
-
|
|
756
|
-
|
|
809
|
+
- **A template obeys every rule a declared class obeys**: `export default
|
|
810
|
+
class Box<T>`, `abstract class Box<T>` and `interface Box<T> extends Base`
|
|
811
|
+
are refused in the words their non-generic spellings are refused in, and
|
|
812
|
+
`declare class Box<T>` (a C struct has one layout) is
|
|
813
|
+
`` A generic `declare class` is not supported ``.
|
|
757
814
|
- **A template claims its name.** `class Box<T>` is a declaration of `Box`, so
|
|
758
815
|
a function, constant, alias, enum or second class of that name is refused
|
|
759
816
|
whichever was written first: `` `Box` is already declared in this module ``,
|
|
@@ -863,16 +920,21 @@ export const main = (): i32 => {
|
|
|
863
920
|
read `this` (bind `const self = this`), or read a function-typed parameter
|
|
864
921
|
of its function. An arrow inside another arrow, or given to a method, a
|
|
865
922
|
constructor, `expose` or `exposeWith`, captures nothing; the callbacks of
|
|
866
|
-
the array methods `sort`, `map`, `filter`, `some`, `every
|
|
867
|
-
are the exception, and capture
|
|
923
|
+
the array methods `sort`, `map`, `filter`, `some`, `every`, `findIndex` and
|
|
924
|
+
`forEach`, and of `Map` and `Set` `forEach`, are the exception, and capture
|
|
925
|
+
as an arrow argument does.
|
|
868
926
|
- **The argument's type must match exactly**: `(x: i32) => i64` for a
|
|
869
927
|
`(x: i32) => i32` parameter is refused. A generic function cannot be passed
|
|
870
928
|
by name — write `(x) => identity(x)`.
|
|
871
929
|
- **Annotate what cannot be inferred**: an arrow parameter whose type no value
|
|
872
930
|
argument binds, and the return type of a block-bodied arrow whose result is a
|
|
873
931
|
type parameter.
|
|
874
|
-
- **Only a top-level function
|
|
875
|
-
|
|
932
|
+
- **Only a top-level function's parameter, written inline**, is one. On a
|
|
933
|
+
method or constructor parameter an inline function type is refused; type it
|
|
934
|
+
through an alias and it is an ordinary [function reference](#function-references)
|
|
935
|
+
parameter. A local holding a reference is a function argument too (a field
|
|
936
|
+
or element is refused, NL2759: read it into a `const`); the runners that check their body (`parallelMap`,
|
|
937
|
+
`parallelReduce`, `spawn`, `expose`, `region`, ...) refuse one (NL2734).
|
|
876
938
|
|
|
877
939
|
```ts nish:err NL2585
|
|
878
940
|
const apply = (f: (x: i32) => i32, x: i32): i32 => f(x);
|
|
@@ -884,6 +946,65 @@ export const main = (): i32 => {
|
|
|
884
946
|
};
|
|
885
947
|
```
|
|
886
948
|
|
|
949
|
+
### Function references
|
|
950
|
+
|
|
951
|
+
A **capture-free top-level function** is a value of a function type written
|
|
952
|
+
through an alias. It can sit in a local, a field, an array element or a
|
|
953
|
+
return value, be passed for an alias-typed parameter, called and compared
|
|
954
|
+
with `===` / `!==`:
|
|
955
|
+
|
|
956
|
+
```ts nish:ok
|
|
957
|
+
type Op = (x: i32) => i32;
|
|
958
|
+
|
|
959
|
+
const inc = (x: i32): i32 => x + 1;
|
|
960
|
+
const square = (x: i32): i32 => x * x;
|
|
961
|
+
|
|
962
|
+
class Stage {
|
|
963
|
+
op: Op;
|
|
964
|
+
constructor(op: Op) { this.op = op; }
|
|
965
|
+
run(x: i32): i32 { return this.op(x); }
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
export const main = (): i32 => {
|
|
969
|
+
const ops: Op[] = [inc, square];
|
|
970
|
+
const s = new Stage(ops[1]);
|
|
971
|
+
console.log(`${s.run(3)}`); // 9
|
|
972
|
+
s.op = inc;
|
|
973
|
+
console.log(`${s.run(3)}`); // 4
|
|
974
|
+
console.log(`${s.op === inc}`); // true
|
|
975
|
+
return 0;
|
|
976
|
+
};
|
|
977
|
+
```
|
|
978
|
+
|
|
979
|
+
- **Only a top-level function with no captures.** An arrow inside a function
|
|
980
|
+
is refused (NL2731 when it captures, NL2336 when it does not); so are a
|
|
981
|
+
generic (NL2725), `async` (NL2727), `declare` (NL2728) or rest-parameter
|
|
982
|
+
(NL2729) function, one with a function parameter (NL2726), and a method
|
|
983
|
+
(NL2732). A written function type has no rest, optional or defaulted
|
|
984
|
+
parameter either: `(x: i32, y?: i32) => i32` is NL2729. A guard helper,
|
|
985
|
+
a function taking a `MutexGuard`, is only ever called by name (NL2739).
|
|
986
|
+
- **No empty value but `null`.** `new Array<Op>(n)` is refused (NL2730);
|
|
987
|
+
`Op | null` is allowed and `new Array<Op | null>(n)` fills with `null`. A
|
|
988
|
+
call needs a `!== null` test first (NL2758); read a nullable field into a
|
|
989
|
+
`const` and test that. A module `const` cannot hold a reference.
|
|
990
|
+
- **A `Map` value, not a key.** `Map<K, Op>`, `Map<K, Op[]>` and
|
|
991
|
+
`Map<K, Op | null>` work; a call through what `get` returns dispatches over
|
|
992
|
+
the functions stored into any `Map` value or array of that type. A
|
|
993
|
+
function-type key is refused.
|
|
994
|
+
- **Not in a `Result` arm.** `Result<Op, E>`, `Result<Op | null, E>` and
|
|
995
|
+
`Result<T, Op>` are refused (NL2762); `Result<Op[], E>` works, or return a
|
|
996
|
+
class that holds the reference.
|
|
997
|
+
- **Called, compared, stored, passed — nothing else.** Not printed or
|
|
998
|
+
interpolated (NL2737), ordered, joined or encoded as JSON.
|
|
999
|
+
- **A function argument**: a local holding one fills an inline
|
|
1000
|
+
function-typed parameter (`const op = ops[0]; apply(op, 3)`); a field or
|
|
1001
|
+
element passed directly is refused (NL2759), a nullable local until it is
|
|
1002
|
+
narrowed (NL2760); `parallelMap`,
|
|
1003
|
+
`spawn`, `expose`, `region` and the other runners that check their body take
|
|
1004
|
+
only a named function or arrow (NL2734).
|
|
1005
|
+
- **It stays in the program**: a `-o` library cannot export it in a
|
|
1006
|
+
signature or an exported class's field (NL2733); `--link` can.
|
|
1007
|
+
|
|
887
1008
|
### Async functions
|
|
888
1009
|
|
|
889
1010
|
`async` compiles natively: a function that awaits becomes a frame and a resume
|
|
@@ -979,14 +1100,17 @@ export const main = (): i32 => {
|
|
|
979
1100
|
NL9012: each element pays for building it and for the release. Storing an
|
|
980
1101
|
allocation into another object (NL2352) and touching `Arena` (NL2351) are
|
|
981
1102
|
refused, because either would make that release unsound.
|
|
982
|
-
- **A map's result is a number, a `boolean`, an enum
|
|
983
|
-
of numbers, booleans or enums**: a string or a scalar array is copied out of
|
|
1103
|
+
- **A map's result is a number, a `boolean`, an enum (of either kind), a
|
|
1104
|
+
`string` or an array of numbers, booleans or enums**: a string or a scalar array is copied out of
|
|
984
1105
|
the worker's arena at the join. An array of strings, a nested array, a class,
|
|
985
1106
|
a `Map` or a `Set` is refused (NL2348): answer a string or a number per
|
|
986
1107
|
element and build the structure after the call. **A reduce's `T` stays a number, a
|
|
987
1108
|
`boolean` or an enum**: map strings to numbers first.
|
|
988
1109
|
- **`dst` may not be reachable from an element of `src`**: mapping `Row[]` into
|
|
989
1110
|
`f64[]` is refused when `Row` holds an `f64[]`, because it could be `dst`.
|
|
1111
|
+
A `Map` or `Set` in `Row` reaches only its keys and values, so `f` may
|
|
1112
|
+
`get`, `has` and `size` a `Map<string, i32>` (but not `set`, `delete`,
|
|
1113
|
+
`clear` or iterate it); a `Map<string, f64[]>` is refused.
|
|
990
1114
|
- **A reduce's `f` is associative and `identity` is its identity** — `0` for
|
|
991
1115
|
`+`, `1` for `*`. The array is folded in fixed blocks and the blocks combined
|
|
992
1116
|
in order, so `-` or a wrong identity is refused when `f` is an arrow of one
|
|
@@ -1053,7 +1177,7 @@ export const main = (): i32 => {
|
|
|
1053
1177
|
above the scope and `s.spawn(entry, arg, answer, 0)`. Either follows the
|
|
1054
1178
|
data-parallel rules: it writes nothing anybody else can see but what it
|
|
1055
1179
|
writes through a `Mutex`'s guard or sends on a `Channel` (below), answers a number,
|
|
1056
|
-
a `boolean`, an enum, a `string` or an array of numbers, booleans or enums
|
|
1180
|
+
a `boolean`, an enum of either kind, a `string` or an array of numbers, booleans or enums
|
|
1057
1181
|
(copied out of its arena at the join), and leaves `Arena` alone. A task cannot open a scope
|
|
1058
1182
|
of its own or call `parallelMapInto`.
|
|
1059
1183
|
- **Any argument will do** — an array, an object — because nothing writes
|
|
@@ -1120,7 +1244,7 @@ export const main = (): i32 => {
|
|
|
1120
1244
|
```
|
|
1121
1245
|
|
|
1122
1246
|
- **Only `g.value`, and only as the base of a field or element access.** Read
|
|
1123
|
-
a number, a `boolean`, an enum or a `string` through it, or store one into a
|
|
1247
|
+
a number, a `boolean`, an enum of either kind or a `string` through it, or store one into a
|
|
1124
1248
|
field or an element that already exists (a string is copied each way) (for a `Mutex<i32>`, `g.value = g.value + 1`).
|
|
1125
1249
|
Don't bind, store, return or walk `g` itself (NL2466), nor bind, store, return
|
|
1126
1250
|
or walk `g.value` or an array it holds (NL2467); store only a scalar or a
|
|
@@ -1217,6 +1341,12 @@ export const main = (): i32 => {
|
|
|
1217
1341
|
- **Add once per batch**: count into a local array, then one `add` per bin.
|
|
1218
1342
|
One `add` per value makes the cores wait on each other.
|
|
1219
1343
|
- **`AtomicI64` takes `i64` values**, exact under Node within ±2^53.
|
|
1344
|
+
- **Many counters — a histogram, a count per route — go in one atomic
|
|
1345
|
+
array**: `new AtomicI32Array(16)` (or `AtomicI64Array`) is 16 counters in
|
|
1346
|
+
one buffer, each `0`; every method takes the index first,
|
|
1347
|
+
`bins.add(b, 1)`, `bins.load(b)`, and checks it as an array index. Prefer it
|
|
1348
|
+
to an `AtomicI32[]`, whose counters are separate objects on separate cache
|
|
1349
|
+
lines. Same rules as above.
|
|
1220
1350
|
|
|
1221
1351
|
```ts nish:err NL2513
|
|
1222
1352
|
import { AtomicI32, scope } from "nish/threads";
|
|
@@ -1285,7 +1415,7 @@ export const main = (): i32 => {
|
|
|
1285
1415
|
};
|
|
1286
1416
|
```
|
|
1287
1417
|
|
|
1288
|
-
- **It carries a number, a `boolean`, an enum or a `string`** (copied in by
|
|
1418
|
+
- **It carries a number, a `boolean`, an enum of either kind or a `string`** (copied in by
|
|
1289
1419
|
`send`, out by the receive), never an array or an object.
|
|
1290
1420
|
- **Declare it as a `const` right before its scope** — in the block that holds
|
|
1291
1421
|
`using s = scope()`, or in the block around the scope's block — and hand it
|
|
@@ -1347,7 +1477,9 @@ export const main = (): i32 => {
|
|
|
1347
1477
|
|
|
1348
1478
|
- **Crosses, by copy:** a number, a `boolean`, an enum, a `string`, an array
|
|
1349
1479
|
of numbers, booleans or enums — a task's answer, a `parallelMap` element, a
|
|
1350
|
-
`Channel<string>` value, a string stored through a guard.
|
|
1480
|
+
`Channel<string>` value, a string stored through a guard. A string enum
|
|
1481
|
+
crosses as its `i32` ordinal, like a numeric one: its strings sit in a
|
|
1482
|
+
constant table every thread reads. Each thread moves
|
|
1351
1483
|
the `parallelMap` elements it answers into blocks of its own, and the caller
|
|
1352
1484
|
takes the blocks whole at the join; a task's answer under 64 KB is copied in
|
|
1353
1485
|
by the joining thread. On one thread every element still pays the move, so
|
|
@@ -1397,10 +1529,49 @@ export const main = (): i32 => {
|
|
|
1397
1529
|
};
|
|
1398
1530
|
```
|
|
1399
1531
|
|
|
1400
|
-
- **A parameter is a scalar, a `CPtr`, a borrowed `string
|
|
1401
|
-
with its count
|
|
1402
|
-
scalars are the integer and float widths,
|
|
1403
|
-
array, a class or an interface is
|
|
1532
|
+
- **A parameter is a scalar, a `CPtr`, a borrowed `string`, a `u8[]` buffer
|
|
1533
|
+
with its count or a borrowed `declare class`; a return is a scalar, a `CPtr`
|
|
1534
|
+
or a copied `string`.** The scalars are the integer and float widths,
|
|
1535
|
+
`boolean` and `void`. Any other array, a Nish class or an interface is
|
|
1536
|
+
rejected, in either position, and a `declare class` is never a return.
|
|
1537
|
+
- **A `declare class` is a C struct, lent by pointer.** Its fields are laid out
|
|
1538
|
+
in declaration order at C's alignment, and `new Name()` zero-fills it. A
|
|
1539
|
+
field is `i32`, `i64`, `u8`, `u16`, `u32`, `u64`, `f32`, `f64`, `CPtr`,
|
|
1540
|
+
`CPtr | null` or another `declare class`, embedded by value. `number` is
|
|
1541
|
+
refused by any spelling, parentheses or an alias included, because `--number-mode` picks
|
|
1542
|
+
its width; spell `i32` or `f64`. Fields only: no initializer, `readonly`,
|
|
1543
|
+
method or constructor. C borrows it for the call, may write its fields, and
|
|
1544
|
+
may not keep the address. It stays in its module: no exported signature
|
|
1545
|
+
holds one, however deep (NL2746, NL2756), and a page module (freestanding
|
|
1546
|
+
wasm, `--emit-dts`) refuses one (NL2757).
|
|
1547
|
+
|
|
1548
|
+
```ts nish:ok
|
|
1549
|
+
declare class Timespec {
|
|
1550
|
+
sec: i64;
|
|
1551
|
+
nsec: i64;
|
|
1552
|
+
}
|
|
1553
|
+
declare function clock_gettime(clock: i32, ts: Timespec): i32;
|
|
1554
|
+
|
|
1555
|
+
export const main = (): i32 => {
|
|
1556
|
+
const now = new Timespec();
|
|
1557
|
+
clock_gettime(1, now);
|
|
1558
|
+
console.log(`${now.sec >= 0}`);
|
|
1559
|
+
return 0;
|
|
1560
|
+
};
|
|
1561
|
+
```
|
|
1562
|
+
|
|
1563
|
+
```ts nish:err NL2755
|
|
1564
|
+
type Coord = number;
|
|
1565
|
+
|
|
1566
|
+
declare class Point {
|
|
1567
|
+
x: Coord;
|
|
1568
|
+
}
|
|
1569
|
+
|
|
1570
|
+
export const main = (): i32 => {
|
|
1571
|
+
return 0;
|
|
1572
|
+
};
|
|
1573
|
+
```
|
|
1574
|
+
|
|
1404
1575
|
- **A run of `u8[]` / `readonly u8[]` parameters is followed by exactly one
|
|
1405
1576
|
`u64`**, the byte count C may touch in each (`memcpy(dst: u8[], src:
|
|
1406
1577
|
readonly u8[], n: u64)`). `readonly` is C's `const`. A run without its count
|
|
@@ -1458,7 +1629,20 @@ export const main = (): i32 => {
|
|
|
1458
1629
|
freed.** `readCString(p: CPtr): string` copies the NUL-terminated bytes at
|
|
1459
1630
|
`p` into a new string; a dangling or unterminated `p` is undefined
|
|
1460
1631
|
behaviour, which is why it needs the import. It takes a `CPtr`, so narrow a
|
|
1461
|
-
`CPtr | null` with `!== null` first.
|
|
1632
|
+
`CPtr | null` with `!== null` first. A `NULL` `p` panics (`ffi-null`) before
|
|
1633
|
+
the copy, so `--deny-panics` refuses the call.
|
|
1634
|
+
- **A struct C owns is copied out with `readStruct` from `nish:unsafe`.**
|
|
1635
|
+
`const lc: Lconv = readStruct(p)` copies the bytes at `p` into a new
|
|
1636
|
+
instance of the `declare class` the context names; write the annotation,
|
|
1637
|
+
since `readStruct<Lconv>(p)` is refused (NL2763) and a call with no context
|
|
1638
|
+
is NL2764. A `NULL` `p` panics (`ffi-null`) before the copy, so
|
|
1639
|
+
`--deny-panics` refuses the call; a dangling `p`, or a class that does not
|
|
1640
|
+
match C's fields, is undefined behaviour.
|
|
1641
|
+
- **errno is read with `cErrno()` from `nish:unsafe`.** It answers the errno
|
|
1642
|
+
the most recent `declare function` call on this thread left; naming it makes
|
|
1643
|
+
every C call in the program zero errno before and save it after, so read it
|
|
1644
|
+
straight after the call you are checking. It is refused on wasm32 without
|
|
1645
|
+
`--profile wasi`.
|
|
1462
1646
|
- **A `CPtr | null` parameter takes the literal `null` or a narrowed pointer.**
|
|
1463
1647
|
`realpath(path, null)` passes `NULL`; a nullable pointer held in a variable
|
|
1464
1648
|
is NL2539, so C is never handed a `NULL` by accident.
|
|
@@ -1649,6 +1833,108 @@ export const main = (): i32 => {
|
|
|
1649
1833
|
};
|
|
1650
1834
|
```
|
|
1651
1835
|
|
|
1836
|
+
### A tree links first child and next sibling
|
|
1837
|
+
|
|
1838
|
+
A tree node keeps `first` and `next` links, **not a `kids: Node[]` per
|
|
1839
|
+
node**. Every `kids` is a 24-byte header plus a block that doubles as it
|
|
1840
|
+
grows, and the blocks it outgrows stay in the arena; a walk over `kids`
|
|
1841
|
+
follows two pointers per child where the links follow one. On a 4M-node
|
|
1842
|
+
tree the links took 0.52x the memory and 0.68x the time of `kids`.
|
|
1843
|
+
|
|
1844
|
+
```ts nish:ok
|
|
1845
|
+
class Node {
|
|
1846
|
+
kind: i32;
|
|
1847
|
+
parent: Node | null;
|
|
1848
|
+
first: Node | null = null;
|
|
1849
|
+
next: Node | null = null;
|
|
1850
|
+
|
|
1851
|
+
constructor(kind: i32, parent: Node | null) {
|
|
1852
|
+
this.kind = kind;
|
|
1853
|
+
this.parent = parent;
|
|
1854
|
+
}
|
|
1855
|
+
}
|
|
1856
|
+
|
|
1857
|
+
// `last` is the parent's last child so far, or null before the first.
|
|
1858
|
+
const add = (parent: Node, last: Node | null, kind: i32): Node => {
|
|
1859
|
+
const kid = new Node(kind, parent);
|
|
1860
|
+
if (last === null) {
|
|
1861
|
+
parent.first = kid;
|
|
1862
|
+
} else {
|
|
1863
|
+
last.next = kid;
|
|
1864
|
+
}
|
|
1865
|
+
return kid;
|
|
1866
|
+
};
|
|
1867
|
+
|
|
1868
|
+
const sum = (n: Node): i32 => {
|
|
1869
|
+
let s = n.kind;
|
|
1870
|
+
let kid = n.first;
|
|
1871
|
+
while (kid !== null) {
|
|
1872
|
+
s = s + sum(kid);
|
|
1873
|
+
kid = kid.next;
|
|
1874
|
+
}
|
|
1875
|
+
return s;
|
|
1876
|
+
};
|
|
1877
|
+
|
|
1878
|
+
export const main = (): i32 => {
|
|
1879
|
+
const root = new Node(1, null);
|
|
1880
|
+
const a = add(root, null, 2);
|
|
1881
|
+
add(root, a, 3);
|
|
1882
|
+
add(a, null, 4);
|
|
1883
|
+
console.log(`${sum(root)}`);
|
|
1884
|
+
return 0;
|
|
1885
|
+
};
|
|
1886
|
+
```
|
|
1887
|
+
|
|
1888
|
+
- Where a pass needs a node's children by index, keep a child count and a
|
|
1889
|
+
`Node[]` filled once, when the node is complete, not pushed to as each child
|
|
1890
|
+
arrives. `new Array<Node>(n)` is refused for a class, so fill it with `push`
|
|
1891
|
+
in one go.
|
|
1892
|
+
- A **hot, closed table** (a token stream, a type or symbol table) uses
|
|
1893
|
+
**columns**: one `i32[]` per field, each `new Array<i32>(n)` at its final
|
|
1894
|
+
length, a row an `i32` index, `-1` for none. Write one out per type; no
|
|
1895
|
+
generic `Pool<T>`. Measured: 0.32x the memory and 0.63x the time of `kids`.
|
|
1896
|
+
- `uncheckedGet` / `uncheckedSet` belong in that table's code only: an index
|
|
1897
|
+
out of range there is undefined behaviour, not a panic.
|
|
1898
|
+
|
|
1899
|
+
```ts nish:ok
|
|
1900
|
+
import { uncheckedGet, uncheckedSet } from "nish:unsafe";
|
|
1901
|
+
|
|
1902
|
+
// One column per field, each allocated once at its final length.
|
|
1903
|
+
class Tokens {
|
|
1904
|
+
kind: i32[];
|
|
1905
|
+
start: i32[];
|
|
1906
|
+
count: i32 = 0;
|
|
1907
|
+
|
|
1908
|
+
constructor(capacity: i32) {
|
|
1909
|
+
this.kind = new Array<i32>(capacity);
|
|
1910
|
+
this.start = new Array<i32>(capacity);
|
|
1911
|
+
}
|
|
1912
|
+
|
|
1913
|
+
add(kind: i32, start: i32): i32 {
|
|
1914
|
+
if (this.count >= this.kind.length) {
|
|
1915
|
+
return -1;
|
|
1916
|
+
}
|
|
1917
|
+
const id = this.count;
|
|
1918
|
+
uncheckedSet(this.kind, id, kind);
|
|
1919
|
+
uncheckedSet(this.start, id, start);
|
|
1920
|
+
this.count = id + 1;
|
|
1921
|
+
return id;
|
|
1922
|
+
}
|
|
1923
|
+
}
|
|
1924
|
+
|
|
1925
|
+
export const main = (): i32 => {
|
|
1926
|
+
const t = new Tokens(3);
|
|
1927
|
+
t.add(7, 0);
|
|
1928
|
+
t.add(9, 4);
|
|
1929
|
+
let s = 0;
|
|
1930
|
+
for (let i = 0; i < t.count; i++) {
|
|
1931
|
+
s = s + uncheckedGet(t.kind, i) * uncheckedGet(t.start, i);
|
|
1932
|
+
}
|
|
1933
|
+
console.log(`${s}`);
|
|
1934
|
+
return 0;
|
|
1935
|
+
};
|
|
1936
|
+
```
|
|
1937
|
+
|
|
1652
1938
|
### Object literals
|
|
1653
1939
|
|
|
1654
1940
|
An object literal takes its type from context — a variable annotation, the
|
|
@@ -1727,6 +2013,43 @@ export const main = (): i32 => {
|
|
|
1727
2013
|
point: `Kind` and `i32` never convert in either direction. Members must be
|
|
1728
2014
|
numeric literals. `===` and `!==` are the **only** operators — no arithmetic,
|
|
1729
2015
|
no bitwise, so **bit flags stay `i32` module constants**.
|
|
2016
|
+
- A **string enum** gives every member a string literal (`Admin = "admin"`),
|
|
2017
|
+
and is just as distinct: it is stored as its member's `i32` ordinal, `===`,
|
|
2018
|
+
`!==` and `switch` compare ordinals, and `String(r)` is the only way to its
|
|
2019
|
+
string (one load from a constant table, no allocation). `Role` and `string`
|
|
2020
|
+
never convert either way — `r === "admin"` is NL2788,
|
|
2021
|
+
`const s: string = r` and `` `${r}` `` NL2789, `const r: Role = "admin"`
|
|
2022
|
+
NL2790 — because a string compare or a hidden conversion is exactly the cost
|
|
2023
|
+
the ordinal exists to avoid: compare members, or write `String(r)` once.
|
|
2024
|
+
Mixing string and numeric members is NL1043, a member without a value
|
|
2025
|
+
NL1064, a template or computed value NL1065/NL1066, two members of one string
|
|
2026
|
+
NL2786, a value that is not valid UTF-8 NL2787. A `Role | null` is NL2010, as for every enum. There is no
|
|
2027
|
+
`Role.parse` yet: test `s === String(Role.Admin)` per member, or decode it
|
|
2028
|
+
with typed JSON.
|
|
2029
|
+
|
|
2030
|
+
```ts nish:ok
|
|
2031
|
+
enum Role {
|
|
2032
|
+
Admin = "admin",
|
|
2033
|
+
Guest = "guest",
|
|
2034
|
+
}
|
|
2035
|
+
|
|
2036
|
+
const parse = (s: string): Role => (s === String(Role.Admin) ? Role.Admin : Role.Guest);
|
|
2037
|
+
|
|
2038
|
+
const rank = (r: Role): i32 => {
|
|
2039
|
+
switch (r) {
|
|
2040
|
+
case Role.Admin:
|
|
2041
|
+
return 2;
|
|
2042
|
+
default:
|
|
2043
|
+
return 1;
|
|
2044
|
+
}
|
|
2045
|
+
};
|
|
2046
|
+
|
|
2047
|
+
export const main = (): i32 => {
|
|
2048
|
+
const r = parse("admin");
|
|
2049
|
+
console.log(`${String(r)} ${rank(r)}`);
|
|
2050
|
+
return r === Role.Admin ? 0 : 1;
|
|
2051
|
+
};
|
|
2052
|
+
```
|
|
1730
2053
|
- **A member is also a type.** `Kind.While` as an annotation is a slot that
|
|
1731
2054
|
holds exactly that member — the shape of a tag field that says which case
|
|
1732
2055
|
its object is. Only the member's own constant (or a value already of that
|
|
@@ -1838,10 +2161,15 @@ export const main = (): i32 => {
|
|
|
1838
2161
|
NL2535, one typed as the whole enum (`readonly kind: Kind`) NL2559. Any
|
|
1839
2162
|
other union is still NL1053.
|
|
1840
2163
|
- A union is a local, parameter, field, return, array element, or nullable
|
|
1841
|
-
(`Shape | null`)
|
|
2164
|
+
(`Shape | null`), and a `Map`'s value is any of those (`Map<string, Shape>`,
|
|
2165
|
+
`Map<string, Shape[]>`, `Map<string, Shape | null>`), and a type argument:
|
|
2166
|
+
`Box<Shape>`, `Stack<Shape>`, a generic call binding `T` to a union,
|
|
2167
|
+
`Result<Shape, E>` / `Result<T, Shape>`, and `nish/map`'s `getOrInsert` /
|
|
2168
|
+
`reserve` on a `Map<K, Shape>`. An alias may name another union, which is flattened. A
|
|
1842
2169
|
variant, or a smaller union, converts into it wherever the union is
|
|
1843
2170
|
expected — argument, `return`, `push`, an annotated array literal, a
|
|
1844
|
-
ternary arm or `??` default whose other side is the union
|
|
2171
|
+
ternary arm or `??` default whose other side is the union, and a generic's
|
|
2172
|
+
`T` bound to it (`new Box<Shape>(new Circle())`, `Ok(new Square())`). A class that
|
|
1845
2173
|
implements an interface variant converts to that interface first. A union
|
|
1846
2174
|
crosses modules but not a sidecar (NL4009).
|
|
1847
2175
|
- **Test the tag to read a variant.** Before a test, the tag is the only
|
|
@@ -1909,11 +2237,13 @@ export const main = (): i32 => {
|
|
|
1909
2237
|
falls back to every member the body stored
|
|
1910
2238
|
anywhere or the whole type, which accepts a few comparisons `tsc` refuses
|
|
1911
2239
|
(TS2367; LANGUAGE.md, "Accepted here, refused by `tsc`").
|
|
1912
|
-
- **Refused by design:**
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
2240
|
+
- **Refused by design:** unions as `Map`/`Set` keys (NL2353), a generic
|
|
2241
|
+
class as a variant (NL2522), covariant arrays (`Circle[]` is not
|
|
2242
|
+
`Shape[]`), inferred unions (an unannotated ternary or array of two
|
|
2243
|
+
variants, or one a generic call would infer: NL2172), a union meeting a
|
|
2244
|
+
constraint `<T extends I>` (NL2328), and a union inside a `Secret`
|
|
2245
|
+
(NL2428), a typed-JSON class (NL2486) or a C header / N-API signature
|
|
2246
|
+
(NL4009), generic instance or not.
|
|
1917
2247
|
- **Declare what you store.** A store of a value that is only some of the
|
|
1918
2248
|
variants into a union slot is NL2534, because `tsc` would narrow the slot
|
|
1919
2249
|
from there on. Declare the slot as the variant, or store a value of the
|
|
@@ -1972,7 +2302,9 @@ export const main = (): i32 => {
|
|
|
1972
2302
|
- Functions and enums may be renamed on import; classes and interfaces may
|
|
1973
2303
|
not — the type name is part of the ABI.
|
|
1974
2304
|
- Import cycles are allowed; a shared dependency is compiled once.
|
|
1975
|
-
- **A function name is unique across the whole program**, exported or not
|
|
2305
|
+
- **A function name is unique across the whole program**, exported or not
|
|
2306
|
+
(a proposal to relax this for private functions is
|
|
2307
|
+
[WP57](https://github.com/amritk/nish/blob/main/docs/wp57-module-scoped-names.md); it has not shipped).
|
|
1976
2308
|
- An `export`ed function is an external C-ABI symbol; every other function gets
|
|
1977
2309
|
`internal` linkage so LLVM may inline or drop it.
|
|
1978
2310
|
- **So an exported function is not named after a C library function**
|
|
@@ -1995,7 +2327,16 @@ export const main = (): i32 => {
|
|
|
1995
2327
|
- `let` / `const` need an initializer and take their type from it; an
|
|
1996
2328
|
annotation must match **exactly**. `const` freezes the binding, not the
|
|
1997
2329
|
contents: `xs[0] = 1` and `xs.push(1)` on a `const xs` are fine.
|
|
1998
|
-
- `var` is forbidden.
|
|
2330
|
+
- `var` is forbidden.
|
|
2331
|
+
- A local or a `for...of` head may destructure: `const { x, y: py } = p`,
|
|
2332
|
+
`let [a, , c] = xs`, `for (const { x, y } of points)`. Each name is one
|
|
2333
|
+
field read, or one bounds-checked element read (past the end panics; it is
|
|
2334
|
+
never `undefined`). No defaults, rests, nested patterns, computed keys or
|
|
2335
|
+
assignment patterns; no pattern over a `Map`, a `string` or a nullable
|
|
2336
|
+
value, and no pattern as a parameter (`const { w, h } = s` over a
|
|
2337
|
+
parameter `s` is fine). A module constant may not destructure either, because a
|
|
2338
|
+
module constant is a compile-time value folded into each use, and a
|
|
2339
|
+
pattern's names are reads of a receiver at run time.
|
|
1999
2340
|
- **Semicolons are optional**, where TypeScript would insert one: at a line
|
|
2000
2341
|
break, before `}` and at the end of the file. It is TypeScript's rule, so a
|
|
2001
2342
|
line starting with `(` or `[` continues the one before it, and `return`
|
|
@@ -2274,7 +2615,16 @@ a `\u` escape `nish/json` decodes) is one unit per byte, and counts its bytes.
|
|
|
2274
2615
|
|
|
2275
2616
|
**Files and the system.** `readFileSync(path)` (exits 1 on failure),
|
|
2276
2617
|
`readFileSyncOrNull(path)` (`string | null`), `readFileBytesSync(path)`
|
|
2277
|
-
(`u8[] | null`, the bytes as they are on disk),
|
|
2618
|
+
(`u8[] | null`, the bytes as they are on disk), and a file a window at a
|
|
2619
|
+
time: `fileOpen(path)` (an `i32` descriptor for a regular file, or a negative
|
|
2620
|
+
Linux errno: `-2` missing, `-13` denied, `-21` a directory, `-22` not a
|
|
2621
|
+
regular file), `fileReadAt(fd, buf, off, len, pos)` (at most `len` bytes from
|
|
2622
|
+
`i64` byte `pos` into `buf[off, off + len)`, a `u8[]`; the count, `0` at the
|
|
2623
|
+
end, short reads allowed so loop; the window panics like `netRead`'s),
|
|
2624
|
+
`fileSize(fd)` (an `i64`, which can change between calls), `fileClose(fd)`
|
|
2625
|
+
(never call it twice: the number may name another file by then); all four
|
|
2626
|
+
`fs.read`, refused on freestanding `wasm32` (NL2718) but not under
|
|
2627
|
+
`--profile wasi`; `writeFileSync(path, data)`,
|
|
2278
2628
|
`appendFileSync(path, data)`, `writeFileBytesSync(path, bytes)` (a `u8[]` as
|
|
2279
2629
|
it is; `i32`: the length, or a negative errno), `renameSync(from, to)` (`0` or
|
|
2280
2630
|
a negative errno; atomic on one filesystem, `-18` across two, so write the
|
|
@@ -2291,6 +2641,9 @@ bytes, no `.`/`..`), `spawnSync(argv)`, `spawnSyncTo(argv, outPath, errPath)`,
|
|
|
2291
2641
|
`spawnPiped(argv, stdin, stdout, stderr)` (stdin from a `u8[]`, both outputs
|
|
2292
2642
|
appended to `u8[]`s, the status; `-2` past 16 MiB; the way to hand a child a
|
|
2293
2643
|
secret, never argv or the environment),
|
|
2644
|
+
`spawnPipedWithin(argv, stdin, stdout, stderr, timeoutMs)` (the same with a
|
|
2645
|
+
deadline in milliseconds, negative for none: `-3` when it passes, the child
|
|
2646
|
+
killed and its bytes so far kept; only the child's pid is killed),
|
|
2294
2647
|
`getenv(name)` (`string | null` — unset and empty are different answers),
|
|
2295
2648
|
`realpathSync(path)` (`string | null`; symbolic links resolved, absolute, and
|
|
2296
2649
|
`null` when it does not resolve),
|
|
@@ -2435,7 +2788,9 @@ order, SameValueZero keys (`-0` is `+0`, `NaN` finds `NaN`). What they have is
|
|
|
2435
2788
|
exactly `size` (a read-only `number`), `get(k)`, `set(k, v)` / `add(x)` (both
|
|
2436
2789
|
answer the receiver, so they chain), `has(k)`, `delete(k)` (answers whether it
|
|
2437
2790
|
was there) and `clear()`, and `keys()` / `values()` as the iterable of a
|
|
2438
|
-
`for...of` and nowhere else
|
|
2791
|
+
`for...of` and nowhere else, and `forEach(f)`: `m.forEach((value, key) => ...)`
|
|
2792
|
+
and `s.forEach((x) => ...)` compile to that `for...of` walk with `f` inlined,
|
|
2793
|
+
and answer `void`. `entries` is refused by name.
|
|
2439
2794
|
|
|
2440
2795
|
```ts nish:ok-body
|
|
2441
2796
|
const seen = new Set<string>();
|
|
@@ -2511,8 +2866,8 @@ console.log(`${total}`); // 121
|
|
|
2511
2866
|
|
|
2512
2867
|
- An iterator is not a value: `keys()` / `values()` stored, passed, returned or
|
|
2513
2868
|
spread are refused. Pass the map itself and walk it where it is used.
|
|
2514
|
-
- `for (const e of m)` over a `Map` itself is refused, because
|
|
2515
|
-
`[key, value]`
|
|
2869
|
+
- `for (const e of m)` over a `Map` itself is refused, because its
|
|
2870
|
+
`[key, value]` pairs are two-type tuples: walk `m.keys()` and call `m.get(k)`.
|
|
2516
2871
|
|
|
2517
2872
|
```ts nish:err-body NL2375
|
|
2518
2873
|
const m = new Map<string, i32>();
|
|
@@ -2555,14 +2910,18 @@ export const main = (): i32 => {
|
|
|
2555
2910
|
|
|
2556
2911
|
`jsonDecode(d, out)` reads one JSON object into a class and `jsonEncode(w,
|
|
2557
2912
|
value)` writes one; the compiler writes the code at each call from the class's
|
|
2558
|
-
fields. A field is `i32`, `u32`, `i64`, `u64`, `f64`, `boolean`, `string`,
|
|
2559
|
-
|
|
2913
|
+
fields. A field is `i32`, `u32`, `i64`, `u64`, `f64`, `boolean`, `string`, an
|
|
2914
|
+
enum, a class, an array of one of those, a `Map<string, V>` of any of
|
|
2560
2915
|
those, or a `string`, class, array or map `| null`; anything else is refused at
|
|
2561
2916
|
the call (NL2485), a `Map` with non-`string` keys and a `Set` included, and so
|
|
2562
2917
|
is a value that is not a class (NL2486). Decoding is strict: every field
|
|
2563
2918
|
required, each key once, an unknown key an error unless `d.ignoreUnknown`, and
|
|
2564
2919
|
every outcome a sticky negative code in `d.failed`, never a panic. An enum is
|
|
2565
|
-
|
|
2920
|
+
read and written as a numeric one's number or a string one's string, and a
|
|
2921
|
+
value that is no member's is `JSON_DECODE_TYPE` (the field keeps its member) —
|
|
2922
|
+
so a string enum field is how a program checks a closed set of strings from
|
|
2923
|
+
input (`role: Role`, `{"role":"admin"}`); a `Role | null` field is NL2010 and a
|
|
2924
|
+
`Map` keyed by an enum NL2485; a
|
|
2566
2925
|
`u64` is exact to 2^64 - 1, and negative is `JSON_DECODE_RANGE`; a map is
|
|
2567
2926
|
emptied and filled in the input's key order, a repeated key an error, and
|
|
2568
2927
|
more keys over all the maps of one decode than `d.maxMapKeys` (4,096 unless
|
|
@@ -2578,7 +2937,18 @@ literal (NL2493), an unknown option (NL2494), a name that is no field (NL2495),
|
|
|
2578
2937
|
a rename to a non-string (NL2496) or to a key that is not valid UTF-8
|
|
2579
2938
|
(NL2499), two fields with one key (NL2497). A
|
|
2580
2939
|
`JsonNumber` field keeps a number's text byte for byte (`text`, `i64`, `u64`,
|
|
2581
|
-
`f64`, `setText`).
|
|
2940
|
+
`f64`, `setText`). A tagged union of classes is a field, an array element or
|
|
2941
|
+
`jsonEncode`'s value too: the object with its tag key first, the tag the
|
|
2942
|
+
member's name (a string enum's member's string) or the variant's `tag`
|
|
2943
|
+
option. Decode one with
|
|
2944
|
+
`const u = jsonDecodeUnion(d, prev)` (never `jsonDecode`, NL2719, and no type
|
|
2945
|
+
argument): it answers `prev` refilled when the tag matches, else a new variant,
|
|
2946
|
+
and `prev` on failure (only at the top: a nested union slot may hold the new
|
|
2947
|
+
variant, half read, so check `d.failed`); a bad tag is `JSON_DECODE_TAG`.
|
|
2948
|
+
`tag: ""` is the same as no `tag`. Every variant writes its
|
|
2949
|
+
tag under one key (NL2721) as a different string (NL2720). A `tag` on a class
|
|
2950
|
+
no union holds does nothing, and a JSON call on that class refuses its
|
|
2951
|
+
enum-member field.
|
|
2582
2952
|
|
|
2583
2953
|
```ts nish:ok
|
|
2584
2954
|
import { JsonWriter } from "nish/json";
|
|
@@ -2712,7 +3082,14 @@ every pass's string, because nothing frees a value a later pass replaced:
|
|
|
2712
3082
|
value with `const` inside the loop when only the pass reads it, or keep
|
|
2713
3083
|
numbers across passes and build the value once after the loop. A server, or
|
|
2714
3084
|
anything that runs for a long time, should compile with `--deny-retention`,
|
|
2715
|
-
which makes this warning and the
|
|
3085
|
+
which makes this warning and the four like it errors.
|
|
3086
|
+
|
|
3087
|
+
**Build a request's temporaries in an arena block.** A pass of a loop with
|
|
3088
|
+
no bound on its passes (`while (true)`, a server's poll loop) that calls
|
|
3089
|
+
`accept`, `respond` or anything else that stores is refused its own scope,
|
|
3090
|
+
so a reply string it builds stays until the loop ends: NL9018. Build it in
|
|
3091
|
+
`{ using a = arena(); ... }` inside the loop body, copy what must outlive the
|
|
3092
|
+
block into a buffer made before the loop, and call what stores after it.
|
|
2716
3093
|
|
|
2717
3094
|
Everything else is bumped from the arena, which is released when `main`
|
|
2718
3095
|
returns. To give memory back sooner, scope it with `using a = arena()`;
|
|
@@ -2761,7 +3138,7 @@ the module (NL4015).
|
|
|
2761
3138
|
|
|
2762
3139
|
## Recipes for what is missing
|
|
2763
3140
|
|
|
2764
|
-
**Iterate and accumulate** — there is no `reduce`
|
|
3141
|
+
**Iterate and accumulate** — there is no `reduce` (`map`, `filter`, `forEach`, `some`, `every`, `findIndex` and `slice` work, but a callback may not assign a local of its caller); fold in a loop:
|
|
2765
3142
|
|
|
2766
3143
|
```ts nish:ok-body
|
|
2767
3144
|
const xs: i32[] = [1, 2, 3];
|
|
@@ -2816,6 +3193,16 @@ never call it on secret data, because its time says where the match is.
|
|
|
2816
3193
|
(No block: a program importing `nish/text` writes two `.ll` files;
|
|
2817
3194
|
`tests/link/std_text_index_of_any` is its program.)
|
|
2818
3195
|
|
|
3196
|
+
**Format a number with fixed digits, or split with a limit** — there are no
|
|
3197
|
+
methods on a number and no optional parameters, so `x.toFixed(n)` is
|
|
3198
|
+
`toFixed(x, n)` and `text.split(sep, limit)` is `splitLimit(text, sep, limit)`,
|
|
3199
|
+
both from `nish/text` and both answering what JavaScript does. `toFixed`
|
|
3200
|
+
rounds the exact binary value (`toFixed(1.005, 2)` is `"1.00"`) and panics
|
|
3201
|
+
outside 0 to 100 digits; `splitLimit` keeps the first `limit` pieces, a
|
|
3202
|
+
negative limit keeps all of them, and an empty separator panics.
|
|
3203
|
+
(No block, as for `nish/text`; `tests/link/std_text_to_fixed` and
|
|
3204
|
+
`tests/link/std_text_split_limit` are its programs.)
|
|
3205
|
+
|
|
2819
3206
|
**Match a pattern** — there is no `RegExp` and no `/re/` literal:
|
|
2820
3207
|
`regexCompile(pattern, flags)` from `nish/regex` answers a
|
|
2821
3208
|
`Result<Regex, string>`, the error text naming the byte. The syntax is
|
|
@@ -3131,22 +3518,25 @@ Run it. `nish file.ts --json` is one command and it is the only proof.
|
|
|
3131
3518
|
in an object-literal property or a method argument expecting a width?
|
|
3132
3519
|
6. Is every `Result` read, and is every `.value` behind an `isOk()`?
|
|
3133
3520
|
7. Is every nullable narrowed with `!== null` before it is touched?
|
|
3134
|
-
8.
|
|
3135
|
-
|
|
3136
|
-
|
|
3521
|
+
8. Is every local read, and does every statement do something? An unread
|
|
3522
|
+
local, `x = x`, `a === a` or a repeated `else if` is an error
|
|
3523
|
+
([Lines that type-check and are still refused](#lines-that-type-check-and-are-still-refused)).
|
|
3524
|
+
9. Did you use `throw`, `try`, `any`, `undefined` or `??` (outside a `T | null`, a chain or `Map.get`), `?.` without a `??`, a cast, a
|
|
3525
|
+
stored or returned closure, a generic *alias*, or `extends`?
|
|
3526
|
+
10. Does it reach only what you meant it to? `nish file.ts --emit-capabilities
|
|
3137
3527
|
caps.json` lists every capability each function can reach — files, processes,
|
|
3138
3528
|
the network, the environment, the clock, entropy, signals, `exit`, C calls —
|
|
3139
3529
|
with the call chain that reaches it, and `nish run --capabilities file.ts`
|
|
3140
3530
|
prints the one-line summary ([LANGUAGE.md](LANGUAGE.md#capabilities)).
|
|
3141
3531
|
A package that must not touch the network says so in `package.json`
|
|
3142
3532
|
([Holding it to its capabilities](#holding-it-to-its-capabilities)).
|
|
3143
|
-
|
|
3533
|
+
11. Must it never panic? Compile with `--deny-panics` (or list the module in
|
|
3144
3534
|
`package.json`'s `"nish": { "noPanic": [...] }`): every index, division,
|
|
3145
3535
|
signed `+ - *`, `pop`, range entry, `expect` and exiting call it cannot
|
|
3146
3536
|
prove is an error
|
|
3147
3537
|
naming the guard ([Proving it cannot panic](#proving-it-cannot-panic)); an
|
|
3148
3538
|
`uncheckedGet` or `uncheckedSet` behind its `nish:unsafe` import is allowed.
|
|
3149
|
-
|
|
3539
|
+
12. If you are adding to this repository: `npm run check` and the touched
|
|
3150
3540
|
`node tests/run.js` sections green locally, every CI `test` shard green
|
|
3151
3541
|
([CLAUDE.md](../CLAUDE.md#definition-of-done)), and a new construct ships a
|
|
3152
3542
|
golden `.ll`, an `llvm-as` pass, a native round trip, a negative test, its
|