@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 +21 -0
- package/README.md +565 -2
- package/docs/design.md +748 -0
- package/docs/guide.md +1672 -0
- package/package.json +30 -4
- package/src/context.js +17 -0
- package/src/data.js +24 -0
- package/src/diag.js +116 -0
- package/src/frag.js +194 -0
- package/src/index.js +41 -0
- package/src/ir.js +1204 -0
- package/src/lower.js +101 -0
- package/src/pass.js +182 -0
- package/src/rules.js +236 -0
- package/src/stages.js +68 -0
- package/src/std/asm.js +65 -0
- package/src/std/dataflow.js +67 -0
- package/src/std/graph.js +197 -0
- package/src/std/lattice.js +23 -0
- package/src/std/passes.js +76 -0
package/src/lower.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// lower.js — from one IR to another: a table of lambdas, one per source op. Each lambda gets the source value, a
|
|
2
|
+
// builder of the target IR (placed in the matching block) and the source arguments already lowered; what it builds
|
|
3
|
+
// records the source value as its origin. Blocks, phis and the cfg terminators carry over when both IRs have them.
|
|
4
|
+
|
|
5
|
+
import { TkError, strict, describe } from './diag.js';
|
|
6
|
+
import { IR, Module, Fn, Value, makeBuilder } from './ir.js';
|
|
7
|
+
import { withBy } from './context.js';
|
|
8
|
+
import { depthFirst } from './std/graph.js';
|
|
9
|
+
|
|
10
|
+
export class Lowering {
|
|
11
|
+
constructor(from, to, name) {
|
|
12
|
+
if (!(from instanceof IR) || !(to instanceof IR))
|
|
13
|
+
throw new TypeError(`tk.lower(from, to) takes two IRs, got ${describe(from)} and ${describe(to)}`);
|
|
14
|
+
this.from = from;
|
|
15
|
+
this.to = to;
|
|
16
|
+
this.name = name ?? `${from.name}->${to.name}`;
|
|
17
|
+
this.cases = new Map();
|
|
18
|
+
return strict(this, t => `lowering ${t.name}`);
|
|
19
|
+
}
|
|
20
|
+
/** how one source op lowers: (value, builder, loweredArgs) => target value (or nothing, for an op without result) */
|
|
21
|
+
op(kind, f) {
|
|
22
|
+
this.from.opNamed(kind);
|
|
23
|
+
if (typeof f !== 'function')
|
|
24
|
+
throw new TypeError(
|
|
25
|
+
`${this.name}: .op('${kind}', f) takes (value, builder, args) => value, got ${describe(f)}`,
|
|
26
|
+
);
|
|
27
|
+
this.cases.set(kind, f);
|
|
28
|
+
return this;
|
|
29
|
+
}
|
|
30
|
+
applyTo() {
|
|
31
|
+
throw new TypeError(`${this.name} makes a new ${this.to.name} module: call .run(module), not apply`);
|
|
32
|
+
}
|
|
33
|
+
/** a new module of the target IR */
|
|
34
|
+
run(mod) {
|
|
35
|
+
if (!(mod instanceof Module) || mod.ir !== this.from)
|
|
36
|
+
throw new TypeError(`${this.name}.run(…) takes a ${this.from.name} module, got ${describe(mod)}`);
|
|
37
|
+
const out = this.to.module();
|
|
38
|
+
for (const f of mod.fns) out._fns.set(f.name, this._fn(f, out));
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
_fn(f, out) {
|
|
42
|
+
const g = new Fn(out, f.name, this.to, false);
|
|
43
|
+
const map = new Map();
|
|
44
|
+
const bmap = new Map();
|
|
45
|
+
return withBy(this.name, () => {
|
|
46
|
+
for (const b of f.blocks) bmap.set(b, g.addBlock(b.name));
|
|
47
|
+
g.entry = bmap.get(f.entry);
|
|
48
|
+
g.params = f.params.map((p, i) => {
|
|
49
|
+
const q = g._create(this.to.ops.get('param'), [], { index: i }, { origin: [p] }).named(p.name);
|
|
50
|
+
map.set(p, q);
|
|
51
|
+
return q;
|
|
52
|
+
});
|
|
53
|
+
const { rpo } = depthFirst(f.graph);
|
|
54
|
+
const order = [...rpo, ...f.blocks.filter(b => !rpo.includes(b))];
|
|
55
|
+
const phis = [];
|
|
56
|
+
for (const blk of order) {
|
|
57
|
+
const b = makeBuilder(this.to, g, bmap.get(blk), { by: this.name });
|
|
58
|
+
for (const v of blk.values()) {
|
|
59
|
+
b._origin = [v];
|
|
60
|
+
if (v.kind === 'phi' && this.to.ops.has('phi') && !this.cases.has('phi')) {
|
|
61
|
+
const q = b.phi();
|
|
62
|
+
if (v.name) q.name = v.name;
|
|
63
|
+
map.set(v, q);
|
|
64
|
+
phis.push([v, q]);
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
const args = v.args.map(a => {
|
|
68
|
+
if (!map.has(a))
|
|
69
|
+
throw new TkError(
|
|
70
|
+
`${this.name}: ${v.ref} (${v.kind}) in ${blk.name} uses ${a.ref} before it is lowered`,
|
|
71
|
+
);
|
|
72
|
+
return map.get(a);
|
|
73
|
+
});
|
|
74
|
+
const r = this._case(v, f)(v, b, args, bmap);
|
|
75
|
+
if (r instanceof Value) {
|
|
76
|
+
if (v.name && !r.name) r.name = v.name;
|
|
77
|
+
map.set(v, r);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
for (const [v, q] of phis)
|
|
82
|
+
v.args.forEach((a, i) => q.incoming(bmap.get(v.incomingBlocks[i]), map.get(a)));
|
|
83
|
+
return g;
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
_case(v, f) {
|
|
87
|
+
const c = this.cases.get(v.kind);
|
|
88
|
+
if (c) return c;
|
|
89
|
+
if (['br', 'cbr', 'ret'].includes(v.kind) && this.to.ops.has(v.kind)) {
|
|
90
|
+
const T = (bmap, k) => bmap.get(v.targets[k]);
|
|
91
|
+
if (v.kind === 'br') return (_, b, __, bmap) => void b.br(T(bmap, 0));
|
|
92
|
+
if (v.kind === 'cbr') return (_, b, [c], bmap) => void b.cbr(c, T(bmap, 0), T(bmap, 1));
|
|
93
|
+
return (_, b, [x]) => void b.ret(x);
|
|
94
|
+
}
|
|
95
|
+
const n = f.values(v.kind).length;
|
|
96
|
+
throw new TkError(
|
|
97
|
+
`${this.name} has no case for ${this.from.name} op '${v.kind}' (${n} value${n > 1 ? 's' : ''} in ${f.name}): ` +
|
|
98
|
+
`add .op('${v.kind}', …)`,
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
}
|
package/src/pass.js
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
// pass.js — passes and how they compose. A pass is a name and a lambda: run on every value (each), on every function
|
|
2
|
+
// (run), or a set of rewrite rules (rules). Anything with applyTo(target) composes: seq, fixpoint, when, choose, and
|
|
3
|
+
// lowerings. A target is a module, a function or an expression graph.
|
|
4
|
+
|
|
5
|
+
import { TkError, strict, checks, didYouMean, describe } from './diag.js';
|
|
6
|
+
import { Module, Fn } from './ir.js';
|
|
7
|
+
import { withBy } from './context.js';
|
|
8
|
+
import { RuleSet, rewriteGreedy } from './rules.js';
|
|
9
|
+
|
|
10
|
+
const fnsOf = target => (target instanceof Module ? target.fns : [target]);
|
|
11
|
+
const revisionOf = target => target.revision;
|
|
12
|
+
|
|
13
|
+
/** an analysis: a named function of a function, cached per revision (on: 'cfg' caches per control-flow revision) */
|
|
14
|
+
export class Analysis {
|
|
15
|
+
constructor(name, compute, opts = {}) {
|
|
16
|
+
if (typeof compute !== 'function')
|
|
17
|
+
throw new TypeError(
|
|
18
|
+
`tk.analysis('${name}', f): f computes the result from a function, got ${describe(compute)}`,
|
|
19
|
+
);
|
|
20
|
+
this.analysisName = name;
|
|
21
|
+
this.compute = compute;
|
|
22
|
+
this.on = opts.on ?? 'all';
|
|
23
|
+
return strict(this, t => `analysis ${t.analysisName}`);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** the analyses a pass asked for, computed on first read; with checks on, reading one it did not ask for is an error */
|
|
28
|
+
function analysesFor(pass, fn) {
|
|
29
|
+
const needs = pass._needs;
|
|
30
|
+
if (!checks()) {
|
|
31
|
+
const o = {};
|
|
32
|
+
for (const k of Object.keys(needs))
|
|
33
|
+
Object.defineProperty(o, k, { get: () => fn.get(needs[k]), enumerable: true });
|
|
34
|
+
return o;
|
|
35
|
+
}
|
|
36
|
+
return new Proxy(
|
|
37
|
+
{},
|
|
38
|
+
{
|
|
39
|
+
get(_, k) {
|
|
40
|
+
if (typeof k === 'symbol') return undefined;
|
|
41
|
+
if (!(k in needs))
|
|
42
|
+
throw new TkError(
|
|
43
|
+
`pass ${pass.name} did not ask for '${k}'${didYouMean(k, Object.keys(needs))}: add it to .needs({ … })` +
|
|
44
|
+
` (it needs: ${Object.keys(needs).join(', ') || 'nothing'})`,
|
|
45
|
+
);
|
|
46
|
+
return fn.get(needs[k]);
|
|
47
|
+
},
|
|
48
|
+
},
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export class Pass {
|
|
53
|
+
constructor(name) {
|
|
54
|
+
this.name = name;
|
|
55
|
+
this.text = '';
|
|
56
|
+
this.kind = null;
|
|
57
|
+
this.body = null;
|
|
58
|
+
this.sets = [];
|
|
59
|
+
this._needs = {};
|
|
60
|
+
return strict(this, t => `pass ${t.name}`);
|
|
61
|
+
}
|
|
62
|
+
about(text) {
|
|
63
|
+
this.text = text;
|
|
64
|
+
return this;
|
|
65
|
+
}
|
|
66
|
+
/** analyses the lambda receives as its last argument: { name: analysis } */
|
|
67
|
+
needs(map) {
|
|
68
|
+
Object.assign(this._needs, map);
|
|
69
|
+
return this;
|
|
70
|
+
}
|
|
71
|
+
/** run f(value, analyses) on every value, in order */
|
|
72
|
+
each(f) {
|
|
73
|
+
return this._set('each', f);
|
|
74
|
+
}
|
|
75
|
+
/** run f(fn, analyses) once per function */
|
|
76
|
+
run(f) {
|
|
77
|
+
return this._set('run', f);
|
|
78
|
+
}
|
|
79
|
+
/** run f(module) once: for passes over the functions together (inlining, removing functions) */
|
|
80
|
+
module(f) {
|
|
81
|
+
return this._set('module', f);
|
|
82
|
+
}
|
|
83
|
+
/** apply rule sets greedily to a fixpoint */
|
|
84
|
+
rules(...sets) {
|
|
85
|
+
for (const s of sets)
|
|
86
|
+
if (!(s instanceof RuleSet))
|
|
87
|
+
throw new TypeError(`pass ${this.name}: .rules(…) takes rule sets (tk.rules), got ${describe(s)}`);
|
|
88
|
+
this.kind = 'rules';
|
|
89
|
+
this.sets = sets;
|
|
90
|
+
return this;
|
|
91
|
+
}
|
|
92
|
+
_set(kind, f) {
|
|
93
|
+
if (typeof f !== 'function')
|
|
94
|
+
throw new TypeError(`pass ${this.name}: .${kind}(…) takes a function, got ${describe(f)}`);
|
|
95
|
+
if (this.kind) throw new TypeError(`pass ${this.name} already has a .${this.kind}(…) body`);
|
|
96
|
+
this.kind = kind;
|
|
97
|
+
this.body = f;
|
|
98
|
+
return this;
|
|
99
|
+
}
|
|
100
|
+
applyTo(target) {
|
|
101
|
+
if (!this.kind)
|
|
102
|
+
throw new TkError(`pass ${this.name} has no body: give it .each(…), .run(…), .module(…) or .rules(…)`);
|
|
103
|
+
if (this.kind === 'module') {
|
|
104
|
+
if (!(target instanceof Module))
|
|
105
|
+
throw new TypeError(`pass ${this.name} works on a module, not on ${describe(target)}`);
|
|
106
|
+
withBy(this.name, () => this.body(target));
|
|
107
|
+
return target;
|
|
108
|
+
}
|
|
109
|
+
for (const fn of fnsOf(target))
|
|
110
|
+
withBy(this.name, () => {
|
|
111
|
+
if (this.kind === 'rules') return rewriteGreedy(fn, this.sets, this.name);
|
|
112
|
+
const a = analysesFor(this, fn);
|
|
113
|
+
if (this.kind === 'run') return this.body(fn, a);
|
|
114
|
+
for (const v of fn.values()) if (!v.erased) this.body(v, a);
|
|
115
|
+
});
|
|
116
|
+
return target;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
class Combinator {
|
|
121
|
+
constructor(name, applyTo) {
|
|
122
|
+
this.name = name;
|
|
123
|
+
this.applyTo = applyTo;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const check = (p, where) => {
|
|
128
|
+
if (!p || typeof p.applyTo !== 'function') throw new TypeError(`${where} takes passes, got ${describe(p)}`);
|
|
129
|
+
return p;
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
/** passes in order */
|
|
133
|
+
export const seq = (...passes) => {
|
|
134
|
+
passes.forEach(p => check(p, 'tk.seq(…)'));
|
|
135
|
+
return new Combinator(`seq(${passes.map(p => p.name).join(', ')})`, target => {
|
|
136
|
+
for (const p of passes) p.applyTo(target);
|
|
137
|
+
return target;
|
|
138
|
+
});
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
/** repeat until the target stops changing */
|
|
142
|
+
export const fixpoint = (pass, { max = 100 } = {}) => {
|
|
143
|
+
check(pass, 'tk.fixpoint(…)');
|
|
144
|
+
return new Combinator(`fixpoint(${pass.name})`, target => {
|
|
145
|
+
for (let n = 0; ; n++) {
|
|
146
|
+
if (n === max)
|
|
147
|
+
throw new TkError(
|
|
148
|
+
`fixpoint(${pass.name}) still changes ${target instanceof Fn ? target.name : 'the module'} after ${max} rounds`,
|
|
149
|
+
);
|
|
150
|
+
const before = revisionOf(target);
|
|
151
|
+
pass.applyTo(target);
|
|
152
|
+
if (revisionOf(target) === before) return target;
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
/** apply a pass to the functions a predicate accepts */
|
|
158
|
+
export const when = (pred, pass) => {
|
|
159
|
+
check(pass, 'tk.when(…)');
|
|
160
|
+
return new Combinator(`when(${pass.name})`, target => {
|
|
161
|
+
for (const fn of fnsOf(target)) if (pred(fn)) pass.applyTo(fn);
|
|
162
|
+
return target;
|
|
163
|
+
});
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
/** run each alternative on a clone of the module and keep the one with the lowest cost */
|
|
167
|
+
export const choose = (alternatives, cost) => {
|
|
168
|
+
alternatives.forEach(p => check(p, 'tk.choose(…)'));
|
|
169
|
+
return new Combinator('choose', target => {
|
|
170
|
+
if (!(target instanceof Module))
|
|
171
|
+
throw new TypeError('tk.choose(…) works on a module: it clones it once per alternative');
|
|
172
|
+
const tried = alternatives.map((p, i) => {
|
|
173
|
+
const m = target.clone();
|
|
174
|
+
p.applyTo(m);
|
|
175
|
+
return { i, name: p.name, m, cost: cost(m) };
|
|
176
|
+
});
|
|
177
|
+
const best = tried.reduce((a, b) => (b.cost < a.cost ? b : a));
|
|
178
|
+
withBy('choose', () => target.adopt(best.m));
|
|
179
|
+
target.choices.push({ picked: best.name, costs: tried.map(t => ({ name: t.name, cost: t.cost })) });
|
|
180
|
+
return target;
|
|
181
|
+
});
|
|
182
|
+
};
|
package/src/rules.js
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
// rules.js — rewrite rules as values. A rule is a pattern over an IR's ops, an optional condition and a builder
|
|
2
|
+
// lambda; a rule set is an ordered list of rules that can be filtered and combined. Drivers (the greedy one here, an
|
|
3
|
+
// equality-saturation one later) take rule sets; the rules do not know how they are driven.
|
|
4
|
+
//
|
|
5
|
+
// Pattern syntax: op(p, …) matches an op and its arguments; a bare name binds any value (the same name twice must be
|
|
6
|
+
// the same value; _ matches anything); `const 0` matches an op whose single attribute is 0; `const c` binds it to c.
|
|
7
|
+
|
|
8
|
+
import { TkError, strict, didYouMean, describe } from './diag.js';
|
|
9
|
+
import { IR, Value, makeBuilder } from './ir.js';
|
|
10
|
+
import { withBy } from './context.js';
|
|
11
|
+
|
|
12
|
+
function tokenize(text) {
|
|
13
|
+
const out = [];
|
|
14
|
+
const re = /\s*(-?0x[0-9a-fA-F]+|-?\d+|[A-Za-z_][\w.]*|[(),])/y;
|
|
15
|
+
let m;
|
|
16
|
+
re.lastIndex = 0;
|
|
17
|
+
while (re.lastIndex < text.length) {
|
|
18
|
+
const at = re.lastIndex;
|
|
19
|
+
if (!(m = re.exec(text))) {
|
|
20
|
+
if (/^\s*$/.test(text.slice(at))) break;
|
|
21
|
+
throw new TkError(`pattern '${text}': cannot read '${text.slice(at).trim()}'`);
|
|
22
|
+
}
|
|
23
|
+
out.push(m[1]);
|
|
24
|
+
}
|
|
25
|
+
return out;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** parse a pattern against an IR: { op, args?, attr? } | { var } */
|
|
29
|
+
export function parsePattern(text, ir) {
|
|
30
|
+
const t = tokenize(text);
|
|
31
|
+
let i = 0;
|
|
32
|
+
const fail = msg => {
|
|
33
|
+
throw new TkError(`pattern '${text}': ${msg}`);
|
|
34
|
+
};
|
|
35
|
+
const isNum = s => /^-?(0x[0-9a-fA-F]+|\d+)$/.test(s);
|
|
36
|
+
const opOf = name => {
|
|
37
|
+
if (!ir.ops.has(name)) fail(`${ir.name} has no op '${name}'${didYouMean(name, ir.opNames)}`);
|
|
38
|
+
return ir.ops.get(name);
|
|
39
|
+
};
|
|
40
|
+
const one = () => {
|
|
41
|
+
const w = t[i++];
|
|
42
|
+
if (w === undefined) fail('it ends too early');
|
|
43
|
+
if (t[i] === '(') {
|
|
44
|
+
const op = opOf(w);
|
|
45
|
+
i++;
|
|
46
|
+
const args = [];
|
|
47
|
+
if (t[i] !== ')')
|
|
48
|
+
for (;;) {
|
|
49
|
+
args.push(one());
|
|
50
|
+
if (t[i] === ',') {
|
|
51
|
+
i++;
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
break;
|
|
55
|
+
}
|
|
56
|
+
if (t[i++] !== ')') fail(`expected ')' after the arguments of ${w}`);
|
|
57
|
+
if (op.args !== '*' && args.length !== op.args)
|
|
58
|
+
fail(`${w} takes ${op.args} args, the pattern gives ${args.length}`);
|
|
59
|
+
return { op: w, args };
|
|
60
|
+
}
|
|
61
|
+
const next = t[i];
|
|
62
|
+
if (next !== undefined && next !== ',' && next !== ')') {
|
|
63
|
+
// `name attr`: an op with one attribute, matched against a literal or bound to a name
|
|
64
|
+
const op = opOf(w);
|
|
65
|
+
if (op.attrNames.length !== 1)
|
|
66
|
+
fail(`${w} has ${op.attrNames.length} attrs; 'op x' patterns need exactly one`);
|
|
67
|
+
i++;
|
|
68
|
+
return {
|
|
69
|
+
op: w,
|
|
70
|
+
args: op.args === 0 ? [] : null,
|
|
71
|
+
attr: isNum(next) ? { lit: Number(next) } : { bind: next },
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
if (isNum(w)) fail(`a number (${w}) needs an op before it, as in 'const ${w}'`);
|
|
75
|
+
if (ir.ops.has(w)) return { op: w, args: null };
|
|
76
|
+
return { var: w };
|
|
77
|
+
};
|
|
78
|
+
const p = one();
|
|
79
|
+
if (i !== t.length) fail(`unexpected '${t[i]}'`);
|
|
80
|
+
return p;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function vars(p, out = new Set()) {
|
|
84
|
+
if (p.var && p.var !== '_') out.add(p.var);
|
|
85
|
+
if (p.attr && p.attr.bind) out.add(p.attr.bind);
|
|
86
|
+
for (const a of p.args ?? []) vars(a, out);
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** match a parsed pattern at a value; returns a Map of bindings, or null */
|
|
91
|
+
export function match(p, v, env = new Map()) {
|
|
92
|
+
if (p.var) {
|
|
93
|
+
if (p.var === '_') return env;
|
|
94
|
+
if (env.has(p.var)) return env.get(p.var) === v ? env : null;
|
|
95
|
+
env.set(p.var, v);
|
|
96
|
+
return env;
|
|
97
|
+
}
|
|
98
|
+
if (v.kind !== p.op) return null;
|
|
99
|
+
if (p.attr) {
|
|
100
|
+
const a = v.attrs[v.op.attrNames[0]];
|
|
101
|
+
if ('lit' in p.attr) {
|
|
102
|
+
if (a !== p.attr.lit) return null;
|
|
103
|
+
} else if (env.has(p.attr.bind)) {
|
|
104
|
+
if (env.get(p.attr.bind) !== a) return null;
|
|
105
|
+
} else env.set(p.attr.bind, a);
|
|
106
|
+
}
|
|
107
|
+
if (p.args) {
|
|
108
|
+
if (p.args.length !== v.args.length) return null;
|
|
109
|
+
for (let k = 0; k < p.args.length; k++) if (!match(p.args[k], v.args[k], env)) return null;
|
|
110
|
+
}
|
|
111
|
+
return env;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** the bindings a rule's lambdas see: a proxy that names the pattern's variables when a lambda asks for another */
|
|
115
|
+
function bindingsOf(rule, env) {
|
|
116
|
+
const o = Object.fromEntries(env);
|
|
117
|
+
return new Proxy(o, {
|
|
118
|
+
get(t, k) {
|
|
119
|
+
if (typeof k === 'symbol' || k in t) return t[k];
|
|
120
|
+
throw new TkError(
|
|
121
|
+
`rule ${rule.name}: no binding '${k}'${didYouMean(k, [...rule.vars])} (the pattern binds: ${[...rule.vars].join(', ') || 'nothing'})`,
|
|
122
|
+
);
|
|
123
|
+
},
|
|
124
|
+
has(t, k) {
|
|
125
|
+
return k in t;
|
|
126
|
+
},
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export class RuleSet {
|
|
131
|
+
constructor(name, ir, list = []) {
|
|
132
|
+
if (!(ir instanceof IR))
|
|
133
|
+
throw new TypeError(
|
|
134
|
+
`tk.rules('${name}', IR): the second argument is the IR the patterns use, got ${describe(ir)}`,
|
|
135
|
+
);
|
|
136
|
+
this.name = name;
|
|
137
|
+
this.ir = ir;
|
|
138
|
+
this.list = list;
|
|
139
|
+
this._cur = null;
|
|
140
|
+
return strict(this, t => `rule set ${t.name}`);
|
|
141
|
+
}
|
|
142
|
+
/** start a rule; .match(), .when() and .to() complete it */
|
|
143
|
+
rule(name) {
|
|
144
|
+
if (this.list.some(r => r.name === name))
|
|
145
|
+
throw new TypeError(`rule set ${this.name} already has a rule '${name}'`);
|
|
146
|
+
this._cur = { name, text: null, pattern: null, vars: new Set(), when: null, to: null };
|
|
147
|
+
this.list.push(this._cur);
|
|
148
|
+
return this;
|
|
149
|
+
}
|
|
150
|
+
match(text) {
|
|
151
|
+
const r = this._need('match');
|
|
152
|
+
r.text = text;
|
|
153
|
+
r.pattern = parsePattern(text, this.ir);
|
|
154
|
+
if (!r.pattern.op) throw new TkError(`rule ${r.name}: the pattern '${text}' must start with an op`);
|
|
155
|
+
r.vars = vars(r.pattern);
|
|
156
|
+
return this;
|
|
157
|
+
}
|
|
158
|
+
when(f) {
|
|
159
|
+
this._need('when').when = f;
|
|
160
|
+
return this;
|
|
161
|
+
}
|
|
162
|
+
to(f) {
|
|
163
|
+
const r = this._need('to');
|
|
164
|
+
if (typeof f !== 'function')
|
|
165
|
+
throw new TypeError(`rule ${r.name}: .to(…) takes (bindings, builder) => value, got ${describe(f)}`);
|
|
166
|
+
r.to = f;
|
|
167
|
+
return this;
|
|
168
|
+
}
|
|
169
|
+
/** a new set without some rules */
|
|
170
|
+
without(...names) {
|
|
171
|
+
for (const n of names)
|
|
172
|
+
if (!this.list.some(r => r.name === n))
|
|
173
|
+
throw new TypeError(
|
|
174
|
+
`rule set ${this.name} has no rule '${n}'${didYouMean(
|
|
175
|
+
n,
|
|
176
|
+
this.list.map(r => r.name),
|
|
177
|
+
)}`,
|
|
178
|
+
);
|
|
179
|
+
return new RuleSet(
|
|
180
|
+
`${this.name}-without`,
|
|
181
|
+
this.ir,
|
|
182
|
+
this.list.filter(r => !names.includes(r.name)),
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
/** a new set with the rules of other sets added */
|
|
186
|
+
with(...sets) {
|
|
187
|
+
return new RuleSet(`${this.name}+`, this.ir, [...this.list, ...sets.flatMap(s => s.list)]);
|
|
188
|
+
}
|
|
189
|
+
get names() {
|
|
190
|
+
return this.list.map(r => r.name);
|
|
191
|
+
}
|
|
192
|
+
_need(what) {
|
|
193
|
+
if (!this._cur) throw new TypeError(`rule set ${this.name}: .${what}(…) needs a .rule(name) first`);
|
|
194
|
+
return this._cur;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** try a rule at a value; returns the value to put in its place, or null */
|
|
199
|
+
export function fire(rule, v, by) {
|
|
200
|
+
if (!rule.pattern || !rule.to)
|
|
201
|
+
throw new TkError(`rule ${rule.name} is incomplete: it needs .match(…) and .to(…)`);
|
|
202
|
+
const env = match(rule.pattern, v);
|
|
203
|
+
if (!env) return null;
|
|
204
|
+
const b = bindingsOf(rule, env);
|
|
205
|
+
if (rule.when && !rule.when(b)) return null;
|
|
206
|
+
const out = withBy(by, () => rule.to(b, makeBuilder(v.ir, v.fn, v.block, { before: v, origin: [v], by })));
|
|
207
|
+
if (out === undefined || out === null || out === v) return null;
|
|
208
|
+
if (!(out instanceof Value))
|
|
209
|
+
throw new TypeError(`rule ${rule.name}: .to(…) returned ${describe(out)}, not a value`);
|
|
210
|
+
return out;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** apply rule sets greedily, at every value, until none fires (or `max` firings) */
|
|
214
|
+
export function rewriteGreedy(fn, sets, passName, max = 10_000) {
|
|
215
|
+
const rules = sets.flatMap(s => s.list);
|
|
216
|
+
let fired = 0;
|
|
217
|
+
for (let changed = true; changed; ) {
|
|
218
|
+
changed = false;
|
|
219
|
+
for (const v of fn.values()) {
|
|
220
|
+
if (v.erased) continue;
|
|
221
|
+
for (const r of rules) {
|
|
222
|
+
const by = `${passName}: ${r.name}`;
|
|
223
|
+
const out = fire(r, v, by);
|
|
224
|
+
if (!out) continue;
|
|
225
|
+
withBy(by, () => v.replaceWith(out));
|
|
226
|
+
changed = true;
|
|
227
|
+
if (++fired > max)
|
|
228
|
+
throw new TkError(
|
|
229
|
+
`${passName}: the rules fired ${max} times in ${fn.name} (the last was ${r.name}): they may not terminate`,
|
|
230
|
+
);
|
|
231
|
+
break;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
return fired;
|
|
236
|
+
}
|
package/src/stages.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// stages.js — a compilation as a graph of stages: each node computes its value from its dependencies' values, once,
|
|
2
|
+
// and again only when one of them changed. set() replaces a node's value (an input), invalidate() recomputes it.
|
|
3
|
+
|
|
4
|
+
import { TkError, strict, didYouMean, describe } from './diag.js';
|
|
5
|
+
|
|
6
|
+
export class StageGraph {
|
|
7
|
+
constructor(name) {
|
|
8
|
+
this.name = name;
|
|
9
|
+
this._nodes = new Map();
|
|
10
|
+
return strict(this, t => `stage graph ${t.name}`);
|
|
11
|
+
}
|
|
12
|
+
/** node(name, f) or node(name, [deps], (…depValues) => value) */
|
|
13
|
+
node(name, deps, f) {
|
|
14
|
+
if (typeof deps === 'function') [f, deps] = [deps, []];
|
|
15
|
+
if (typeof f !== 'function')
|
|
16
|
+
throw new TypeError(`node('${name}', …) needs a function, got ${describe(f)}`);
|
|
17
|
+
for (const d of deps) this._get(d, name);
|
|
18
|
+
this._nodes.set(name, { name, deps, f, value: undefined, version: 0, seen: null, fixed: false, runs: 0 });
|
|
19
|
+
return this;
|
|
20
|
+
}
|
|
21
|
+
get(name) {
|
|
22
|
+
const n = this._get(name);
|
|
23
|
+
this._ensure(n, []);
|
|
24
|
+
return n.value;
|
|
25
|
+
}
|
|
26
|
+
/** use this value for a node; the nodes after it recompute when read */
|
|
27
|
+
set(name, value) {
|
|
28
|
+
const n = this._get(name);
|
|
29
|
+
n.value = value;
|
|
30
|
+
n.version++;
|
|
31
|
+
n.fixed = true;
|
|
32
|
+
return this;
|
|
33
|
+
}
|
|
34
|
+
/** forget a node's value (and any set()): it recomputes when read */
|
|
35
|
+
invalidate(name) {
|
|
36
|
+
const n = this._get(name);
|
|
37
|
+
n.seen = null;
|
|
38
|
+
n.fixed = false;
|
|
39
|
+
return this;
|
|
40
|
+
}
|
|
41
|
+
/** how many times a node has been computed */
|
|
42
|
+
runs(name) {
|
|
43
|
+
return this._get(name).runs;
|
|
44
|
+
}
|
|
45
|
+
get names() {
|
|
46
|
+
return [...this._nodes.keys()];
|
|
47
|
+
}
|
|
48
|
+
_get(name, from) {
|
|
49
|
+
const n = this._nodes.get(name);
|
|
50
|
+
if (!n)
|
|
51
|
+
throw new TypeError(
|
|
52
|
+
`stage graph ${this.name} has no node '${name}'${didYouMean(name, [...this._nodes.keys()])}${from ? ` (a dependency of ${from})` : ''}`,
|
|
53
|
+
);
|
|
54
|
+
return n;
|
|
55
|
+
}
|
|
56
|
+
_ensure(n, path) {
|
|
57
|
+
if (path.includes(n.name))
|
|
58
|
+
throw new TkError(`stage graph ${this.name}: a cycle ${[...path, n.name].join(' -> ')}`);
|
|
59
|
+
for (const d of n.deps) this._ensure(this._nodes.get(d), [...path, n.name]);
|
|
60
|
+
if (n.fixed) return;
|
|
61
|
+
const now = n.deps.map(d => this._nodes.get(d).version);
|
|
62
|
+
if (n.seen && now.every((v, i) => v === n.seen[i])) return;
|
|
63
|
+
n.value = n.f(...n.deps.map(d => this._nodes.get(d).value));
|
|
64
|
+
n.version++;
|
|
65
|
+
n.runs++;
|
|
66
|
+
n.seen = now;
|
|
67
|
+
}
|
|
68
|
+
}
|
package/src/std/asm.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// std/asm.js — assembly text from a machine IR's templates ({d} the value's register, {0} {1} its arguments', {t0}
|
|
2
|
+
// {t1} its branch targets, {name} an attribute). Every line keeps the value it came from, so a line can be traced.
|
|
3
|
+
|
|
4
|
+
import { TkError } from '../diag.js';
|
|
5
|
+
import { traceOf, trace } from '../ir.js';
|
|
6
|
+
|
|
7
|
+
function fill(t, v) {
|
|
8
|
+
return t.replace(/\{(\w+)\}/g, (_, k) => {
|
|
9
|
+
if (k === 'd') return v.reg;
|
|
10
|
+
if (/^\d+$/.test(k)) return v.arg(Number(k)).reg;
|
|
11
|
+
if (/^t\d+$/.test(k)) return `.${v.targets[Number(k.slice(1))].name}`;
|
|
12
|
+
if (k in v.attrs) return String(v.attrs[k]);
|
|
13
|
+
throw new TkError(
|
|
14
|
+
`asm template '${t}' of ${v.kind}: no {${k}} (it has {d}, {0}…, {t0}…, and the attrs ${Object.keys(v.attrs).join(', ') || 'none'})`,
|
|
15
|
+
);
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function asm(mod) {
|
|
20
|
+
if (!mod.ir.machine)
|
|
21
|
+
throw new TypeError(`asm(…) needs a machine IR (.use(tk.frag.machine)); ${mod.ir.name} is not one`);
|
|
22
|
+
const lines = [];
|
|
23
|
+
for (const f of mod.fns) {
|
|
24
|
+
lines.push({ text: `${f.name}:`, value: null });
|
|
25
|
+
for (const b of f.blocks) {
|
|
26
|
+
lines.push({ text: `.${b.name}:`, value: null });
|
|
27
|
+
for (const v of b.values()) {
|
|
28
|
+
if (v.kind === 'phi') {
|
|
29
|
+
lines.push({
|
|
30
|
+
text: ` # ${v.reg} = phi ${v.args.map((a, i) => `${v.incomingBlocks[i].name}: ${a.reg}`).join(', ')}`,
|
|
31
|
+
value: v,
|
|
32
|
+
});
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
const tpl = v.spec.asm ?? v.ir.machine.asm[v.kind];
|
|
36
|
+
if (tpl === undefined)
|
|
37
|
+
throw new TkError(`${v.ir.name} op '${v.kind}' has no asm template: give it { asm: '…' }`);
|
|
38
|
+
for (const t of [].concat(tpl)) lines.push({ text: ` ${fill(t, v)}`, value: v });
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const text = lines.map(l => l.text).join('\n');
|
|
43
|
+
return {
|
|
44
|
+
lines,
|
|
45
|
+
/** line n (1-based) with its value; .trace() follows it back to the source */
|
|
46
|
+
line(n) {
|
|
47
|
+
const l = lines[n - 1];
|
|
48
|
+
if (!l) throw new RangeError(`asm has ${lines.length} lines: line(${n}) does not exist`);
|
|
49
|
+
return {
|
|
50
|
+
...l,
|
|
51
|
+
trace: () =>
|
|
52
|
+
traceOf([
|
|
53
|
+
{ ir: 'asm', text: `${String(n).padStart(3)} ${l.text.trim()}`, how: '' },
|
|
54
|
+
...(l.value ? trace(l.value).rows : []),
|
|
55
|
+
]),
|
|
56
|
+
};
|
|
57
|
+
},
|
|
58
|
+
find: re => lines.findIndex(l => re.test(l.text)) + 1,
|
|
59
|
+
toString: () => text,
|
|
60
|
+
print() {
|
|
61
|
+
console.log(text);
|
|
62
|
+
return this;
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
}
|