-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVMWriter.js
85 lines (71 loc) · 1.46 KB
/
VMWriter.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
const fs = require('fs');
const arithmeticCommands = [
'add',
'sub',
'neg',
'eq',
'gt',
'lt',
'and',
'or',
'not'
];
const segments = [
'constant',
'argument',
'local',
'static',
'this',
'that',
'pointer',
'temp'
];
class VMWriter {
constructor(destPath) {
this.destPath = destPath;
this.file = '';
}
replace(s, d) {
this.file.replace(s, d);
}
writePush(segment, index) {
if (!segments.includes(segment)) {
throw new Error('Unrecognized segment: ' + segment);
}
this.file += `push ${segment} ${index}\n`;
}
writePop(segment, index) {
if (!segments.includes(segment)) {
throw new Error('Unrecognized segment: ' + segment);
}
this.file += `pop ${segment} ${index}\n`;
}
writeArithmetic(command) {
if (!arithmeticCommands.includes(command)) {
throw new Error('Unrecognized arithmetic command: ' + command);
}
this.file += `${command}\n`;
}
writeLabel(labelName) {
this.file += `label ${labelName}\n`;
}
writeGoto(labelName) {
this.file += `goto ${labelName}\n`;
}
writeIf(labelName) {
this.file += `if-goto ${labelName}\n`;
}
writeCall(name, nArgs) {
this.file += `call ${name} ${nArgs}\n`;
}
writeFunction(name, nLocals) {
this.file += `function ${name} ${nLocals}\n`;
}
writeReturn() {
this.file += `return\n`;
}
end() {
fs.writeFileSync(this.destPath, this.file, 'utf8');
}
}
module.exports = VMWriter;