-
Notifications
You must be signed in to change notification settings - Fork 1
/
example.js
100 lines (92 loc) · 2.35 KB
/
example.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
/* Small example driver program for compiling/running programs */
const fs = require("fs");
const { exec } = require("child_process");
var args = process.argv.slice(2);
/** We execute this with the path of the file we want to compile */
const compile_cmd = "sh compile.sh";
/** Memory that will be imported in WASM runtime */
const memory = new WebAssembly.Memory({ initial: 1 });
/** Utility for parsing strings out of C0's memory */
const c0_parse_str = (address) => {
const bytes = new Uint8Array(memory.buffer.slice(address | 0));
var i = 0;
var msg = "";
while (i < bytes.length && bytes[i] !== undefined && bytes[i] !== 0) {
msg += String.fromCharCode(bytes[i]);
i += 1;
}
return msg;
};
/** Required imports */
const imports = {
c0deine: {
memory: memory,
result: (res) => {
console.log(res | 0);
},
abort: (sig) => {
console.log("abort: " + (sig | 0));
},
error: (str) => {
console.log("error: " + c0_parse_str(str));
},
debug: (lbl) => {
console.log("debug: entered label " + lbl);
setTimeout(() => {
return 0;
}, 0);
},
},
conio: {
print: (str) => {
process.stdout.write(c0_parse_str(str));
},
println: (str) => {
process.stdout.write(c0_parse_str(str) + "\n");
},
flush: () => {
process.stdout.flush();
setTimeout(() => {}, 0);
},
eof: () => {
console.log("TODO: eof unimplemented!");
},
readline: () => {
console.log("TODO: readline unimplemented!");
},
},
};
/** Drivers to compile and evaluate programs */
function compile(filename, exe, next) {
exec(compile_cmd + " " + filename, (error, stdout, stderr) => {
if (error !== null) {
console.log(stdout);
console.log(stderr);
return next();
}
return exe();
});
}
function run(filename, imports) {
const bytes = fs.readFileSync(filename + ".wasm");
const wasm = new WebAssembly.Module(bytes);
try {
const instance = new WebAssembly.Instance(wasm, imports);
} catch (e) {
console.log(e + "");
}
}
if (!fs.existsSync(args[0])) {
console.log("Couldn't find file: " + args[0] + "\n");
} else if (fs.lstatSync(args[0]).isFile()) {
const filename = args[0];
compile(
filename,
() => {
run(filename, imports);
},
() => {
console.log("Compilation failed.");
}
);
}