-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathchapter01.js
More file actions
258 lines (205 loc) · 5.4 KB
/
chapter01.js
File metadata and controls
258 lines (205 loc) · 5.4 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
import assert from 'node:assert';
import {basename} from 'node:path';
import process from 'node:process';
import {default as nodeTest} from 'node:test';
import {fileURLToPath} from 'node:url';
function makeTestFn(url) {
const filename = fileURLToPath(url);
// Return a function with the same interface as Node's `test` function.
return (name, ...args) => {
// Only register the test if the current module is on the command line.
// All other tests are ignored.
if (process.argv[1] === filename) {
// Add the chapter name to the test description.
const chapterName = basename(filename, '.js');
nodeTest(`[${chapterName}] ${name}`, ...args);
}
};
}
const test = makeTestFn(import.meta.url);
test('setup', () => {
assert(true);
});
function compileVoidLang(code) {
if (code !== '') {
throw new Error(`Expected empty code, got: "${code}"`);
}
const bytes = [magic(), version()].flat(Infinity);
return Uint8Array.from(bytes);
}
test('compileVoidLang result compiles to a WebAssembly object', async () => {
const {instance, module} = await WebAssembly.instantiate(compileVoidLang(''));
assert.strictEqual(instance instanceof WebAssembly.Instance, true);
assert.strictEqual(module instanceof WebAssembly.Module, true);
});
function stringToBytes(s) {
const bytes = new TextEncoder().encode(s);
return Array.from(bytes);
}
function magic() {
// [0x00, 0x61, 0x73, 0x6d]
return stringToBytes('\0asm');
}
function version() {
return [0x01, 0x00, 0x00, 0x00];
}
// for simplicity we include the complete implementation of u32 and i32 here
// this allows the next chapters to use all the functionality from this chapter
// without having to redefine or patch the complete definitions
const CONTINUATION_BIT = 0b10000000;
const SEVEN_BIT_MASK_BIG_INT = 0b01111111n;
function leb128(v) {
let val = BigInt(v);
let more = true;
const r = [];
while (more) {
const b = Number(val & SEVEN_BIT_MASK_BIG_INT);
val = val >> 7n;
more = val !== 0n;
if (more) {
r.push(b | CONTINUATION_BIT);
} else {
r.push(b);
}
}
return r;
}
const MIN_U32 = 0;
const MAX_U32 = 2 ** 32 - 1;
function u32(v) {
if (v < MIN_U32 || v > MAX_U32) {
throw Error(`Value out of range for u32: ${v}`);
}
return leb128(v);
}
function sleb128(v) {
let val = BigInt(v);
let more = true;
const r = [];
while (more) {
const b = Number(val & SEVEN_BIT_MASK_BIG_INT);
const signBitSet = !!(b & 0x40);
val = val >> 7n;
if ((val === 0n && !signBitSet) || (val === -1n && signBitSet)) {
more = false;
r.push(b);
} else {
r.push(b | CONTINUATION_BIT);
}
}
return r;
}
const MIN_I32 = -(2 ** 32 / 2);
const MAX_I32 = 2 ** 32 / 2 - 1;
const I32_NEG_OFFSET = 2 ** 32;
function i32(v) {
if (v < MIN_I32 || v > MAX_U32) {
throw Error(`Value out of range for i32: ${v}`);
}
if (v > MAX_I32) {
return sleb128(v - I32_NEG_OFFSET);
}
return sleb128(v);
}
function section(id, contents) {
const sizeInBytes = contents.flat(Infinity).length;
return [id, u32(sizeInBytes), contents];
}
function vec(elements) {
return [u32(elements.length), elements];
}
const SECTION_ID_TYPE = 1;
function functype(paramTypes, resultTypes) {
return [0x60, vec(paramTypes), vec(resultTypes)];
}
function typesec(functypes) {
return section(SECTION_ID_TYPE, vec(functypes));
}
const SECTION_ID_FUNCTION = 3;
const typeidx = (x) => u32(x);
function funcsec(typeidxs) {
return section(SECTION_ID_FUNCTION, vec(typeidxs));
}
const SECTION_ID_CODE = 10;
function code(func) {
const sizeInBytes = func.flat(Infinity).length;
return [u32(sizeInBytes), func];
}
function func(locals, body) {
return [vec(locals), body];
}
function codesec(codes) {
return section(SECTION_ID_CODE, vec(codes));
}
const instr = {
end: 0x0b,
};
function compileNopLang(source) {
if (source !== '') {
throw new Error(`Expected empty code, got: "${source}"`);
}
const mod = module([
typesec([functype([], [])]),
funcsec([typeidx(0)]),
exportsec([export_('main', exportdesc.func(0))]),
codesec([code(func([], [instr.end]))]),
]);
return Uint8Array.from(mod.flat(Infinity));
}
test('compileNopLang compiles to a wasm module', async () => {
const {instance, module} = await WebAssembly.instantiate(compileNopLang(''));
assert.strictEqual(instance instanceof WebAssembly.Instance, true);
assert.strictEqual(module instanceof WebAssembly.Module, true);
});
const SECTION_ID_EXPORT = 7;
function name(s) {
return vec(stringToBytes(s));
}
function export_(nm, exportdesc) {
return [name(nm), exportdesc];
}
function exportsec(exports) {
return section(SECTION_ID_EXPORT, vec(exports));
}
const funcidx = (x) => u32(x);
const exportdesc = {
func(idx) {
return [0x00, funcidx(idx)];
},
};
function module(sections) {
return [magic(), version(), sections];
}
test('compileNopLang result compiles to a wasm module', async () => {
const {instance} = await WebAssembly.instantiate(compileNopLang(''));
assert.strictEqual(instance.exports.main(), undefined);
assert.throws(() => compileNopLang('42'));
});
export {
code,
codesec,
export_,
exportdesc,
exportsec,
func,
funcidx,
funcsec,
functype,
i32,
instr,
magic,
makeTestFn,
module,
name,
section,
SECTION_ID_CODE,
SECTION_ID_EXPORT,
SECTION_ID_FUNCTION,
SECTION_ID_TYPE,
stringToBytes,
typeidx,
typesec,
u32,
vec,
version,
};