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
package/scripts/fuzz.sh DELETED
@@ -1,280 +0,0 @@
1
- #!/usr/bin/env bash
2
- # Build, run and replay the libFuzzer targets in tests/fuzz/targets/.
3
- #
4
- # scripts/fuzz.sh --build <name> build/fuzz/bin/<name>
5
- # scripts/fuzz.sh --run <name> [-- <libFuzzer args>]
6
- # fuzz it, growing its corpus
7
- # scripts/fuzz.sh --replay [<name>] every corpus and regression
8
- # input once; a crash fails
9
- # scripts/fuzz.sh --smoke every target: build, replay,
10
- # then a short fixed-seed run,
11
- # FUZZ_JOBS targets at a time
12
- #
13
- # A target is `tests/fuzz/targets/<name>.ts` exporting
14
- # `export const fuzzOne = (data: u8[]): void` (tests/fuzz/README.md). It is
15
- # compiled to a library .ll with the repository's compiler and std, and linked
16
- # with tests/fuzz/harness.c and the runtime under
17
- # `-fsanitize=fuzzer,address,undefined`, with the runtime built
18
- # `-DNISH_FUZZ_ABORT` so a panic, a failed bounds or division check and an
19
- # out-of-memory are crashes. The runtime units are linked from source, so a
20
- # change to runtime/ needs nothing but a rebuild.
21
- #
22
- # Environment:
23
- # NISH the compiler (default build/nish; `npm run build`). It
24
- # must be one built from this checkout: a compiler finds
25
- # std/ beside itself, so the seed would fuzz its own std.
26
- # FUZZ_SMOKE_SECONDS --smoke's fuzzing time per target (default 20)
27
- # FUZZ_SEED --smoke's libFuzzer -seed (default 1)
28
- # FUZZ_JOBS how many targets --smoke builds and fuzzes at once
29
- # (default: the online cores). Each libFuzzer run is one
30
- # process on one core, so a serial smoke left three of a
31
- # CI runner's four idle; four at a time ran as many
32
- # inputs per target as one at a time, in a quarter of
33
- # the wall time.
34
- # FUZZ_OUT where binaries, scratch corpora and artifacts go
35
- # (default build/fuzz)
36
- #
37
- # Every libFuzzer run is given `-timeout=1` (an input over a second is a crash,
38
- # as the target interface says) and `-rss_limit_mb=2048`, before the caller's
39
- # own arguments, which may override them.
40
- set -euo pipefail
41
-
42
- root="$(cd "$(dirname "$0")/.." && pwd)"
43
- cd "$root"
44
-
45
- NISH="${NISH:-build/nish}"
46
- FUZZ_OUT="${FUZZ_OUT:-build/fuzz}"
47
- FUZZ_SMOKE_SECONDS="${FUZZ_SMOKE_SECONDS:-20}"
48
- FUZZ_SEED="${FUZZ_SEED:-1}"
49
- FUZZ_JOBS="${FUZZ_JOBS:-$(getconf _NPROCESSORS_ONLN 2>/dev/null || echo 1)}"
50
- CC="${CC:-clang}"
51
-
52
- # The runtime's C units: tests/run.js's RUNTIME_C, which its `fuzz` section
53
- # checks this list against. runtime-wasm.c is wasm32's alone.
54
- RUNTIME_C=(
55
- runtime/runtime.c
56
- runtime/runtime-text.c
57
- runtime/runtime-os.c
58
- runtime/runtime-parallel.c
59
- runtime/runtime-cross.c
60
- runtime/runtime-host.c
61
- runtime/runtime-net.c
62
- runtime/runtime-simd.c
63
- runtime/runtime-aes.c
64
- runtime/runtime-sha256.c
65
- runtime/runtime-chacha20.c
66
- runtime/runtime-checksum.c
67
- runtime/runtime-term.c
68
- runtime/runtime-bytes.c
69
- runtime/runtime-sandbox.c
70
- runtime/runtime-shm.c
71
- runtime/runtime-region.c
72
- runtime/runtime-async.c
73
- )
74
-
75
- SAN_FLAGS=(-g -O1 "-fsanitize=fuzzer,address,undefined" -fno-sanitize-recover=undefined)
76
- LIBFUZZER_DEFAULTS=(-timeout=1 -rss_limit_mb=2048)
77
-
78
- die() {
79
- echo "fuzz.sh: $*" >&2
80
- exit 2
81
- }
82
-
83
- usage() {
84
- sed -n '2,12p' "$0" | sed 's/^# \{0,1\}//' >&2
85
- exit "${1:-2}"
86
- }
87
-
88
- targets() {
89
- local f
90
- for f in tests/fuzz/targets/*.ts; do
91
- [ -e "$f" ] || continue
92
- basename "$f" .ts
93
- done
94
- }
95
-
96
- need_target() {
97
- [ -f "tests/fuzz/targets/$1.ts" ] || die "no target tests/fuzz/targets/$1.ts"
98
- }
99
-
100
- # The runtime objects, compiled once per invocation of this script: every
101
- # target links the same ones.
102
- runtime_objs=()
103
- build_runtime() {
104
- [ ${#runtime_objs[@]} -eq 0 ] || return 0
105
- [ -x "$NISH" ] || die "no compiler at $NISH: run \`npm run build\`, or set NISH"
106
- command -v "$CC" >/dev/null || die "no $CC on PATH"
107
- mkdir -p "$FUZZ_OUT/obj"
108
- local src obj
109
- for src in "${RUNTIME_C[@]}"; do
110
- obj="$FUZZ_OUT/obj/$(basename "$src" .c).o"
111
- "$CC" "${SAN_FLAGS[@]}" -ffp-contract=off -DNISH_FUZZ_ABORT -Iruntime -c "$src" -o "$obj" \
112
- || die "compiling $src under the sanitizers failed (is libclang-rt-18-dev installed?)"
113
- runtime_objs+=("$obj")
114
- done
115
- "$CC" "${SAN_FLAGS[@]}" -DNISH_FUZZ_ABORT -Iruntime -c tests/fuzz/harness.c \
116
- -o "$FUZZ_OUT/obj/harness.o"
117
- runtime_objs+=("$FUZZ_OUT/obj/harness.o")
118
- }
119
-
120
- build() {
121
- local name="$1"
122
- need_target "$name"
123
- build_runtime
124
- local ir="$FUZZ_OUT/ir/$name"
125
- rm -rf "$ir"
126
- mkdir -p "$ir" "$FUZZ_OUT/bin"
127
- if ! "$NISH" "tests/fuzz/targets/$name.ts" -o "$ir/" >"$ir.log" 2>&1; then
128
- cat "$ir.log" >&2
129
- die "$name: compile failed"
130
- fi
131
- # clang instruments only functions carrying `sanitize_address`, which the
132
- # compiler never emits, so every definition is given it here; without it the
133
- # compiled Nish code links under ASan uninstrumented. Every `define` line
134
- # ends `) {`, `) #N {` (an attribute group) or `) <attributes> {` (a raw
135
- # definition's inline list, such as `nounwind` or `"probe-stack"="inline-asm"`),
136
- # and the attribute is appended to whichever list is there. UBSan instruments
137
- # in clang's frontend, so it never reaches a .ll: the compiled code's own
138
- # bounds and division checks stand in for it. A define this misses fails the
139
- # build rather than going quiet. The check reads all of grep's output instead
140
- # of `grep -q`: under pipefail, -q's early exit SIGPIPEs the first grep, and
141
- # the pipeline's 141 read as "no miss", so a miss passed whenever the first
142
- # grep was still writing.
143
- sed -i -E 's/^(define .*\)( [^!{]*)?) \{$/\1 sanitize_address {/' "$ir"/*.ll
144
- if grep -h '^define ' "$ir"/*.ll | grep -v ' sanitize_address {$' >/dev/null; then
145
- die "$name: a define in $ir/ was not given sanitize_address"
146
- fi
147
- # A library build writes one module per source module, the std modules the
148
- # target imports included, and the link takes them all.
149
- "$CC" "${SAN_FLAGS[@]}" -Wno-override-module "$ir"/*.ll "${runtime_objs[@]}" -lm \
150
- -o "$FUZZ_OUT/bin/$name" || die "$name: link failed"
151
- echo "fuzz.sh: built $FUZZ_OUT/bin/$name"
152
- }
153
-
154
- # The directories of inputs a target is replayed over: its seed corpus and its
155
- # regressions, those that exist.
156
- input_dirs() {
157
- local d
158
- for d in "tests/fuzz/corpus/$1" "tests/fuzz/regressions/$1"; do
159
- [ -d "$d" ] && echo "$d"
160
- done
161
- return 0
162
- }
163
-
164
- replay() {
165
- local name="$1" dirs
166
- mapfile -t dirs < <(input_dirs "$name")
167
- if [ ${#dirs[@]} -eq 0 ]; then
168
- die "$name: no tests/fuzz/corpus/$name/ to replay"
169
- fi
170
- mkdir -p "$FUZZ_OUT/artifacts/$name"
171
- # -runs=0 runs each input once and fuzzes nothing; nothing is written to the
172
- # corpus directories.
173
- "$FUZZ_OUT/bin/$name" "${LIBFUZZER_DEFAULTS[@]}" -runs=0 \
174
- -artifact_prefix="$FUZZ_OUT/artifacts/$name/" "${dirs[@]}"
175
- }
176
-
177
- # Fuzz `name` with a scratch copy of its corpus as the first (written)
178
- # directory, so the checked-in corpus only grows when someone copies inputs
179
- # back by hand (tests/fuzz/README.md).
180
- run() {
181
- local name="$1"
182
- shift
183
- local work="$FUZZ_OUT/work/$name" dirs
184
- mkdir -p "$work" "$FUZZ_OUT/artifacts/$name"
185
- mapfile -t dirs < <(input_dirs "$name")
186
- "$FUZZ_OUT/bin/$name" "${LIBFUZZER_DEFAULTS[@]}" \
187
- -artifact_prefix="$FUZZ_OUT/artifacts/$name/" "$@" "$work" "${dirs[@]}"
188
- }
189
-
190
- [ $# -ge 1 ] || usage
191
- mode="$1"
192
- shift
193
- case "$mode" in
194
- --build)
195
- [ $# -eq 1 ] || usage
196
- build "$1"
197
- ;;
198
- --run)
199
- [ $# -ge 1 ] || usage
200
- name="$1"
201
- shift
202
- if [ $# -ge 1 ]; then
203
- [ "$1" = "--" ] || usage
204
- shift
205
- fi
206
- build "$name"
207
- run "$name" "$@"
208
- ;;
209
- --replay)
210
- if [ $# -eq 1 ]; then
211
- names=("$1")
212
- else
213
- [ $# -eq 0 ] || usage
214
- mapfile -t names < <(targets)
215
- fi
216
- for name in "${names[@]}"; do
217
- build "$name"
218
- replay "$name"
219
- done
220
- ;;
221
- --smoke)
222
- [ $# -eq 0 ] || usage
223
- mapfile -t names < <(targets)
224
- [ ${#names[@]} -gt 0 ] || die "no targets in tests/fuzz/targets/"
225
- [[ "$FUZZ_JOBS" =~ ^[1-9][0-9]*$ ]] || die "FUZZ_JOBS must be a positive integer, not '$FUZZ_JOBS'"
226
- # The lanes share the runtime objects, so they are built here, once,
227
- # before any lane starts: a lane that found them missing would build them
228
- # itself, into the same files as the others.
229
- build_runtime
230
- logs="$FUZZ_OUT/smoke"
231
- rm -rf "$logs"
232
- mkdir -p "$logs"
233
- # Each target is a lane writing its own log and, as it exits, its status,
234
- # so the logs are printed whole and in target order once every lane is
235
- # done, and one target's crash does not stop the others. The status comes
236
- # from an EXIT trap: the lane stops at its first failing step under
237
- # `set -e`, which a status written after the lane, or a lane run as a
238
- # condition, would not keep.
239
- running=0
240
- for name in "${names[@]}"; do
241
- if [ "$running" -ge "$FUZZ_JOBS" ]; then
242
- # A lane's status is read from its file below, not from here.
243
- wait -n || true
244
- running=$((running - 1))
245
- fi
246
- (
247
- status_file="$logs/$name.status"
248
- trap 'echo "$?" >"$status_file"' EXIT
249
- build "$name"
250
- replay "$name"
251
- rm -rf "$FUZZ_OUT/work/$name"
252
- run "$name" -seed="$FUZZ_SEED" -max_total_time="$FUZZ_SMOKE_SECONDS" -print_final_stats=1
253
- ) >"$logs/$name.log" 2>&1 &
254
- running=$((running + 1))
255
- done
256
- wait
257
- # Under GitHub Actions each target's log folds into a group of its own.
258
- group=""
259
- [ "${GITHUB_ACTIONS:-}" = true ] && group=1
260
- failed=()
261
- for name in "${names[@]}"; do
262
- [ -n "$group" ] && echo "::group::fuzz.sh: $name"
263
- cat "$logs/$name.log"
264
- [ -n "$group" ] && echo "::endgroup::"
265
- status="$(cat "$logs/$name.status" 2>/dev/null || echo missing)"
266
- [ "$status" = 0 ] || failed+=("$name (exit $status)")
267
- done
268
- if [ ${#failed[@]} -gt 0 ]; then
269
- echo "fuzz.sh: smoke failed in ${#failed[@]} of ${#names[@]} targets: ${failed[*]}" >&2
270
- exit 1
271
- fi
272
- echo "fuzz.sh: smoke passed over ${#names[@]} targets, $FUZZ_JOBS at a time"
273
- ;;
274
- -h | --help)
275
- usage 0
276
- ;;
277
- *)
278
- usage
279
- ;;
280
- esac
@@ -1,243 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Check the stable diagnostic-code registry: the `code` field of `--json`.
4
- *
5
- * node scripts/gen-diagnostic-codes.mjs --check exit 1 if the registry is malformed
6
- * node scripts/gen-diagnostic-codes.mjs the same, then the next free code per band
7
- * node scripts/gen-diagnostic-codes.mjs --check F check the registry in file F instead
8
- *
9
- * The third form is for `tests/run.js`, which hands it a copy of the registry
10
- * with one line broken to show that each rule below is really enforced.
11
- *
12
- * **The registry is kept by hand now.** It used to be generated: this script
13
- * scanned stage0's `src/` for every diagnostic message, cut each at its interpolations,
14
- * and wrote the same table into stage0's `src/codes.ts` and this compiler's `self/codes.ts`
15
- * (now `src/codes.ts`). That scan
16
- * read stage0's source, and stage0 is deleted (wp19 §5 R6), so the generator
17
- * was frozen with the table it last wrote and `src/codes.ts` became the
18
- * registry. A new diagnostic gets its code by hand: append a fragment and the
19
- * next free number in its band (the second mode above prints those), at the
20
- * position the ordering rule below puts it. `tests/diagnostic-coverage.js`
21
- * is what notices a diagnostic that has no code, by counting `NL0000`.
22
- *
23
- * What `--check` still holds, because each is what makes a code worth keying
24
- * on:
25
- *
26
- * - **Every number is well-formed and in its band.** `NL1xxx` Phase 0,
27
- * `NL2xxx` the checker, `NL3xxx` the driver, `NL4xxx` the interop
28
- * sidecars, `NL7xxx` a deprecation warning, `NL8xxx` a WP33 portability
29
- * warning, `NL9xxx` a WP15 section 8 performance warning. Band 0 is not
30
- * in the tables: `NL0000` (no rule matched), `NL0001` (a syntax error),
31
- * `NL0002` (the toolchain) and `NL0003` (an internal error) are
32
- * constants. A performance fragment is in
33
- * `performanceRules` and nowhere else, a portability fragment is in
34
- * `portabilityRules` and nowhere else, and a deprecation fragment is in
35
- * `deprecationRules` and nowhere else.
36
- * - **Nothing is used twice.** A number handed out once is never handed to a
37
- * different rule, and a retired rule keeps its entry -- it matches nothing,
38
- * so carrying it costs a string -- precisely so that its number stays
39
- * reserved. Two entries for one fragment would make the second dead.
40
- * - **Longest fragment first**, ties in `localeCompare` order, the order the
41
- * generator wrote: the compilers take the first fragment the message
42
- * contains, so a specific rule has to come before a general one it
43
- * contains ("Cannot assign to `length` of " before "Cannot assign ").
44
- * - **No fragment too short to identify a rule** (ten characters, trimmed),
45
- * which would match half the suite.
46
- * - **Every string in a table is half of a pair.** `codeFor` in
47
- * `src/codes.ts` reads each table as one flat array and steps through it
48
- * by two, so a fragment added without its code line -- or a code without
49
- * its fragment -- shifts every pairing after it, and from there on
50
- * messages get their neighbour's code. The pair reader cannot see that:
51
- * it matches a fragment line followed by a code line, and a stray line is
52
- * simply not a match. So each table's strings are counted on their own
53
- * and have to come to twice its pairs ([#107](https://github.com/amritk/nish/issues/107)).
54
- * - **The `NL9xxx` codes run from `NL9001` with no gap**, one per WP15
55
- * section 8 rule, so a missing number is a rule that lost its code; and
56
- * the `NL8xxx` codes run from `NL8001` the same way, one per WP33 row,
57
- * and the `NL7xxx` codes from `NL7001`, one per deprecation, retired ones
58
- * included.
59
- * - **`RULE_COUNT` is the number of entries.**
60
- *
61
- * A fragment is the longest literal run of its message's template -- the rule
62
- * in words, with every interpolated name, type and count removed -- matched as
63
- * a substring. Cutting at the interpolations is also what keeps the project's
64
- * name out of the table: "... is forbidden in ${LANGUAGE}" contributes the run
65
- * before the name, never the name, so `branding.ts` stays the only place it is
66
- * spelled (rule 5 in `.claude/orientation.md`). Keep to that when adding one.
67
- */
68
- import fs from "node:fs"
69
- import path from "node:path"
70
- import { fileURLToPath } from "node:url"
71
- import { parseCodesRegistry, STRING_LITERAL } from "./codes-registry.js"
72
-
73
- const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..")
74
- const REGISTRY =
75
- process.argv.slice(2).find((arg) => !arg.startsWith("--")) ?? path.join(ROOT, "src", "codes.ts")
76
-
77
- /** The bands a table entry may use. Band 0 is constants, never a table row. */
78
- const BANDS = new Set(["1", "2", "3", "4", "7", "8", "9"])
79
-
80
- /** Shorter than this, a fragment would match half the suite. */
81
- const MIN_FRAGMENT = 10
82
-
83
- /**
84
- * The four tables, the band each warning table owns alone, and that warning
85
- * class's name: a warning table holds only its band's codes and its band's
86
- * codes live only there, because `codeFor` matches a warning's message against
87
- * its own table and nothing else. `null` is the table of errors, which takes
88
- * every other band.
89
- */
90
- const TABLES = [
91
- ["diagnosticRules", null, null],
92
- ["deprecationRules", "7", "deprecation"],
93
- ["portabilityRules", "8", "portability"],
94
- ["performanceRules", "9", "performance"],
95
- ]
96
-
97
- /**
98
- * The text of one table in `src/codes.ts`: from its `name = (): string[] => [`
99
- * to the `];` that closes it. Parsed per table, because the table a fragment
100
- * sits in is part of what it means -- a performance rule is matched only
101
- * against a performance message.
102
- */
103
- const tableText = (text, name) => {
104
- const header = new RegExp(`^(?:export )?const ${name} = \\(\\): string\\[\\] => \\[`, "m").exec(text)
105
- const open = header === null ? -1 : header.index
106
- if (open < 0) {
107
- return null
108
- }
109
- const close = text.indexOf("\n]", open)
110
- return close < 0 ? null : text.slice(open, close + 1)
111
- }
112
-
113
- /**
114
- * How many strings one table holds: every literal after the line that opens
115
- * it. That is what `codeFor` steps through two at a time, so it is counted on
116
- * its own rather than read off the pairs -- a stray literal is exactly what
117
- * the pair reader skips.
118
- */
119
- const literalCount = (body) => body.slice(body.indexOf("\n")).match(STRING_LITERAL)?.length ?? 0
120
-
121
- /** The order the compilers rely on: longest fragment first, then `localeCompare`. */
122
- const inOrder = (a, b) => b.fragment.length - a.fragment.length || a.fragment.localeCompare(b.fragment)
123
-
124
- /** Every rule of `src/codes.ts` it breaks, as a line each; empty when it holds. */
125
- const problems = (text) => {
126
- const found = []
127
- const tables = []
128
- for (const [name, owns, kind] of TABLES) {
129
- const body = tableText(text, name)
130
- if (body === null) {
131
- found.push(`src/codes.ts has no \`${name}\` table`)
132
- continue
133
- }
134
- try {
135
- const pairs = parseCodesRegistry(body, `src/codes.ts ${name}`)
136
- const literals = literalCount(body)
137
- if (literals !== 2 * pairs.length) {
138
- found.push(
139
- `\`${name}\` holds ${literals} strings and ${pairs.length} fragment/code pairs: a string ` +
140
- "without its other half shifts every later pairing `codeFor` makes"
141
- )
142
- }
143
- tables.push({ name, owns, kind, pairs })
144
- } catch (err) {
145
- found.push(err.message)
146
- }
147
- }
148
- const all = tables.flatMap((t) => t.pairs)
149
-
150
- // The tables are the whole registry: a pair the reader finds outside them is
151
- // one the compilers never match, and one of theirs the reader misses is one
152
- // `tests/diagnostic-coverage.js` never asks about.
153
- let whole = []
154
- try {
155
- whole = parseCodesRegistry(text, "src/codes.ts")
156
- } catch (err) {
157
- found.push(err.message)
158
- }
159
- if (whole.length !== all.length) {
160
- found.push(`src/codes.ts holds ${whole.length} pairs, ${all.length} of them inside the four tables`)
161
- }
162
-
163
- const warningBands = TABLES.map(([, owns]) => owns).filter((band) => band !== null)
164
- for (const { name, owns, pairs } of tables) {
165
- for (let i = 0; i < pairs.length; i++) {
166
- const { fragment, code } = pairs[i]
167
- const band = code[2]
168
- if (!BANDS.has(band)) {
169
- found.push(`${code} is not in a table band (1, 2, 3, 4, 7, 8 or 9): ${JSON.stringify(fragment)}`)
170
- }
171
- if (owns !== null && band !== owns) {
172
- found.push(`${code} is in \`${name}\`, which holds only NL${owns}xxx codes`)
173
- }
174
- if (owns === null && warningBands.includes(band)) {
175
- found.push(`${code} is in \`${name}\`, which holds no NL${band}xxx codes`)
176
- }
177
- if (fragment.trim().length < MIN_FRAGMENT) {
178
- found.push(`${code}'s fragment ${JSON.stringify(fragment)} is under ${MIN_FRAGMENT} characters`)
179
- }
180
- if (i > 0 && inOrder(pairs[i - 1], pairs[i]) > 0) {
181
- found.push(`${code} is out of order in \`${name}\`: it has to come before ${pairs[i - 1].code}`)
182
- }
183
- }
184
- }
185
-
186
- // A warning band is gap-free from its first number, so a missing one is a
187
- // rule that lost its code rather than a number nobody took yet.
188
- for (const { name, owns, kind, pairs } of tables) {
189
- if (owns === null) {
190
- continue
191
- }
192
- const numbers = pairs.map((p) => Number(p.code.slice(3))).sort((a, b) => a - b)
193
- const gap = numbers.findIndex((n, i) => n !== i + 1)
194
- if (gap >= 0) {
195
- const base = Number(owns) * 1000
196
- found.push(
197
- `\`${name}\` has no NL${base + gap + 1} in its place: its ${kind} codes run from NL${base + 1} with no gap`
198
- )
199
- }
200
- }
201
-
202
- const seen = (key) => {
203
- const counts = new Map()
204
- for (const pair of all) {
205
- counts.set(pair[key], (counts.get(pair[key]) ?? 0) + 1)
206
- }
207
- return [...counts].filter(([, n]) => n > 1).map(([value]) => value)
208
- }
209
- for (const code of seen("code")) {
210
- found.push(`${code} names two rules`)
211
- }
212
- for (const fragment of seen("fragment")) {
213
- found.push(`${JSON.stringify(fragment)} has two entries`)
214
- }
215
-
216
- const count = /export const RULE_COUNT: i32 = (\d+);?$/m.exec(text)
217
- if (count === null) {
218
- found.push("src/codes.ts has no `RULE_COUNT`")
219
- } else if (Number(count[1]) !== all.length) {
220
- found.push(`RULE_COUNT is ${count[1]} and the tables hold ${all.length} rules`)
221
- }
222
-
223
- return { found, all }
224
- }
225
-
226
- /** The next number nobody has held, per band -- what a hand-added rule takes. */
227
- const nextFree = (pairs) => {
228
- const highest = new Map()
229
- for (const { code } of pairs) {
230
- const band = code[2]
231
- highest.set(band, Math.max(highest.get(band) ?? 0, Number(code.slice(3))))
232
- }
233
- return [...BANDS].map((band) => `NL${band}${String((highest.get(band) ?? 0) + 1).padStart(3, "0")}`)
234
- }
235
-
236
- const { found, all } = problems(fs.readFileSync(REGISTRY, "utf8"))
237
- for (const problem of found) {
238
- console.error(`error: ${problem}`)
239
- }
240
- if (found.length === 0 && !process.argv.includes("--check")) {
241
- console.log(`src/codes.ts: ${all.length} rules, well-formed; next free: ${nextFree(all).join(" ")}`)
242
- }
243
- process.exit(found.length > 0 ? 1 : 0)
@@ -1,130 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Generate the power-of-five table of `std/json-tokenizer.ts`.
4
- *
5
- * node scripts/gen-json-pow5.mjs rewrite the table in std/json-tokenizer.ts
6
- * node scripts/gen-json-pow5.mjs --check exit 1 if the table there differs by a byte
7
- *
8
- * The table is the region of `json-tokenizer.ts` between the
9
- * `gen-json-pow5:begin` and `gen-json-pow5:end` lines: `jsonTokPowerOfFive`,
10
- * which answers the 128-bit truncation of 5^q for q from -342 to 308 as two
11
- * 64-bit words, high first, so 1,302 words. For q ≥ 0 it is 5^q shifted left
12
- * or right until its top bit is bit 127, truncated. For q < 0 it is
13
- * 2^b / 5^-q rounded up, for the b that puts its top bit there; while 5^-q
14
- * fits in 64 bits (q ≥ -27) that b is z + 127, with z the bit length of 5^-q,
15
- * and past it the quotient of 2^(2z + 128) is halved down to 128 bits.
16
- *
17
- * This is fast_float's `script/table_generation.py`, at commit 0de7a21,
18
- * written again with BigInt: the table is computed with exact integer
19
- * arithmetic, so a reader can check it rather than trust a transcription. The
20
- * region lives inside `json-tokenizer.ts` rather than in a module of its own
21
- * because a file under `std/` is a public `nish/` module.
22
- *
23
- * Adapted from fast_float (https://github.com/fastfloat/fast_float),
24
- * include/fast_float/decimal_to_binary.h and script/table_generation.py.
25
- * Copyright 2021 The fast_float authors. Used under the Boost Software License,
26
- * Version 1.0; see std/LICENSE-fast-float.
27
- */
28
- import fs from "node:fs"
29
- import path from "node:path"
30
- import { fileURLToPath } from "node:url"
31
-
32
- const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..")
33
- const target = path.join(root, "std", "json-tokenizer.ts")
34
-
35
- /** `JSON_TOK_SMALLEST_POWER` and `JSON_TOK_LARGEST_POWER`. */
36
- const SMALLEST = -342
37
- const LARGEST = 308
38
-
39
- const TOP = 1n << 127n
40
- const LIMIT = 1n << 128n
41
- const WORD = (1n << 64n) - 1n
42
-
43
- /** The bit length of a positive BigInt. */
44
- const bits = (n) => n.toString(2).length
45
-
46
- const entries = []
47
- for (let q = SMALLEST; q < 0; q++) {
48
- const p = 5n ** BigInt(-q)
49
- const z = BigInt(bits(p))
50
- let c
51
- if (q >= -27) {
52
- c = (1n << (z + 127n)) / p + 1n
53
- } else {
54
- c = (1n << (2n * z + 128n)) / p + 1n
55
- while (c >= LIMIT) {
56
- c /= 2n
57
- }
58
- }
59
- entries.push(c)
60
- }
61
- for (let q = 0; q <= LARGEST; q++) {
62
- let p = 5n ** BigInt(q)
63
- while (p < TOP) {
64
- p *= 2n
65
- }
66
- while (p >= LIMIT) {
67
- p /= 2n
68
- }
69
- entries.push(p)
70
- }
71
- for (const [i, c] of entries.entries()) {
72
- if (c < TOP || c >= LIMIT) {
73
- throw new Error(`gen-json-pow5: the entry for q = ${i + SMALLEST} does not have its top bit at bit 127`)
74
- }
75
- }
76
-
77
- const words = entries.flatMap((c) => [c >> 64n, c & WORD])
78
- const half = (w) => `0x${w.toString(16).padStart(8, "0")}`
79
- const cases = words.flatMap((w, i) => [
80
- ` case ${i}:`,
81
- ` return jsonTokW64(${half(w >> 32n)}, ${half(w & 0xffffffffn)})`,
82
- ])
83
-
84
- const BEGIN = "// gen-json-pow5:begin"
85
- const END = "// gen-json-pow5:end"
86
- const region = [
87
- `${BEGIN} -- generated by scripts/gen-json-pow5.mjs; edit that, not this.`,
88
- "/**",
89
- ` * The 128-bit truncation of 5^q, high word at \`2 × (q + ${-SMALLEST})\` and low word`,
90
- ` * after it, for q from ${SMALLEST} to ${LARGEST}: for q ≥ 0, 5^q shifted until its top bit`,
91
- " * is bit 127; for q < 0, 2^b / 5^-q rounded up, for the b that puts its top",
92
- " * bit there. Upstream's `power_of_five_128`.",
93
- " *",
94
- " * A function over a `switch` rather than an array for `std/crypto/sha512.ts`'s",
95
- " * reason: a module constant cannot be an array, and LLVM turns a `switch`",
96
- " * whose every arm is a constant into one read-only table. `index` is computed",
97
- " * from the exponent, which `numberF64` has bounded.",
98
- " */",
99
- "const jsonTokPowerOfFive = (index: i32): u64 => {",
100
- " switch (index) {",
101
- ...cases,
102
- ` // Unreachable: \`jsonTokEiselLemire\` asks only for 0 to ${words.length - 1}.`,
103
- " default:",
104
- " return toU64(0)",
105
- " }",
106
- "}",
107
- END,
108
- ].join("\n")
109
-
110
- const source = fs.readFileSync(target, "utf8")
111
- const from = source.indexOf(BEGIN)
112
- const to = source.indexOf(END)
113
- if (from < 0 || to < from) {
114
- console.error(`gen-json-pow5: no ${BEGIN} ... ${END} region in ${path.relative(root, target)}`)
115
- process.exit(1)
116
- }
117
- const next = source.slice(0, from) + region + source.slice(to + END.length)
118
-
119
- if (process.argv.includes("--check")) {
120
- if (next !== source) {
121
- console.error(
122
- `gen-json-pow5: the table in ${path.relative(root, target)} is not what the generator writes; run node scripts/gen-json-pow5.mjs`
123
- )
124
- process.exit(1)
125
- }
126
- console.log(`gen-json-pow5: ${words.length} words, as generated`)
127
- } else {
128
- fs.writeFileSync(target, next)
129
- console.log(`gen-json-pow5: wrote ${words.length} words to ${path.relative(root, target)}`)
130
- }