-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsLoxLang.js
113 lines (93 loc) · 3.08 KB
/
jsLoxLang.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/*
This is the main file (entry file also) for JsLoxLang.
The main() function expects a string inside an array,
which should be the raw input given by the user
*/
const fs = require('fs');
const readline = require('readline');
const { Scanner } = require('./src/scanner');
const { Parser } = require('./src/parser');
const { Interpreter } = require('./src/interpreter');
const { Resolver } = require('./src/resolver');
class JsLox {
constructor(rawCode) {
this.rawCode = rawCode.slice(2);
this.hadError = false;
this.interpreter = new Interpreter(this);
}
// Do extra check to ensure only a string is contained in the array?
main() {
if (this.rawCode.length > 1) {
console.error('Input array is too long')
process.on('error', () => {
console.log('Exiting process')
process.exit(0);
})
process.emit('error')
}
else if (this.rawCode.length === 1) {
this.runFile(this.rawCode[0]);
}
else {
this.runPrompt();
}
}
runFile(givenArg) {
if (this.hadError === true) {
process.exit(0)
}
const fileContents = fs.readFileSync(`/Users/luciemacaigne/Desktop/jsLoxLang/jsLoxTests/${givenArg}`, 'utf-8');
this.run(fileContents)
}
runPrompt() {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.setPrompt("> ");
rl.prompt()
rl.on("line", userInput => {
let currentInput = '';
currentInput += userInput;
this.run(currentInput)
this.hadError = false;
rl.prompt();
})
rl.on("close", () => {
console.log('exiting process')
process.exit(0)
})
}
run(source) {
const scanner = new Scanner(source, this);
const tokens = scanner.scanTokens();
const parser = new Parser(tokens, this);
const statements = parser.parse();
if (this.hadError) return;
const resolver = new Resolver(this.interpreter, this);
resolver.resolve(statements)
if (this.hadError) return;
this.interpreter.interpret(statements);
}
error(line, message) {
return this.report(line, "", message)
}
report(line, where, message) {
line = parseInt(line)
console.error(`Line: ${line} Error: ${where}: ${message}`);
this.hadError = true;
return `Line: ${line} Error: ${where}: ${message}`;
}
parseError(token, message) {
if (token.type === 'EOF') {
this.report(token.line, ' at end', message)
}
else {
this.report(token.line, " at '", token.lexeme, "' ", message)
}
}
}
const jsLoxInstance = new JsLox(process.argv);
jsLoxInstance.main();
// https://stackoverflow.com/questions/61394928/get-user-input-through-node-js-console
// https://stackoverflow.com/questions/17837147/user-input-in-node-js