nish 0.28.0 → 0.30.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.
- package/README.md +5 -4
- package/docs/AI.md +114 -24
- package/docs/INSTALL.md +8 -5
- package/llms.txt +4 -2
- package/package.json +5 -5
- package/runtime/core/host.d.ts +2 -1
- package/runtime/core/host.mjs +4 -0
- package/runtime/nish.d.ts +127 -0
- package/runtime/nish.h +94 -5
- package/runtime/nish.mjs +18 -4
- package/runtime/runtime-net.c +386 -5
- package/runtime/runtime-os.c +59 -8
- package/runtime/runtime-parallel.c +60 -5
- package/runtime/runtime-region.c +231 -0
- package/runtime/runtime-sandbox.c +43 -34
- package/runtime/runtime-shm.c +541 -0
- package/runtime/runtime.c +838 -792
- package/scripts/build.sh +55 -12
- package/scripts/fuzz.sh +2 -0
- package/scripts/gen-pow10-table.py +80 -0
- package/scripts/gen-union-scale.mjs +294 -0
- package/scripts/size-report.sh +2 -2
- package/std/README.md +12 -3
- package/std/collections.ts +5 -5
- package/std/crypto/hmac.ts +305 -2
- package/std/crypto/jwt.ts +1661 -0
- package/std/json-typed.ts +34 -0
- package/std/json.ts +35 -6
- package/std/net/handler.ts +1348 -0
- package/std/net/http-client.ts +97 -16
- package/std/net/http-compress.ts +54 -12
- package/std/net/http1-client.ts +270 -41
- package/std/net/http1-server.ts +145 -32
- package/std/net/http1.ts +274 -51
- package/std/net/outbound.ts +409 -0
- package/std/net/postgres-carrier.ts +985 -0
- package/std/net/postgres.ts +297 -4
- package/std/net/prefork.ts +344 -20
- package/std/net/upstream.ts +759 -0
- package/std/secret.ts +1 -1
- package/std/sync/ring.ts +587 -0
- package/std/sync/shm.ts +284 -0
- package/std/term-rate.ts +13 -1
- package/std/threads.ts +35 -3
- package/scripts/gen-pow5-tables.py +0 -50
- /package/runtime/{LICENSE-ryu → LICENSE-zmij} +0 -0
package/scripts/build.sh
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
#
|
|
4
4
|
# scripts/build.sh <module.ll> [more .ll/.c files...] -o <out> [--profile debug|speed|size|wasm|wasi|napi]
|
|
5
5
|
#
|
|
6
|
-
# The C runtime is
|
|
6
|
+
# The C runtime is fifteen translation units and is named as one: an input
|
|
7
7
|
# <dir>/runtime.c also compiles <dir>/runtime-os.c, the half that wraps the
|
|
8
8
|
# system calls (files, directories, subprocesses, the environment, the clock),
|
|
9
9
|
# <dir>/runtime-parallel.c, the half that divides a range of work across
|
|
@@ -16,8 +16,10 @@
|
|
|
16
16
|
# <dir>/runtime-sha256.c, SHA-256 on the CPU's SHA instructions,
|
|
17
17
|
# <dir>/runtime-checksum.c, CRC-32 on its carry-less multiply or CRC instructions,
|
|
18
18
|
# <dir>/runtime-term.c, stdin and the terminal of `nish:term`,
|
|
19
|
-
# <dir>/runtime-bytes.c, the byte-class runs of `nish/bytes`,
|
|
20
|
-
# <dir>/runtime-sandbox.c, the confinement `--sandbox` applies
|
|
19
|
+
# <dir>/runtime-bytes.c, the byte-class runs of `nish/bytes`,
|
|
20
|
+
# <dir>/runtime-sandbox.c, the confinement `--sandbox` applies,
|
|
21
|
+
# <dir>/runtime-shm.c, the shared-memory regions of `nish/sync/shm`, and
|
|
22
|
+
# <dir>/runtime-region.c, the arenas a program makes and frees one at a time. Each of those
|
|
21
23
|
# files says why they are compiled and measured apart.
|
|
22
24
|
#
|
|
23
25
|
# Profiles:
|
|
@@ -112,6 +114,12 @@
|
|
|
112
114
|
# --sqlite-from <dir> link <dir>/<unit>.o in place of compiling
|
|
113
115
|
# runtime/sqlite/, when the IR calls SQLite.
|
|
114
116
|
# All four refuse the wasm, wasi and napi profiles and --pgo-*, with exit 2.
|
|
117
|
+
# --module-objects <dir> debug with --runtime-from only: the object of each
|
|
118
|
+
# input X.ll is <dir>/X.o, linked as it stands when
|
|
119
|
+
# the file is there and compiled into it when it is
|
|
120
|
+
# not, so the caller keeps every object it compiled
|
|
121
|
+
# (`nish run`'s module cache, src/build-cache.ts).
|
|
122
|
+
# The inputs' file names must differ.
|
|
115
123
|
#
|
|
116
124
|
# Works on Linux (clang + lld preferred, GNU ld tolerated) and macOS (Apple ld64
|
|
117
125
|
# or Homebrew llvm). Set CC to pick a compiler (default: clang on PATH).
|
|
@@ -128,6 +136,7 @@ objects_from="" # --runtime-from <dir>: link against the
|
|
|
128
136
|
cpu="" # --cpu x86-64-v3: the one CPU level above the baseline (WP38 S2)
|
|
129
137
|
sqlite_to="" # --sqlite-objects <dir>: compile runtime/sqlite/ alone, into <dir>
|
|
130
138
|
sqlite_from="" # --sqlite-from <dir>: link runtime/sqlite/ compiled there
|
|
139
|
+
modules_at="" # --module-objects <dir>: each X.ll's object is <dir>/X.o
|
|
131
140
|
while [ $# -gt 0 ]; do
|
|
132
141
|
case "$1" in
|
|
133
142
|
-o) out="$2"; shift 2 ;;
|
|
@@ -141,6 +150,7 @@ while [ $# -gt 0 ]; do
|
|
|
141
150
|
--runtime-from) objects_from="$2"; shift 2 ;;
|
|
142
151
|
--sqlite-objects) sqlite_to="$2"; shift 2 ;;
|
|
143
152
|
--sqlite-from) sqlite_from="$2"; shift 2 ;;
|
|
153
|
+
--module-objects) modules_at="$2"; shift 2 ;;
|
|
144
154
|
--pgo-generate) pgo=(-fprofile-generate); shift ;;
|
|
145
155
|
--pgo-use)
|
|
146
156
|
[ -f "$2" ] || { echo "error: --pgo-use: profile '$2' not found (run the instrumented binary, then llvm-profdata merge)" >&2; exit 2; }
|
|
@@ -195,6 +205,12 @@ if [ -n "$objects_to" ] || [ -n "$objects_from" ]; then
|
|
|
195
205
|
[ ${#pgo[@]} -eq 0 ] || { echo "error: --runtime-objects and --runtime-from do not take --pgo-*" >&2; exit 2; }
|
|
196
206
|
[ -z "$objects_to" ] || [ -z "$objects_from" ] || { echo "error: --runtime-objects and --runtime-from are two different builds" >&2; exit 2; }
|
|
197
207
|
fi
|
|
208
|
+
if [ -n "$modules_at" ]; then
|
|
209
|
+
[ -n "$objects_from" ] || { echo "error: --module-objects takes --runtime-from" >&2; exit 2; }
|
|
210
|
+
[ -d "$modules_at" ] || { echo "error: --module-objects: $modules_at is not a directory" >&2; exit 2; }
|
|
211
|
+
# Speed and size compile a module to LTO bitcode, not the native object kept there.
|
|
212
|
+
[ "$profile" = debug ] || { echo "error: --module-objects takes the debug profile, not '$profile'" >&2; exit 2; }
|
|
213
|
+
fi
|
|
198
214
|
if [ -n "$sqlite_to" ] || [ -n "$sqlite_from" ]; then
|
|
199
215
|
# The cached SQLite objects sit beside the cached runtime and take what it takes.
|
|
200
216
|
case "$profile" in
|
|
@@ -207,17 +223,18 @@ if [ -n "$sqlite_to" ] || [ -n "$sqlite_from" ]; then
|
|
|
207
223
|
fi
|
|
208
224
|
[ -n "$out" ] || [ -n "$objects_to" ] || [ -n "$sqlite_to" ] || { echo "error: -o <out> is required" >&2; exit 2; }
|
|
209
225
|
|
|
210
|
-
# The runtime is
|
|
226
|
+
# The runtime is fifteen translation units, and a caller names one: whoever passes
|
|
211
227
|
# <dir>/runtime.c gets <dir>/runtime-os.c, <dir>/runtime-parallel.c,
|
|
212
228
|
# <dir>/runtime-cross.c, <dir>/runtime-host.c, <dir>/runtime-net.c, <dir>/runtime-simd.c,
|
|
213
229
|
# <dir>/runtime-aes.c, <dir>/runtime-sha256.c, <dir>/runtime-checksum.c, <dir>/runtime-term.c,
|
|
214
|
-
# <dir>/runtime-bytes.c and <dir>/runtime-
|
|
230
|
+
# <dir>/runtime-bytes.c, <dir>/runtime-sandbox.c, <dir>/runtime-shm.c and <dir>/runtime-region.c compiled beside it, on every profile,
|
|
215
231
|
# wasi included: runtime-simd.c and runtime-bytes.c take their scalar paths there
|
|
216
232
|
# unless the build adds -msimd128,
|
|
217
233
|
# runtime-aes.c, runtime-sha256.c and runtime-checksum.c compile to an answer of 0 and
|
|
218
234
|
# stubs that nothing calls, because the compiler emits no call to their kernels for wasm32, and
|
|
219
235
|
# runtime-term.c reads stdin and answers "not a terminal", and runtime-sandbox.c
|
|
220
|
-
# compiles to two functions that refuse to run, which no wasm build calls
|
|
236
|
+
# compiles to two functions that refuse to run, which no wasm build calls, and
|
|
237
|
+
# runtime-shm.c answers -95 for every region. They were one file until the
|
|
221
238
|
# operating-system half was split out for its own size budget, and the parallel
|
|
222
239
|
# half followed for the same reason (each file's header comment says why), and
|
|
223
240
|
# a link line is where those splits
|
|
@@ -227,7 +244,7 @@ fi
|
|
|
227
244
|
# here keeps every one of those correct, and keeps "the runtime" one thing to
|
|
228
245
|
# name from the outside. A caller that names one itself is left alone, because
|
|
229
246
|
# naming one object twice is a duplicate-symbol error.
|
|
230
|
-
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-checksum.c runtime-term.c runtime-bytes.c runtime-sandbox.c"
|
|
247
|
+
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-checksum.c runtime-term.c runtime-bytes.c runtime-sandbox.c runtime-shm.c runtime-region.c"
|
|
231
248
|
for i in ${inputs[@]+"${inputs[@]}"}; do
|
|
232
249
|
case "$i" in
|
|
233
250
|
*/runtime.c|runtime.c)
|
|
@@ -262,11 +279,15 @@ if [ -n "$sqlite_to" ]; then
|
|
|
262
279
|
fi
|
|
263
280
|
sqlite_wanted=1
|
|
264
281
|
fi
|
|
282
|
+
# One grep reads every module, not one grep each: a program of forty modules
|
|
283
|
+
# spent a third of a second here starting greps.
|
|
284
|
+
lls=()
|
|
265
285
|
for i in ${inputs[@]+"${inputs[@]}"}; do
|
|
266
|
-
case "$i" in
|
|
267
|
-
*.ll) if grep -Eq '^declare [^"]*@(sqlite3|nishsqlite)_' "$i"; then sqlite_wanted=1; fi ;;
|
|
268
|
-
esac
|
|
286
|
+
case "$i" in *.ll) lls+=("$i") ;; esac
|
|
269
287
|
done
|
|
288
|
+
if [ ${#lls[@]} -gt 0 ] && grep -Eq '^declare [^"]*@(sqlite3|nishsqlite)_' "${lls[@]}"; then
|
|
289
|
+
sqlite_wanted=1
|
|
290
|
+
fi
|
|
270
291
|
for i in ${inputs[@]+"${inputs[@]}"}; do
|
|
271
292
|
case "$i" in
|
|
272
293
|
*.c) if [ -n "$sqlite_dir" ] && [ "$(cd "$(dirname -- "$i")" && pwd -P)" = "$sqlite_dir" ]; then sqlite_wanted=0; break; fi ;;
|
|
@@ -611,9 +632,19 @@ if [ -n "$objects_from" ]; then
|
|
|
611
632
|
for i in "${inputs[@]}"; do
|
|
612
633
|
case "$i" in */runtime.c|runtime.c) echo "error: --runtime-from links the runtime in $objects_from, so $i is not an input" >&2; exit 2 ;; esac
|
|
613
634
|
n=$((n + 1))
|
|
614
|
-
"$
|
|
635
|
+
object="$work/$n.o"
|
|
636
|
+
if [ -n "$modules_at" ]; then
|
|
637
|
+
case "$i" in
|
|
638
|
+
*.ll)
|
|
639
|
+
name=${i##*/}
|
|
640
|
+
object="$modules_at/${name%.ll}.o"
|
|
641
|
+
# An object the caller left there is this module's, compiled before.
|
|
642
|
+
if [ -f "$object" ]; then objects+=("$object"); continue; fi ;;
|
|
643
|
+
esac
|
|
644
|
+
fi
|
|
645
|
+
"$CC" "${module_compile[@]}" -c "$i" -o "$object" &
|
|
615
646
|
pids+=("$!")
|
|
616
|
-
objects+=("$
|
|
647
|
+
objects+=("$object")
|
|
617
648
|
done
|
|
618
649
|
join_jobs || { echo "error: a module did not compile" >&2; exit 1; }
|
|
619
650
|
# In the order the one-command link names them: the inputs, then runtime.c
|
|
@@ -641,6 +672,18 @@ case "$profile" in
|
|
|
641
672
|
"$CC" "${common[@]}" "${optimise[@]}" ${lto_parts[@]+"${lto_parts[@]}"} \
|
|
642
673
|
"${gc[@]}" ${strip_flag[@]+"${strip_flag[@]}"} "${inputs[@]}" -lm -o "$out" ;;
|
|
643
674
|
wasm)
|
|
675
|
+
# A region's chunks come from malloc, and the freestanding wasm runtime
|
|
676
|
+
# (runtime-wasm.c) has none, so IR that makes or enters one is refused here
|
|
677
|
+
# rather than failing at the link on an undefined `nish_region_*`. The wasi
|
|
678
|
+
# profile links runtime-region.c with the rest of the runtime.
|
|
679
|
+
for i in ${inputs[@]+"${inputs[@]}"}; do
|
|
680
|
+
case "$i" in
|
|
681
|
+
*.ll) if grep -q "@nish_region_" "$i"; then
|
|
682
|
+
echo "error: $i uses regions, which the wasm profile cannot link (it has no malloc); build it with --profile wasi" >&2
|
|
683
|
+
exit 2
|
|
684
|
+
fi ;;
|
|
685
|
+
esac
|
|
686
|
+
done
|
|
644
687
|
# clang resolves wasm-ld next to its own binary first, then on PATH; ask it
|
|
645
688
|
# rather than probing PATH so a Homebrew llvm without a PATH entry still works.
|
|
646
689
|
wasm_ld=$("$CC" -print-prog-name=wasm-ld)
|
package/scripts/fuzz.sh
CHANGED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Regenerate the power-of-ten table `runtime/runtime.c` uses for Zmij.
|
|
3
|
+
|
|
4
|
+
python3 scripts/gen-pow10-table.py
|
|
5
|
+
|
|
6
|
+
Prints the C to stdout; paste it over the `NISH_POW10_SIG` definition. The
|
|
7
|
+
point of having this in the tree is that the ~10 KB of constants in the
|
|
8
|
+
runtime are *derived*, with exact integer arithmetic, rather than transcribed
|
|
9
|
+
from somewhere -- so a reader can check them rather than trust them. See
|
|
10
|
+
docs/wp15-performance.md section 7a.
|
|
11
|
+
|
|
12
|
+
Each row is the 128-bit significand of 10^k, normalised so its top bit is set
|
|
13
|
+
and rounded *down*, as `{ hi, lo }`: the convention of Zmij's
|
|
14
|
+
`pow10_significands` (zmij.c, Copyright (c) 2025 - present, Victor Zverovich,
|
|
15
|
+
used under the Boost Software License, Version 1.0; runtime/LICENSE-zmij has
|
|
16
|
+
the text and THIRD_PARTY_NOTICES.md the entry). Upstream ships 10^-307 to
|
|
17
|
+
10^341 because its fixed-precision paths read further out; the shortest-digits
|
|
18
|
+
path, the only one ported, reaches fewer, and the range below is computed from
|
|
19
|
+
the same exponent arithmetic `nish_shortest_digits` does rather than copied.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
M = (1 << 64) - 1
|
|
23
|
+
EXP_OFFSET = 1075 # a double is sig * 2^(raw_exp - 1075)
|
|
24
|
+
EXTRA_SHIFT = 6
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def dec_exp_of(bin_exp, regular):
|
|
28
|
+
# compute_dec_exp: floor(log10(2^bin_exp)), or of 3/4 of it when irregular.
|
|
29
|
+
# Python's >> floors like the arithmetic shift clang emits for C's int.
|
|
30
|
+
return (bin_exp * 315653 - (0 if regular else 131072)) >> 20
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def exp_shift(bin_exp, dec_exp):
|
|
34
|
+
# compute_exp_shift(bin_exp, dec_exp + 1) + extra_shift, as the runtime does it.
|
|
35
|
+
return bin_exp + ((-(dec_exp + 1) * 217707) >> 16) + 1 + EXTRA_SHIFT
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def significand(k):
|
|
39
|
+
# floor(10^k * 2^s) for the s that leaves exactly 128 bits.
|
|
40
|
+
if k >= 0:
|
|
41
|
+
p = 10**k
|
|
42
|
+
s = 128 - p.bit_length()
|
|
43
|
+
v = p << s if s >= 0 else p >> -s
|
|
44
|
+
else:
|
|
45
|
+
p = 10**-k
|
|
46
|
+
# 2^(127 + b) / 10^-k with b the bit length of 10^-k lands in [2^127, 2^128).
|
|
47
|
+
v = (1 << (127 + p.bit_length())) // p
|
|
48
|
+
assert v >> 127 == 1, k
|
|
49
|
+
return v
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
# Every power the shortest path reads: raw_exp 1 (the subnormals and 2^-1022,
|
|
53
|
+
# which share its spacing) to 2046, the irregular branch only from 2 up.
|
|
54
|
+
reach = set()
|
|
55
|
+
for raw_exp in range(1, 2047):
|
|
56
|
+
bin_exp = raw_exp - EXP_OFFSET
|
|
57
|
+
for regular in (True, False) if raw_exp > 1 else (True,):
|
|
58
|
+
d = dec_exp_of(bin_exp, regular)
|
|
59
|
+
shift = exp_shift(bin_exp, d)
|
|
60
|
+
# `bin_sig << shift` must keep a 53-bit significand, and the half-ulp
|
|
61
|
+
# shift `extra_shift + 1 - shift` must be a legal shift count.
|
|
62
|
+
assert 0 <= shift and 53 + shift <= 64, (raw_exp, shift)
|
|
63
|
+
assert 0 <= EXTRA_SHIFT + 1 - shift < 64, (raw_exp, shift)
|
|
64
|
+
reach.add(-d - 1)
|
|
65
|
+
lo, hi = min(reach), max(reach)
|
|
66
|
+
assert reach == set(range(lo, hi + 1))
|
|
67
|
+
assert (lo, hi) == (-293, 323), (lo, hi)
|
|
68
|
+
|
|
69
|
+
# Spot checks against values a reader can do by hand.
|
|
70
|
+
assert significand(0) == 1 << 127
|
|
71
|
+
assert significand(-1) == int("cc" * 16, 16)
|
|
72
|
+
assert significand(1) == 0xA << 124
|
|
73
|
+
|
|
74
|
+
print(f"/* Generated by scripts/gen-pow10-table.py; do not hand-edit. 10^{lo} to 10^{hi}. */")
|
|
75
|
+
print(f"#define NISH_POW10_MIN ({lo})")
|
|
76
|
+
print(f"static const uint64_t NISH_POW10_SIG[{hi - lo + 1}][2] = {{")
|
|
77
|
+
for k in range(lo, hi + 1):
|
|
78
|
+
v = significand(k)
|
|
79
|
+
print(f" {{ 0x{v >> 64:016x}u, 0x{v & M:016x}u }},")
|
|
80
|
+
print("};")
|
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Write a discriminated union at typescript-go scale: the shape of its AST
|
|
4
|
+
* node data, with as many variants as asked.
|
|
5
|
+
*
|
|
6
|
+
* node scripts/gen-union-scale.mjs tests/cases/union_scale.ts, 200 variants
|
|
7
|
+
* node scripts/gen-union-scale.mjs --variants N N variants instead
|
|
8
|
+
* node scripts/gen-union-scale.mjs --nodes N build N nodes instead of 4000 (for timing the walk)
|
|
9
|
+
* node scripts/gen-union-scale.mjs --out FILE write FILE instead ("-" is stdout)
|
|
10
|
+
* node scripts/gen-union-scale.mjs --check exit 1 if the case is not what this writes
|
|
11
|
+
*
|
|
12
|
+
* The program is an `enum Kind` of N members; N classes, each tagged
|
|
13
|
+
* `readonly kind: Kind.X = Kind.X` and carrying 2 to 6 further fields (an
|
|
14
|
+
* `i32`, a `string`, a `Node | null` child, a `Node[]` of children); `type
|
|
15
|
+
* Node` over all of them; a builder that makes a tree of a few thousand nodes
|
|
16
|
+
* from a fixed seed; a `switch (n.kind)` over every variant that reads the
|
|
17
|
+
* variant's own fields; a forEachChild-style walk; and accessors for the two
|
|
18
|
+
* fields many variants share. Its checksum stays below 2^31 at every step, so
|
|
19
|
+
* Node prints what the native binary prints. The case's purpose is the
|
|
20
|
+
* compile time and the IR of a 200-way union (`tests/cases/union_scale.ts`),
|
|
21
|
+
* so the output is deterministic and the generator is the only author: edit
|
|
22
|
+
* this file, never the case.
|
|
23
|
+
*/
|
|
24
|
+
import { readFileSync, writeFileSync } from "node:fs"
|
|
25
|
+
import { dirname, join } from "node:path"
|
|
26
|
+
import { fileURLToPath } from "node:url"
|
|
27
|
+
|
|
28
|
+
const root = join(dirname(fileURLToPath(import.meta.url)), "..")
|
|
29
|
+
const args = process.argv.slice(2)
|
|
30
|
+
const flag = (option) => {
|
|
31
|
+
const at = args.indexOf(option)
|
|
32
|
+
return at < 0 ? null : args[at + 1]
|
|
33
|
+
}
|
|
34
|
+
const variants = Number(flag("--variants") ?? 200)
|
|
35
|
+
const nodes = Number(flag("--nodes") ?? 4000)
|
|
36
|
+
const out = flag("--out") ?? join(root, "tests/cases/union_scale.ts")
|
|
37
|
+
if (!Number.isInteger(variants) || variants < 2 || !Number.isInteger(nodes) || nodes < 1) {
|
|
38
|
+
console.error("gen-union-scale: --variants takes an integer of at least 2, --nodes one of at least 1")
|
|
39
|
+
process.exit(2)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Field kinds, in the order a variant's fields cycle through them.
|
|
43
|
+
const I32 = 0
|
|
44
|
+
const STR = 1
|
|
45
|
+
const CHILD = 2
|
|
46
|
+
const LIST = 3
|
|
47
|
+
|
|
48
|
+
/** The fields after the tag of variant `i`: 2 to 6, a fixed mix of kinds. */
|
|
49
|
+
const fieldsOf = (i) => {
|
|
50
|
+
const count = 2 + ((i * 7) % 5)
|
|
51
|
+
const fields = []
|
|
52
|
+
// `flags` and `name` are the fields many variants share, as typescript-go's
|
|
53
|
+
// node data shares `Flags` and `Name()`: an accessor switches over them.
|
|
54
|
+
if (i % 4 === 0) {
|
|
55
|
+
fields.push({ name: "flags", kind: I32 })
|
|
56
|
+
}
|
|
57
|
+
if (i % 3 === 0) {
|
|
58
|
+
fields.push({ name: "name", kind: STR })
|
|
59
|
+
}
|
|
60
|
+
for (let j = 0; fields.length < count; j++) {
|
|
61
|
+
const kind = (i * 3 + j) % 4
|
|
62
|
+
const prefix = ["v", "s", "c", "cs"][kind]
|
|
63
|
+
fields.push({ name: `${prefix}${j}`, kind })
|
|
64
|
+
}
|
|
65
|
+
// Laid out with no padding: one `i32` beside the tag fills its word, then
|
|
66
|
+
// the pointers, then the other `i32`s.
|
|
67
|
+
const ints = fields.filter((f) => f.kind === I32)
|
|
68
|
+
const refs = fields.filter((f) => f.kind !== I32)
|
|
69
|
+
return [...ints.slice(0, 1), ...refs, ...ints.slice(1)]
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const typeOf = (kind) => ["i32", "string", "Node | null", "Node[]"][kind]
|
|
73
|
+
|
|
74
|
+
const lines = []
|
|
75
|
+
const emit = (s = "") => lines.push(s)
|
|
76
|
+
const name = (i) => `N${i}`
|
|
77
|
+
const tag = (i) => `K${i}`
|
|
78
|
+
const all = Array.from({ length: variants }, (_, i) => {
|
|
79
|
+
const fields = fieldsOf(i)
|
|
80
|
+
return { i, fields, kids: fields.filter((f) => f.kind === CHILD || f.kind === LIST) }
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
/** The body of a walk's case: `call(child, state)` on every child and list element. */
|
|
84
|
+
const emitKids = (kids, call, state) => {
|
|
85
|
+
for (const f of kids) {
|
|
86
|
+
if (f.kind === CHILD) {
|
|
87
|
+
emit(` const ${f.name} = n.${f.name};`)
|
|
88
|
+
emit(` if (${f.name} !== null) {`)
|
|
89
|
+
emit(` ${call}(${f.name}, ${state});`)
|
|
90
|
+
emit(" }")
|
|
91
|
+
} else {
|
|
92
|
+
emit(` for (const c of n.${f.name}) {`)
|
|
93
|
+
emit(` ${call}(c, ${state});`)
|
|
94
|
+
emit(" }")
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
emit("// GENERATED by scripts/gen-union-scale.mjs: edit the generator, never this file.")
|
|
100
|
+
emit(`// A discriminated union of ${variants} variants shaped like typescript-go's node`)
|
|
101
|
+
emit("// data: each class tagged by its first field, with 2 to 6 fields of scalars,")
|
|
102
|
+
emit("// strings, children and lists of children; a tree built from a fixed seed; a")
|
|
103
|
+
emit("// `switch (n.kind)` over every variant that reads its own fields; a")
|
|
104
|
+
emit("// forEachChild-style walk; and accessors for the fields many variants share.")
|
|
105
|
+
emit("enum Kind {")
|
|
106
|
+
for (const { i } of all) {
|
|
107
|
+
emit(` ${tag(i)},`)
|
|
108
|
+
}
|
|
109
|
+
emit("}")
|
|
110
|
+
emit()
|
|
111
|
+
for (const { i, fields } of all) {
|
|
112
|
+
emit(`class ${name(i)} {`)
|
|
113
|
+
emit(` readonly kind: Kind.${tag(i)} = Kind.${tag(i)};`)
|
|
114
|
+
for (const f of fields) {
|
|
115
|
+
emit(` ${f.name}: ${typeOf(f.kind)};`)
|
|
116
|
+
}
|
|
117
|
+
emit(` constructor(${fields.map((f) => `${f.name}: ${typeOf(f.kind)}`).join(", ")}) {`)
|
|
118
|
+
for (const f of fields) {
|
|
119
|
+
emit(` this.${f.name} = ${f.name};`)
|
|
120
|
+
}
|
|
121
|
+
emit(" }")
|
|
122
|
+
emit("}")
|
|
123
|
+
emit()
|
|
124
|
+
}
|
|
125
|
+
emit("type Node =")
|
|
126
|
+
// One variant a line, the `|` trailing: the parser takes no leading `|`.
|
|
127
|
+
for (const { i } of all) {
|
|
128
|
+
emit(` ${name(i)}${i === variants - 1 ? ";" : " |"}`)
|
|
129
|
+
}
|
|
130
|
+
emit()
|
|
131
|
+
|
|
132
|
+
// The builder: a linear congruential seed and a budget of nodes left.
|
|
133
|
+
emit("class Builder {")
|
|
134
|
+
emit(" left: i32;")
|
|
135
|
+
emit(" seed: i32 = 7;")
|
|
136
|
+
emit(" constructor(left: i32) {")
|
|
137
|
+
emit(" this.left = left;")
|
|
138
|
+
emit(" }")
|
|
139
|
+
emit()
|
|
140
|
+
emit(" next(): i32 {")
|
|
141
|
+
// A full-period generator mod 2^16 (a - 1 divisible by 4, c odd) whose low
|
|
142
|
+
// bits are dropped, because they cycle with a short period.
|
|
143
|
+
emit(" this.seed = (this.seed * 1105 + 12345) % 65536;")
|
|
144
|
+
emit(" return this.seed >> 4;")
|
|
145
|
+
emit(" }")
|
|
146
|
+
emit("}")
|
|
147
|
+
emit()
|
|
148
|
+
emit("const child = (b: Builder, depth: i32): Node | null =>")
|
|
149
|
+
emit(" depth <= 0 || b.left <= 0 ? null : build(b, depth - 1);")
|
|
150
|
+
emit()
|
|
151
|
+
emit("const children = (b: Builder, depth: i32): Node[] => {")
|
|
152
|
+
emit(" const out: Node[] = [];")
|
|
153
|
+
emit(" if (depth > 0) {")
|
|
154
|
+
emit(" const n = b.next() % 4;")
|
|
155
|
+
emit(" for (let i = 0; i < n && b.left > 0; i++) {")
|
|
156
|
+
emit(" out.push(build(b, depth - 1));")
|
|
157
|
+
emit(" }")
|
|
158
|
+
emit(" }")
|
|
159
|
+
emit(" return out;")
|
|
160
|
+
emit("};")
|
|
161
|
+
emit()
|
|
162
|
+
const arg = (f) => {
|
|
163
|
+
switch (f.kind) {
|
|
164
|
+
case I32:
|
|
165
|
+
return "b.next()"
|
|
166
|
+
case STR:
|
|
167
|
+
// biome-ignore lint/suspicious/noTemplateCurlyInString: Nish source text; the template is the program's
|
|
168
|
+
return "`s${b.next() % 100}`"
|
|
169
|
+
case CHILD:
|
|
170
|
+
return "child(b, depth)"
|
|
171
|
+
default:
|
|
172
|
+
return "children(b, depth)"
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
emit("const build = (b: Builder, depth: i32): Node => {")
|
|
176
|
+
emit(" b.left -= 1;")
|
|
177
|
+
emit(` switch (b.next() % ${variants}) {`)
|
|
178
|
+
for (const { i, fields } of all) {
|
|
179
|
+
emit(i === variants - 1 ? " default:" : ` case ${i}:`)
|
|
180
|
+
emit(` return new ${name(i)}(${fields.map(arg).join(", ")});`)
|
|
181
|
+
}
|
|
182
|
+
emit(" }")
|
|
183
|
+
emit("};")
|
|
184
|
+
emit()
|
|
185
|
+
|
|
186
|
+
// The switch over every variant, reading the variant's own scalars.
|
|
187
|
+
const scalar = (f) => (f.kind === I32 ? `n.${f.name}` : `n.${f.name}.length`)
|
|
188
|
+
emit("const score = (n: Node): i32 => {")
|
|
189
|
+
emit(" switch (n.kind) {")
|
|
190
|
+
for (const { i, fields } of all) {
|
|
191
|
+
const terms = fields.filter((f) => f.kind === I32 || f.kind === STR).map(scalar)
|
|
192
|
+
emit(` case Kind.${tag(i)}:`)
|
|
193
|
+
emit(` return ${[String(i), ...terms].join(" + ")};`)
|
|
194
|
+
}
|
|
195
|
+
emit(" }")
|
|
196
|
+
emit("};")
|
|
197
|
+
emit()
|
|
198
|
+
|
|
199
|
+
// forEachChild: every child field and every list, per variant.
|
|
200
|
+
emit("class Walk {")
|
|
201
|
+
emit(" count: i32 = 0;")
|
|
202
|
+
emit(" sum: i32 = 0;")
|
|
203
|
+
emit("}")
|
|
204
|
+
emit()
|
|
205
|
+
emit("const visit = (n: Node, w: Walk): void => {")
|
|
206
|
+
emit(" w.count += 1;")
|
|
207
|
+
emit(" w.sum = (w.sum * 31 + score(n)) % 1000003;")
|
|
208
|
+
emit(" forEachChild(n, w);")
|
|
209
|
+
emit("};")
|
|
210
|
+
emit()
|
|
211
|
+
emit("const forEachChild = (n: Node, w: Walk): void => {")
|
|
212
|
+
emit(" switch (n.kind) {")
|
|
213
|
+
for (const { i, kids } of all) {
|
|
214
|
+
emit(` case Kind.${tag(i)}: {`)
|
|
215
|
+
emitKids(kids, "visit", "w")
|
|
216
|
+
emit(" break;")
|
|
217
|
+
emit(" }")
|
|
218
|
+
}
|
|
219
|
+
emit(" }")
|
|
220
|
+
emit("};")
|
|
221
|
+
emit()
|
|
222
|
+
|
|
223
|
+
// Accessors over the fields many variants share; every other variant answers
|
|
224
|
+
// the default, as typescript-go's `Name()` answers nil.
|
|
225
|
+
const accessor = (fn, field, type, none) => {
|
|
226
|
+
emit(`const ${fn} = (n: Node): ${type} => {`)
|
|
227
|
+
emit(" switch (n.kind) {")
|
|
228
|
+
for (const { i, fields } of all) {
|
|
229
|
+
if (fields.some((f) => f.name === field)) {
|
|
230
|
+
emit(` case Kind.${tag(i)}:`)
|
|
231
|
+
emit(` return n.${field};`)
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
emit(" default:")
|
|
235
|
+
emit(` return ${none};`)
|
|
236
|
+
emit(" }")
|
|
237
|
+
emit("};")
|
|
238
|
+
emit()
|
|
239
|
+
}
|
|
240
|
+
accessor("flagsOf", "flags", "i32", "0")
|
|
241
|
+
accessor("nameOf", "name", "string", '""')
|
|
242
|
+
|
|
243
|
+
emit("class Tally {")
|
|
244
|
+
emit(" flags: i32 = 0;")
|
|
245
|
+
emit(" names: i32 = 0;")
|
|
246
|
+
emit("}")
|
|
247
|
+
emit()
|
|
248
|
+
emit("const tally = (n: Node, t: Tally): void => {")
|
|
249
|
+
emit(" t.flags = (t.flags + flagsOf(n)) % 1000003;")
|
|
250
|
+
emit(" t.names += nameOf(n).length;")
|
|
251
|
+
emit(" switch (n.kind) {")
|
|
252
|
+
for (const { i, kids } of all) {
|
|
253
|
+
if (kids.length === 0) {
|
|
254
|
+
continue
|
|
255
|
+
}
|
|
256
|
+
emit(` case Kind.${tag(i)}: {`)
|
|
257
|
+
emitKids(kids, "tally", "t")
|
|
258
|
+
emit(" break;")
|
|
259
|
+
emit(" }")
|
|
260
|
+
}
|
|
261
|
+
emit(" default:")
|
|
262
|
+
emit(" break;")
|
|
263
|
+
emit(" }")
|
|
264
|
+
emit("};")
|
|
265
|
+
emit()
|
|
266
|
+
emit("export const main = (): void => {")
|
|
267
|
+
emit(` const b = new Builder(${nodes});`)
|
|
268
|
+
emit(" const roots: Node[] = [];")
|
|
269
|
+
emit(" while (b.left > 0) {")
|
|
270
|
+
emit(" roots.push(build(b, 8));")
|
|
271
|
+
emit(" }")
|
|
272
|
+
emit(" const w = new Walk();")
|
|
273
|
+
emit(" const t = new Tally();")
|
|
274
|
+
emit(" for (const r of roots) {")
|
|
275
|
+
emit(" visit(r, w);")
|
|
276
|
+
emit(" tally(r, t);")
|
|
277
|
+
emit(" }")
|
|
278
|
+
// biome-ignore lint/suspicious/noTemplateCurlyInString: Nish source text; the template is the program's
|
|
279
|
+
emit(" console.log(`roots ${roots.length} nodes ${w.count} checksum ${w.sum}`);")
|
|
280
|
+
// biome-ignore lint/suspicious/noTemplateCurlyInString: Nish source text; the template is the program's
|
|
281
|
+
emit(" console.log(`flags ${t.flags} names ${t.names}`);")
|
|
282
|
+
emit("};")
|
|
283
|
+
|
|
284
|
+
const text = `${lines.join("\n")}\n`
|
|
285
|
+
if (args.includes("--check")) {
|
|
286
|
+
if (readFileSync(out, "utf8") !== text) {
|
|
287
|
+
console.error(`gen-union-scale: ${out} is not what the generator writes; rerun it`)
|
|
288
|
+
process.exit(1)
|
|
289
|
+
}
|
|
290
|
+
} else if (out === "-") {
|
|
291
|
+
process.stdout.write(text)
|
|
292
|
+
} else {
|
|
293
|
+
writeFileSync(out, text)
|
|
294
|
+
}
|
package/scripts/size-report.sh
CHANGED
|
@@ -51,7 +51,7 @@ fi
|
|
|
51
51
|
# It was reported here as the `text` *column* of `size` once, which also counts `.rodata`
|
|
52
52
|
# and the `.eh_frame` entries the size profile strips -- so this row read 4,696 against a
|
|
53
53
|
# 4,096 budget while the code it is about was at 2,775. Read-only data ships too, so it
|
|
54
|
-
# gets its own row rather than being folded in:
|
|
54
|
+
# gets its own row rather than being folded in: Zmij's power-of-ten table is 9,872
|
|
55
55
|
# bytes of it, and section GC keeps them out of any binary that never formats a double (WP15).
|
|
56
56
|
# `.text.unlikely.` is summed with `.text` because a linked binary pays for both, and a ceiling
|
|
57
57
|
# on `.text` alone can be met by moving code to another section instead of by shrinking it.
|
|
@@ -67,7 +67,7 @@ while IFS=$'\t' read -r label src budget constant flags; do
|
|
|
67
67
|
row "$label" "$(text_sum "$obj")" \
|
|
68
68
|
"clang -Oz ${flags:+$flags }-c $src && size -A (.text*; budget $budget, $constant)"
|
|
69
69
|
done <<< "$budgets"
|
|
70
|
-
row rodata "$(sect .rodata build/size/runtime_c.o)" "the core object's .rodata (no budget; the
|
|
70
|
+
row rodata "$(sect .rodata build/size/runtime_c.o)" "the core object's .rodata (no budget; the Zmij table lives here)"
|
|
71
71
|
if [ "$budgets_only" = 1 ]; then exit 0; fi
|
|
72
72
|
# `scripts/build.sh` compiles runtime-os.c beside any runtime.c it is handed, so naming the
|
|
73
73
|
# core here builds the whole runtime -- and `--gc-sections` then drops whatever this module
|