-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcodegen.js
43 lines (37 loc) · 923 Bytes
/
codegen.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
var parser = require('./grammar').parser;
var program = " \
x is 5. \
y is 6. \
z is x + y. \
\
show z. \
";
function main () {
var ast = parser.parse(program),
source = codegen(ast);
print(source);
}
function codegen (ast) {
switch (ast[0]) {
case 'Program':
return codegenList(ast.slice(2));
case 'NumberLit':
return ast[1].val;
case 'IdentExpr':
return ast[1].name;
case 'AddExpr':
return codegen(ast[2]) + ' + ' + codegen(ast[3]);
case 'IsStmt':
return ast[2] + ' = ' + codegen(ast[3]) + ';\n';
case 'ShowStmt':
return 'print('+codegen(ast[2])+');\n';
default:
throw 'Unknown statement/expression: '+ast[0];
}
}
function codegenList (list) {
return list.reduce(function (prev, curr) {
return prev + codegen(curr);
}, '');
}
main();