-
-
Notifications
You must be signed in to change notification settings - Fork 667
/
Copy pathcompiler.js
656 lines (605 loc) · 21.2 KB
/
compiler.js
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
import fs from "fs";
import path from "path";
import os from "os";
import v8 from "v8";
import cluster from "cluster";
import { createRequire } from "module";
import { fileURLToPath, pathToFileURL } from "url";
import { globSync } from "glob";
import { stderrColors, stdoutColors } from "../util/terminal.js";
import * as optionsUtil from "../util/options.js";
import { coreCount, threadCount } from "../util/cpu.js";
import { diff } from "../util/text.js";
import { Rtrace } from "../lib/rtrace/index.js";
import asc from "../dist/asc.js";
const dirname = path.dirname(fileURLToPath(import.meta.url));
const require = createRequire(import.meta.url);
const startTime = Date.now();
const config = {
"create": {
"description": [
"Recreates the fixture for the specified test(s)",
"or all the fixtures if no specific test is given."
],
"type": "b"
},
"createBinary": {
"description": [
"Also creates the respective .wasm binaries."
],
"type": "b"
},
"noDiff": {
"description": [
"Disables output of detailed fixture differences."
],
"type": "b"
},
"noColors": {
"description": [
"Disables terminal colors."
],
"type": "b"
},
"rtraceVerbose": {
"description": [
"Enables verbose rtrace output."
]
},
"parallel": {
"description": [
"Runs tests in parallel."
]
},
"help": {
"description": "Prints this message and exits.",
"type": "b",
"alias": "h"
}
};
const opts = optionsUtil.parse(process.argv.slice(2), config);
const args = opts.options;
const argv = opts.arguments;
stdoutColors.enabled = process.stdout.isTTY && !args.noColors;
stderrColors.enabled = process.stderr.isTTY && !args.noColors;
if (args.help) {
console.log([
stdoutColors.white("SYNTAX"),
" " + stdoutColors.cyan("npm run test:compiler --") + " [test1, test2 ...] [options]",
"",
stdoutColors.white("OPTIONS"),
optionsUtil.help(config)
].join(os.EOL) + os.EOL);
process.exit(0);
}
const features = process.env.ASC_FEATURES ? process.env.ASC_FEATURES.split(",") : [];
const featuresConfig = require("./features.json");
const basedir = path.join(dirname, "compiler");
process.chdir(basedir);
// Gets a list of all relevant tests
function getTests() {
let tests = globSync("**/!(_*).ts", { posix: true })
.map(name => name.replace(/\.ts$/, ""))
.filter(name => !name.endsWith(".d") && !name.includes("node_modules"));
if (argv.length) { // run matching tests only
tests = tests.filter(filename => argv.indexOf(filename.replace(/\.ts$/, "")) >= 0);
if (!tests.length) {
console.log(stdoutColors.red("FAILURE: ") + stdoutColors.white("No matching tests: " + argv.join(" ") + "\n"));
process.exit(1);
}
}
return tests;
}
function measureStart() {
return process.hrtime();
}
function measureEnd(start) {
const hrtime = process.hrtime(start);
return `${(hrtime[0] * 1e3 + hrtime[1] / 1e6).toFixed(3)} ms`;
}
// Starts a new section within a test
function section(title) {
const start = measureStart();
console.log("- " + title);
return {
title,
end(code) {
const time = measureEnd(start);
switch (code) {
case SUCCESS: console.log(" " + stdoutColors.green("SUCCESS") + " (" + time + ")\n"); break;
default: console.log(" " + stdoutColors.red("FAILURE") + " (" + time + ")\n"); break;
case SKIPPED: console.log(" " + stdoutColors.yellow("SKIPPED") + " (" + time + ")\n"); break;
}
}
};
}
const SUCCESS = 0;
const FAILURE = 1;
const SKIPPED = 2;
// Runs a single test
async function runTest(basename) {
console.log(stdoutColors.white("# compiler/" + basename) + "\n");
const configPath = path.join(basedir, basename + ".json");
const config = fs.existsSync(configPath) ? require(configPath) : {};
const stdout = asc.createMemoryStream();
const stderr = asc.createMemoryStream(chunk => process.stderr.write(chunk.toString().replace(/^(?!$)/mg, " ")));
stderr.isTTY = true;
const dummy = new Map();
const writeFile = Map.prototype.set.bind(dummy);
let asc_flags = [];
let asc_rtrace = !!config.asc_rtrace;
let v8_flags = "";
let v8_no_flags = "";
let missing_features = [];
// Makes sure to reset the environment after
function prepareResult(code, message = null) {
if (v8_no_flags) v8.setFlagsFromString(v8_no_flags);
// Delete the .wasm files in case the subsequent run doesn't specify the
// --createBinary flag, thereby preventing confusion. Also, the .debug.wasm
// file is used by the bindings/esm test.
if (!args.createBinary) {
fs.unlink(basename + ".debug.wasm", err => { /* nop */ });
fs.unlink(basename + ".release.wasm", err => { /* nop */ });
}
return { code, message };
}
function afterCompile(mode) {
// The ESM bindings test requires the .wasm file to be present. The file is
// promptly deleted after the test has completed, unless --createBinary is
// specified.
{
const filename = `${basename}.${mode}.wasm`;
fs.writeFileSync(filename, dummy.get(filename));
}
const compareFixture = section("compare fixture");
const fixtureExtensions = ["wat", "js", "d.ts"];
if (args.create) {
for (const extension of fixtureExtensions) {
const filename = `${basename}.${mode}.${extension}`;
if (!dummy.has(filename)) {
fs.unlink(filename, err => { /* nop */ });
continue;
}
fs.writeFileSync(filename, dummy.get(filename));
console.log(" " + stdoutColors.yellow(`Created fixture ${filename}`));
}
compareFixture.end(SKIPPED);
return;
}
// Displaying the diffs in console for release fixtures isn't usually
// meaningful, so release fixtures are compared as if --noDiff was passed.
if (args.noDiff || mode === "release") {
for (const extension of fixtureExtensions) {
const filename = `${basename}.${mode}.${extension}`;
const actual = (
dummy.has(filename) &&
dummy.get(filename).replace(/\r\n/g, "\n")
);
const expected = (
fs.existsSync(filename) &&
fs.readFileSync(filename, { encoding: "utf8" }).replace(/\r\n/g, "\n")
);
// If a fixture/generated file is missing, false will be compared to a
// string. If both are missing, nothing happens below (as it should).
if (actual !== expected) {
if (filename == "std/math.release.wat" && os.version().startsWith("Darwin Kernel") && os.arch() == "arm64") {
// FIXME: in arm64 macos, binaryen will optimize math.ts with different output.
compareFixture.end(SKIPPED);
return;
}
compareFixture.end(FAILURE);
return prepareResult(FAILURE, "fixture mismatch");
}
}
compareFixture.end(SUCCESS);
return;
}
let failed = false;
for (const extension of fixtureExtensions) {
const filename = `${basename}.${mode}.${extension}`;
const actualExists = dummy.has(filename);
const expectedExists = fs.existsSync(filename);
if (!actualExists && !expectedExists) {
// Neither exists, which is perfectly fine. Carry on.
continue;
} else if (actualExists != expectedExists) {
const message = actualExists
? `Fixture ${filename} is missing!`
: `File ${filename} was not generated!`;
console.log(" " + stdoutColors.yellow(message));
failed = true;
continue;
}
const actual = dummy.has(filename) && dummy.get(filename).replace(/\r\n/g, "\n");
const expected = (
fs.existsSync(filename) &&
fs.readFileSync(filename, { encoding: "utf8" }).replace(/\r\n/g, "\n")
);
const diffResult = diff(filename, expected, actual);
if (diffResult !== null) {
console.log(diffResult);
failed = true;
}
}
if (failed) {
compareFixture.end(FAILURE);
return prepareResult(FAILURE, "fixture mismatch");
}
compareFixture.end(SUCCESS);
}
if (config.features) {
config.features.forEach(feature => {
if (!features.includes(feature) && !features.includes("*")) {
missing_features.push(feature);
}
let featureConfig = featuresConfig[feature];
if (featureConfig.asc_flags) {
featureConfig.asc_flags.forEach(flag => {
Array.prototype.push.apply(asc_flags, flag.split(" "));
});
}
if (featureConfig.v8_flags) {
featureConfig.v8_flags.forEach(flag => {
if (v8_flags) v8_flags += " ";
v8_flags += flag;
if (v8_no_flags) v8_no_flags += " ";
v8_no_flags += "--no-" + flag.substring(2);
});
}
});
}
if (config.asc_flags) {
config.asc_flags.forEach(flag => { asc_flags.push(...flag.split(" ")); });
}
// Build debug
{
const cmd = [
basename + ".ts",
"--debug",
"--outFile", basename + ".debug.wasm",
"--textFile", basename + ".debug.wat"
];
if (asc_flags) cmd.push(...asc_flags);
if (args.noColors) cmd.push("--noColors");
const compileDebug = section("compile debug");
const { error } = await asc.main(cmd, { stdout, stderr, writeFile });
let expectStderr = config.stderr;
if (error) {
stderr.write("---\n");
stderr.write(error.stack);
stderr.write("\n---\n");
if (expectStderr) {
compileDebug.end(SKIPPED);
} else {
compileDebug.end(FAILURE);
}
} else {
compileDebug.end(SUCCESS);
}
// check expected stderr patterns in order
if (expectStderr) {
const compareStderr = section("compare stderr");
const stderrString = stderr.toString();
if (typeof expectStderr === "string") expectStderr = [ expectStderr ];
let lastIndex = 0;
let failed = false;
expectStderr.forEach((substr, i) => {
let index = stderrString.indexOf(substr, lastIndex);
if (index < 0) {
console.log(" missing pattern #" + (i + 1) + " '" + substr + "' in stderr at " + lastIndex + "+.");
failed = true;
} else {
lastIndex = index + substr.length;
}
});
if (failed) {
compareStderr.end(FAILURE);
return prepareResult(FAILURE, "stderr mismatch");
}
compareStderr.end(SUCCESS);
return prepareResult(SUCCESS);
} else if (error) {
// Don't bother comparing fixtures or doing anything else if the
// compilation failed.
return prepareResult(FAILURE, "compile failed");
}
const afterCompileResult = afterCompile("debug");
if (afterCompileResult) return afterCompileResult;
}
stdout.length = 0;
stderr.length = 0;
const gluePath = basename + ".js";
const glue = fs.existsSync(gluePath) ? await import(pathToFileURL(gluePath)) : {};
// Build release
{
const cmd = [
basename + ".ts",
"--outFile", basename + ".release.wasm",
"--textFile", basename + ".release.wat",
"-O"
];
if (asc_flags) cmd.push(...asc_flags);
if (args.noColors) cmd.push("--noColors");
const compileRelease = section("compile release");
const { error } = await asc.main(cmd, { stdout, stderr, writeFile });
if (error) {
stderr.write("---\n");
stderr.write(error.stack);
stderr.write("\n---\n");
compileRelease.end(FAILURE);
return prepareResult(FAILURE, error.message);
}
compileRelease.end(SUCCESS);
const afterCompileResult = afterCompile("release");
if (afterCompileResult) return afterCompileResult;
if (missing_features.length) {
console.log("- " + stdoutColors.yellow("instantiate SKIPPED") + ": " + missing_features.join(", ") + " not enabled\n");
return prepareResult(SKIPPED, "feature not enabled: " + missing_features.join(", "));
} else if (v8_flags) {
v8.setFlagsFromString(v8_flags);
}
const debugBuffer = dummy.get(basename + ".debug.wasm");
const releaseBuffer = dummy.get(basename + ".release.wasm");
const instantiateDebug = section("instantiate debug");
if (config.skipInstantiate) {
instantiateDebug.end(SKIPPED);
} else {
if (!await testInstantiate(debugBuffer, glue, stderr)) {
instantiateDebug.end(FAILURE);
return prepareResult(FAILURE, "instantiate error (debug)");
}
instantiateDebug.end(SUCCESS);
const instantiateRelease = section("instantiate release");
if (!await testInstantiate(releaseBuffer, glue, stderr)) {
instantiateRelease.end(FAILURE);
return prepareResult(FAILURE, "instantiate error (release)");
}
instantiateRelease.end(SUCCESS);
}
}
stdout.length = 0;
stderr.length = 0;
// Build rtraced
if (asc_rtrace) {
const cmd = [
basename + ".ts",
"--outFile", // -> stdout
"--debug",
"--use", "ASC_RTRACE=1",
"--exportStart", "_initialize",
// "--runPasses", "instrument-memory"
];
if (asc_flags) cmd.push(...asc_flags);
const compileRtraced = section("compile rtraced");
const { error } = await asc.main(cmd, { stdout, stderr });
if (error) {
stderr.write("---\n");
stderr.write(error.stack);
stderr.write("\n---\n");
compileRtraced.end(FAILURE);
return prepareResult(FAILURE, error.message);
}
compileRtraced.end(SUCCESS);
const rtracedBuffer = stdout.toBuffer();
const instantiateRtrace = section("instantiate rtrace");
if (!await testInstantiate(rtracedBuffer, glue, stderr)) {
instantiateRtrace.end(FAILURE);
return prepareResult(FAILURE, "rtrace error");
}
instantiateRtrace.end(SUCCESS);
}
return prepareResult(SUCCESS);
}
// Tests if instantiation of a module succeeds
async function testInstantiate(binaryBuffer, glue, stderr) {
let failed = false;
try {
const memory = new WebAssembly.Memory({ initial: 10 });
const exports = {};
function getString(ptr) {
const RUNTIME_HEADER_SIZE = 16;
if (!ptr) return "null";
let U32 = new Uint32Array(exports.memory ? exports.memory.buffer : memory.buffer);
let U16 = new Uint16Array(exports.memory ? exports.memory.buffer : memory.buffer);
let len16 = U32[(ptr - RUNTIME_HEADER_SIZE + 12) >>> 2] >>> 1;
let ptr16 = ptr >>> 1;
return String.fromCharCode.apply(String, U16.subarray(ptr16, ptr16 + len16));
}
const rtrace = new Rtrace({
onerror(err, info) {
console.log(` ERROR: ${err.stack}`);
failed = true;
},
oninfo(msg, info) {
if (!args.rtraceVerbose) return;
console.log(` ${msg}`);
},
getMemory() {
return instance.exports.memory;
}
});
function toEnv(name, ref) {
let env = {};
for (let key of Object.getOwnPropertyNames(ref)) env[`${name}.${key}`] = ref[key];
let prototype = ref.prototype;
if (prototype) {
for (const key of Object.getOwnPropertyNames(prototype)) {
const original = prototype[key];
env[`${name}#${key}`] = (thisArg, ...args) => {
return original.apply(thisArg, args);
};
}
}
return env;
}
const imports = rtrace.install({
env: Object.assign({}, globalThis, {
memory,
abort: function(msg, file, line, column) {
console.log(stdoutColors.red(" abort: " + getString(msg) + " in " + getString(file) + "(" + line + ":" + column + ")"));
},
trace: function(msg, n) {
console.log(" trace: " + getString(msg) + (n ? " " : "") + Array.prototype.slice.call(arguments, 2, 2 + n).join(", "));
},
seed: function() {
return 0xA5534817; // make tests deterministic
},
visit: function() {
// override in tests
},
"Date.getTimezoneOffset"() {
// @external.js in bindings tests
return new Date().getTimezoneOffset();
},
...toEnv("Date", Date),
...toEnv("Math", Math)
})
});
if (glue.preInstantiate) {
console.log(" [invoke glue.preInstantiate]");
const start = measureStart();
await glue.preInstantiate(imports, exports);
console.log(" [return glue.preInstantiate] " + measureEnd(start));
}
const { instance } = await WebAssembly.instantiate(binaryBuffer, imports);
Object.setPrototypeOf(exports, instance.exports);
if (glue.postInstantiate) {
console.log(" [invoke glue.postInstantiate]");
const start = measureStart();
await glue.postInstantiate(instance);
console.log(" [return glue.postInstantiate] " + measureEnd(start));
}
if (exports._start) {
console.log(" [invoke exports._start]");
const start = measureStart();
exports._start();
console.log(" [return exports._start] " + measureEnd(start));
} else if (exports._initialize) {
console.log(" [invoke exports._initialize]");
const start = measureStart();
exports._initialize();
console.log(" [return exports._initialize] " + measureEnd(start));
}
if (glue.postStart) {
console.log(" [invoke glue.postStart]");
const start = measureStart();
glue.postStart(instance);
console.log(" [return glue.postStart] " + measureEnd(start));
}
const leakCount = rtrace.check();
if (leakCount) {
failed = true;
console.log(` memory leak detected: ${leakCount} leaking`);
}
if (!failed) {
if (rtrace.active) {
console.log(" " +
rtrace.allocCount + " allocs, " +
rtrace.freeCount + " frees, " +
rtrace.resizeCount + " resizes, " +
rtrace.moveCount + " moves"
);
}
return true;
}
} catch (err) {
stderr.write("---\n");
stderr.write(err.stack);
stderr.write("\n---\n");
}
return false;
}
// Evaluates the overall test result
function evaluateResult(failedTests, skippedTests) {
if (skippedTests.size) {
console.log(stdoutColors.yellow("WARNING: ") + stdoutColors.white(skippedTests.size + " compiler tests have been skipped:\n"));
for (let [name, message] of skippedTests) {
console.log(" " + name + " " + stdoutColors.gray("[" + (message || "???") + "]"));
}
console.log();
}
if (failedTests.size) {
process.exitCode = 1;
console.log(stdoutColors.red("FAILURE: ") + stdoutColors.white(failedTests.size + " compiler tests had failures:\n"));
for (let [name, message] of failedTests) {
console.log(" " + name + " " + stdoutColors.gray("[" + (message || "???") + "]"));
}
console.log();
}
console.log(`Time: ${(Date.now() - startTime)} ms\n`);
if (!process.exitCode) {
console.log("[ " + stdoutColors.white("SUCCESS") + " ]");
}
}
// Run tests in parallel if requested (except with coverage)
const isCoverage = process.env.NODE_V8_COVERAGE != null;
if (!isCoverage && args.parallel && coreCount > 2) {
if (cluster.isWorker) {
process.on("message", msg => {
if (msg.cmd != "run") throw Error("invalid command: " + JSON.stringify(msg));
stdoutColors.enabled = !msg.noColors;
stderrColors.enabled = !msg.noColors;
runTest(msg.test).then(({ code, message }) => {
process.send({ code, message });
}, err => {
process.send({ code: FAILURE, message: err.message });
});
});
process.send({ code: SUCCESS, message: null });
} else {
const tests = getTests();
const failedTests = new Map();
const skippedTests = new Map();
const workers = [];
const current = [];
const outputs = [];
let numWorkers = Math.min(coreCount - 1, tests.length);
console.log(`Spawning ${numWorkers} workers (assuming ${coreCount} cores, ${threadCount} threads)...\n`);
cluster.settings.silent = true;
let index = 0;
for (let i = 0; i < numWorkers; ++i) {
let worker = cluster.fork();
workers[i] = worker;
current[i] = null;
outputs[i] = [];
worker.process.stdout.on("data", buf => { outputs[i].push(buf); });
worker.process.stderr.on("data", buf => { outputs[i].push(buf); });
worker.on("message", msg => {
const { code, message } = msg;
process.stdout.write(Buffer.concat(outputs[i]).toString());
switch (code) {
case SUCCESS: break;
case FAILURE: failedTests.set(current[i], message); break;
case SKIPPED: skippedTests.set(current[i], message); break;
default: throw Error(`invalid code: ${code}`);
}
if (index >= tests.length) {
workers[i] = null;
worker.kill();
return;
}
current[i] = tests[index++];
outputs[i] = [];
worker.send({ cmd: "run", test: current[i], noColors: !stdoutColors.enabled });
});
worker.on("disconnect", () => {
if (workers[i]) throw Error(`worker#${i} died unexpectedly`);
if (!--numWorkers) evaluateResult(failedTests, skippedTests);
});
}
}
// Otherwise run tests sequentially
} else {
let failedTests = new Map();
let skippedTests = new Map();
for (const test of getTests()) {
const { code, message } = await runTest(test);
switch (code) {
case SUCCESS: break;
case FAILURE: failedTests.set(test, message); break;
case SKIPPED: skippedTests.set(test, message); break;
default: new Error(`invalid code: ${code}`);
}
}
evaluateResult(failedTests, skippedTests);
}