@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/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "@go-go-golems/compiler-toolkit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "A composable compiler toolkit: IRs, passes, rewrite rules, a standard library of algorithms, and provenance",
5
+ "keywords": ["compiler", "ir", "ssa", "passes", "rewrite-rules", "provenance", "quickjs"],
6
+ "license": "MIT",
7
+ "author": "Manuel Odendahl",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/go-go-golems/compiler-toolkit.git"
11
+ },
12
+ "homepage": "https://github.com/go-go-golems/compiler-toolkit#readme",
13
+ "bugs": "https://github.com/go-go-golems/compiler-toolkit/issues",
14
+ "type": "module",
15
+ "main": "src/index.js",
16
+ "exports": {
17
+ ".": "./src/index.js",
18
+ "./package.json": "./package.json"
19
+ },
20
+ "files": ["src/", "docs/", "README.md", "LICENSE"],
21
+ "engines": {
22
+ "node": ">=22"
23
+ },
24
+ "scripts": {
25
+ "test": "node --test test/*.test.mjs && TK_CHECKS=1 node --test test/*.test.mjs",
26
+ "test:quickjs": "node scripts/quickjs-check.mjs",
27
+ "bench:checks": "node scripts/checks-cost.bench.mjs && TK_CHECKS=1 node scripts/checks-cost.bench.mjs"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public"
31
+ }
32
+ }
package/src/context.js ADDED
@@ -0,0 +1,17 @@
1
+ // context.js — who is changing the IR right now. Passes, rules and lowerings push their name while they run; every
2
+ // value created, replaced, moved or erased records it. That is all provenance needs: nobody declares anything.
3
+
4
+ const stack = [];
5
+
6
+ /** The name of the pass (or 'pass: rule', or lowering) that is running, or 'user' outside any. */
7
+ export const currentBy = () => (stack.length ? stack[stack.length - 1] : 'user');
8
+
9
+ /** Run f with `by` as the current actor. */
10
+ export function withBy(by, f) {
11
+ stack.push(by);
12
+ try {
13
+ return f();
14
+ } finally {
15
+ stack.pop();
16
+ }
17
+ }
package/src/data.js ADDED
@@ -0,0 +1,24 @@
1
+ // data.js — side tables: data attached to values without changing the IR. With { follows: 'replace' } an entry moves
2
+ // to the value that replaces its value; every table's entries are copied by module.clone().
3
+
4
+ import { strict } from './diag.js';
5
+ import { FOLLOWING, ALL_ATTRS } from './ir.js';
6
+
7
+ export function attr(name, { follows } = {}) {
8
+ if (follows !== undefined && follows !== 'replace')
9
+ throw new TypeError(`tk.attr('${name}', { follows }): follows is 'replace' or nothing`);
10
+ const m = new WeakMap();
11
+ const a = {
12
+ name,
13
+ set(v, x) {
14
+ m.set(v, x);
15
+ return a;
16
+ },
17
+ get: v => m.get(v),
18
+ has: v => m.has(v),
19
+ delete: v => m.delete(v),
20
+ };
21
+ ALL_ATTRS.add(a);
22
+ if (follows) FOLLOWING.add(a);
23
+ return strict(a, t => `attr ${t.name}`);
24
+ }
package/src/diag.js ADDED
@@ -0,0 +1,116 @@
1
+ // diag.js — diagnostics. With checks on, the toolkit's objects are proxies that turn a misspelled or missing member into
2
+ // an error that names what exists and the closest match, instead of `undefined` three calls later.
3
+ //
4
+ // Checks are off by default: a proxy runs on every property read, and in a pass that reads many (gvn on real code) the
5
+ // proxies take about three quarters of the time. Turn them on to write and debug passes, and in tests:
6
+ // TK_CHECKS=1 in the environment, or globalThis.TK_CHECKS = true, before the toolkit loads (this also covers the
7
+ // toolkit's own objects: tk, tk.std, tk.frag), or tk.checks(true) before the IRs, modules and passes are made.
8
+ // An object keeps the mode it was made in. Checks never change what a pass computes, only how early a mistake throws.
9
+ // What does not depend on the mode: the validation of each new value's args and attrs, of op and attr definitions,
10
+ // of rule patterns and of lowerings (once per creation or definition, not per read).
11
+
12
+ export class TkError extends Error {
13
+ constructor(message) {
14
+ super(message);
15
+ this.name = 'TkError';
16
+ }
17
+ }
18
+
19
+ /** Edit distance where swapping two neighbours counts as one edit (optimal string alignment), for "did you mean". */
20
+ export function distance(a, b) {
21
+ const d = Array.from({ length: a.length + 1 }, (_, i) => [i]);
22
+ for (let j = 1; j <= b.length; j++) d[0][j] = j;
23
+ for (let i = 1; i <= a.length; i++)
24
+ for (let j = 1; j <= b.length; j++) {
25
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
26
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1])
27
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
28
+ }
29
+ return d[a.length][b.length];
30
+ }
31
+
32
+ /** ': did you mean "x"?' when a candidate is close enough, else ''. */
33
+ export function didYouMean(word, candidates) {
34
+ let best = null;
35
+ let bestD = Infinity;
36
+ for (const c of candidates) {
37
+ const x = distance(String(word).toLowerCase(), String(c).toLowerCase());
38
+ if (x < bestD) [best, bestD] = [c, x];
39
+ }
40
+ const n = String(word).length;
41
+ // a suggestion must keep part of the word: 'y' is not a typo of 'x'
42
+ const near =
43
+ best !== null &&
44
+ bestD < Math.min(n, String(best).length) &&
45
+ bestD <= (n <= 3 ? 1 : Math.max(2, Math.floor(n / 3)));
46
+ return near ? `: did you mean '${best}'?` : '';
47
+ }
48
+
49
+ /** How a value reads in an error message. */
50
+ export function describe(x) {
51
+ if (typeof x === 'string') return `the string '${x}'`;
52
+ if (x === null || x === undefined) return String(x);
53
+ if (Array.isArray(x)) return 'an array';
54
+ if (typeof x === 'object') return x.constructor?.name ? `a ${x.constructor.name}` : 'an object';
55
+ return `${typeof x} ${x}`;
56
+ }
57
+
58
+ // Names that JavaScript itself, the test runner or console.log probe on any object: missing, they read as undefined.
59
+ export const PROBES = new Set([
60
+ 'then',
61
+ 'catch',
62
+ 'finally',
63
+ 'toJSON',
64
+ 'constructor',
65
+ 'valueOf',
66
+ 'toString',
67
+ 'inspect',
68
+ 'asymmetricMatch',
69
+ '$$typeof',
70
+ 'nodeType',
71
+ 'tagName',
72
+ 'prototype',
73
+ 'length',
74
+ '__proto__',
75
+ 'toPrimitive',
76
+ 'call',
77
+ 'apply',
78
+ 'bind',
79
+ ]);
80
+
81
+ /** The public member names of an object, along its prototype chain. */
82
+ export function memberNames(o) {
83
+ const names = new Set();
84
+ for (let p = o; p && p !== Object.prototype; p = Object.getPrototypeOf(p))
85
+ for (const k of Object.getOwnPropertyNames(p))
86
+ if (!k.startsWith('_') && k !== 'constructor') names.add(k);
87
+ return [...names];
88
+ }
89
+
90
+ const fromEnvironment = () => {
91
+ const g = globalThis;
92
+ const v = g.TK_CHECKS !== undefined ? g.TK_CHECKS : g.process?.env?.TK_CHECKS;
93
+ return v !== undefined && v !== false && v !== '' && v !== '0' && v !== 'false';
94
+ };
95
+ let checking = fromEnvironment();
96
+
97
+ /** checks() says whether checks are on; checks(on) turns them on or off for the objects made from then on */
98
+ export function checks(on) {
99
+ if (on !== undefined) checking = !!on;
100
+ return checking;
101
+ }
102
+
103
+ /**
104
+ * With checks on, a proxy that throws on a read of a member the object does not have; with checks off, the object. `what(target)` names the object in the
105
+ * message; `names(target)` lists the candidates (default: its public members).
106
+ */
107
+ export function strict(target, what, names = memberNames) {
108
+ if (!checking) return target;
109
+ return new Proxy(target, {
110
+ get(t, k, r) {
111
+ if (typeof k === 'symbol' || k in t) return Reflect.get(t, k, r);
112
+ if (PROBES.has(k)) return undefined;
113
+ throw new TypeError(`${what(t)} has no '${k}'${didYouMean(k, names(t))}`);
114
+ },
115
+ });
116
+ }
package/src/frag.js ADDED
@@ -0,0 +1,194 @@
1
+ // frag.js — the built-in fragments: control flow (blocks and terminators), SSA (phis), and machine IRs (registers and
2
+ // assembly templates). Each is an ordinary tk.fragment: an IR takes what it needs with .use(...).
3
+
4
+ import { Fragment } from './ir.js';
5
+ import { TkError } from './diag.js';
6
+ import { currentBy } from './context.js';
7
+
8
+ /** physical registers chosen by a register allocator; a value without one prints as its virtual name */
9
+ export const REGS = new WeakMap();
10
+
11
+ function target(b, t) {
12
+ if (!t || t.fn !== b.fn)
13
+ throw new TkError(`branch target ${t && t.name ? t.name : String(t)} is not a block of ${b.fn.name}`);
14
+ return t;
15
+ }
16
+
17
+ /** blocks, and the terminators br, cbr and ret; their control lambdas drive the interpreter */
18
+ export const cfg = new Fragment('cfg')
19
+ .define(ir => {
20
+ ir.hasBlocks = true;
21
+ ir.op('br', { terminator: true, control: (_, [t]) => t });
22
+ ir.op('cbr', { args: 1, terminator: true, control: ([c], [t, e]) => (c ? t : e) });
23
+ ir.op('ret', { args: 1, terminator: true, control: ([v]) => ({ ret: v }) });
24
+ })
25
+ .builder({
26
+ br(to) {
27
+ this._make(this.ir.ops.get('br'), [], { targets: [target(this, to)] });
28
+ return this.self;
29
+ },
30
+ cbr(cond, then, otherwise) {
31
+ this._make(this.ir.ops.get('cbr'), [cond], { targets: [target(this, then), target(this, otherwise)] });
32
+ return this.self;
33
+ },
34
+ ret(v) {
35
+ this._make(this.ir.ops.get('ret'), [v]);
36
+ return this.self;
37
+ },
38
+ });
39
+
40
+ /** phis: a phi gets its inputs one edge at a time with phi.incoming(block, value) */
41
+ export const ssa = new Fragment('ssa')
42
+ .define(ir => ir.op('phi', { args: '*' }))
43
+ .builder({
44
+ phi() {
45
+ return this._make(this.ir.ops.get('phi'), []);
46
+ },
47
+ })
48
+ .op({
49
+ incoming(block, v) {
50
+ if (this.kind !== 'phi') throw new TypeError(`incoming(…) is for phis; ${this.ref} is a ${this.kind}`);
51
+ if (v.fn !== this.fn) throw new TkError(`incoming: ${v.ref} belongs to another function`);
52
+ this.args.push(v);
53
+ this.incomingBlocks.push(block);
54
+ v.uses.push(this);
55
+ this.fn._log(currentBy(), 'set-arg', this);
56
+ return this;
57
+ },
58
+ });
59
+
60
+ /** an edge given as block.to(...args); checked against the builder's function */
61
+ function edgeOf(b, e, what) {
62
+ if (!e || !e.block || !Array.isArray(e.args))
63
+ throw new TypeError(
64
+ `${what} takes edges (block.to(...args)), got ${e && e.name ? `the block ${e.name}` : String(e)}`,
65
+ );
66
+ target(b, e.block);
67
+ return e;
68
+ }
69
+
70
+ /**
71
+ * Blocks with parameters instead of phis, as MLIR, Cranelift and the book's Host IR have them. A terminator passes
72
+ * each target block its arguments; the arguments are ordinary uses of the terminator (after its own operands), so use
73
+ * lists, replaceWith and the interpreter need nothing special. The terminators: jump, br (condition, then, else, an
74
+ * optional hint), switch (a value, cases [[k, edge]], a default edge), ret (0 or 1 values), trap.
75
+ */
76
+ export const edges = new Fragment('edges')
77
+ .define(ir => {
78
+ ir.hasBlocks = true;
79
+ ir.op('arg'); // a block parameter: its place among block.params is its index
80
+ ir.op('jump', { args: '*', terminator: true, control: () => 0 });
81
+ ir.op('br', { args: '*', attrs: { hint: 'any?' }, terminator: true, control: ([c]) => (c ? 0 : 1) });
82
+ ir.op('switch', {
83
+ args: '*',
84
+ attrs: { cases: 'any' },
85
+ terminator: true,
86
+ control: ([x], _, __, v) => {
87
+ const k = v.attrs.cases.indexOf(x);
88
+ return k < 0 ? v.attrs.cases.length : k;
89
+ },
90
+ format: v => {
91
+ const e = v.edges.map(({ block, args }) => `${block.name}(${args.map(a => a.ref).join(', ')})`);
92
+ const cases = v.attrs.cases.map((k, i) => `${k} -> ${e[i]}`).join(', ');
93
+ return `switch ${v.own[0].ref} [${cases}], ${e[e.length - 1]}`;
94
+ },
95
+ });
96
+ ir.op('ret', { args: '*', terminator: true, control: a => ({ ret: a[0] }) });
97
+ ir.op('trap', {
98
+ terminator: true,
99
+ control: () => {
100
+ throw new TkError('trap');
101
+ },
102
+ });
103
+ })
104
+ .builder({
105
+ /** n new parameters of a block (opts.ids: their ids, for an importer) */
106
+ params(block, n, opts = {}) {
107
+ target(this, block);
108
+ return Array.from({ length: n }, (_, i) =>
109
+ this.fn._create(this.ir.ops.get('arg'), [], {}, { block, id: opts.ids?.[i], by: this._by }),
110
+ );
111
+ },
112
+ jump(to) {
113
+ const e = edgeOf(this, to, 'jump');
114
+ this._make(this.ir.ops.get('jump'), [...e.args], { targets: [e.block], edgeArgc: [e.args.length] });
115
+ return this.self;
116
+ },
117
+ br(cond, then, otherwise, hint) {
118
+ const t = edgeOf(this, then, 'br'),
119
+ e = edgeOf(this, otherwise, 'br');
120
+ this._make(
121
+ this.ir.ops.get('br'),
122
+ [cond, ...t.args, ...e.args, ...(hint === undefined ? [] : [{ hint }])],
123
+ {
124
+ targets: [t.block, e.block],
125
+ edgeArgc: [t.args.length, e.args.length],
126
+ },
127
+ );
128
+ return this.self;
129
+ },
130
+ switch(x, cases, dflt) {
131
+ const es = cases.map(([, e]) => edgeOf(this, e, 'switch'));
132
+ const d = edgeOf(this, dflt, 'switch');
133
+ this._make(
134
+ this.ir.ops.get('switch'),
135
+ [x, ...es.flatMap(e => e.args), ...d.args, { cases: cases.map(([k]) => k) }],
136
+ {
137
+ targets: [...es.map(e => e.block), d.block],
138
+ edgeArgc: [...es.map(e => e.args.length), d.args.length],
139
+ },
140
+ );
141
+ return this.self;
142
+ },
143
+ ret(...xs) {
144
+ this._make(this.ir.ops.get('ret'), xs);
145
+ return this.self;
146
+ },
147
+ trap() {
148
+ this._make(this.ir.ops.get('trap'), []);
149
+ return this.self;
150
+ },
151
+ })
152
+ .op({
153
+ /** a terminator's operands before its edges' arguments */
154
+ get own() {
155
+ const n = this.edgeArgc ? this.edgeArgc.reduce((a, b) => a + b, 0) : 0;
156
+ return this.args.slice(0, this.args.length - n);
157
+ },
158
+ /** a terminator's edges: [{ block, args }] (for switch: the cases', then the default's) */
159
+ get edges() {
160
+ if (!this.edgeArgc) return [];
161
+ let at = this.own.length;
162
+ return this.targets.map((block, k) => ({ block, args: this.args.slice(at, (at += this.edgeArgc[k])) }));
163
+ },
164
+ /** point edge k elsewhere, with new arguments */
165
+ setEdge(k, to) {
166
+ const fn = this.fn;
167
+ fn._writable();
168
+ const e = edgeOf({ fn }, to, 'setEdge');
169
+ if (!(k >= 0 && k < this.targets.length))
170
+ throw new TypeError(`${this.kind} has ${this.targets.length} edges: no edge ${k}`);
171
+ let at = this.own.length;
172
+ for (let i = 0; i < k; i++) at += this.edgeArgc[i];
173
+ const old = this.args.splice(at, this.edgeArgc[k], ...e.args);
174
+ for (const o of old) o.uses.splice(o.uses.indexOf(this), 1);
175
+ for (const a of e.args) a.uses.push(this);
176
+ this.targets[k] = e.block;
177
+ this.edgeArgc[k] = e.args.length;
178
+ const by = currentBy();
179
+ this._history.push({ by, what: `edge ${k} set to ${e.block.name}` });
180
+ fn._log(by, 'set-arg', this);
181
+ return this;
182
+ },
183
+ });
184
+
185
+ /** virtual registers (a value's own name, or what a 'reg' side table says) and assembly templates for the cfg ops */
186
+ export const machine = new Fragment('machine')
187
+ .define(ir => {
188
+ ir.machine = { asm: { br: 'j {t0}', cbr: ['bnez {0}, {t0}', 'j {t1}'], ret: ['mv a0, {0}', 'ret'] } };
189
+ })
190
+ .op({
191
+ get reg() {
192
+ return REGS.get(this) ?? this.ref;
193
+ },
194
+ });
package/src/index.js ADDED
@@ -0,0 +1,41 @@
1
+ // index.js — the toolkit: tk.ir, tk.fragment and tk.frag, tk.rules, tk.pass, tk.analysis, tk.seq / fixpoint / when /
2
+ // choose, tk.lower, tk.attr, tk.graph and tk.view, tk.std (algorithms and passes), tk.lattice.
3
+
4
+ import { strict, checks, TkError } from './diag.js';
5
+ import { IR, Fragment } from './ir.js';
6
+ import { cfg, ssa, edges, machine, REGS } from './frag.js';
7
+ import { RuleSet } from './rules.js';
8
+ import { Pass, Analysis, seq, fixpoint, when, choose } from './pass.js';
9
+ import { Lowering } from './lower.js';
10
+ import { attr } from './data.js';
11
+ import { StageGraph } from './stages.js';
12
+ import { asGraph, depthFirst, dominators, loops, scc } from './std/graph.js';
13
+ import { dataflow } from './std/dataflow.js';
14
+ import { sets, constants, TOP } from './std/lattice.js';
15
+ import { fold, dce, verifySSA } from './std/passes.js';
16
+ import { asm } from './std/asm.js';
17
+
18
+ const named = (name, o) => strict(o, () => name);
19
+
20
+ export const tk = named('tk', {
21
+ ir: name => new IR(name),
22
+ fragment: name => new Fragment(name),
23
+ frag: named('tk.frag', { cfg, ssa, edges, machine }),
24
+ rules: (name, ir) => new RuleSet(name, ir),
25
+ pass: name => new Pass(name),
26
+ analysis: (name, compute, opts) => new Analysis(name, compute, opts),
27
+ seq,
28
+ fixpoint,
29
+ when,
30
+ choose,
31
+ lower: (from, to, name) => new Lowering(from, to, name),
32
+ attr,
33
+ graph: name => new StageGraph(name),
34
+ view: named('tk.view', { graph: spec => asGraph(spec) }),
35
+ std: named('tk.std', { fold, dce, verifySSA, dataflow, dominators, loops, scc, depthFirst, asm }),
36
+ lattice: named('tk.lattice', { sets, constants, TOP }),
37
+ regs: REGS,
38
+ checks,
39
+ TkError,
40
+ });
41
+ export { TkError };