-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
68 lines (52 loc) · 1.5 KB
/
index.ts
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
// index.ts | The entry point of our REPL
import Parser from "./front-end/parser";
import Environment from "./runtime/environment";
import { evaluate } from "./runtime/interpreter";
import { log } from "./utils/errors";
import fs from "node:fs";
import { readCrustFilesFromStdlib } from "./utils/stdlib";
// Read all crust files from the stdlib folder
const crustSTDLIB = await readCrustFilesFromStdlib();
function combineStdlib(input: string) {
return `${crustSTDLIB}\n${input}`;
}
function repl() {
const parser = new Parser();
// Global environment
const environment = new Environment();
console.log("Crust REPL");
while (true) {
const input = combineStdlib(prompt("Crust> ") || "");
if (input === "exit" || !input) {
break;
}
// Produce AST from the source code
const program = parser.produceAst(input);
// log(program);
// Evaluate the AST
const result = evaluate(program, environment);
log(result);
}
}
function run(fileName: string) {
const parser = new Parser();
// Global environment
const environment = new Environment();
fs.readFile(fileName, "utf8", (err, data) => {
if (err) {
throw err;
}
const input = combineStdlib(data.toString());
// Produce AST from the source code
const program = parser.produceAst(input);
// Evaluate the AST
const result = evaluate(program, environment);
log(result);
});
}
const args = process.argv.slice(2);
if (args.length === 0) {
repl();
} else {
run(args[0]);
}