@go-go-golems/compiler-toolkit 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Manuel Odendahl
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,566 @@
1
- # Temporary Holding Version
1
+ # compiler-toolkit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A composable compiler toolkit for JavaScript: `@go-go-golems/compiler-toolkit`.
4
+
5
+ The toolkit is a small JavaScript library for writing compilers. An IR is a set of ops; a function is built with a
6
+ builder whose methods are those ops; passes, rewrite rules and lowerings to other IRs then change it. An op can carry
7
+ an `eval` lambda, which makes every stage of a compilation runnable. Every change records the pass or rule that made
8
+ it, so any value, and any line of the assembly at the end, can be traced back to the source. The toolkit is plain ES
9
+ modules with no dependencies, and runs under node and under QuickJS.
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ npm install @go-go-golems/compiler-toolkit
15
+ ```
16
+
17
+ Node 22 or later. The package is ES modules only (`import`, not `require`). In a clone of this repository, import
18
+ `./src/index.js` instead.
19
+
20
+ ## Quick start
21
+
22
+ A script run with node 22 or later:
23
+
24
+ ```js
25
+ import { tk } from '@go-go-golems/compiler-toolkit';
26
+
27
+ // An IR is a set of ops. `eval` gives an op its meaning; the fragments add blocks, terminators and phis.
28
+ const Mini = tk.ir('mini')
29
+ .use(tk.frag.cfg, tk.frag.ssa)
30
+ .op('const', { attrs: { value: 'i32' }, eval: (_, { value }) => value })
31
+ .op('add', { args: 2, eval: ([a, b]) => (a + b) | 0 })
32
+ .op('mul', { args: 2, eval: ([a, b]) => Math.imul(a, b) })
33
+ .op('shl', { args: 2, eval: ([a, b]) => a << b })
34
+ .op('lt', { args: 2, eval: ([a, b]) => +(a < b) });
35
+
36
+ // A function, built with the IR's builder: the builder's methods are the IR's ops.
37
+ const mod = Mini.module();
38
+ mod.fn('scale', ['x'], (b, x) => {
39
+ b.loc('scale.js:1', 'return x * 8 + 0'); // the source position of the values built next
40
+ b.ret(b.add(b.mul(x, b.const(8)), b.const(0)));
41
+ });
42
+ mod.run('scale', [5]); // 40: the eval lambdas interpret the function
43
+
44
+ // Rewrite rules, a pass that drives them, and a pipeline with two passes from the standard library.
45
+ const peephole = tk.rules('peephole', Mini)
46
+ .rule('add-zero').match('add(x, const 0)').to(({ x }) => x)
47
+ .rule('mul-pow2').match('mul(x, const c)').when(({ c }) => c > 0 && (c & (c - 1)) === 0)
48
+ .to(({ x, c }, b) => b.shl(x, b.const(Math.log2(c))));
49
+ const O1 = tk.seq(tk.pass('peephole').rules(peephole), tk.std.fold, tk.std.dce);
50
+
51
+ mod.apply(O1).print();
52
+ mod.run('scale', [5]); // 40
53
+
54
+ // Every value knows where it came from.
55
+ mod.fn('scale').values('shl')[0].trace().print();
56
+ ```
57
+
58
+ ```text
59
+ fn scale(%x) {
60
+ entry:
61
+ %5 = const 3
62
+ %6 = shl %x, %5
63
+ ret %6
64
+ }
65
+ mini %6 = shl %x, %5 peephole: mul-pow2
66
+ mini %2 = mul %x, %1
67
+ source return x * 8 + 0 scale.js:1
68
+ ```
69
+
70
+ The rule `mul-pow2` replaced `x * 8` by `x << 3`; `add-zero` replaced the `add` of 0 by its first argument; `dce`
71
+ erased the two constants nobody used. The trace reads from the top: the `shl` was built by the rule `mul-pow2` of the
72
+ pass `peephole`, in place of `%2 = mul %x, %1`, which came from line 1 of `scale.js`. Nobody wrote that record: each
73
+ change notes the pass that made it.
74
+
75
+ ## Concepts
76
+
77
+ The examples in this section continue from the quick start, and each builds on the ones before it.
78
+
79
+ ### IRs and ops
80
+
81
+ `tk.ir(name)` makes an IR and `.op(name, spec)` adds an op to it. The spec's fields:
82
+
83
+ | Field | Meaning |
84
+ |---|---|
85
+ | `args` | the number of arguments, or `'*'` for any number (default 0) |
86
+ | `attrs` | `{ name: type }`, with the types `i32`, `i12`, `i8`, `u8`, `u5`, `u16`, `int`, `num`, `str`, `bool` and `any`; a trailing `?` makes an attribute optional |
87
+ | `eval(args, attrs, ctx)` | the op's meaning: its result from its arguments' values |
88
+ | `effect` | any truthy value: the op has a side effect, so it is not pure (`dce` keeps it, `fold` leaves it) |
89
+ | `terminator`, `control` | a block terminator, and `control(args, targets, ctx, value)`, which says where execution goes |
90
+ | `result` | `false`, or a function of the attributes, for an op that defines no value; such values take no id |
91
+ | `constant` | marks the IR's constant op (an op named `const` with no arguments and one attribute needs no mark) |
92
+ | `asm`, `format` | an assembly template (for machine IRs); a function that prints the value |
93
+
94
+ Any other field stays on the op's spec for your own use (`v.spec.cost`).
95
+
96
+ An IR without blocks builds free expressions: `IR.builder()` gives a builder, `IR.eval(v)` evaluates, and
97
+ `v.apply(pass)` runs a pass on the expression `v` is the root of and returns the new root.
98
+
99
+ ```js
100
+ const Arith = tk.ir('arith')
101
+ .op('const', { attrs: { value: 'i32' }, eval: (_, { value }) => value })
102
+ .op('add', { args: 2, eval: ([a, b]) => (a + b) | 0 })
103
+ .op('mul', { args: 2, eval: ([a, b]) => Math.imul(a, b) });
104
+ const e = Arith.builder();
105
+ const x = e.add(e.const(2), e.mul(e.const(3), e.const(4)));
106
+ String(x); // 'add(const 2, mul(const 3, const 4))'
107
+ Arith.eval(x); // 14
108
+ String(x.apply(tk.std.fold)); // 'const 14'
109
+ ```
110
+
111
+ ### Fragments
112
+
113
+ A fragment adds ops, value members or builder members to an IR. Control flow is not built in: an IR takes it from a
114
+ fragment with `.use(...)`.
115
+
116
+ - `tk.frag.cfg`: blocks, and the terminators `br block`, `cbr cond, then, else` and `ret value`.
117
+ - `tk.frag.ssa`: `phi`. A phi gets one input per incoming edge with `phi.incoming(block, value)`.
118
+ - `tk.frag.edges`: blocks with parameters instead of phis, as in MLIR or Cranelift. `b.params(block, n)` makes a
119
+ block's parameters, and the terminators `jump`, `br`, `switch`, `ret` and `trap` take edges, written
120
+ `block.to(...args)`. A terminator's `edges` lists its edges, and `setEdge(k, block.to(...))` redirects one.
121
+ - `tk.frag.machine`: for machine IRs. `v.reg` is the register a value is in (what `tk.regs` says, else its virtual
122
+ name), and the cfg terminators get assembly templates.
123
+
124
+ A loop written with block parameters:
125
+
126
+ ```js
127
+ const H = tk.ir('h')
128
+ .use(tk.frag.edges)
129
+ .op('const', { attrs: { value: 'i32' }, eval: (_, { value }) => value })
130
+ .op('add', { args: 2, eval: ([a, b]) => (a + b) | 0 })
131
+ .op('lt', { args: 2, eval: ([a, b]) => +(a < b) });
132
+ const hm = H.module();
133
+ hm.fn('sum', ['n'], (b, n) => {
134
+ const head = b.block('head'), body = b.block('body'), exit = b.block('exit');
135
+ const [i, s] = b.params(head, 2), [r] = b.params(exit, 1);
136
+ const zero = b.const(0);
137
+ b.jump(head.to(zero, zero)).at(head);
138
+ b.br(b.lt(i, n), body.to(), exit.to(s)).at(body);
139
+ b.jump(head.to(b.add(i, b.const(1)), b.add(s, i))).at(exit);
140
+ b.ret(r);
141
+ });
142
+ hm.run('sum', [10]); // 45
143
+ String(hm.fn('sum').block('head').terminator); // 'br %5, body(), exit(%2)'
144
+ ```
145
+
146
+ Your own fragments are made with `tk.fragment(name)`: `.op({...})` adds members to values, `.builder({...})` adds
147
+ methods to builders, and `.define(ir => ...)` runs once on each IR that uses it. `IR.extend(names, x)` applies a
148
+ fragment, or plain spec fields, to some ops only.
149
+
150
+ ```js
151
+ const cost = tk.fragment('cost').op({
152
+ get cost() {
153
+ return this.spec.cost ?? 1;
154
+ },
155
+ });
156
+ Mini.use(cost).extend('shl', { cost: 2 });
157
+ mod.fn('scale').values('shl')[0].cost; // 2
158
+ ```
159
+
160
+ ### Values, and the mutations that record provenance
161
+
162
+ A value is an instance of an op. It has `kind`, `args` (`arg(i)` checks the index), `attrs` (and a getter per
163
+ attribute, such as `v.value`), `uses`, `block`, `fn`, `ref` (`%name` or `%id`), `is(kind, attrs?)` and `pure`. Passes
164
+ change values in place, through a few mutations:
165
+
166
+ | Mutation | What it does |
167
+ |---|---|
168
+ | a builder call | creates a value |
169
+ | `v.replaceWith(x)` | every use of `v` reads `x`, then `v` is erased; `x` is a value, or `b => value` built where `v` was |
170
+ | `v.replaceUses(x)` | every use of `v` reads `x`; `v` stays, unused, for a later `dce` |
171
+ | `v.erase()`, `fn.eraseAll(values)` | removes a value nothing uses; removes a set of values used only by each other |
172
+ | `v.moveTo(block)` | moves `v` to the end of a block, before its terminator |
173
+ | `v.setArg(i, x)`, `v.swapArgs()` | changes an argument; swaps two |
174
+ | `phi.incoming(block, x)`, `t.setEdge(k, edge)` | the fragments' own: adds a phi input; redirects an edge |
175
+
176
+ Each mutation records who made it: the running pass (`dce`), the rule inside a pass (`peephole: mul-pow2`), the
177
+ lowering, `build` inside `mod.fn`'s body, or `user` outside any of them. That record is the provenance.
178
+ `v.history()` lists what happened to a value, `v.origin()` gives the values it was made from, and `v.trace()` follows
179
+ the origins back to the source position given with `b.loc(where, text)`.
180
+
181
+ ```js
182
+ const f = mod.fn('twice', ['x'], (b, x) => b.ret(b.mul(x, b.const(2))));
183
+ const double = tk.pass('double').each(v => {
184
+ if (v.is('mul') && v.arg(1).is('const', { value: 2 })) v.replaceWith(b => b.add(v.arg(0), v.arg(0)));
185
+ });
186
+ f.apply(double);
187
+ const add = f.values('add')[0];
188
+ String(add); // '%3 = add %x, %x'
189
+ add.history(); // ['created by double']
190
+ add.origin()[0].history(); // ['created by build', 'double: replaced by %3']
191
+ add.erase(); // TkError: cannot erase %3 (add): 1 use remains (ret in entry): replaceWith(…) first
192
+ ```
193
+
194
+ ### Functions, blocks and modules
195
+
196
+ A module holds functions. `mod.fn(name, params, body)` defines one and calls `body(b, ...params)` with a builder
197
+ placed in the entry block; `mod.fn(name)` finds it again. In the body, `b.block(name)` makes a block, `b.at(block)`
198
+ continues at its end, `b.before(v)` inserts before a value, and `b.current` is the block being built. A terminator
199
+ returns the builder, so `b.br(head).at(head)` reads in order.
200
+
201
+ ```js
202
+ const sum = mod.fn('sum', ['n'], (b, n) => {
203
+ const entry = b.current, head = b.block('head'), body = b.block('body'), exit = b.block('exit');
204
+ const zero = b.const(0);
205
+ b.br(head).at(head);
206
+ const i = b.phi().named('i'), s = b.phi().named('s');
207
+ b.cbr(b.lt(i, n), body, exit).at(body);
208
+ const i1 = b.add(i, b.const(1)).named('i1'), s1 = b.add(s, i).named('s1');
209
+ b.br(head).at(exit).ret(s);
210
+ i.incoming(entry, zero).incoming(body, i1);
211
+ s.incoming(entry, zero).incoming(body, s1);
212
+ });
213
+ mod.run('sum', [10]); // 45
214
+ sum.print();
215
+ ```
216
+
217
+ ```text
218
+ fn sum(%n) {
219
+ entry:
220
+ %1 = const 0
221
+ br head
222
+ head:
223
+ %i = phi [entry: %1, body: %i1]
224
+ %s = phi [entry: %1, body: %s1]
225
+ %4 = lt %i, %n
226
+ cbr %4, body, exit
227
+ body:
228
+ %5 = const 1
229
+ %i1 = add %i, %5
230
+ %s1 = add %s, %i
231
+ br head
232
+ exit:
233
+ ret %s
234
+ }
235
+ ```
236
+
237
+ A function has `blocks`, `entry`, `params`, `block(name)`, `values(kind?)` and `size`; a block has `values()`,
238
+ `terminator`, `succs`, `preds`, `phis` and `params`. `mod.clone()` makes an editable copy whose values remember the
239
+ values they copy, and `mod.snapshot()` a read-only one that `mod.diff(snapshot)` compares against:
240
+
241
+ ```js
242
+ mod.fn('g', ['a'], (b, a) => b.ret(b.add(b.mul(a, b.const(8)), b.const(0))));
243
+ const before = mod.snapshot();
244
+ mod.apply(O1);
245
+ mod.diff(before).print();
246
+ before.fn('g').values()[0].erase(); // TkError: snapshot r47 is read-only: .clone() gives an editable copy
247
+ ```
248
+
249
+ ```text
250
+ twice 3 -> 2 values
251
+ dce: erase 1
252
+ g 5 -> 3 values
253
+ peephole: mul-pow2: create 2, replace 1
254
+ peephole: add-zero: replace 1
255
+ dce: erase 2
256
+ ```
257
+
258
+ `twice` lost the `const 2` that `double` left unused; `scale` and `sum` did not change, so they are not listed.
259
+
260
+ `tk.attr(name)` makes a side table, which attaches data to values without changing the IR; with
261
+ `{ follows: 'replace' }`, an entry moves to the value that replaces its value.
262
+
263
+ ### Passes
264
+
265
+ A pass is a name and one body:
266
+
267
+ - `.each(f)`: `f(value, analyses)` on every value, in order;
268
+ - `.run(f)`: `f(fn, analyses)` once per function;
269
+ - `.module(f)`: `f(module)` once, for work across functions;
270
+ - `.rules(...sets)`: rule sets, driven greedily until no rule fires.
271
+
272
+ `.needs({ name: analysis })` names the analyses the body receives, and `.about(text)` describes the pass. A pass
273
+ applies to a module (each function), to one function, or, with `v.apply(pass)`, to an expression.
274
+
275
+ ```js
276
+ const licm = tk.pass('licm')
277
+ .about('move loop-invariant pure values to the preheader')
278
+ .needs({ loops: tk.std.loops })
279
+ .run((f, { loops }) => {
280
+ for (const loop of loops.innermostFirst())
281
+ if (loop.preheader)
282
+ for (const v of loop.values())
283
+ if (v.pure && v.args.every(a => !loop.contains(a))) v.moveTo(loop.preheader);
284
+ });
285
+ sum.apply(licm);
286
+ sum.block('entry').values().map(String); // ['%1 = const 0', '%5 = const 1', 'br head']
287
+ mod.run('sum', [10]); // 45
288
+ ```
289
+
290
+ ### Rule sets and combinators
291
+
292
+ A rule is a pattern, an optional condition and a replacement. In a pattern, `op(p, ...)` matches an op and its
293
+ arguments; a bare name binds any value (the same name twice must be the same value; `_` matches anything); `const 0`
294
+ matches an op whose one attribute is 0, and `const c` binds that attribute to `c`. Patterns are checked against the IR
295
+ when the rule is defined. `.when(bindings => bool)` is the condition, and `.to((bindings, b) => value)` builds the
296
+ replacement with a builder placed before the matched value. A rule set is a value: `set.names` lists its rules,
297
+ `set.without(...names)` and `set.with(...sets)` make new sets.
298
+
299
+ Anything with an `applyTo(target)` method composes, and the combinators make new passes:
300
+
301
+ - `tk.seq(...passes)`: in order;
302
+ - `tk.fixpoint(pass, { max: 100 })`: repeated until the target stops changing;
303
+ - `tk.when(fn => bool, pass)`: on the functions the predicate accepts;
304
+ - `tk.choose(alternatives, cost)`: each alternative on a clone of the module; the cheapest one is kept, and
305
+ `mod.choices` records the costs.
306
+
307
+ ```js
308
+ const O2 = tk.seq(tk.fixpoint(O1), licm, O1, tk.std.verifySSA);
309
+ mod.fn('k', [], b => b.ret(b.mul(b.add(b.const(2), b.const(3)), b.const(4))));
310
+ mod.apply(tk.when(f => f.size < 40, O2));
311
+ mod.fn('k').print();
312
+ ```
313
+
314
+ ```text
315
+ fn k() {
316
+ entry:
317
+ %8 = const 20
318
+ ret %8
319
+ }
320
+ ```
321
+
322
+ ### Analyses and their caching
323
+
324
+ An analysis is a named function of a function, made with `tk.analysis(name, fn => result, { on })`; a plain
325
+ function works too. `f.get(analysis)` computes it once and returns the cached result until the function changes.
326
+ Every change increments `f.revision`, and a change to blocks or terminators also increments `f.cfgRevision`. An
327
+ analysis made with `{ on: 'cfg' }`, such as `tk.std.dominators` and `tk.std.loops`, is recomputed only when the
328
+ control flow changes. With checks on (below), a result read after a change throws instead of answering from stale
329
+ data.
330
+
331
+ ```js
332
+ const liveness = tk.analysis('liveness', fn =>
333
+ tk.std.dataflow(fn, {
334
+ dir: 'backward',
335
+ ...tk.lattice.sets,
336
+ transfer: (block, live) => {
337
+ const out = new Set(live);
338
+ for (const v of block.values().reverse()) {
339
+ out.delete(v);
340
+ v.args.forEach(a => out.add(a));
341
+ }
342
+ return out;
343
+ },
344
+ }),
345
+ );
346
+ const live = sum.get(liveness);
347
+ sum.get(liveness) === live; // true: cached for this revision
348
+ [...live.in(sum.block('body'))].map(v => v.ref).sort(); // ['%1', '%5', '%i', '%n', '%s']
349
+ ```
350
+
351
+ This transfer function counts a phi's inputs as uses in the phi's own block, so the entry's `%1` is live through the
352
+ loop; `%5` is live because `licm` moved it to the entry block.
353
+
354
+ ### Lowerings
355
+
356
+ `tk.lower(from, to, name)` makes a lowering, a table with one case per source op: `.op(kind, (v, b, args) =>
357
+ value)`. A case gets the source value, a builder of the target IR placed in the matching block, and the source
358
+ arguments already lowered. Blocks, phis and the `cfg` terminators carry over by themselves when both IRs have them.
359
+ `lowering.run(module)` returns a new module of the target IR, whose values record the source values as their origins.
360
+ `tk.std.asm(module)` prints a machine IR's assembly from the ops' `asm` templates (`{d}` is the value's register, `{0}`
361
+ an argument's, `{imm}` an attribute).
362
+
363
+ ```js
364
+ const RV = tk.ir('rv32')
365
+ .use(tk.frag.cfg, tk.frag.ssa, tk.frag.machine)
366
+ .op('li', { attrs: { imm: 'i32' }, asm: 'li {d}, {imm}', eval: (_, { imm }) => imm })
367
+ .op('addi', { args: 1, attrs: { imm: 'i12' }, asm: 'addi {d}, {0}, {imm}', eval: ([a], { imm }) => (a + imm) | 0 })
368
+ .op('add', { args: 2, asm: 'add {d}, {0}, {1}', eval: ([a, b]) => (a + b) | 0 })
369
+ .op('mul', { args: 2, asm: 'mul {d}, {0}, {1}', eval: ([a, b]) => Math.imul(a, b) })
370
+ .op('slli', { args: 1, attrs: { imm: 'u5' }, asm: 'slli {d}, {0}, {imm}', eval: ([a], { imm }) => a << imm })
371
+ .op('slt', { args: 2, asm: 'slt {d}, {0}, {1}', eval: ([a, b]) => +(a < b) });
372
+
373
+ const small = v => v.is('const') && v.value >= -2048 && v.value < 2048;
374
+ const select = tk.lower(Mini, RV, 'select')
375
+ .op('const', (v, b) => b.li(v.value))
376
+ .op('add', (v, b, [x, y]) => (small(v.arg(1)) ? b.addi(x, v.arg(1).value) : b.add(x, y)))
377
+ .op('mul', (v, b, [x, y]) => b.mul(x, y))
378
+ .op('shl', (v, b, [x]) => b.slli(x, v.arg(1).value))
379
+ .op('lt', (v, b, [x, y]) => b.slt(x, y));
380
+
381
+ const rv = select.run(mod).apply(tk.std.dce);
382
+ rv.run('sum', [10]); // 45: the rv32 ops' eval lambdas run the lowered code
383
+ const asm = tk.std.asm(rv);
384
+ asm.line(asm.find(/slli/)).trace().print();
385
+ ```
386
+
387
+ ```text
388
+ asm 3 slli %2, %x, 3
389
+ rv32 %2 = slli %x, 3 select
390
+ mini %6 = shl %x, %5 peephole: mul-pow2
391
+ mini %2 = mul %x, %1
392
+ source return x * 8 + 0 scale.js:1
393
+ ```
394
+
395
+ Each function numbers its own values, so the `slli` is `%2` in rv32 while the `shl` it came from is `%6` in mini;
396
+ names (`%x`, `%i1`) carry over.
397
+
398
+ ### The standard library
399
+
400
+ `tk.std` holds:
401
+
402
+ - passes: `fold` (evaluates pure ops whose arguments are constants, with their `eval` lambdas), `dce` (erases unused
403
+ pure values and phis), `verifySSA` (throws unless the function is well-formed SSA);
404
+ - graph algorithms: `depthFirst` (orders and retreating edges), `dominators`, `loops` (natural loops, with
405
+ preheaders), `scc` (Tarjan);
406
+ - `dataflow`, a worklist solver, forward or backward, with lattices in `tk.lattice` (`sets`, `constants`);
407
+ - `asm`, assembly text whose lines trace back to their values.
408
+
409
+ The graph algorithms take a function, or any graph described with `tk.view.graph({ nodes, succ, entry? })`:
410
+
411
+ ```js
412
+ const calls = tk.view.graph({
413
+ nodes: ['main', 'a', 'b', 'c'],
414
+ succ: n => ({ main: ['a'], a: ['b'], b: ['a', 'c'], c: [] })[n],
415
+ });
416
+ tk.std.scc(calls); // [['c'], ['a', 'b'], ['main']]: callees first
417
+ tk.std.dominators(calls).dominates('a', 'c'); // true
418
+ ```
419
+
420
+ ### The stage graph
421
+
422
+ `tk.graph(name)` connects a compiler's stages. `.node(name, deps, f)` computes a stage from the values of the stages
423
+ it depends on; `get(name)` computes what is missing and caches it; `set(name, value)` replaces a stage's value, and
424
+ only the stages after it are computed again.
425
+
426
+ ```js
427
+ const build = tk.graph('scale')
428
+ .node('k', () => 8)
429
+ .node('mini', ['k'], k => {
430
+ const m = Mini.module();
431
+ m.fn('scale', ['x'], (b, x) => b.ret(b.mul(x, b.const(k))));
432
+ return m;
433
+ })
434
+ .node('opt', ['mini'], m => m.clone().apply(O1))
435
+ .node('rv', ['opt'], m => select.run(m));
436
+ build.get('rv').run('scale', [5]); // 40
437
+ build.set('k', 3);
438
+ build.get('rv').run('scale', [5]); // 15
439
+ build.runs('opt'); // 2
440
+ ```
441
+
442
+ ### The checks mode
443
+
444
+ The toolkit can check its own use: with checks on, its objects are proxies that turn a misspelled or missing member
445
+ into an error naming what exists and the closest match, analysis results throw once their function has changed, and a
446
+ pass that reads an analysis it did not ask for in `.needs` gets an error. Checks never change what a pass computes,
447
+ only how early a mistake throws. They are off by default, because a proxy runs on every property read: in passes that
448
+ read many properties they cost several times the run time.
449
+
450
+ Turn them on to write or debug passes, and in tests:
451
+
452
+ - `TK_CHECKS=1` in the environment, or `globalThis.TK_CHECKS = true` before the toolkit loads; these two also cover
453
+ `tk`, `tk.std` and `tk.frag`, which are made when the toolkit loads;
454
+ - `tk.checks(true)`, before the IRs, modules and passes to be checked are made: an object keeps the mode it was made
455
+ in.
456
+
457
+ ```js
458
+ tk.checks(true);
459
+ const Checked = tk.ir('checked').op('const', { attrs: { value: 'i32' } }).op('add', { args: 2 });
460
+ const cb = Checked.builder();
461
+ const one = cb.const(1);
462
+ cb.ad(one, one); // TypeError: checked has no op 'ad': did you mean 'add'? (ops: const, add)
463
+ one.vlaue; // TypeError: checked value %0 (const) has no 'vlaue': did you mean 'value'?
464
+ tk.checks(false);
465
+ ```
466
+
467
+ Without checks, `cb.ad(one, one)` is JavaScript's own `TypeError` (not a function) and `one.vlaue` is `undefined`.
468
+ Some validation runs in both modes, once per creation or definition: a value's arguments and attributes, op and
469
+ attribute definitions, rule patterns, lowering cases.
470
+
471
+ ## API overview
472
+
473
+ | Call | Makes | Its main members |
474
+ |---|---|---|
475
+ | `tk.ir(name)` | an IR | `op`, `use`, `extend`, `builder`, `module`, `eval`, `opNames`, `opNamed` |
476
+ | `IR.module()` | a module | `fn`, `fns`, `run`, `apply`, `clone`, `snapshot`, `diff`, `remove`, `size`, `meta` |
477
+ | `mod.fn(name, params, body, opts?)` | a function | `blocks`, `entry`, `params`, `block`, `values`, `size`, `addBlock`, `eraseAll`, `get`, `apply`, `graph`, `meta` |
478
+ | a builder (`body`'s `b`, `IR.builder()`) | values | one method per op, `block`, `at`, `before`, `current`, `loc`, `id` |
479
+ | a builder call | a value | `kind`, `args`, `arg`, `attrs`, `uses`, `is`, `pure`, `ref`, `named`, the mutations, `history`, `origin`, `trace` |
480
+ | `tk.fragment(name)` | a fragment | `op`, `builder`, `define` |
481
+ | `tk.frag` | the built-in fragments | `cfg`, `ssa`, `edges`, `machine` |
482
+ | `tk.rules(name, IR)` | a rule set | `rule`, `match`, `when`, `to`, `names`, `without`, `with` |
483
+ | `tk.pass(name)` | a pass | `each`, `run`, `module`, `rules`, `needs`, `about` |
484
+ | `tk.analysis(name, f, { on })` | an analysis | used with `fn.get(analysis)` |
485
+ | `tk.seq`, `tk.fixpoint`, `tk.when`, `tk.choose` | a combined pass | `applyTo` |
486
+ | `tk.lower(from, to, name?)` | a lowering | `op`, `run` |
487
+ | `tk.attr(name, { follows })` | a side table | `set`, `get`, `has`, `delete` |
488
+ | `tk.graph(name)` | a stage graph | `node`, `get`, `set`, `invalidate`, `runs`, `names` |
489
+ | `tk.view.graph({ nodes, succ, entry })` | a graph view for `tk.std` | |
490
+ | `tk.std` | the standard library | `fold`, `dce`, `verifySSA`, `depthFirst`, `dominators`, `loops`, `scc`, `dataflow`, `asm` |
491
+ | `tk.lattice` | lattices for `dataflow` | `sets`, `constants`, `TOP` |
492
+ | `tk.regs` | a `WeakMap` from values to physical registers, read by `v.reg` | |
493
+ | `tk.checks(on?)` | the checks mode | |
494
+ | `tk.TkError` | the toolkit's error class | |
495
+
496
+ ## Source layout
497
+
498
+ | File | What it holds |
499
+ |---|---|
500
+ | `src/index.js` | the `tk` namespace |
501
+ | `src/ir.js` | IRs, ops, values and their mutations, blocks, functions, modules, the builder, the analysis cache, traces |
502
+ | `src/frag.js` | the fragments `cfg`, `ssa`, `edges` and `machine` |
503
+ | `src/rules.js` | patterns, rule sets, the greedy driver |
504
+ | `src/pass.js` | passes, analyses, `seq`, `fixpoint`, `when`, `choose` |
505
+ | `src/lower.js` | lowering between IRs |
506
+ | `src/stages.js` | `tk.graph` |
507
+ | `src/data.js` | `tk.attr` |
508
+ | `src/context.js` | the current actor (the pass, rule or lowering running), which every mutation records |
509
+ | `src/diag.js` | errors, "did you mean", the checks switch (`tk.checks`, `TK_CHECKS`) and the strict proxy |
510
+ | `src/std/graph.js` | `depthFirst`, `dominators`, `loops`, `scc` |
511
+ | `src/std/dataflow.js` | the worklist solver |
512
+ | `src/std/lattice.js` | `sets`, `constants` |
513
+ | `src/std/passes.js` | `fold`, `dce`, `verifySSA` |
514
+ | `src/std/asm.js` | assembly text from a machine IR, with traceable lines |
515
+ | `test/examples.test.mjs` | the design doc's examples, as tests |
516
+ | `test/more.test.mjs` | errors a pass author meets, regressions, and 300 random programs through optimization and lowering |
517
+ | `test/blocks.test.mjs` | editing existing functions: builders on them, adding, removing and ordering blocks, `moveTo`, `setAttr` |
518
+ | `scripts/quickjs-check.mjs` | the tests under QuickJS |
519
+ | `scripts/checks-cost.bench.mjs` | what the checks mode costs |
520
+ | `scripts/doc-outputs.mjs` | the design doc's example 14 listings |
521
+ | `docs/guide.md` | the manual |
522
+ | `docs/design.md` | the design document |
523
+
524
+ ## Testing
525
+
526
+ - **node:** `npm test`, with node 22 or later. It runs every test twice: with checks off, then
527
+ with `TK_CHECKS=1`. Both runs must end with `fail 0`. One file in one mode:
528
+ `TK_CHECKS=1 node --test test/more.test.mjs`.
529
+ - **QuickJS**, the JavaScript engine the toolkit also runs under on an ESP32-P4:
530
+
531
+ ```sh
532
+ QJS_STACK=57344 QJS=/path/to/qjs-run npm run test:quickjs
533
+ ```
534
+
535
+ `QJS` is a host QuickJS runner that evaluates one plain script; gb-riscv32 builds one (`build/qjs/qjs-run`) over
536
+ the QuickJS its P4 firmware embeds. `QJS_STACK=57344` limits the JavaScript stack to the P4's 56 KB. The script bundles each test file with the toolkit and runs it with checks off
537
+ and on; every run must print `failed 0`, and the script exits 1 otherwise. This QuickJS has no `structuredClone`
538
+ and no `Array.prototype.at`: the toolkit and its tests do not use them.
539
+
540
+ ## Status
541
+
542
+ Version 0.1: the API may still change between minor versions. Its first real user is
543
+ [gb-riscv32](https://github.com/wesen/2026-12-04--gb-riscv32)'s Game Boy compiler, which runs on the toolkit from its
544
+ regions' IR to RV32 machine code and gives machine code identical to its original compiler's on all 1,728 regions of
545
+ three games. Not in the toolkit yet: SSA construction from variables, register allocation (gb-riscv32 has its own),
546
+ and an equality-saturation rule driver (see section 6 of the design doc).
547
+
548
+ The toolkit started as `toolkit/` in
549
+ [compiler-workbench](https://github.com/wesen/2026-11-24--compiler-workbench); this repository carries that history.
550
+
551
+ ## Releasing
552
+
553
+ 1. Bump `version` in `package.json` and commit; tag it `vX.Y.Z` and push the tag.
554
+ 2. Run the workflow **publish-npm** (Actions, `workflow_dispatch`) with `dry_run` on, read what it would publish,
555
+ then again with `dry_run` off. It runs the tests first and publishes with npm provenance through trusted
556
+ publishing, so no npm token is stored in the repository.
557
+
558
+ ## License
559
+
560
+ MIT; see [LICENSE](LICENSE).
561
+
562
+ ## Further reading
563
+
564
+ - [The guide](docs/guide.md), the toolkit's manual: each part of the toolkit by task, with runnable examples, and a
565
+ reference of every public function and option.
566
+ - [The design doc](docs/design.md) presents the API in fourteen examples, from simple to complex, with the reasons for each decision.