-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
56 lines (50 loc) · 1.41 KB
/
index.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
const fs = require("fs");
const createLexer = require("./lib/Lexer");
const Parser = require("./lib/Parser");
const vm = require("./lib/VM");
const { isInt, isNil } = require("./lib/VM/type-checks");
const { InvalidExitCodeError } = require("./lib/errors");
const format = require("./lib/VM/format");
function runFile(filePath) {
const code = fs.readFileSync(filePath, "utf8");
const result = vm.main(parse(code));
switch (true) {
case isInt(result):
process.exit(result);
case isNil(result):
process.exit(0);
case result === undefined:
process.exit(0);
default:
throw new InvalidExitCodeError(
`main returned with '${format(result)}' (expected an int or nil)`
);
}
}
function repl() {
const stdin = process.openStdin();
process.stdout.write("> ");
stdin.addListener("data", data => {
const code = data.toString();
try {
const ast = parse(code);
for (const statement of ast.iter) {
const result = vm.runLine(statement);
if (result !== undefined) {
console.log(";", format(result));
}
}
} catch (e) {
console.error(e.toString());
} finally {
process.stdout.write("> ");
}
});
}
function parse(code) {
const lexer = createLexer();
const tokens = lexer.tokenize(code);
const parser = new Parser(tokens);
return parser.parse();
}
process.argv[2] ? runFile(process.argv[2]) : repl();