@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/docs/design.md ADDED
@@ -0,0 +1,748 @@
1
+
2
+ # The toolkit API in examples
3
+
4
+ The toolkit's design document, written with the prototype in compiler-workbench (ticket IRWB-143, December 2026),
5
+ where the toolkit lived as `toolkit/` until it became this repository. Sections 6 and 7 (status, open questions) are
6
+ as they stood then; [the guide](guide.md) describes the toolkit as it is now.
7
+
8
+ ## 1. Summary
9
+
10
+ The toolkit is a small JavaScript library for writing compilers. A compiler written with it is ordinary data and
11
+ ordinary lambdas:
12
+
13
+ - an **IR** is a set of ops, each declared with its arguments, its attributes and, optionally, an `eval` lambda;
14
+ - a **pass** is a name and a lambda that changes values directly;
15
+ - **rewrite rules** are values that can be filtered and combined;
16
+ - **analyses** are functions whose results are cached and refuse to be read once the code has changed;
17
+ - a **lowering** is a table of lambdas from one IR to another;
18
+ - a **stage graph** connects the stages of a compiler and recomputes only what changed.
19
+
20
+ Every change records who made it, so any value, and any line of the final assembly, can be traced back through each
21
+ IR to the source position it came from. Checks such as SSA verification are passes like any other. They run where the
22
+ compiler author puts them, not as a protocol around every step.
23
+
24
+ Fourteen examples, ordered from simple to complex, specify the design (section 4). Thirteen of them run: each is a
25
+ test in `test/examples.test.mjs`, and every output shown here is asserted by those tests (example 14's two
26
+ listings are printed by `scripts/doc-outputs.mjs`). Example 12, equality saturation, is planned and not built.
27
+
28
+ The prototype is plain ES-module JavaScript with no dependencies. Its 20 tests pass under node 24, and under QuickJS
29
+ with the ESP32-P4's 56 KB stack (`scripts/quickjs-check.mjs`).
30
+
31
+ ## 2. Why a new API
32
+
33
+ The compiler workbench ([wesen/2026-11-24--compiler-workbench](https://github.com/wesen/2026-11-24--compiler-workbench):
34
+ its `src/framework/`, 14,096 lines, and `src/stdlib/`, 2,486 lines) grew around a protocol. Steps
35
+ declare relations, discharge obligations and emit certificates, and the framework checks each of them. Every pass
36
+ becomes a negotiation with the framework, and most of the code a compiler author reads is about checking rather than
37
+ compiling. In its author's words, the workbench "got a bit too detailed and non composable and worried about testing and
38
+ checks vs building elegant compilers".
39
+
40
+ The toolkit keeps what proved useful and drops the protocol.
41
+
42
+ - **Kept:**
43
+ - the standard-library algorithms, all generic over a graph view `{ nodes, entry, succ }`: Cooper-Harvey-Kennedy
44
+ dominators, natural loops with the preheader rule, Tarjan SCCs, a worklist dataflow solver;
45
+ - the idea that each op's meaning is executable;
46
+ - provenance from the output back to the source.
47
+ - **Dropped:** relations, obligations, certificates and the step protocol. Evidence of correctness becomes ordinary
48
+ code:
49
+ - the interpreter runs any stage of any IR;
50
+ - `verifySSA` is a pass;
51
+ - a test can compare stages on random programs (`test/more.test.mjs` does this for 300 programs).
52
+
53
+ The prototype does far less than the workbench (no frontend, no register allocation, no equality saturation), so the
54
+ line counts are not a like-for-like comparison. Its source is about 2,200 lines.
55
+
56
+ ## 3. The grammar on one page
57
+
58
+ | Component | Made with | Its lambdas | When they run |
59
+ |---|---|---|---|
60
+ | IR | `tk.ir(name).op(name, spec)…` | `eval(args, attrs, ctx)`; `control(args, targets)` for terminators | run time (`IR.eval`, `module.run`) and compile time (`tk.std.fold`) |
61
+ | Fragment | `tk.fragment(name).op({…}).builder({…}).define(ir => …)` | value members, builder members, IR setup | setup when an IR uses it; members whenever called |
62
+ | Value | a builder call: `b.add(x, y)` | none | none |
63
+ | Rule set | `tk.rules(name, IR).rule(n).match(p).when(f).to(f)` | condition, replacement | when a driver fires the rule |
64
+ | Pass | `tk.pass(name).each(f)`, `.run(f)` or `.rules(set)` | the pass body | when the pass is applied |
65
+ | Analysis | `tk.analysis(name, f, { on })`, or a plain function | the computation | on the first read per revision |
66
+ | Combinator | `tk.seq`, `tk.fixpoint`, `tk.when`, `tk.choose` | predicates, costs | when applied |
67
+ | Lowering | `tk.lower(A, B).op(kind, f)` | one per source op | `.run(module)` |
68
+ | Side table | `tk.attr(name, { follows })` | none | none |
69
+ | Stage graph | `tk.graph(name).node(name, deps, f)` | one per stage | on `get`, when an input changed |
70
+
71
+ Only five kinds of change exist:
72
+
73
+ - create (a builder call);
74
+ - `replaceWith`;
75
+ - `erase`;
76
+ - `moveTo`;
77
+ - `setArg` / `swapArgs`.
78
+
79
+ Each records the current actor: the pass, the rule inside a pass, the lowering, or `build`. That record is the
80
+ provenance; a pass writes nothing extra to get it.
81
+
82
+ A builder's methods are its IR's op names. With **checks** on, every object the toolkit hands out is a proxy: a
83
+ misspelled or missing member raises an error that names what exists and the closest match. The same mode also guards
84
+ analysis results against use after a change.
85
+
86
+ Checks are off by default, because a proxy runs on every property read. Measured on gb-riscv32's compiler, the proxies
87
+ took about three quarters of a ported gvn's time. They make no difference to what a pass computes.
88
+
89
+ Turn checks on to write or debug passes, and in tests, in any of three ways:
90
+ - `TK_CHECKS=1` in the environment;
91
+ - `globalThis.TK_CHECKS = true` before the toolkit loads (both of these also cover `tk`, `tk.std` and `tk.frag`);
92
+ - `tk.checks(true)` before the objects are made.
93
+
94
+ An object keeps the mode it was made in. Validation that runs once per creation or definition does not depend on the
95
+ mode: a value's args and attributes, op and attribute definitions, rule patterns, lowering cases.
96
+
97
+ ## 4. The examples
98
+
99
+ The examples build on each other. `Mini` and `sum` (example 4), `peep` (example 6) and `peephole`, `dce` and `licm`
100
+ (example 7) are defined once and reused. Unless it says otherwise, each example starts from a fresh module with `sum`
101
+ in it:
102
+
103
+ ```js
104
+ const mod = Mini.module();
105
+ sum(mod);
106
+ ```
107
+
108
+ ### Example 1: define an IR and build with it
109
+
110
+ An IR is a set of ops, and a builder's methods are those ops. An IR without blocks builds a free expression graph.
111
+
112
+ ```js
113
+ import { tk } from '@go-go-golems/compiler-toolkit';
114
+
115
+ const Arith = tk.ir('arith')
116
+ .op('const', { attrs: { value: 'i32' } })
117
+ .op('add', { args: 2 })
118
+ .op('mul', { args: 2 });
119
+
120
+ const b = Arith.builder();
121
+ const e = b.add(b.const(2), b.mul(b.const(3), b.const(4)));
122
+ e.print();
123
+ ```
124
+
125
+ ```text
126
+ add(const 2, mul(const 3, const 4))
127
+ ```
128
+
129
+ ### Example 2: one lambda, used at run time and at compile time
130
+
131
+ An op's `eval` lambda gives it a meaning. The same lambda interprets the expression and, through the standard `fold`
132
+ pass, folds constants at compile time. Nothing about folding is written for this IR.
133
+
134
+ ```js
135
+ const Arith = tk.ir('arith')
136
+ .op('const', { attrs: { value: 'i32' }, eval: (_, { value }) => value })
137
+ .op('add', { args: 2, eval: ([a, b]) => (a + b) | 0 })
138
+ .op('mul', { args: 2, eval: ([a, b]) => Math.imul(a, b) });
139
+
140
+ const b = Arith.builder();
141
+ const e = b.add(b.const(2), b.mul(b.const(3), b.const(4)));
142
+ Arith.eval(e); // 14: the eval lambdas as an interpreter
143
+ e.apply(tk.std.fold).print(); // the same lambdas, folding at compile time
144
+ ```
145
+
146
+ ```text
147
+ const 14
148
+ ```
149
+
150
+ `fold` needs two facts about an IR, both from the op declarations:
151
+
152
+ - which op is its constant: an op named `const`, or one declared `constant: true`, with no arguments and one
153
+ attribute;
154
+ - which ops are pure: no `effect`, and not a terminator.
155
+
156
+ ### Example 3: misuse gets a precise message
157
+
158
+ Each call below throws the message shown. The two misspelled members (`b.ad`, `x.vlaue`) give these messages with
159
+ checks on. With checks off, `b.ad(x, x)` is a plain `TypeError` (not a function), and `x.vlaue` is `undefined`.
160
+
161
+ ```js
162
+ b.ad(x, x) // arith has no op 'ad': did you mean 'add'? (ops: const, add, mul)
163
+ b.add(x) // add takes 2 args, got 1
164
+ b.const('7') // const.value is i32, got the string '7'
165
+ b.add(x, y) // %0 (const) belongs to another builder (y came from another builder)
166
+ x.vlaue // arith value %0 (const) has no 'vlaue': did you mean 'value'?
167
+ tk.ir('bad').op('k', { attrs: { v: 'int32' } })
168
+ // op k: attr 'v' has unknown type 'int32': did you mean 'i32'? (types: i32, i12, i8, u8, u5, u16, int, num,
169
+ // str, bool, any)
170
+ ```
171
+
172
+ "Did you mean" counts a swap of two neighbouring letters as one edit. It only suggests a name that keeps part of the
173
+ word, so a pattern variable `y` is not reported as a typo of `x`.
174
+
175
+ ### Example 4: a function IR assembled from fragments
176
+
177
+ Blocks, terminators and phis are not built in; they come from two fragments:
178
+
179
+ - `tk.frag.cfg`: blocks, and the terminators `br`, `cbr` and `ret`, each with a `control` lambda;
180
+ - `tk.frag.ssa`: `phi`, and `phi.incoming(block, value)`.
181
+
182
+ A third fragment, `tk.frag.edges`, gives blocks parameters instead of phis, as MLIR, Cranelift and the book's Host IR
183
+ have them. Its terminators are `jump`, `br`, `switch`, `ret` and `trap`, and each edge passes arguments to its target:
184
+ `b.br(c, body.to(), exit.to(s))`. The edge arguments are ordinary uses of the terminator. Use lists, `replaceWith` and
185
+ the interpreter therefore need nothing special for them, and `t.setEdge(k, block.to(...))` redirects an edge.
186
+
187
+ A value takes an id only if its op has a result. Terminators, and ops declared `result: false` (or with a function of
188
+ the attributes, such as `result: a => !a.void`), print without `%n =`. `b.id(n)` gives the next value a chosen id, for
189
+ importers that keep another IR's numbering.
190
+
191
+ The `Mini` IR and the `sum` function below are used by the later examples.
192
+
193
+ ```js
194
+ const Mini = tk.ir('mini')
195
+ .use(tk.frag.cfg, tk.frag.ssa)
196
+ .op('const', { attrs: { value: 'i32' }, eval: (_, { value }) => value })
197
+ .op('add', { args: 2, eval: ([a, b]) => (a + b) | 0 })
198
+ .op('mul', { args: 2, eval: ([a, b]) => Math.imul(a, b) })
199
+ .op('shl', { args: 2, eval: ([a, b]) => a << b })
200
+ .op('lt', { args: 2, eval: ([a, b]) => +(a < b) })
201
+ .op('load', { args: 1, effect: 'read' })
202
+ .op('store', { args: 2, effect: 'write' });
203
+
204
+ function sum(mod) {
205
+ return mod.fn('sum', ['n'], (b, n) => {
206
+ const entry = b.current, head = b.block('head'), body = b.block('body'), exit = b.block('exit');
207
+ const zero = b.const(0);
208
+ b.br(head).at(head);
209
+ const i = b.phi().named('i'), s = b.phi().named('s');
210
+ b.cbr(b.lt(i, n), body, exit).at(body);
211
+ const i1 = b.add(i, b.const(1)).named('i1'), s1 = b.add(s, i).named('s1');
212
+ b.br(head).at(exit).ret(s);
213
+ i.incoming(entry, zero).incoming(body, i1);
214
+ s.incoming(entry, zero).incoming(body, s1);
215
+ });
216
+ }
217
+
218
+ const mod = Mini.module();
219
+ sum(mod);
220
+ mod.run('sum', [10]); // 45: the same eval lambdas, now with control flow
221
+ mod.fn('sum').print();
222
+ ```
223
+
224
+ ```text
225
+ fn sum(%n) {
226
+ entry:
227
+ %1 = const 0
228
+ br head
229
+ head:
230
+ %i = phi [entry: %1, body: %i1]
231
+ %s = phi [entry: %1, body: %s1]
232
+ %4 = lt %i, %n
233
+ cbr %4, body, exit
234
+ body:
235
+ %5 = const 1
236
+ %i1 = add %i, %5
237
+ %s1 = add %s, %i
238
+ br head
239
+ exit:
240
+ ret %s
241
+ }
242
+ ```
243
+
244
+ ### Example 5: direct mutation, with provenance recorded automatically
245
+
246
+ A pass changes values directly. `replaceWith` takes either a value, or a lambda that receives a builder placed where
247
+ the old value was. Every use moves to the new value. Nobody writes provenance, yet every value knows how it came to
248
+ be.
249
+
250
+ ```js
251
+ const f = mod.fn('scale', ['x'], (b, x) => b.ret(b.add(b.mul(x, b.const(2)), b.const(0))));
252
+
253
+ const double = tk.pass('double').each(v => {
254
+ if (v.is('mul') && v.arg(1).is('const', { value: 2 })) v.replaceWith(b => b.add(v.arg(0), v.arg(0)));
255
+ });
256
+ f.apply(double);
257
+
258
+ const add = f.values('add')[0];
259
+ add.print(); // %5 = add %x, %x
260
+ add.history(); // ['created by double']
261
+ add.origin()[0].history(); // ['created by build', 'double: replaced by %5'] (the mul it replaced)
262
+ add.erase(); // cannot erase %5 (add): 1 use remains (%4 (add) in entry): replaceWith(…) first
263
+ ```
264
+
265
+ ### Example 6: rewrite rules are values
266
+
267
+ A rule has three parts:
268
+
269
+ - a pattern over the IR's ops, checked against the IR when the rule is defined;
270
+ - an optional condition;
271
+ - a replacement, built with a builder.
272
+
273
+ A rule set is a value: it can be filtered (`without`) and combined (`with`), and any driver can run it.
274
+
275
+ ```js
276
+ const isPow2 = c => c > 0 && (c & (c - 1)) === 0;
277
+ const peep = tk.rules('peephole', Mini)
278
+ .rule('add-zero').match('add(x, const 0)').to(({ x }) => x)
279
+ .rule('mul-one').match('mul(x, const 1)').to(({ x }) => x)
280
+ .rule('mul-pow2').match('mul(x, const c)').when(({ c }) => isPow2(c))
281
+ .to(({ x, c }, b) => b.shl(x, b.const(Math.log2(c))))
282
+ .rule('const-right').match('add(const c, x)').when(({ x }) => !x.is('const'))
283
+ .to(({ c, x }, b) => b.add(x, b.const(c)));
284
+
285
+ peep.names; // ['add-zero', 'mul-one', 'mul-pow2', 'const-right']
286
+ peep.without('mul-pow2').names; // ['add-zero', 'mul-one', 'const-right']
287
+ ```
288
+
289
+ The pattern syntax:
290
+
291
+ - `op(p, …)` matches an op and its arguments;
292
+ - a bare name binds any value; the same name twice must be the same value, and `_` matches anything;
293
+ - `const 0` matches an op whose single attribute is 0, and `const c` binds that attribute to `c`.
294
+
295
+ Mistakes are reported where they are made:
296
+
297
+ ```js
298
+ tk.rules('oops', Mini).rule('r').match('add(x, cnst 0)')
299
+ // pattern 'add(x, cnst 0)': mini has no op 'cnst': did you mean 'const'?
300
+ tk.rules('oops', Mini).rule('r').match('add(x, const 0)').to(({ y }) => y) // when it fires:
301
+ // rule r: no binding 'y' (the pattern binds: x)
302
+ ```
303
+
304
+ ### Example 7: passes, from rules, from a walk, from a function with analyses
305
+
306
+ A pass has one body, of one of three kinds:
307
+
308
+ - `.rules(set)`: the rules, driven greedily until none fires;
309
+ - `.each(f)`: `f` on every value, in order;
310
+ - `.run(f)`: `f` once per function.
311
+
312
+ `.needs({ … })` names the analyses the body receives. Reading one it did not ask for is an error.
313
+
314
+ ```js
315
+ const peephole = tk.pass('peephole').rules(peep);
316
+ const dce = tk.pass('dce').each(v => v.pure && !v.uses.length && v.erase());
317
+
318
+ const licm = tk.pass('licm')
319
+ .about('move loop-invariant pure values to the preheader')
320
+ .needs({ loops: tk.std.loops })
321
+ .run((f, { loops }) => {
322
+ for (const loop of loops.innermostFirst())
323
+ if (loop.preheader)
324
+ for (const v of loop.values())
325
+ if (v.pure && v.args.every(a => !loop.contains(a))) v.moveTo(loop.preheader);
326
+ });
327
+
328
+ const g = mod.fn('g', ['a'], (b, a) => b.ret(b.add(b.mul(a, b.const(8)), b.const(0))));
329
+ g.apply(peephole).apply(dce).print();
330
+ ```
331
+
332
+ ```text
333
+ fn g(%a) {
334
+ entry:
335
+ %5 = const 3
336
+ %6 = shl %a, %5
337
+ ret %6
338
+ }
339
+ ```
340
+
341
+ `licm` on `sum` moves the loop's `const 1` to the entry block, which is the loop's preheader. The entry block becomes
342
+ `%1 = const 0`, `%5 = const 1`, `br head`, and `sum(10)` is still 45.
343
+
344
+ ### Example 8: standard-library algorithms are generic and configured with lambdas
345
+
346
+ The library has no liveness analysis; it has the dataflow solver, which liveness is configured from. An analysis is a
347
+ named function of a function, cached per revision.
348
+
349
+ ```js
350
+ const liveness = tk.analysis('liveness', fn => tk.std.dataflow(fn, {
351
+ dir: 'backward',
352
+ ...tk.lattice.sets,
353
+ transfer: (block, live) => {
354
+ const out = new Set(live);
355
+ for (const v of block.values().reverse()) {
356
+ out.delete(v);
357
+ v.args.forEach(a => out.add(a));
358
+ }
359
+ return out;
360
+ },
361
+ }));
362
+
363
+ const f = mod.fn('sum');
364
+ const live = f.get(liveness); // computed once: f.get(liveness) again returns the same object
365
+ live.in(f.block('body')); // %1, %i, %n, %s
366
+ ```
367
+
368
+ The graph algorithms take any graph, not only a function's blocks:
369
+
370
+ ```js
371
+ const calls = tk.view.graph({
372
+ nodes: ['main', 'a', 'b', 'c'],
373
+ succ: n => ({ main: ['a'], a: ['b'], b: ['a', 'c'], c: [] })[n],
374
+ });
375
+ tk.std.scc(calls); // [['c'], ['a', 'b'], ['main']]: callees first
376
+ tk.std.dominators(calls).dominates('a', 'c'); // true
377
+ ```
378
+
379
+ An analysis result is guarded: once the function changes, reading it throws instead of answering from stale data.
380
+ `loops` and `dominators` declare `on: 'cfg'`, so they survive passes that only move or rewrite values.
381
+
382
+ ```js
383
+ const loops = f.get(tk.std.loops);
384
+ f.apply(licm);
385
+ live.in(f.block('body'));
386
+ // liveness of sum is from revision 20, and sum is now at revision 21: call sum.get(liveness) again
387
+ f.get(tk.std.loops) === loops; // true: licm did not change the control flow
388
+ ```
389
+
390
+ ### Example 9: composition
391
+
392
+ Anything with `applyTo` composes: passes, rule-driven passes, combinators, the standard passes. A check is a pass,
393
+ placed where the author wants it.
394
+
395
+ ```js
396
+ const O1 = tk.seq(tk.std.fold, peephole, tk.std.dce);
397
+ const O2 = tk.seq(tk.fixpoint(O1), licm, O1);
398
+ const Os = tk.seq(tk.when(f => f.size < 40, O2), tk.std.verifySSA);
399
+
400
+ mod.fn('k', [], b => b.ret(b.mul(b.add(b.const(2), b.const(3)), b.const(4))));
401
+ mod.apply(Os);
402
+ mod.fn('k').print();
403
+ ```
404
+
405
+ ```text
406
+ fn k() {
407
+ entry:
408
+ %6 = const 20
409
+ ret %6
410
+ }
411
+ ```
412
+
413
+ `tk.choose` runs each alternative on a clone of the module and keeps the cheapest. Here the cost counts a value inside
414
+ a loop as 10:
415
+
416
+ ```js
417
+ const weighted = m => m.fns.reduce((n, f) => {
418
+ const loops = f.get(tk.std.loops);
419
+ return n + f.values().reduce((c, v) => c + 10 ** loops.depthOf(v.block), 0);
420
+ }, 0);
421
+
422
+ mod.apply(tk.choose([O1, O2], weighted)); // a fresh module with sum
423
+ mod.choices[0].costs; // O1: 83, O2: 74. O2 is kept: its const 1 is now in the entry block.
424
+ ```
425
+
426
+ ### Example 10: lowering to another IR
427
+
428
+ A machine IR is an IR like any other, with two additions:
429
+
430
+ - `tk.frag.machine`: registers, and assembly templates for the cfg ops;
431
+ - an `asm` template on each op.
432
+
433
+ Its ops have `eval` lambdas too, so the lowered program runs.
434
+
435
+ ```js
436
+ const RV = tk.ir('rv32')
437
+ .use(tk.frag.cfg, tk.frag.ssa, tk.frag.machine)
438
+ .op('li', { attrs: { imm: 'i32' }, asm: 'li {d}, {imm}', eval: (_, { imm }) => imm })
439
+ .op('addi', { args: 1, attrs: { imm: 'i12' }, asm: 'addi {d}, {0}, {imm}', eval: ([a], { imm }) => (a + imm) | 0 })
440
+ .op('add', { args: 2, asm: 'add {d}, {0}, {1}', eval: ([a, b]) => (a + b) | 0 })
441
+ .op('slli', { args: 1, attrs: { imm: 'u5' }, asm: 'slli {d}, {0}, {imm}', eval: ([a], { imm }) => a << imm })
442
+ .op('slt', { args: 2, asm: 'slt {d}, {0}, {1}', eval: ([a, b]) => +(a < b) });
443
+
444
+ const small = v => v.is('const') && v.value >= -2048 && v.value < 2048;
445
+ const select = tk.lower(Mini, RV, 'select')
446
+ .op('const', (v, b) => b.li({ imm: v.value }))
447
+ .op('add', (v, b, [x, y]) => (small(v.arg(1)) ? b.addi(x, { imm: v.arg(1).value }) : b.add(x, y)))
448
+ .op('shl', (v, b, [x]) => b.slli(x, { imm: v.arg(1).value }))
449
+ .op('lt', (v, b, [x, y]) => b.slt(x, y));
450
+
451
+ const rv = select.run(mod).apply(tk.std.dce);
452
+ rv.run('sum', [10]); // 45
453
+ tk.std.asm(rv).print();
454
+ ```
455
+
456
+ ```text
457
+ sum:
458
+ .entry:
459
+ li %1, 0
460
+ j .head
461
+ .head:
462
+ # %i = phi entry: %1, body: %i1
463
+ # %s = phi entry: %1, body: %s1
464
+ slt %4, %i, %n
465
+ bnez %4, .body
466
+ j .exit
467
+ .body:
468
+ addi %i1, %i, 1
469
+ add %s1, %s, %i
470
+ j .head
471
+ .exit:
472
+ mv a0, %s
473
+ ret
474
+ ```
475
+
476
+ Each lowering case receives the source value, a builder of the target IR placed in the matching block, and the
477
+ source arguments already lowered. Blocks, phis and the cfg terminators carry over without cases.
478
+
479
+ Whatever a case builds records the source value as its origin; `addi`'s origin is `%i1 = add %i, %5`. An op without
480
+ a case is an error that says how many values need it:
481
+
482
+ ```js
483
+ mod.fn('m', ['a'], (b, a) => b.ret(b.mul(a, a)));
484
+ select.run(mod); // select has no case for mini op 'mul' (1 value in m): add .op('mul', …)
485
+ ```
486
+
487
+ ### Example 11: fragments extend ops, values and builders
488
+
489
+ A fragment adds members to values or to builders, or ops to an IR. `extend` applies a fragment to some ops only, or
490
+ adds spec fields to them.
491
+
492
+ ```js
493
+ const commutative = tk.fragment('commutative').op({
494
+ canonicalize() {
495
+ if (this.arg(0).is('const') && !this.arg(1).is('const')) this.swapArgs();
496
+ },
497
+ });
498
+ const cost = tk.fragment('cost').op({ get cost() { return this.spec.cost ?? 1; } });
499
+ Mini.extend(['add', 'mul'], commutative).extend('mul', { cost: 3 }).use(cost);
500
+
501
+ const forRange = tk.fragment('for-range').builder({
502
+ forRange(n, init, body) {
503
+ const from = this.current, head = this.block(), loop = this.block(), exit = this.block();
504
+ const zero = this.const(0);
505
+ this.br(head).at(head);
506
+ const i = this.phi(), acc = init.map(() => this.phi());
507
+ this.cbr(this.lt(i, n), loop, exit).at(loop);
508
+ const next = body(this, i, acc);
509
+ const i1 = this.add(i, this.const(1));
510
+ this.br(head).at(exit);
511
+ i.incoming(from, zero).incoming(loop, i1);
512
+ acc.forEach((p, k) => p.incoming(from, init[k]).incoming(loop, next[k]));
513
+ return acc;
514
+ },
515
+ });
516
+ Mini.use(forRange);
517
+
518
+ const mod = Mini.module(); // an empty module
519
+ mod.fn('sum', ['n'], (b, n) => b.ret(b.forRange(n, [b.const(0)], (b, i, [s]) => [b.add(s, i)])[0]));
520
+ mod.run('sum', [10]); // 45
521
+
522
+ const canon = tk.pass('canon').each(v => 'canonicalize' in v && v.canonicalize());
523
+ const t = mod.fn('t', ['a'], (b, a) => b.ret(b.mul(b.const(5), a))).apply(canon);
524
+ const m = t.values('mul')[0];
525
+ m.print(); // %2 = mul %a, %1
526
+ m.cost; // 3
527
+ m.history(); // ['created by build', 'canon: args swapped']
528
+ ```
529
+
530
+ ### Example 12: equality saturation (planned, not in the prototype)
531
+
532
+ A rule set does not know how it is driven. The same `peep` set could therefore be run by a saturating driver, which
533
+ keeps every equivalent form in an e-graph and extracts the cheapest. The intended shape:
534
+
535
+ ```js
536
+ const algebra = tk.rules('algebra', Mini)
537
+ .rule('add-comm').match('add(x, y)').to(({ x, y }, b) => b.add(y, x))
538
+ .rule('mul-comm').match('mul(x, y)').to(({ x, y }, b) => b.mul(y, x));
539
+
540
+ mod.apply(tk.pass('eqsat').run(fn => tk.std.saturate(fn, [peep, algebra], { limit: 10_000, cost: v => v.cost })));
541
+ ```
542
+
543
+ The greedy driver cannot take `algebra`, because commutativity never stops firing. It stops itself with:
544
+
545
+ ```text
546
+ greedy: the rules fired 10000 times in sum (the last was add-comm): they may not terminate
547
+ ```
548
+
549
+ That is the case for building `saturate` next.
550
+
551
+ ### Example 13: data: snapshots, diffs and side tables
552
+
553
+ A snapshot is a read-only clone, and `diff` reports, per function, what each actor has done since. Side tables attach
554
+ data to values without changing the IR. With `follows: 'replace'`, an entry moves to the value that replaces its
555
+ value.
556
+
557
+ ```js
558
+ mod.fn('g', ['a'], (b, a) => b.ret(b.add(b.mul(a, b.const(8)), b.const(0))));
559
+ const before = mod.snapshot();
560
+ mod.apply(tk.seq(peephole, licm, tk.std.dce));
561
+ mod.diff(before).print();
562
+ ```
563
+
564
+ ```text
565
+ sum 11 -> 11 values
566
+ licm: move 1
567
+ g 5 -> 3 values
568
+ peephole: mul-pow2: create 2, replace 1
569
+ peephole: add-zero: replace 1
570
+ dce: erase 2
571
+ ```
572
+
573
+ ```js
574
+ before.fn('g').values()[0].erase();
575
+ // snapshot r27 is read-only: .clone() gives an editable copy
576
+
577
+ const home = tk.attr('home', { follows: 'replace' });
578
+ const shl = mod.fn('g').values('shl')[0];
579
+ home.set(shl, 'stack+8');
580
+ const w = shl.replaceWith(b => b.mul(shl.arg(0), b.const(8)));
581
+ home.get(w); // 'stack+8'
582
+ ```
583
+
584
+ ### Example 14: a whole compiler as a graph of stages, with provenance end to end
585
+
586
+ A stage graph names each stage of a compiler and its inputs. `get` computes whatever is missing; `set` replaces an
587
+ input, and only the stages after it recompute.
588
+
589
+ Here the frontend is a function of one parameter, the loop's step, and records source positions with
590
+ `b.loc(where, text)`. A parser's tree would be walked the same way.
591
+
592
+ ```js
593
+ const O2 = tk.seq(tk.fixpoint(tk.seq(tk.std.fold, peephole, tk.std.dce)), licm);
594
+
595
+ const frontend = step => {
596
+ const mod = Mini.module();
597
+ mod.fn('sum', ['n'], (b, n) => {
598
+ const entry = b.current, head = b.block('head'), body = b.block('body'), exit = b.block('exit');
599
+ const zero = b.loc('sum.js:2', 'let s = 0, i = 0').const(0);
600
+ b.br(head).at(head);
601
+ const i = b.phi().named('i'), s = b.phi().named('s');
602
+ b.loc('sum.js:3', `i < n`).cbr(b.lt(i, n), body, exit).at(body);
603
+ const s1 = b.loc('sum.js:4', 's = s + i').add(s, i).named('s1');
604
+ const i1 = b.loc('sum.js:5', `i = i + ${step}`).add(b.const(step), i).named('i1');
605
+ b.br(head).at(exit).loc('sum.js:7', 'return s').ret(s);
606
+ i.incoming(entry, zero).incoming(body, i1);
607
+ s.incoming(entry, zero).incoming(body, s1);
608
+ });
609
+ return mod;
610
+ };
611
+
612
+ const build = tk.graph('mini -> rv32')
613
+ .node('step', () => 1)
614
+ .node('mini', ['step'], step => frontend(step))
615
+ .node('opt', ['mini'], m => m.clone().apply(O2))
616
+ .node('rv', ['opt'], m => select.run(m).apply(tk.std.dce))
617
+ .node('asm', ['rv'], m => tk.std.asm(m));
618
+
619
+ build.get('opt').run('sum', [10]); // 45: any stage runs
620
+ build.get('rv').run('sum', [10]); // 45
621
+ ```
622
+
623
+ The optimized `mini` function (left) and the assembly (right), as printed by `scripts/doc-outputs.mjs`:
624
+
625
+ ```text
626
+ fn sum(%n) { 1 sum:
627
+ entry: 2 .entry:
628
+ %1 = const 0 3 li %1, 0
629
+ %8 = const 1 4 j .head
630
+ br head 5 .head:
631
+ head: 6 # %i = phi entry: %1, body: %i1
632
+ %i = phi [entry: %1, body: %i1] 7 # %s = phi entry: %1, body: %s1
633
+ %s = phi [entry: %1, body: %s1] 8 slt %5, %i, %n
634
+ %4 = lt %i, %n 9 bnez %5, .body
635
+ cbr %4, body, exit 10 j .exit
636
+ body: 11 .body:
637
+ %s1 = add %s, %i 12 add %s1, %s, %i
638
+ %i1 = add %i, %8 13 addi %i1, %i, 1
639
+ br head 14 j .head
640
+ exit: 15 .exit:
641
+ ret %s 16 mv a0, %s
642
+ } 17 ret
643
+ ```
644
+
645
+ Any line of the assembly traces back through every IR to the source:
646
+
647
+ ```js
648
+ const asm = build.get('asm');
649
+ asm.line(asm.find(/addi/)).trace().print();
650
+ ```
651
+
652
+ ```text
653
+ asm 13 addi %i1, %i, 1
654
+ rv32 %i1 = addi %i, 1 select
655
+ mini %i1 = add %i, %8 peephole: const-right
656
+ mini %i1 = add %6, %i
657
+ source i = i + 1 sum.js:5
658
+ ```
659
+
660
+ Read from the bottom up:
661
+
662
+ 1. Line 5 of the source became `add %6, %i`, with the constant on the left, as written.
663
+ 2. The peephole rule `const-right` rebuilt it as `add %i, %8`, and `licm` moved the new constant to the entry block.
664
+ 3. Instruction selection turned it into `addi`, with the constant as an immediate.
665
+
666
+ The name `i1` follows the value through each replacement.
667
+
668
+ The stage graph caches: a second `build.get('asm')` computes nothing. A new input recomputes only what depends on it:
669
+
670
+ ```js
671
+ build.set('step', 2);
672
+ build.get('rv').run('sum', [10]); // 20: 0 + 2 + 4 + 6 + 8
673
+ build.runs('opt'); // 2
674
+ ```
675
+
676
+ ## 5. Design decisions
677
+
678
+ - **One lambda, two uses.** An op's `eval` is its meaning. The interpreter uses it to run a program, `fold` uses it
679
+ to fold constants, and a lowered program runs on its own IR's lambdas. A compiler therefore gets an executable
680
+ reference at every stage without writing an interpreter, and differential tests come for free (`more.test.mjs`).
681
+ - **Mutation, with provenance on the side.** Passes change values in place, the way compiler code is naturally
682
+ written. Each of the five kinds of change records the current actor (`withBy`, a stack), so passes do no
683
+ provenance bookkeeping. A clone's values point at the values they copy, and traces treat them as one entity.
684
+ - **Names belong to what is computed.** When a value is replaced, an unnamed replacement takes its name, so `i1` stays
685
+ `i1` through rewriting and lowering.
686
+ - **Checks are passes.** `verifySSA` is a pass like `dce`. The toolkit does not run it between steps; the author
687
+ places it where wanted (example 9). Analysis results guard themselves instead: reading a stale one throws.
688
+ - **Analyses depend on a revision, not on declared invalidation.** Every change bumps a function's `revision`; changes
689
+ to blocks and terminators also bump its `cfgRevision`. An analysis says which of the two it depends on. No list of
690
+ preserved analyses has to be maintained.
691
+ - **Rule sets are values, and drivers are separate.** The greedy driver exists. An equality-saturation driver can take
692
+ the same sets (example 12).
693
+ - **Proxies for diagnostics, when asked for.** With checks on (§3), every object the toolkit returns rejects unknown
694
+ members with a message that lists what exists. They are off by default for speed. The other errors are raised where
695
+ the mistake is made, in both modes:
696
+ - a bad pattern, when the rule is defined;
697
+ - a bad attribute, when the value is built;
698
+ - a missing lowering case, when lowering reaches it.
699
+ - **Fragments instead of a class hierarchy.** Control flow, SSA and machine features are fragments an IR opts into;
700
+ users add their own the same way (example 11).
701
+ - **Plain ES modules, no dependencies.** The toolkit must also run on the ESP32-P4 under QuickJS, and it does, with
702
+ the P4's 56 KB stack.
703
+
704
+ ## 6. Status and what comes next
705
+
706
+ Built and tested: everything in examples 1–11, 13 and 14.
707
+
708
+ - IRs, the builder, values and the five kinds of change.
709
+ - Fragments: `cfg`, `ssa`, `edges` (block parameters), `machine`.
710
+ - Rule sets and the greedy driver.
711
+ - Passes, and analyses with the staleness guard.
712
+ - The combinators `seq`, `fixpoint`, `when` and `choose`.
713
+ - Lowering, side tables, snapshots and diffs, the stage graph, traces.
714
+ - The standard library: `depthFirst`, `dominators`, `loops`, `scc`, `dataflow`, `lattice.sets` and
715
+ `lattice.constants`, `fold`, `dce`, `verifySSA`, `asm`.
716
+
717
+ Next, in the order that would let a real compiler be written:
718
+
719
+ 1. SSA construction from variables (Braun et al.), so a frontend can assign variables instead of placing phis.
720
+ 2. An ESTree frontend: JavaScript source to `mini`, with `b.loc` set from the parser's positions.
721
+ 3. Out-of-SSA, and a linear-scan register allocator writing `tk.regs`, so `asm` prints physical registers.
722
+ 4. `sccp`, `gvn` and `inline` in the standard library.
723
+ 5. `tk.std.saturate` (example 12).
724
+ 6. A worklist rule driver, instead of rounds over the whole function.
725
+
726
+ ## 7. Open questions
727
+
728
+ - **Where the toolkit lives in the end:** in the workbench repo next to `src/`, or in a repo of its own. It imports
729
+ nothing from `src/`, so either is a move, not a rewrite.
730
+ - **TypeScript declarations** (`.d.ts`) for editor completion. A builder's methods depend on its IR, so the types
731
+ would be generic over a record of op names.
732
+ - **A first real user:** should the gb-riscv32 compiler (GBRV-004/006) be it? Its regions are already an IR, and the
733
+ toolkit runs on the P4.
734
+
735
+ ## 8. References
736
+
737
+ - `docs/guide.md`: the user guide, by task, with a reference of every public function and option.
738
+ - `src/index.js`: the `tk` surface.
739
+ - `src/ir.js`: values, the five kinds of change, the builder, the analysis cache, traces.
740
+ - `test/examples.test.mjs`: examples 1–11, 13 and 14.
741
+ - `test/more.test.mjs`: pass-author errors, and 300 random programs through O2 and lowering.
742
+ - `scripts/quickjs-check.mjs`: the tests under QuickJS.
743
+ - `scripts/doc-outputs.mjs`: example 14's two listings.
744
+ - compiler-workbench sources ported: `src/stdlib/graph/dominators.ts`, `src/stdlib/graph/loops.ts`,
745
+ `src/stdlib/flow/solve.ts`.
746
+ - Cooper, Harvey and Kennedy, "A Simple, Fast Dominance Algorithm" (2001).
747
+ - Braun et al., "Simple and Efficient Construction of Static Single Assignment Form" (CC 2013).
748
+ - Willsey et al., "egg: Fast and Extensible Equality Saturation" (POPL 2021).