nish 0.39.0 → 0.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.md +190 -555
  2. package/docs/AI.md +112 -33
  3. package/docs/INSTALL.md +79 -133
  4. package/llms.txt +2 -9
  5. package/package.json +17 -19
  6. package/runtime/nish.d.ts +21 -17
  7. package/runtime/nish.h +10 -0
  8. package/runtime/page-frame.d.ts +123 -0
  9. package/runtime/page-frame.mjs +736 -0
  10. package/runtime/page-game.d.ts +132 -0
  11. package/runtime/page-game.mjs +738 -0
  12. package/runtime/runtime-aes.c +85 -8
  13. package/runtime/runtime-bytes.c +88 -4
  14. package/runtime/runtime-net.c +32 -0
  15. package/runtime/runtime-sandbox.c +55 -28
  16. package/runtime/runtime-uring.c +1194 -0
  17. package/runtime/runtime-wasm.c +422 -0
  18. package/runtime/vite.mjs +1 -1
  19. package/scripts/build.sh +22 -6
  20. package/std/README.md +74 -87
  21. package/std/array.ts +36 -3
  22. package/std/collections.ts +51 -0
  23. package/std/crypto/hmac.ts +37 -10
  24. package/std/crypto/p256.ts +1388 -2664
  25. package/std/crypto/pki.ts +116 -4
  26. package/std/crypto/sha256.ts +34 -6
  27. package/std/crypto/x509.ts +7 -0
  28. package/std/host/game.ts +273 -0
  29. package/std/input.ts +56 -0
  30. package/std/json-tokenizer.ts +325 -112
  31. package/std/json-typed.ts +43 -8
  32. package/std/json-value.ts +144 -3
  33. package/std/json.ts +63 -8
  34. package/std/net/fetch.ts +22 -4
  35. package/std/net/http-server.ts +3382 -0
  36. package/std/net/http1-client-codec.ts +6 -2
  37. package/std/net/http1-codec.ts +137 -12
  38. package/std/net/http1-server.ts +83 -29
  39. package/std/net/http2.ts +47 -14
  40. package/std/net/http3-server.ts +29 -3
  41. package/std/net/http3.ts +180 -7
  42. package/std/net/prefork.ts +49 -13
  43. package/std/net/quic-recovery.ts +240 -9
  44. package/std/net/quic-stream.ts +21 -1
  45. package/std/net/quic.ts +98 -4
  46. package/std/net/router.ts +378 -31
  47. package/std/net/serve.ts +873 -65
  48. package/std/net/tls/verify.ts +19 -1
  49. package/std/net/url.ts +83 -35
  50. package/std/net/websocket.ts +74 -1
  51. package/std/net/webtransport.ts +7 -1
  52. package/std/raster.ts +837 -0
  53. package/std/release.ts +593 -0
  54. package/std/synth.ts +143 -0
  55. package/std/temporal.ts +3091 -0
  56. package/std/threads.ts +298 -0
  57. package/std/yaml-json.ts +368 -28
  58. package/std/yaml.ts +122 -27
  59. package/scripts/bootstrap.sh +0 -375
  60. package/scripts/build-id-smoke.sh +0 -28
  61. package/scripts/changelog-gen.mjs +0 -649
  62. package/scripts/changelog-section.sh +0 -28
  63. package/scripts/check-hardening.mjs +0 -202
  64. package/scripts/ci-profile.mjs +0 -200
  65. package/scripts/codes-registry.js +0 -85
  66. package/scripts/fuzz.sh +0 -280
  67. package/scripts/gen-diagnostic-codes.mjs +0 -243
  68. package/scripts/gen-json-pow5.mjs +0 -130
  69. package/scripts/gen-p256-table.mjs +0 -177
  70. package/scripts/gen-pow10-table.py +0 -80
  71. package/scripts/gen-regex-unicode.mjs +0 -822
  72. package/scripts/gen-union-scale.mjs +0 -294
  73. package/scripts/nish-compiler.sh +0 -19
  74. package/scripts/platform-package.mjs +0 -93
  75. package/scripts/security-scope.mjs +0 -139
  76. package/scripts/shard-costs.mjs +0 -429
  77. package/scripts/size-report.sh +0 -84
  78. package/scripts/smoke.sh +0 -105
  79. package/scripts/std-module-paths.mjs +0 -25
  80. package/scripts/undocumented.txt +0 -14
  81. package/scripts/verify-binaries.sh +0 -214
@@ -1,28 +0,0 @@
1
- #!/usr/bin/env bash
2
- # Print the CHANGELOG.md section for one version, for use as GitHub release notes.
3
- #
4
- # scripts/changelog-section.sh <version> e.g. 0.2.0 (a leading `v` is ignored)
5
- #
6
- # Prints the body between `## [<version>]` and the next `## ` heading. If the
7
- # version has no section yet, prints the `## [Unreleased]` body instead and
8
- # says so on stderr, so a release never ships with empty notes.
9
- set -euo pipefail
10
- cd "$(dirname "$0")/.."
11
-
12
- version=${1:?usage: scripts/changelog-section.sh <version>}
13
- version=${version#v}
14
-
15
- section() { # section <heading-text>
16
- awk -v h="## [$1]" '
17
- index($0, h) == 1 { on = 1; next }
18
- on && /^## / { exit }
19
- on { print }
20
- ' CHANGELOG.md
21
- }
22
-
23
- body=$(section "$version")
24
- if [ -z "$(printf '%s' "$body" | tr -d '[:space:]')" ]; then
25
- echo "warning: CHANGELOG.md has no [$version] section; using [Unreleased]" >&2
26
- body=$(section Unreleased)
27
- fi
28
- printf '%s\n' "$body"
@@ -1,202 +0,0 @@
1
- #!/usr/bin/env node
2
- // Reads the hardening a native binary carries, from its headers rather than
3
- // from the flags that should have put it there.
4
- //
5
- // node scripts/check-hardening.mjs <binary> [--imports name,name,...]
6
- //
7
- // An ELF binary must be position independent (DYN), carry GNU_RELRO, bind now
8
- // (DF_BIND_NOW or DF_1_NOW), have a GNU_STACK header without E, and carry
9
- // control-flow protection: the x86 feature note naming IBT and SHSTK, or on
10
- // AArch64 the feature note naming BTI and PAC, or failing that `bti` and
11
- // `paciasp` in its code. The note is the linker's AND over every object, the C
12
- // library's start files included, so the instructions are what show that the
13
- // objects scripts/build.sh compiled carry the protection when a start file
14
- // does not. A Mach-O binary must be MH_PIE and must not be
15
- // MH_ALLOW_STACK_EXECUTION.
16
- //
17
- // `--imports` names undefined symbols the binary must import, without
18
- // Mach-O's leading underscore: `__stack_chk_fail` shows the stack protector
19
- // reached it, and a `__*_chk` function shows _FORTIFY_SOURCE did. Whether one
20
- // appears depends on the code linked, so the caller names them. Exits 0 when
21
- // every property holds, 1 naming the ones that do not, and 2 when no tool to
22
- // read the binary is installed. tests/run.js ("hardening") and CI's
23
- // `bootstrap` job call it (docs/security/runtime.md, RT-HARDEN).
24
-
25
- import { spawnSync } from "node:child_process"
26
- import fs from "node:fs"
27
- import path from "node:path"
28
-
29
- /** The first of `names` that runs, or null. */
30
- const firstTool = (names) =>
31
- names.find((name) => spawnSync(name, ["--version"], { encoding: "utf8" }).status === 0) ?? null
32
-
33
- const run = (tool, args) => {
34
- const r = spawnSync(tool, args, { encoding: "utf8", maxBuffer: 256 * 1024 * 1024 })
35
- return r.status === 0 ? r.stdout : null
36
- }
37
-
38
- const ELF_MAGIC = "7f454c46"
39
- const MACHO_MAGICS = ["cffaedfe", "cefaedfe", "feedfacf", "feedface"]
40
-
41
- const magicOf = (file) => {
42
- const fd = fs.openSync(file, "r")
43
- const buf = Buffer.alloc(4)
44
- fs.readSync(fd, buf, 0, 4, 0)
45
- fs.closeSync(fd)
46
- return buf.toString("hex")
47
- }
48
-
49
- const elfProblems = (file, imports) => {
50
- const readelf = firstTool(["llvm-readelf", "llvm-readelf-18", "readelf"])
51
- if (readelf === null) {
52
- return { skip: "no llvm-readelf or readelf on PATH", problems: [] }
53
- }
54
- const out = run(readelf, ["-W", "-h", "-l", "-d", "-n", "--dyn-syms", file])
55
- if (out === null) {
56
- return { skip: null, problems: [`${readelf} could not read ${file}`] }
57
- }
58
- const problems = []
59
- const type = /^\s*Type:\s+(\S+)/m.exec(out)
60
- if (type === null || type[1] !== "DYN") {
61
- problems.push(`not position independent: Type is ${type === null ? "missing" : type[1]}, not DYN`)
62
- }
63
- if (!/^\s*GNU_RELRO\s/m.test(out)) {
64
- problems.push("no GNU_RELRO program header (-z relro)")
65
- }
66
- const flags = /\(FLAGS\)\s+(.*)$/m.exec(out)
67
- const flags1 = /\(FLAGS_1\)\s+(.*)$/m.exec(out)
68
- const bindNow =
69
- (flags !== null && /\bBIND_NOW\b/.test(flags[1])) || (flags1 !== null && /\bNOW\b/.test(flags1[1]))
70
- if (!bindNow) {
71
- problems.push("does not bind now: no BIND_NOW in FLAGS or NOW in FLAGS_1 (-z now), so RELRO is partial")
72
- }
73
- const stack = /^\s*GNU_STACK\s+(?:0x[0-9a-f]+\s+){5}([RWE ]{3})/m.exec(out)
74
- if (stack === null) {
75
- problems.push("no GNU_STACK program header, so the stack may be executable (-z noexecstack)")
76
- } else if (stack[1].includes("E")) {
77
- problems.push(`the stack is executable: GNU_STACK flags are "${stack[1].trim()}"`)
78
- }
79
- const machine = /^\s*Machine:\s+(.*)$/m.exec(out)
80
- const machineName = machine === null ? "" : machine[1]
81
- if (/X86-64/.test(machineName)) {
82
- const note = /x86 feature:\s*(.*)$/m.exec(out)
83
- if (note === null || !/\bIBT\b/.test(note[1]) || !/\bSHSTK\b/.test(note[1])) {
84
- problems.push(
85
- `no control-flow protection: the x86 feature note is ${note === null ? "missing" : `"${note[1].trim()}"`}, not IBT, SHSTK (-fcf-protection=full)`
86
- )
87
- }
88
- } else if (/AArch64/.test(machineName)) {
89
- const note = /AArch64 feature:\s*(.*)$/m.exec(out)
90
- if (note === null || !/\bBTI\b/.test(note[1]) || !/\bPAC\b/.test(note[1])) {
91
- problems.push(...aarch64CodeProblems(file))
92
- }
93
- }
94
- const undefinedNames = new Set(
95
- out
96
- .split("\n")
97
- .filter((line) => /\sUND\s/.test(line))
98
- .map((line) => line.trim().split(/\s+/).at(-1).replace(/@.*$/, ""))
99
- )
100
- for (const name of imports) {
101
- if (!undefinedNames.has(name)) {
102
- problems.push(`does not import ${name}`)
103
- }
104
- }
105
- return { skip: null, problems }
106
- }
107
-
108
- /** Without the feature note, the protection shown in the instructions themselves. */
109
- const aarch64CodeProblems = (file) => {
110
- const objdump = firstTool(["llvm-objdump", "llvm-objdump-18", "objdump"])
111
- if (objdump === null) {
112
- return ["no AArch64 feature note naming BTI and PAC, and no llvm-objdump to look for the instructions"]
113
- }
114
- const code = run(objdump, ["-d", "--no-show-raw-insn", file]) ?? ""
115
- const problems = []
116
- if (!/\sbti\b/.test(code)) {
117
- problems.push(
118
- "no BTI: neither the AArch64 feature note nor a `bti` instruction (-mbranch-protection=standard)"
119
- )
120
- }
121
- if (!/\spaciasp\b/.test(code)) {
122
- problems.push(
123
- "no return-address signing: neither the AArch64 feature note nor a `paciasp` instruction (-mbranch-protection=standard)"
124
- )
125
- }
126
- return problems
127
- }
128
-
129
- const machoProblems = (file, imports) => {
130
- const readobj = firstTool(["llvm-readobj", "llvm-readobj-18"])
131
- if (readobj === null) {
132
- return { skip: "no llvm-readobj on PATH", problems: [] }
133
- }
134
- const header = run(readobj, ["--file-headers", file])
135
- if (header === null) {
136
- return { skip: null, problems: [`${readobj} could not read ${file}`] }
137
- }
138
- const problems = []
139
- if (!/\bMH_PIE\b/.test(header)) {
140
- problems.push("not position independent: no MH_PIE flag")
141
- }
142
- if (/\bMH_ALLOW_STACK_EXECUTION\b/.test(header)) {
143
- problems.push("the stack is executable: MH_ALLOW_STACK_EXECUTION is set")
144
- }
145
- if (imports.length > 0) {
146
- const nm = firstTool(["llvm-nm", "llvm-nm-18", "nm"])
147
- const names = new Set(
148
- (nm === null ? "" : (run(nm, ["-u", file]) ?? ""))
149
- .split("\n")
150
- .map((line) => line.trim().split(/\s+/).at(-1) ?? "")
151
- .map((name) => (name.startsWith("_") ? name.slice(1) : name))
152
- )
153
- for (const name of imports) {
154
- if (!names.has(name)) {
155
- problems.push(`does not import ${name}`)
156
- }
157
- }
158
- }
159
- return { skip: null, problems }
160
- }
161
-
162
- /**
163
- * What `file` lacks of the hardening, or why it could not be read: `skip` is
164
- * the missing tool, and `problems` is empty when every property holds.
165
- */
166
- export const hardeningProblems = (file, imports = []) => {
167
- const magic = magicOf(file)
168
- if (magic === ELF_MAGIC) {
169
- return elfProblems(file, imports)
170
- }
171
- if (MACHO_MAGICS.includes(magic)) {
172
- return machoProblems(file, imports)
173
- }
174
- return { skip: null, problems: [`${file} is neither ELF nor Mach-O (magic ${magic})`] }
175
- }
176
-
177
- const main = () => {
178
- const args = process.argv.slice(2)
179
- const at = args.indexOf("--imports")
180
- const imports = at < 0 ? [] : (args[at + 1] ?? "").split(",").filter((name) => name !== "")
181
- const files = at < 0 ? args : args.filter((_, i) => i !== at && i !== at + 1)
182
- if (files.length !== 1 || (at >= 0 && imports.length === 0)) {
183
- process.stderr.write("usage: node scripts/check-hardening.mjs <binary> [--imports name,name,...]\n")
184
- process.exit(2)
185
- }
186
- const result = hardeningProblems(files[0], imports)
187
- if (result.skip !== null) {
188
- process.stderr.write(`check-hardening: ${result.skip}\n`)
189
- process.exit(2)
190
- }
191
- if (result.problems.length > 0) {
192
- for (const problem of result.problems) {
193
- process.stderr.write(`check-hardening: ${files[0]}: ${problem}\n`)
194
- }
195
- process.exit(1)
196
- }
197
- process.stdout.write(`check-hardening: ${files[0]}: hardened\n`)
198
- }
199
-
200
- if (path.resolve(process.argv[1] ?? "") === import.meta.filename) {
201
- main()
202
- }
@@ -1,200 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Where a CI job's wall clock actually goes, per check.
4
- *
5
- * node scripts/ci-profile.mjs profile `node tests/run.js`
6
- * node scripts/ci-profile.mjs --top 60 more rows in each table
7
- * node scripts/ci-profile.mjs --json the same numbers, machine-readable
8
- * node scripts/ci-profile.mjs -- node tests/run.js --seed <nish>
9
- * node scripts/ci-profile.mjs -- npm run test:nish
10
- *
11
- * Why this exists. `tests/run.js` is one process printing about nineteen
12
- * hundred `PASS` lines, and a slow run says only that the total grew. Every
13
- * attempt to find the slow part by hand ran into the trap that a filtered run
14
- * is not a measurement (`.claude/testing.md`: a filtered count means nothing
15
- * until `rm -rf build/test`, and fifteen `fs.existsSync` guards drop checks
16
- * silently rather than skipping them). So this profiles the *unfiltered* run
17
- * instead, from the outside, and attributes time to the checks that were
18
- * actually printed. It needs no change to the suite and cannot alter what the
19
- * suite proves.
20
- *
21
- * **How to read the numbers, including the one way they mislead.** A check's
22
- * cost here is the gap between the previous printed line and its own, so the
23
- * work is attributed to the line printed *after* it finished. That is the right
24
- * answer for a check that does its work and then reports, which is every check
25
- * in this suite. It is the wrong answer in one case worth naming: because
26
- * `tests/run.js` drives 234 `spawnSync` calls, the event loop is blocked for
27
- * the whole of each one and queued writes flush in bursts when it unblocks. So
28
- * a *gap* is real, and the line it lands on is real, but the ordering of the
29
- * lines inside one burst is not something to read a per-line cost out of. Look
30
- * at the expensive rows, not at the cheap ones.
31
- *
32
- * The totals are wall clock on the machine this runs on. A `ubuntu-latest`
33
- * runner measured about 1.34x this box on the same suite, so the shape
34
- * transfers and the absolute seconds do not.
35
- */
36
- import { spawn } from "node:child_process"
37
-
38
- const argv = process.argv.slice(2)
39
- const asJson = argv.includes("--json")
40
- const topAt = argv.indexOf("--top")
41
- const TOP = topAt >= 0 && Number.isFinite(Number(argv[topAt + 1])) ? Number(argv[topAt + 1]) : 40
42
-
43
- /**
44
- * Everything after `--` is the command to profile. The default is the suite as
45
- * CI runs it, minus the build: `npm test` would rebuild `dist/` first, and a
46
- * `tsc` run is not what this is measuring.
47
- */
48
- const dashdash = argv.indexOf("--")
49
- const command =
50
- dashdash >= 0 && argv.length > dashdash + 1 ? argv.slice(dashdash + 1) : ["node", "tests/run.js"]
51
-
52
- /**
53
- * One row per line the child printed, with `dt` the gap since the line before
54
- * it. `text` keeps the line as it was printed so that a reader can find the
55
- * check in the log, and `t` is kept as well as `dt` because "which minute of
56
- * the run was this" is how a reader locates a slow block.
57
- */
58
- const rows = []
59
- const t0 = process.hrtime.bigint()
60
- let last = 0
61
- let buffered = ""
62
-
63
- const takeLine = (line) => {
64
- const t = Number(process.hrtime.bigint() - t0) / 1e6
65
- rows.push({ t, dt: t - last, text: line })
66
- last = t
67
- }
68
-
69
- const onData = (data) => {
70
- buffered += data
71
- let i = buffered.indexOf("\n")
72
- while (i >= 0) {
73
- takeLine(buffered.slice(0, i))
74
- buffered = buffered.slice(i + 1)
75
- i = buffered.indexOf("\n")
76
- }
77
- }
78
-
79
- /**
80
- * A heartbeat on stderr, because the tables below cannot be printed until the
81
- * child has exited and `npm test` takes eleven minutes. It goes to stderr so
82
- * that `--json` on stdout stays machine-readable, and it names the last check
83
- * seen rather than only a count: that is what says whether a long silence is
84
- * the oracles working or the run wedged.
85
- */
86
- const heartbeat = setInterval(() => {
87
- const latest = rows.length > 0 ? rows[rows.length - 1].text.slice(0, 72) : "nothing printed yet"
88
- const elapsed = (Number(process.hrtime.bigint() - t0) / 1e9).toFixed(0)
89
- process.stderr.write(`[ci-profile] ${elapsed}s, ${rows.length} lines: ${latest}\n`)
90
- }, 30_000)
91
- heartbeat.unref()
92
-
93
- const child = spawn(command[0], command.slice(1), { stdio: ["ignore", "pipe", "pipe"] })
94
- child.stdout.setEncoding("utf8")
95
- child.stderr.setEncoding("utf8")
96
- child.stdout.on("data", onData)
97
- child.stderr.on("data", onData)
98
-
99
- const status = await new Promise((resolve) => {
100
- child.on("close", (code) => resolve(code ?? 1))
101
- child.on("error", (err) => {
102
- console.error(`could not run ${command.join(" ")}: ${err.message}`)
103
- resolve(1)
104
- })
105
- })
106
- clearInterval(heartbeat)
107
- if (buffered.length > 0) {
108
- takeLine(buffered)
109
- }
110
-
111
- /**
112
- * A check's name up to its first colon, which is how this suite names a family:
113
- * `link/argv_import: llvm-as accepts args.ll` and its six siblings are one
114
- * fixture compiled once, and the family is what a reader can act on. A line
115
- * with no colon is grouped under its first forty characters, which is enough to
116
- * keep the oracles — each of which prints one long line — apart.
117
- */
118
- const familyOf = (text) => {
119
- const body = text.replace(/^(PASS|FAIL|SKIP)\s+/, "")
120
- const colon = body.indexOf(":")
121
- return colon > 0 ? body.slice(0, colon) : body.slice(0, 40)
122
- }
123
-
124
- const families = new Map()
125
- for (const row of rows) {
126
- const key = familyOf(row.text)
127
- const seen = families.get(key) ?? { ms: 0, lines: 0 }
128
- seen.ms += row.dt
129
- seen.lines += 1
130
- families.set(key, seen)
131
- }
132
-
133
- const total = rows.length > 0 ? rows[rows.length - 1].t : 0
134
- const byCost = [...rows].sort((a, b) => b.dt - a.dt).slice(0, TOP)
135
- const byFamily = [...families].sort((a, b) => b[1].ms - a[1].ms).slice(0, TOP)
136
-
137
- if (asJson) {
138
- console.log(
139
- JSON.stringify(
140
- {
141
- command,
142
- status,
143
- totalMs: Math.round(total),
144
- lines: rows.length,
145
- checks: byCost.map((r) => ({ ms: Math.round(r.dt), atMs: Math.round(r.t), text: r.text })),
146
- families: byFamily.map(([name, f]) => ({ name, ms: Math.round(f.ms), lines: f.lines })),
147
- },
148
- null,
149
- 2
150
- )
151
- )
152
- process.exit(status)
153
- }
154
-
155
- const secs = (ms) => `${(ms / 1000).toFixed(1)}s`.padStart(8)
156
-
157
- console.log(`\n${command.join(" ")}`)
158
- console.log(`exit ${status} — ${secs(total).trim()} of wall clock over ${rows.length} printed lines\n`)
159
-
160
- /**
161
- * The run's own verdict, echoed verbatim.
162
- *
163
- * A profile that swallowed this would be worse than useless here, because exit
164
- * 0 is not the whole answer: `tests/run.js` reports a *skip count* beside the
165
- * passes, and a green run with more skips than the last one proved less while
166
- * looking the same (`.claude/orientation.md` calls reading the count rather than
167
- * the exit status the thing to do). So the summary is printed before the
168
- * timings, where it cannot be missed.
169
- */
170
- const verdict = rows.filter((r) => r.text.trim().length > 0).slice(-3)
171
- if (verdict.length > 0) {
172
- console.log("=== what the run itself reported ===")
173
- for (const row of verdict) {
174
- console.log(` ${row.text}`)
175
- }
176
- console.log("")
177
- }
178
-
179
- console.log(`=== the ${byCost.length} most expensive checks (cost = the gap before the line was printed) ===`)
180
- for (const row of byCost) {
181
- console.log(`${secs(row.dt)} at ${secs(row.t)} ${row.text.slice(0, 104)}`)
182
- }
183
-
184
- console.log(`\n=== the ${byFamily.length} most expensive families (cumulative) ===`)
185
- for (const [name, f] of byFamily) {
186
- console.log(`${secs(f.ms)} ${String(f.lines).padStart(5)} line(s) ${name.slice(0, 84)}`)
187
- }
188
-
189
- /**
190
- * The share the expensive tail accounts for, because "the top ten are 70% of
191
- * the run" is the sentence that decides whether to optimise a check or the
192
- * shape of the job around it.
193
- */
194
- const topTen = [...rows]
195
- .sort((a, b) => b.dt - a.dt)
196
- .slice(0, 10)
197
- .reduce((sum, r) => sum + r.dt, 0)
198
- console.log(`\nthe ten most expensive checks are ${((topTen / total) * 100).toFixed(0)}% of the run.`)
199
-
200
- process.exit(status)
@@ -1,85 +0,0 @@
1
- /**
2
- * The diagnostic-code registry, read back out of a `codes.ts`.
3
- *
4
- * `src/codes.ts` holds the table -- a fragment line, then the `NL####` line
5
- * that names its rule. Three places in this repository read it back:
6
- * `scripts/gen-diagnostic-codes.mjs`, which checks the registry's shape, its
7
- * order and that no number is used twice; `tests/diagnostic-coverage.js`,
8
- * which asks which codes the suite reaches; and the `codes:` checks in
9
- * `tests/run.js`. This module is that parse, once, so the copies cannot drift
10
- * apart again ([issue #96](https://github.com/amritk/nish/issues/96)).
11
- *
12
- * It lives here rather than under `tests/` for two reasons. The format was
13
- * written by `rows()` in the generator next door until the registry was
14
- * frozen and kept by hand (R6), and #96 was the writer and the readers
15
- * drifting apart -- WP22 stage C changed what the emitter wrote and no reader
16
- * followed -- so the reader belongs beside the checker. And `scripts/` ships in
17
- * the npm tarball while `tests/` does not, so a shared module under `tests/`
18
- * would leave the shipped checker importing a path the package cannot
19
- * resolve, which `tests/run.js` refuses
20
- * (`npm pack ships no script whose imports it cannot resolve`).
21
- *
22
- * Two properties are the whole point of having it, and both are here because
23
- * they have failed:
24
- *
25
- * - **The indentation is not part of the contract.** `src/codes.ts` lost a
26
- * level when WP22 stage C rewrote its tables as arrows with concise
27
- * bodies, and every reader keyed on four literal spaces then read it as
28
- * *empty* rather than as changed. `^\s+` is what a pair is recognised by.
29
- * - **Nothing is an empty registry.** A reader that answers `[]` for a file
30
- * whose shape has moved makes "every code is covered" and "there are no
31
- * codes" the same answer, which is what let the first instance of this
32
- * survive unnoticed. This one raises instead.
33
- */
34
- import fs from "node:fs"
35
- import path from "node:path"
36
-
37
- const root = path.resolve(import.meta.dirname, "..")
38
-
39
- /**
40
- * One string literal in either quote: the formatter writes a fragment that
41
- * holds a `"` with single quotes, because that needs no escape.
42
- */
43
- export const STRING_LITERAL = /"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g
44
-
45
- /**
46
- * One entry of the emitted table: the quoted fragment on its own line, then
47
- * the code on the next. Anchored to the line rather than to a column, for the
48
- * reason in the header.
49
- */
50
- const PAIR = new RegExp(`^\\s+(${STRING_LITERAL.source}),\\n\\s+"(NL\\d{4})",$`, "gm")
51
-
52
- /** The text of a string literal in either quote, as JavaScript reads it. */
53
- const unquote = (literal) =>
54
- literal.startsWith("'")
55
- ? JSON.parse(`"${literal.slice(1, -1).replaceAll("\\'", "'").replaceAll('"', '\\"')}"`)
56
- : JSON.parse(literal)
57
-
58
- /**
59
- * Every `{ fragment, code }` of one registry file, in the order the file holds
60
- * them -- which is the order the compilers match in, longest fragment first,
61
- * so a caller comparing two registries is comparing their behaviour and not
62
- * just their contents.
63
- *
64
- * Pairs rather than a `Map` because the three callers key it three different
65
- * ways, and because a `Map` would quietly swallow a duplicated fragment that a
66
- * caller may want to see.
67
- *
68
- * Throws when it parses nothing: an unreadable registry is a broken one, and
69
- * the one thing it may not do is pass for an empty one. `label` is what that
70
- * message names the text by.
71
- */
72
- export const parseCodesRegistry = (text, label) => {
73
- const pairs = []
74
- for (const m of text.matchAll(PAIR)) {
75
- pairs.push({ fragment: unquote(m[1]), code: m[2] })
76
- }
77
- if (pairs.length === 0) {
78
- throw new Error(`${label}: no diagnostic codes parsed -- the registry's shape has moved`)
79
- }
80
- return pairs
81
- }
82
-
83
- /** The same, for a registry on disk. The three callers all read a file. */
84
- export const readCodesRegistry = (file) =>
85
- parseCodesRegistry(fs.readFileSync(file, "utf8"), path.relative(root, file))