-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgenerate.js
84 lines (75 loc) · 2.45 KB
/
generate.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
const fs = require("mz/fs");
async function main() {
const filename = process.argv[2];
if (!filename) {
console.log("error reading ast or ast not provided");
return;
}
const astJson = (await fs.readFile(filename)).toString();
const runtimeJs = (await fs.readFile("library.js")).toString();
const statements = JSON.parse(astJson);
const jsCode = generateJsForStatements(statements) + "\n" + runtimeJs;
const outputFilename = filename.replace(".ast", ".js");
await fs.writeFile(outputFilename, jsCode);
// console.log(`Wrote ${outputFilename}.`);
}
function generateJsForStatements(statements) {
const lines = [];
for (let statement of statements) {
const line = generateJsForStatementOrExpr(statement);
lines.push(line);
}
return lines.join("\n");
}
// author: Tanmay Hinge
function generateJsForStatementOrExpr(node) {
if (node.type === "var_assignment") {
const varName = node.var_name.value;
const jsExpr = generateJsForStatementOrExpr(node.value);
const js = `var ${varName} = ${jsExpr};`;
return js;
}
else if (node.type === "fun_call") {
let funName = node.fun_name.value;
if (funName === "if") {
funName = "$if";
}
const argList = node.arguments.map((arg) => {
return generateJsForStatementOrExpr(arg);
}).join(", ");
return `${funName}(${argList})`;
}
else if (node.type === "string") {
return node.value;
}
else if (node.type === "number") {
return node.value;
}
else if (node.type === "identifier") {
return node.value;
}
else if (node.type === "lambda") {
const paramList = node.parameters
.map(param => param.value)
.join(", ");
const jsBody = node.body.map((arg, i) => {
const jsCode = generateJsForStatementOrExpr(arg);
if (i === node.body.length - 1) {
return "return " + jsCode;
} else {
return jsCode;
}
}).join(";\n");
return `function (${paramList}) {\n${indent(jsBody)}\n}`;
}
else if (node.type === "comment") {
return "";
}
else {
throw new Error(`Unhandled AST node type ${node.type}`);
}
}
function indent(string) {
return string.split("\n").map(line => " " + line).join("\n");
}
main().catch(err => console.log(err.stack));