-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathchapter05.js
More file actions
344 lines (311 loc) · 9.1 KB
/
chapter05.js
File metadata and controls
344 lines (311 loc) · 9.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
import assert from 'node:assert';
import * as ohm from 'ohm-js';
import {
// buildSymbolTable,
code,
codesec,
export_,
exportdesc,
exportsec,
func,
funcidx,
funcsec,
functype,
i32,
instr,
loadMod,
localidx,
locals,
makeTestFn,
module,
resolveSymbol,
testExtractedExamples,
typeidx,
typesec,
valtype,
} from './chapter04.js';
const test = makeTestFn(import.meta.url);
function buildModule(functionDecls) {
const types = functionDecls.map((f) =>
functype(f.paramTypes, [f.resultType]),
);
const funcs = functionDecls.map((f, i) => typeidx(i));
const codes = functionDecls.map((f) => code(func(f.locals, f.body)));
const exports = functionDecls.map((f, i) =>
export_(f.name, exportdesc.func(i)),
);
const mod = module([
typesec(types),
funcsec(funcs),
exportsec(exports),
codesec(codes),
]);
return Uint8Array.from(mod.flat(Infinity));
}
test('buildModule', () => {
const functionDecls = [
{
name: 'main',
paramTypes: [],
resultType: valtype.i32,
locals: [locals(1, valtype.i32)],
body: [instr.i32.const, i32(42), instr.call, funcidx(1), instr.end],
},
{
name: 'backup',
paramTypes: [valtype.i32],
resultType: valtype.i32,
locals: [],
body: [instr.i32.const, i32(43), instr.end],
},
];
const exports = loadMod(buildModule(functionDecls));
assert.strictEqual(exports.main(), 43);
assert.strictEqual(exports.backup(), 43);
});
instr.call = 0x10;
const grammarDef = `
Wafer {
Module = FunctionDecl*
Statement = LetStatement
| ExprStatement
//+ "let x = 3 + 4;", "let distance = 100 + 2;"
//- "let y;"
LetStatement = "let" identifier "=" Expr ";"
//+ "func zero() { 0 }", "func add(x, y) { x + y }"
//- "func x", "func x();"
FunctionDecl = "func" identifier "(" Params? ")" BlockExpr
Params = identifier ("," identifier)*
//+ "{ 42 }", "{ 66 + 99 }", "{ 1 + 2 - 3 }"
//+ "{ let x = 3; 42 }"
//- "{ 3abc }"
BlockExpr = "{" Statement* Expr "}"
ExprStatement = Expr ";"
Expr = AssignmentExpr -- assignment
| PrimaryExpr (op PrimaryExpr)* -- arithmetic
//+ "x := 3", "y := 2 + 1"
AssignmentExpr = identifier ":=" Expr
PrimaryExpr = "(" Expr ")" -- paren
| number
| CallExpr
| identifier -- var
CallExpr = identifier "(" Args? ")"
Args = Expr ("," Expr)*
op = "+" | "-" | "*" | "/"
number = digit+
//+ "x", "élan", "_", "_99"
//- "1", "$nope"
identifier = identStart identPart*
identStart = letter | "_"
identPart = identStart | digit
// Examples:
//+ "func addOne(x) { x + one }", "func one() { 1 } func two() { 2 }"
//- "42", "let x", "func x {}"
}
`;
test('extracted examples', () => testExtractedExamples(grammarDef));
const wafer = ohm.grammar(grammarDef);
function defineToWasm(semantics, symbols) {
const scopes = [symbols];
semantics.addOperation('toWasm', {
FunctionDecl(_func, ident, _lparen, optParams, _rparen, blockExpr) {
scopes.push(symbols.get(ident.sourceString));
const result = [blockExpr.toWasm(), instr.end];
scopes.pop();
return result;
},
BlockExpr(_lbrace, iterStatement, expr, _rbrace) {
return [...iterStatement.children, expr].map((c) => c.toWasm());
},
LetStatement(_let, ident, _eq, expr, _) {
const info = resolveSymbol(ident, scopes.at(-1));
return [expr.toWasm(), instr.local.set, localidx(info.idx)];
},
ExprStatement(expr, _) {
return [expr.toWasm(), instr.drop];
},
Expr_arithmetic(num, iterOps, iterOperands) {
const result = [num.toWasm()];
for (let i = 0; i < iterOps.numChildren; i++) {
const op = iterOps.child(i);
const operand = iterOperands.child(i);
result.push(operand.toWasm(), op.toWasm());
}
return result;
},
AssignmentExpr(ident, _, expr) {
const info = resolveSymbol(ident, scopes.at(-1));
return [expr.toWasm(), instr.local.tee, localidx(info.idx)];
},
PrimaryExpr_paren(_lparen, expr, _rparen) {
return expr.toWasm();
},
CallExpr(ident, _lparen, optArgs, _rparen) {
const name = ident.sourceString;
const funcNames = Array.from(scopes[0].keys());
const idx = funcNames.indexOf(name);
return [
optArgs.children.map((c) => c.toWasm()),
[instr.call, funcidx(idx)],
];
},
Args(exp, _, iterExp) {
return [exp, ...iterExp.children].map((c) => c.toWasm());
},
PrimaryExpr_var(ident) {
const info = resolveSymbol(ident, scopes.at(-1));
return [instr.local.get, localidx(info.idx)];
},
op(char) {
const op = char.sourceString;
const instructionByOp = {
'+': instr.i32.add,
'-': instr.i32.sub,
'*': instr.i32.mul,
'/': instr.i32.div_s,
};
if (!Object.hasOwn(instructionByOp, op)) {
throw new Error(`Unhandled operator '${op}'`);
}
return instructionByOp[op];
},
number(_digits) {
const num = parseInt(this.sourceString, 10);
return [instr.i32.const, ...i32(num)];
},
});
}
test('toWasm bytecodes - locals & assignment', () => {
assert.deepEqual(
toWasmFlat('func main() { 42 }'),
[[instr.i32.const, 42], instr.end].flat(),
);
assert.deepEqual(
toWasmFlat('func main() { let x = 0; 42 }'),
[
[instr.i32.const, 0],
[instr.local.set, 0],
[instr.i32.const, 42],
instr.end,
].flat(),
);
assert.deepEqual(
toWasmFlat('func main() { let x = 0; x }'),
[
[instr.i32.const, 0],
[instr.local.set, 0],
[instr.local.get, 0],
instr.end,
].flat(),
);
assert.deepEqual(
toWasmFlat('func f1(a) { let x = 12; x }'),
[
[instr.i32.const, 12],
[instr.local.set, 1], // set `x`
[instr.local.get, 1], // get `x`
instr.end,
].flat(),
);
assert.deepEqual(
toWasmFlat('func f2(a, b) { let x = 12; b }'),
[
[instr.i32.const, 12],
[instr.local.set, 2], // set `x`
[instr.local.get, 1], // get `b`
instr.end,
].flat(),
);
});
function toWasmFlat(input) {
const matchResult = wafer.match(input, 'FunctionDecl');
const symbols = buildSymbolTable(wafer, matchResult);
const semantics = wafer.createSemantics();
defineToWasm(semantics, symbols);
return semantics(matchResult).toWasm().flat(Infinity);
}
function buildSymbolTable(grammar, matchResult) {
const tempSemantics = grammar.createSemantics();
const scopes = [new Map()];
tempSemantics.addOperation('buildSymbolTable', {
_default(...children) {
return children.forEach((c) => c.buildSymbolTable());
},
FunctionDecl(_func, ident, _lparen, optParams, _rparen, blockExpr) {
const name = ident.sourceString;
const locals = new Map();
scopes.at(-1).set(name, locals);
scopes.push(locals);
optParams.child(0)?.buildSymbolTable();
blockExpr.buildSymbolTable();
scopes.pop();
},
Params(ident, _, iterIdent) {
for (const id of [ident, ...iterIdent.children]) {
const name = id.sourceString;
const idx = scopes.at(-1).size;
const info = {name, idx, what: 'param'};
scopes.at(-1).set(name, info);
}
},
LetStatement(_let, id, _eq, _expr, _) {
const name = id.sourceString;
const idx = scopes.at(-1).size;
const info = {name, idx, what: 'local'};
scopes.at(-1).set(name, info);
},
});
tempSemantics(matchResult).buildSymbolTable();
return scopes[0];
}
function compile(source) {
const matchResult = wafer.match(source);
if (!matchResult.succeeded()) {
throw new Error(matchResult.message);
}
const symbols = buildSymbolTable(wafer, matchResult);
const semantics = wafer.createSemantics();
defineToWasm(semantics, symbols);
defineFunctionDecls(semantics, symbols);
const functionDecls = semantics(matchResult).functionDecls();
return buildModule(functionDecls);
}
function defineFunctionDecls(semantics, symbols) {
semantics.addOperation('functionDecls', {
_default(...children) {
return children.flatMap((c) => c.functionDecls());
},
FunctionDecl(_func, ident, _l, _params, _r, _blockExpr) {
const name = ident.sourceString;
const localVars = Array.from(symbols.get(name).values());
const params = localVars.filter((info) => info.what === 'param');
const paramTypes = params.map((_) => valtype.i32);
const varsCount = localVars.filter(
(info) => info.what === 'local',
).length;
return [
{
name,
paramTypes,
resultType: valtype.i32,
locals: [locals(varsCount, valtype.i32)],
body: this.toWasm(),
},
];
},
});
}
test('module with multiple functions', () => {
assert.deepEqual(
loadMod(compile('func main() { let x = 42; x }')).main(),
42,
);
assert.deepEqual(
loadMod(
compile('func doIt() { add(1, 2) } func add(x, y) { x + y }'),
).doIt(),
3,
);
});
export * from './chapter04.js';
export {buildModule, buildSymbolTable, defineFunctionDecls, defineToWasm};