-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
49 lines (46 loc) · 1.5 KB
/
main.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
import fs from 'fs';
import { lex } from './lexer/lexer.js';
import { Parser } from './parser/parser.js';
import { evalStatements } from './eval/eval.js';
import { Context } from './eval/model.js';
import { MochaError } from './common/error.js';
import { getBuildInCtx } from './sdk/util.js';
import readline from 'readline';
async function evaluate(input, ctx = getBuildInCtx()) {
var tokens = lex(input);
// console.log(statements)
var statements = new Parser(tokens).parse();
// statements.forEach(statement => console.log(statement.toString()))
return await evalStatements(statements, ctx, false);
}
// 俩参数第二个参数是文件
if (process.argv.length >= 3) {
const filename = process.argv[2];
console.log(">> run file: " + filename)
const content = fs.readFileSync(filename, 'utf-8');
evaluate(content)
} else {
// 一个参数则是repl
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const ctx = getBuildInCtx();
async function play() {
// 单行输入
rl.question('>> ', async (answer) => {
try {
var res = await evaluate(answer, ctx);
console.log(res ? res.toString() : res);
} catch (e) {
if (e instanceof MochaError) {
console.error(e.toString());
} else {
throw e;
}
}
await play();
});
}
await play();
}