nish 0.36.0 → 0.38.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 (108) hide show
  1. package/README.md +8 -7
  2. package/docs/AI.md +75 -14
  3. package/docs/INSTALL.md +92 -71
  4. package/package.json +12 -7
  5. package/runtime/async.d.mts +2 -0
  6. package/runtime/async.mjs +7 -0
  7. package/runtime/core/arrays.d.ts +4 -0
  8. package/runtime/core/arrays.mjs +33 -0
  9. package/runtime/nish.d.ts +1045 -512
  10. package/runtime/nish.h +53 -6
  11. package/runtime/page.d.ts +53 -0
  12. package/runtime/page.mjs +146 -0
  13. package/runtime/runtime-async.c +740 -0
  14. package/runtime/runtime-cross.c +2 -1
  15. package/runtime/runtime-region.c +85 -7
  16. package/runtime/runtime-text.c +1068 -0
  17. package/runtime/runtime-wasm.c +65 -9
  18. package/runtime/runtime.c +50 -961
  19. package/runtime/vite.mjs +48 -11
  20. package/scripts/build.sh +231 -31
  21. package/scripts/fuzz.sh +59 -8
  22. package/scripts/gen-pow10-table.py +1 -1
  23. package/scripts/postinstall.mjs +8 -7
  24. package/scripts/size-report.sh +2 -2
  25. package/scripts/undocumented.txt +14 -0
  26. package/std/LICENSE-fdlibm +8 -0
  27. package/std/README.md +109 -82
  28. package/std/array.ts +266 -0
  29. package/std/bytes.ts +23 -19
  30. package/std/compress/checksum.ts +1 -1
  31. package/std/crypto/aes.ts +48 -43
  32. package/std/crypto/base64url.ts +7 -5
  33. package/std/crypto/bcrypt-batch.ts +13 -13
  34. package/std/crypto/bcrypt.ts +33 -27
  35. package/std/crypto/chacha20poly1305.ts +16 -14
  36. package/std/crypto/ed25519.ts +19 -16
  37. package/std/crypto/hmac.ts +7 -6
  38. package/std/crypto/jwt.ts +23 -20
  39. package/std/crypto/p256.ts +63 -56
  40. package/std/crypto/p384.ts +23 -20
  41. package/std/crypto/pki.ts +18 -15
  42. package/std/crypto/rsa.ts +23 -19
  43. package/std/crypto/x25519.ts +11 -10
  44. package/std/crypto/x509.ts +69 -62
  45. package/std/host/ring.ts +124 -0
  46. package/std/host/text.ts +86 -0
  47. package/std/json-equal.ts +12 -11
  48. package/std/json-number.ts +12 -12
  49. package/std/json-tokenizer.ts +26 -22
  50. package/std/json-typed.ts +92 -78
  51. package/std/json-value.ts +38 -33
  52. package/std/json.ts +32 -28
  53. package/std/math.ts +743 -41
  54. package/std/net/dns-resolver.ts +46 -6
  55. package/std/net/dns.ts +50 -13
  56. package/std/net/fetch.ts +1744 -295
  57. package/std/net/handler.ts +30 -0
  58. package/std/net/hpack.ts +29 -26
  59. package/std/net/http-compress.ts +42 -28
  60. package/std/net/http-fields.ts +19 -4
  61. package/std/net/http1-client-codec.ts +29 -25
  62. package/std/net/http1-codec.ts +62 -91
  63. package/std/net/http1-server.ts +79 -57
  64. package/std/net/http2-frame.ts +17 -16
  65. package/std/net/http2-tls.ts +17 -15
  66. package/std/net/http2.ts +67 -54
  67. package/std/net/http3-frame.ts +11 -10
  68. package/std/net/http3-server.ts +36 -35
  69. package/std/net/http3.ts +70 -58
  70. package/std/net/postgres-async.ts +1005 -0
  71. package/std/net/postgres.ts +185 -164
  72. package/std/net/prefork.ts +38 -34
  73. package/std/net/qpack.ts +15 -14
  74. package/std/net/quic-conn-ack.ts +1 -0
  75. package/std/net/quic-conn-cid.ts +11 -0
  76. package/std/net/quic-conn-params.ts +41 -14
  77. package/std/net/quic-datagram.ts +7 -0
  78. package/std/net/quic-frame.ts +48 -12
  79. package/std/net/quic-listener.ts +61 -44
  80. package/std/net/quic-packet.ts +71 -52
  81. package/std/net/quic-recovery.ts +59 -21
  82. package/std/net/quic-stream.ts +83 -55
  83. package/std/net/quic.ts +204 -152
  84. package/std/net/serve.ts +763 -0
  85. package/std/net/tls/client.ts +1 -0
  86. package/std/net/tls/codec.ts +81 -12
  87. package/std/net/tls/record-client.ts +30 -18
  88. package/std/net/tls/record-server.ts +74 -46
  89. package/std/net/tls/record.ts +33 -24
  90. package/std/net/tls/ticket.ts +2 -0
  91. package/std/net/tls/verify.ts +8 -7
  92. package/std/net/tls-tcp.ts +58 -50
  93. package/std/net/tls.ts +55 -43
  94. package/std/net/url.ts +12 -9
  95. package/std/net/websocket.ts +23 -19
  96. package/std/net/webtransport.ts +24 -18
  97. package/std/random.ts +8 -6
  98. package/std/regex.ts +70 -59
  99. package/std/sync/ring.ts +24 -21
  100. package/std/sync/shm.ts +9 -7
  101. package/std/term-io.ts +17 -14
  102. package/std/term-probe.ts +11 -10
  103. package/std/term-rate.ts +71 -61
  104. package/std/term.ts +73 -59
  105. package/std/text.ts +242 -15
  106. package/std/threads.ts +19 -15
  107. package/std/yaml-json.ts +17 -15
  108. package/std/yaml-write.ts +21 -14
package/runtime/vite.mjs CHANGED
@@ -23,7 +23,7 @@
23
23
  * `resolveId`, `load`), so `tests/run.js` calls them directly, with no Vite.
24
24
  */
25
25
  import { execFile } from "node:child_process";
26
- import { mkdirSync, readFileSync } from "node:fs";
26
+ import { mkdirSync, readFileSync, statSync } from "node:fs";
27
27
  import path from "node:path";
28
28
  import { fileURLToPath } from "node:url";
29
29
  import { promisify } from "node:util";
@@ -68,6 +68,15 @@ function exportNames(dts) {
68
68
  return names;
69
69
  }
70
70
 
71
+ /** Vite's default `resolve.extensions`, in the order it tries them. */
72
+ const VITE_EXTENSIONS = [".mjs", ".js", ".mts", ".ts", ".jsx", ".tsx", ".json"];
73
+
74
+ /** Whether `p` is a file (`"file"`), a directory (`"dir"`) or neither. */
75
+ const kind = (p) => {
76
+ const st = statSync(p, { throwIfNoEntry: false });
77
+ return st?.isFile() ? "file" : st?.isDirectory() ? "dir" : undefined;
78
+ };
79
+
71
80
  /** The plugin. `compiler` and `buildScript` default to the ones in this package. */
72
81
  export default function nish(options = {}) {
73
82
  const compiler = options.compiler ?? path.join(packageDir, "bin", "nish");
@@ -77,9 +86,11 @@ export default function nish(options = {}) {
77
86
  let building = false;
78
87
  let cacheDir = path.join(root, "node_modules", ".vite");
79
88
  let entries = new Set();
89
+ let extensions = VITE_EXTENSIONS;
80
90
 
81
91
  const configure = (config) => {
82
92
  root = config.root ?? root;
93
+ extensions = config.resolve?.extensions ?? VITE_EXTENSIONS;
83
94
  building = config.command === "build";
84
95
  cacheDir = config.cacheDir ?? path.join(root, "node_modules", ".vite");
85
96
  entries = new Set((options.entries ?? []).map((e) => path.resolve(root, e)));
@@ -96,13 +107,26 @@ export default function nish(options = {}) {
96
107
  const host = (options.host ?? []).flatMap((h) => ["--host", path.resolve(root, h)]);
97
108
  await run(compiler, [entry, "--target", "wasm32", ...host, "--emit-dts", dts, "-o", ll], { cwd: root });
98
109
  const loader = path.join(dir, `${stem}.mjs`);
110
+ const loaderText = readFileSync(loader, "utf8");
111
+ // The generated module imports `loadSync`. A compiler older than it writes
112
+ // a loader without one, which Rollup would report only as a missing
113
+ // export of a file in the cache, naming neither the compiler nor the fix.
114
+ if (!/^export function loadSync\(/m.test(loaderText)) {
115
+ const version = await run(compiler, ["--version"], { cwd: root }).then(
116
+ (r) => r.stdout.trim(),
117
+ () => "an unknown version",
118
+ );
119
+ throw new Error(
120
+ `nish/vite: the compiler ${compiler} (${version}) wrote a loader with no \`loadSync\` export: ` +
121
+ "it predates `loadSync` (WP50 stage 1), which the generated module calls. " +
122
+ "Use a newer one: update the nish package, or pass its path as `nish({ compiler })`.",
123
+ );
124
+ }
99
125
  const ir = readFileSync(ll, "utf8");
100
126
  // runtime-wasm.c is linked when the IR needs a runtime function (a weak
101
127
  // `extern_weak` one, a panic stub wasm-ld writes itself, does not count)
102
128
  // or the loader calls the arena.
103
- const needsRuntime =
104
- /^declare (?!extern_weak)[^"\n]*@nish_/m.test(ir) ||
105
- readFileSync(loader, "utf8").includes("raw.nish_arena_mark(");
129
+ const needsRuntime = /^declare (?!extern_weak)[^"\n]*@nish_/m.test(ir) || loaderText.includes("raw.nish_arena_mark(");
106
130
  const inline = path.join(dir, `${stem}.bytes.mjs`);
107
131
  const inputs = needsRuntime ? [ll, runtimeWasm] : [ll];
108
132
  await run("bash", [buildScript, ...inputs, "-o", path.join(dir, `${stem}.wasm`), "--profile", "wasm-host", "--inline", inline], {
@@ -117,16 +141,29 @@ export default function nish(options = {}) {
117
141
  enforce: "pre",
118
142
  configResolved: configure,
119
143
  async resolveId(source, importer) {
120
- if (!building) return null;
144
+ if (!building || entries.size === 0) return null;
121
145
  // The seam for a `./client.nish` specifier (the page's client module of a
122
146
  // later stage) is here; stage 1 resolves only the entries.
147
+ // A specifier may leave out the `.ts`, or name a directory for its
148
+ // `index.ts`. It is resolved as Vite would, file then extensions in
149
+ // order then the directory's index, so a sibling `add.js` keeps `./add`.
123
150
  const base = importer ? path.dirname(importer) : root;
124
- const candidates = source.startsWith(".")
125
- ? [path.resolve(base, source)]
126
- : path.isAbsolute(source)
127
- ? [source, path.join(root, source)]
128
- : [];
129
- const hit = candidates.find((c) => entries.has(c));
151
+ // A candidate that no entry's path starts with resolves to no entry, so
152
+ // it is dropped before anything is read from the disk.
153
+ const candidates = (
154
+ source.startsWith(".")
155
+ ? [path.resolve(base, source)]
156
+ : path.isAbsolute(source)
157
+ ? [source, path.join(root, source)]
158
+ : []
159
+ ).filter((c) => [...entries].some((e) => e.startsWith(c)));
160
+ if (candidates.length === 0) return null;
161
+ const withExtension = (stem) => extensions.map((e) => stem + e).find((f) => kind(f) === "file");
162
+ const resolve = (c) => {
163
+ if (entries.has(c) || kind(c) === "file") return c;
164
+ return withExtension(c) ?? (kind(c) === "dir" ? withExtension(path.join(c, "index")) : undefined);
165
+ };
166
+ const hit = candidates.map(resolve).find((c) => c !== undefined && entries.has(c));
130
167
  return hit === undefined ? null : PREFIX + hit;
131
168
  },
132
169
  async load(id) {
package/scripts/build.sh CHANGED
@@ -3,8 +3,9 @@
3
3
  #
4
4
  # scripts/build.sh <module.ll> [more .ll/.c files...] -o <out> [--profile debug|speed|size|wasm|wasm-host|wasi|napi]
5
5
  #
6
- # The C runtime is sixteen translation units and is named as one: an input
7
- # <dir>/runtime.c also compiles <dir>/runtime-os.c, the half that wraps the
6
+ # The C runtime is seventeen translation units and is named as one: an input
7
+ # <dir>/runtime.c also compiles <dir>/runtime-text.c, the strings and the digits
8
+ # of numbers, <dir>/runtime-os.c, the half that wraps the
8
9
  # system calls (files, directories, subprocesses, the environment, the clock),
9
10
  # <dir>/runtime-parallel.c, the half that divides a range of work across
10
11
  # threads, <dir>/runtime-cross.c, the copies that carry a string or an array
@@ -20,7 +21,9 @@
20
21
  # <dir>/runtime-bytes.c, the byte-class runs of `nish/bytes`,
21
22
  # <dir>/runtime-sandbox.c, the confinement `--sandbox` applies,
22
23
  # <dir>/runtime-shm.c, the shared-memory regions of `nish/sync/shm`, and
23
- # <dir>/runtime-region.c, the arenas a program makes and frees one at a time. Each of those
24
+ # <dir>/runtime-region.c, the arenas a program makes and frees one at a time, and,
25
+ # only for a program whose IR declares one of its functions,
26
+ # <dir>/runtime-async.c, the executor `spawn` and `nish:async`'s waits park tasks on. Each of those
24
27
  # files says why they are compiled and measured apart.
25
28
  #
26
29
  # Profiles:
@@ -39,10 +42,13 @@
39
42
  # when runtime-wasm.c is linked, the arena entry points the
40
43
  # `--emit-dts` loader calls (nish_arena_mark, nish_arena_release,
41
44
  # nish_alloc_array, nish_reset_arena, nish_free_arena). The stack is
42
- # a fixed 64 KiB (-z stack-size=65536). Runs `wasm-opt -Oz` on the
43
- # module when wasm-opt (binaryen) is on PATH; the build line says
44
- # whether it ran. Two flags take this profile alone, and any other
45
- # refuses them with exit 2:
45
+ # a fixed 64 KiB (-z stack-size=65536). Runs `wasm-opt -Oz
46
+ # --strip-target-features` on the module when wasm-opt (binaryen)
47
+ # is on PATH; the build line says whether it ran. NISH_WASM_OPT=0
48
+ # links without it even when it is installed (clang's own wasm-opt
49
+ # call too): the module a machine without binaryen builds, which
50
+ # the size guard measures. Two flags take this profile alone, and
51
+ # any other refuses them with exit 2:
46
52
  # --memory <MiB> memory fixed at <MiB> MiB (1 to 4096), the
47
53
  # initial size and the maximum both, so it
48
54
  # never grows and `memory.buffer` is one
@@ -120,7 +126,7 @@
120
126
  #
121
127
  # The runtime compiled once (the debug, speed and size profiles only; `nish
122
128
  # --link` and `nish run` use these through their runtime cache, src/compile.ts):
123
- # --runtime-objects <dir> compile the runtime.c input and its seven siblings,
129
+ # --runtime-objects <dir> compile the runtime.c input, its sixteen halves and runtime-async.c,
124
130
  # one $CC -c each and all at once, into
125
131
  # <dir>/<unit>.o with the profile's compile flags,
126
132
  # and link nothing. speed and size store LTO bitcode,
@@ -265,8 +271,8 @@ if [ -n "$sqlite_to" ] || [ -n "$sqlite_from" ]; then
265
271
  fi
266
272
  [ -n "$out" ] || [ -n "$objects_to" ] || [ -n "$sqlite_to" ] || { echo "error: -o <out> is required" >&2; exit 2; }
267
273
 
268
- # The runtime is sixteen translation units, and a caller names one: whoever passes
269
- # <dir>/runtime.c gets <dir>/runtime-os.c, <dir>/runtime-parallel.c,
274
+ # The runtime is seventeen translation units, and a caller names one: whoever passes
275
+ # <dir>/runtime.c gets <dir>/runtime-text.c, <dir>/runtime-os.c, <dir>/runtime-parallel.c,
270
276
  # <dir>/runtime-cross.c, <dir>/runtime-host.c, <dir>/runtime-net.c, <dir>/runtime-simd.c,
271
277
  # <dir>/runtime-aes.c, <dir>/runtime-sha256.c, <dir>/runtime-chacha20.c, <dir>/runtime-checksum.c, <dir>/runtime-term.c,
272
278
  # <dir>/runtime-bytes.c, <dir>/runtime-sandbox.c, <dir>/runtime-shm.c and <dir>/runtime-region.c compiled beside it, on every profile,
@@ -278,7 +284,7 @@ fi
278
284
  # compiles to two functions that refuse to run, which no wasm build calls, and
279
285
  # runtime-shm.c answers -95 for every region. They were one file until the
280
286
  # operating-system half was split out for its own size budget, and the parallel
281
- # half followed for the same reason (each file's header comment says why), and
287
+ # and text halves followed for the same reason (each file's header comment says why), and
282
288
  # a link line is where those splits
283
289
  # would otherwise leak: `nish --link` builds its command line in
284
290
  # src/compile.ts, the published package's recipe in every document and
@@ -286,7 +292,7 @@ fi
286
292
  # here keeps every one of those correct, and keeps "the runtime" one thing to
287
293
  # name from the outside. A caller that names one itself is left alone, because
288
294
  # naming one object twice is a duplicate-symbol error.
289
- halves="runtime-os.c runtime-parallel.c runtime-cross.c runtime-host.c runtime-net.c runtime-simd.c runtime-aes.c runtime-sha256.c runtime-chacha20.c runtime-checksum.c runtime-term.c runtime-bytes.c runtime-sandbox.c runtime-shm.c runtime-region.c"
295
+ halves="runtime-text.c runtime-os.c runtime-parallel.c runtime-cross.c runtime-host.c runtime-net.c runtime-simd.c runtime-aes.c runtime-sha256.c runtime-chacha20.c runtime-checksum.c runtime-term.c runtime-bytes.c runtime-sandbox.c runtime-shm.c runtime-region.c"
290
296
  for i in ${inputs[@]+"${inputs[@]}"}; do
291
297
  case "$i" in
292
298
  */runtime.c|runtime.c)
@@ -335,6 +341,34 @@ for i in ${inputs[@]+"${inputs[@]}"}; do
335
341
  *.c) if [ -n "$sqlite_dir" ] && [ "$(cd "$(dirname -- "$i")" && pwd -P)" = "$sqlite_dir" ]; then sqlite_wanted=0; break; fi ;;
336
342
  esac
337
343
  done
344
+ # The async executor (runtime-async.c) is selected by the IR the same way: a
345
+ # module that declares one of its `nish_async_*` functions -- every program
346
+ # that spawns, awaits a kernel wait or runs an async main does -- gets it
347
+ # compiled and linked beside runtime.c. Any other program links none of it, so
348
+ # its binary holds no `nish_async` symbol and its bytes stay as they were.
349
+ # `--runtime-objects` compiles it with the rest, so the runtime cache holds it,
350
+ # and `--runtime-from` links its object only when it is wanted. A caller that
351
+ # names it itself is left alone, as `halves` leaves a half.
352
+ async_wanted=0
353
+ if [ ${#lls[@]} -gt 0 ] && grep -Eq '^declare [^"]*@nish_async_' "${lls[@]}"; then
354
+ async_wanted=1
355
+ fi
356
+ if [ "$async_wanted" = 1 ]; then
357
+ for i in ${inputs[@]+"${inputs[@]}"}; do
358
+ case "$i" in
359
+ */runtime-async.c|runtime-async.c) async_wanted=0 ;;
360
+ esac
361
+ done
362
+ fi
363
+ if [ "$async_wanted" = 1 ] && [ -z "$objects_from" ]; then
364
+ for i in ${inputs[@]+"${inputs[@]}"}; do
365
+ case "$i" in
366
+ */runtime.c|runtime.c)
367
+ side="${i%runtime.c}runtime-async.c"
368
+ if [ -f "$side" ]; then inputs+=("$side"); fi ;;
369
+ esac
370
+ done
371
+ fi
338
372
  if [ "$sqlite_wanted" = 1 ] && [ -z "$sqlite_dir" ]; then
339
373
  echo "error: the module calls SQLite, and $(dirname "$0")/../runtime/sqlite/ is not there" >&2
340
374
  exit 2
@@ -346,6 +380,12 @@ fi
346
380
 
347
381
  CC=${CC:-clang}
348
382
  common=(-Wno-override-module) # our IR is target-neutral; clang fills the triple in
383
+ # -ffp-contract=off on every unit, every profile (WP50 S5): clang's default
384
+ # contracts a*b+c in C into one fused multiply-add wherever the target has one
385
+ # (arm64 always, x86-64 at v3), which rounds once where the source rounds
386
+ # twice, so the runtime would print another float on arm64 than on x86-64.
387
+ # Nish's own IR asks for no contraction, so the flag changes only the C units.
388
+ common+=(-ffp-contract=off)
349
389
  elf=() # flags that only make sense for ELF targets
350
390
  lld=0 # 1 when the link goes through ld.lld
351
391
 
@@ -417,10 +457,10 @@ if [ "$debug" = 1 ]; then common+=(-g); strip_flag=(); fi
417
457
  # runtime-parallel.c compiles to its sequential fallback because it tests
418
458
  # __wasi__ and __wasm__ as well as the macro.
419
459
  # --cpu: every unit at the one level, so the module, the runtime and the link
420
- # (LTO generates code there) agree. -ffp-contract=off keeps the meaning fixed:
421
- # v3 has FMA, and contracting a*b+c into one rounding would print a different
422
- # float than the baseline build (docs/LANGUAGE.md, "The CPU level").
423
- if [ -n "$cpu" ]; then common+=(-march=x86-64-v3 -ffp-contract=off); fi
460
+ # (LTO generates code there) agree. v3 has FMA, and the -ffp-contract=off every
461
+ # unit has above keeps a*b+c two roundings, so it prints the float the baseline
462
+ # build does (docs/LANGUAGE.md, "The CPU level").
463
+ if [ -n "$cpu" ]; then common+=(-march=x86-64-v3); fi
424
464
 
425
465
  # Hardening, on every native profile (the wasm and wasi ones build their own
426
466
  # command line and have none of these to give). docs/security/runtime.md
@@ -656,7 +696,7 @@ if [ -n "$objects_to" ]; then
656
696
  # the file `runtime.c` in the runtime's own directory, whichever directory
657
697
  # the first link that compiled it was run in.
658
698
  runtime_dir=$(dirname -- "$runtime")
659
- for unit in runtime.c $halves; do
699
+ for unit in runtime.c $halves runtime-async.c; do
660
700
  (cd -- "$runtime_dir" && exec "$CC" "${compile[@]}" -c "$unit" -o "$objects_to/${unit%.c}.o") &
661
701
  pids+=("$!")
662
702
  done
@@ -694,6 +734,10 @@ if [ -n "$objects_from" ]; then
694
734
  for unit in runtime.c $halves; do
695
735
  objects+=("$objects_from/${unit%.c}.o")
696
736
  done
737
+ if [ "$async_wanted" = 1 ]; then
738
+ [ -f "$objects_from/runtime-async.o" ] || { echo "error: --runtime-from: $objects_from/runtime-async.o is missing" >&2; exit 2; }
739
+ objects+=("$objects_from/runtime-async.o")
740
+ fi
697
741
  inputs=("${objects[@]}")
698
742
  # clang runs dsymutil itself when one command compiles and links with -g on
699
743
  # macOS; a link of objects does not, so it is run here, while the program's
@@ -774,6 +818,21 @@ case "$profile" in
774
818
  if [ "$bytes_wanted" = 1 ] && [ "$bytes_named" = 0 ]; then
775
819
  inputs+=("$(cd "$(dirname "$0")/../runtime" && pwd)/runtime-bytes.c")
776
820
  fi
821
+ # IR that builds a string (`+`, a template, `String(x)`, a number's digits)
822
+ # calls runtime-text.c, which compiles freestanding for wasm32 (WP50 stage 4).
823
+ # It is added the same way, only for such IR and only when the caller has not
824
+ # named it; it allocates through runtime-wasm.c's arena, so that is linked too.
825
+ text_named=0
826
+ text_wanted=0
827
+ for i in ${inputs[@]+"${inputs[@]}"}; do
828
+ case "$i" in
829
+ */runtime-text.c|runtime-text.c) text_named=1 ;;
830
+ *.ll) if grep -qE '@nish_(str_|f64_format|json_put_f64)' "$i"; then text_wanted=1; fi ;;
831
+ esac
832
+ done
833
+ if [ "$text_wanted" = 1 ] && [ "$text_named" = 0 ]; then
834
+ inputs+=("$(cd "$(dirname "$0")/../runtime" && pwd)/runtime-text.c")
835
+ fi
777
836
  # IR compiled for the host rounds through runtime-simd.c's `nish_floor` and its
778
837
  # kin behind the constructor `nish_round_init` (#943). runtime-wasm.c has their
779
838
  # wasm32 bodies, and it is added the same way when such IR does not name it.
@@ -785,18 +844,121 @@ case "$profile" in
785
844
  *.ll) if grep -q '@nish_round_init' "$i"; then round_wanted=1; fi ;;
786
845
  esac
787
846
  done
847
+ if [ "$text_wanted" = 1 ]; then round_wanted=1; fi
848
+ # Under wasm-host a program whose loader guards panics (one with module
849
+ # storage or a host module: the compiler ends its IR with a
850
+ # `; nish.sites <count>` line) reports each panic through the page's
851
+ # `nish.panic` import, which runtime-wasm.c makes the call to when it is
852
+ # compiled with NISH_WASM_HOST. Any other program links the bytes it always
853
+ # did, with no import. IR with a tagged site links the runtime for the
854
+ # import, or the panic would stay the silent trap of an undefined weak
855
+ # stub; linked for that, it exports the arena entry points as any link of
856
+ # runtime-wasm.c does, since a guarded loader that moves an array marks
857
+ # and releases the arena around each call.
858
+ host_panics=0
859
+ if [ "$profile" = wasm-host ]; then
860
+ for i in ${inputs[@]+"${inputs[@]}"}; do
861
+ case "$i" in
862
+ *.ll) if grep -qE '^; nish\.sites [0-9]+$' "$i"; then host_panics=1; fi ;;
863
+ esac
864
+ done
865
+ fi
866
+ if [ "$host_panics" = 1 ] && [ "$wasm_named" = 0 ] && [ "$round_wanted" = 0 ]; then
867
+ for i in ${inputs[@]+"${inputs[@]}"}; do
868
+ case "$i" in
869
+ *.ll) if grep -qE '^[[:space:]]+call void @nish_panic[A-Za-z0-9_]*\(.*, !nish\.site !\{i32 ' "$i"; then round_wanted=1; fi ;;
870
+ esac
871
+ done
872
+ fi
788
873
  if [ "$round_wanted" = 1 ] && [ "$wasm_named" = 0 ]; then
789
874
  inputs+=("$(cd "$(dirname "$0")/../runtime" && pwd)/runtime-wasm.c")
790
875
  fi
791
876
  # -mbulk-memory lowers llvm.memset/memcpy (`new Array<T>(n)`, `push` growth) to the
792
877
  # memory.fill/memory.copy instructions instead of libc calls the freestanding link lacks.
793
- wasm_compile=(-Wno-override-module --target=wasm32-unknown-unknown -Oz -nostdlib -mbulk-memory)
878
+ wasm_compile=(-Wno-override-module --target=wasm32-unknown-unknown -Oz -nostdlib -mbulk-memory -ffp-contract=off)
794
879
  if [ "$profile" = wasm ]; then
795
880
  "$CC" "${wasm_compile[@]}" \
796
881
  ${tls[@]+"${tls[@]}"} \
797
882
  -Wl,--no-entry -Wl,--export-all -Wl,--strip-all -Wl,--gc-sections \
798
883
  "${inputs[@]}" -o "$out"
799
884
  else
885
+ # Panic sites (WP50 stage 3). For a program whose loader guards panics
886
+ # the compiler tags each call of a runtime panic `!nish.site !{i32 N}`
887
+ # and lists the sites at the end of the module as
888
+ # `; nish.site N <kind> <path:line:col>` comments; code generation drops
889
+ # both, so `--profile wasm` links what it always did. Here each tagged
890
+ # call becomes its `_at` form taking the site as a first argument,
891
+ # numbered across the inputs, runtime-wasm.c (compiled with
892
+ # NISH_WASM_HOST) hands it to the page's `nish.panic` import, and the
893
+ # sites are written to `<out>.sites.json` for the loader. A program
894
+ # without the `; nish.sites` line has no tag, no import and no sidecar,
895
+ # and its build never touches `<out>.sites.json`; a guarded build
896
+ # removes the one an earlier build left before it writes its own.
897
+ host_define=()
898
+ host_inputs=("${inputs[@]}")
899
+ if [ "$host_panics" = 1 ]; then
900
+ rm -f "$out.sites.json"
901
+ host_define=(-DNISH_WASM_HOST)
902
+ make_work
903
+ sites_dir="$work/sites"
904
+ mkdir -p "$sites_dir"
905
+ sites_base=0
906
+ sites_json="$sites_dir/sites"
907
+ : > "$sites_json"
908
+ host_inputs=()
909
+ for i in "${inputs[@]}"; do
910
+ case "$i" in
911
+ *.ll)
912
+ rewritten="$sites_dir/${#host_inputs[@]}.ll"
913
+ awk -v base="$sites_base" -v list="$sites_json" '
914
+ # One tagged call: "call void @nish_panic<x>(<args>)<attrs>, !nish.site !{i32 N}<rest>".
915
+ # (`close` is a builtin, so the brace is `shut`.)
916
+ function untag(line, at, rest, shut, n, head, open, args) {
917
+ at = index(line, ", !nish.site !{i32 ")
918
+ rest = substr(line, at + 19)
919
+ shut = index(rest, "}")
920
+ n = substr(rest, 1, shut - 1) + base
921
+ head = substr(line, 1, at - 1)
922
+ open = index(head, "(")
923
+ args = substr(head, open + 1)
924
+ return substr(head, 1, open - 1) "_at(i32 " n (substr(args, 1, 1) == ")" ? "" : ", ") args substr(rest, shut + 1)
925
+ }
926
+ /^; nish\.site [0-9]+ / {
927
+ kind = $4
928
+ where = $0
929
+ sub(/^; nish\.site [0-9]+ [a-z]+ /, "", where)
930
+ gsub(/\\/, "\\\\", where)
931
+ gsub(/"/, "\\\"", where)
932
+ printf " { \"kind\": \"%s\", \"at\": \"%s\" }\n", kind, where >> list
933
+ count++
934
+ print
935
+ next
936
+ }
937
+ /^declare [a-z_ ]*void @nish_panic[a-z_]*\(/ {
938
+ print
939
+ open = index($0, "(")
940
+ print substr($0, 1, open - 1) "_at(i32" (substr($0, open + 1, 1) == ")" ? "" : ", ") substr($0, open + 1)
941
+ next
942
+ }
943
+ # Only a call line: a string constant may spell the tag in its bytes.
944
+ /^[ \t]+call void @nish_panic[A-Za-z0-9_]*\(.*, !nish\.site !\{i32 [0-9]+\}/ { print untag($0); next }
945
+ { print }
946
+ END { print count + 0 > (list ".count") }
947
+ ' "$i" > "$rewritten"
948
+ sites_base=$((sites_base + $(cat "$sites_json.count")))
949
+ host_inputs+=("$rewritten") ;;
950
+ *) host_inputs+=("$i") ;;
951
+ esac
952
+ done
953
+ {
954
+ printf '['
955
+ if [ -s "$sites_json" ]; then
956
+ printf '\n'
957
+ sed '$!s/$/,/' "$sites_json"
958
+ fi
959
+ printf ']\n'
960
+ } > "$out.sites.json"
961
+ fi
800
962
  # The export list. A module's exported functions are its `define` lines
801
963
  # with external linkage and default visibility: the compiler gives
802
964
  # everything else `internal` or `private`, and the other linkages are
@@ -811,7 +973,13 @@ case "$profile" in
811
973
  exports+=("-Wl,--export=$name")
812
974
  done < <(grep -E '^define ' "$i" \
813
975
  | grep -Ev '^define (internal|private|linkonce|linkonce_odr|weak|weak_odr|available_externally|extern_weak|common|hidden|protected) ' \
814
- | sed -nE 's/^[^@]*@"?([^"(]+)"?\(.*/\1/p') ;;
976
+ | sed -nE 's/^[^@]*@"?([^"(]+)"?\(.*/\1/p')
977
+ # Module storage (WP50 stage 3): each `@<name>.data` global is
978
+ # exported, and wasm-ld exports a data symbol as a global holding
979
+ # its address, which the loader reads into `layout.<name>.at`.
980
+ while IFS= read -r name; do
981
+ exports+=("-Wl,--export=$name")
982
+ done < <(sed -nE 's/^@"?([^" =]+\.data)"? = global .*/\1/p' "$i") ;;
815
983
  esac
816
984
  done
817
985
  if [ "$runtime_linked" = 1 ]; then
@@ -825,17 +993,49 @@ case "$profile" in
825
993
  bytes=$((memory_mib * 1048576))
826
994
  memory+=("-Wl,--initial-memory=$bytes" "-Wl,--max-memory=$bytes")
827
995
  fi
828
- "$CC" "${wasm_compile[@]}" \
829
- ${tls[@]+"${tls[@]}"} \
830
- -Wl,--no-entry ${exports[@]+"${exports[@]}"} "${memory[@]}" -Wl,--strip-all -Wl,--gc-sections \
831
- "${inputs[@]}" -o "$out"
832
996
  # binaryen's size pass is optional: the module is complete without it.
833
- if command -v wasm-opt >/dev/null 2>&1; then
834
- wasm-opt -Oz --enable-bulk-memory "$out" -o "$out"
835
- wasm_opt="wasm-opt -Oz"
836
- else
837
- wasm_opt="no wasm-opt"
838
- fi
997
+ # It runs twice when wasm-opt is installed. clang 18 runs it itself after
998
+ # any link with an -O flag, finding it on PATH, and has wasm-ld keep the
999
+ # `target_features` section for it: 48 bytes or more that nothing at
1000
+ # run time reads, which put add.wasm at 150 bytes against 102 without
1001
+ # wasm-opt (#1257). The pass below drops that section again.
1002
+ # NISH_WASM_OPT=0 runs neither: each source is compiled alone and the
1003
+ # objects linked with no -O flag, so clang starts no wasm-opt and the
1004
+ # module is byte for byte the one a machine without binaryen links.
1005
+ # That is the build the size guard pins.
1006
+ case "${NISH_WASM_OPT:-1}" in
1007
+ 0)
1008
+ make_work
1009
+ host_objects=()
1010
+ for i in "${host_inputs[@]}"; do
1011
+ # What clang compiles in a one-step link is compiled here (.ll, .c,
1012
+ # .bc, .s, ...); what it hands straight to wasm-ld passes through.
1013
+ case "$i" in
1014
+ *.o|*.a) host_objects+=("$i") ;;
1015
+ *)
1016
+ object="$work/host-${#host_objects[@]}.o"
1017
+ "$CC" "${wasm_compile[@]}" ${host_define[@]+"${host_define[@]}"} \
1018
+ ${tls[@]+"${tls[@]}"} -c "$i" -o "$object"
1019
+ host_objects+=("$object") ;;
1020
+ esac
1021
+ done
1022
+ "$CC" --target=wasm32-unknown-unknown -nostdlib \
1023
+ -Wl,--no-entry ${exports[@]+"${exports[@]}"} "${memory[@]}" -Wl,--strip-all -Wl,--gc-sections \
1024
+ "${host_objects[@]}" -o "$out"
1025
+ wasm_opt="no wasm-opt, NISH_WASM_OPT=0" ;;
1026
+ 1)
1027
+ "$CC" "${wasm_compile[@]}" ${host_define[@]+"${host_define[@]}"} \
1028
+ ${tls[@]+"${tls[@]}"} \
1029
+ -Wl,--no-entry ${exports[@]+"${exports[@]}"} "${memory[@]}" -Wl,--strip-all -Wl,--gc-sections \
1030
+ "${host_inputs[@]}" -o "$out"
1031
+ if command -v wasm-opt >/dev/null 2>&1; then
1032
+ wasm-opt -Oz --enable-bulk-memory --strip-target-features "$out" -o "$out"
1033
+ wasm_opt="wasm-opt -Oz"
1034
+ else
1035
+ wasm_opt="no wasm-opt"
1036
+ fi ;;
1037
+ *) echo "error: NISH_WASM_OPT must be 0 or 1, not '$NISH_WASM_OPT'" >&2; exit 2 ;;
1038
+ esac
839
1039
  if [ -n "$inline_to" ]; then
840
1040
  # Decimal, one array literal: of the inline forms the smallest after
841
1041
  # compression (docs/wp50-wasm-host.md, Q10). od prints each byte as an
@@ -885,9 +1085,9 @@ case "$profile" in
885
1085
  fi
886
1086
  # SQLite builds on wasi-libc as it is: the amalgamation sees __wasi__ and
887
1087
  # takes dot-file locking, no mmap and no WAL shared memory.
888
- sqlite_objects --target=wasm32-wasi --sysroot="$sysroot" -Oz -DNDEBUG \
1088
+ sqlite_objects --target=wasm32-wasi --sysroot="$sysroot" -Oz -DNDEBUG -ffp-contract=off \
889
1089
  ${tls[@]+"${tls[@]}"} -ffunction-sections -fdata-sections
890
- "$CC" -Wno-override-module --target=wasm32-wasi --sysroot="$sysroot" -Oz -DNDEBUG \
1090
+ "$CC" -Wno-override-module --target=wasm32-wasi --sysroot="$sysroot" -Oz -DNDEBUG -ffp-contract=off \
891
1091
  ${tls[@]+"${tls[@]}"} \
892
1092
  -ffunction-sections -fdata-sections -Wl,--gc-sections -Wl,--strip-all \
893
1093
  "${inputs[@]}" ${libs[@]+"${libs[@]}"} -o "$out" ;;
package/scripts/fuzz.sh CHANGED
@@ -7,7 +7,8 @@
7
7
  # scripts/fuzz.sh --replay [<name>] every corpus and regression
8
8
  # input once; a crash fails
9
9
  # scripts/fuzz.sh --smoke every target: build, replay,
10
- # then a short fixed-seed run
10
+ # then a short fixed-seed run,
11
+ # FUZZ_JOBS targets at a time
11
12
  #
12
13
  # A target is `tests/fuzz/targets/<name>.ts` exporting
13
14
  # `export const fuzzOne = (data: u8[]): void` (tests/fuzz/README.md). It is
@@ -24,6 +25,12 @@
24
25
  # std/ beside itself, so the seed would fuzz its own std.
25
26
  # FUZZ_SMOKE_SECONDS --smoke's fuzzing time per target (default 20)
26
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.
27
34
  # FUZZ_OUT where binaries, scratch corpora and artifacts go
28
35
  # (default build/fuzz)
29
36
  #
@@ -39,12 +46,14 @@ NISH="${NISH:-build/nish}"
39
46
  FUZZ_OUT="${FUZZ_OUT:-build/fuzz}"
40
47
  FUZZ_SMOKE_SECONDS="${FUZZ_SMOKE_SECONDS:-20}"
41
48
  FUZZ_SEED="${FUZZ_SEED:-1}"
49
+ FUZZ_JOBS="${FUZZ_JOBS:-$(getconf _NPROCESSORS_ONLN 2>/dev/null || echo 1)}"
42
50
  CC="${CC:-clang}"
43
51
 
44
52
  # The runtime's C units: tests/run.js's RUNTIME_C, which its `fuzz` section
45
53
  # checks this list against. runtime-wasm.c is wasm32's alone.
46
54
  RUNTIME_C=(
47
55
  runtime/runtime.c
56
+ runtime/runtime-text.c
48
57
  runtime/runtime-os.c
49
58
  runtime/runtime-parallel.c
50
59
  runtime/runtime-cross.c
@@ -60,6 +69,7 @@ RUNTIME_C=(
60
69
  runtime/runtime-sandbox.c
61
70
  runtime/runtime-shm.c
62
71
  runtime/runtime-region.c
72
+ runtime/runtime-async.c
63
73
  )
64
74
 
65
75
  SAN_FLAGS=(-g -O1 "-fsanitize=fuzzer,address,undefined" -fno-sanitize-recover=undefined)
@@ -71,7 +81,7 @@ die() {
71
81
  }
72
82
 
73
83
  usage() {
74
- sed -n '2,11p' "$0" | sed 's/^# \{0,1\}//' >&2
84
+ sed -n '2,12p' "$0" | sed 's/^# \{0,1\}//' >&2
75
85
  exit "${1:-2}"
76
86
  }
77
87
 
@@ -98,7 +108,7 @@ build_runtime() {
98
108
  local src obj
99
109
  for src in "${RUNTIME_C[@]}"; do
100
110
  obj="$FUZZ_OUT/obj/$(basename "$src" .c).o"
101
- "$CC" "${SAN_FLAGS[@]}" -DNISH_FUZZ_ABORT -Iruntime -c "$src" -o "$obj" \
111
+ "$CC" "${SAN_FLAGS[@]}" -ffp-contract=off -DNISH_FUZZ_ABORT -Iruntime -c "$src" -o "$obj" \
102
112
  || die "compiling $src under the sanitizers failed (is libclang-rt-18-dev installed?)"
103
113
  runtime_objs+=("$obj")
104
114
  done
@@ -212,13 +222,54 @@ case "$mode" in
212
222
  [ $# -eq 0 ] || usage
213
223
  mapfile -t names < <(targets)
214
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
215
240
  for name in "${names[@]}"; do
216
- build "$name"
217
- replay "$name"
218
- rm -rf "$FUZZ_OUT/work/$name"
219
- run "$name" -seed="$FUZZ_SEED" -max_total_time="$FUZZ_SMOKE_SECONDS" -print_final_stats=1
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))
220
255
  done
221
- echo "fuzz.sh: smoke passed over ${#names[@]} targets"
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"
222
273
  ;;
223
274
  -h | --help)
224
275
  usage 0
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env python3
2
- """Regenerate the power-of-ten table `runtime/runtime.c` uses for Zmij.
2
+ """Regenerate the power-of-ten table `runtime/runtime-text.c` uses for Zmij.
3
3
 
4
4
  python3 scripts/gen-pow10-table.py
5
5
 
@@ -53,13 +53,14 @@ import { pathToFileURL } from "node:url"
53
53
  const root = path.resolve(import.meta.dirname, "..")
54
54
 
55
55
  const swap = async () => {
56
- // A checkout, not an install. The repository is its own package, so `npm ci`
57
- // here installs this package's own optionalDependencies -- and without this
58
- // guard, the first `npm ci` after they are published would overwrite the
59
- // tracked `bin/nish` with a binary and leave the working tree dirty. The
60
- // landmark is `src/compile.ts`, which is the check `scripts/bootstrap.sh`
61
- // makes and is not in `files`; it used to be stage0's `src/launcher.ts`, which stopped
62
- // being a landmark when the launcher moved into `bin/` and ships.
56
+ // A checkout, not an install. The checked-in package.json pins no platform
57
+ // package (release.yml adds them at pack time), but a `node_modules` left from
58
+ // before it stopped can still hold one, and without this guard `npm ci` would
59
+ // overwrite the tracked `bin/nish` with that binary and leave the working
60
+ // tree dirty. The landmark is `src/compile.ts`, which is the check
61
+ // `scripts/bootstrap.sh` makes and is not in `files`; it used to be stage0's
62
+ // `src/launcher.ts`, which stopped being a landmark when the launcher moved
63
+ // into `bin/` and ships.
63
64
  if (fs.existsSync(path.join(root, "src", "compile.ts"))) {
64
65
  return "a checkout, so the shim stays"
65
66
  }