forked from PostFixJS/PostFixJS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·61 lines (56 loc) · 1.67 KB
/
index.js
File metadata and controls
executable file
·61 lines (56 loc) · 1.67 KB
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
#!/usr/bin/env node
/**
* @fileoverview This is a PostFix REPL that runs in NodeJS. It is interactive by default but also
* supports reading from stdin by specifying -- as first argument.
* If tests are used and a test fails, the exit code is set to -1 to enable simple integration with
* other CLI applications (e.g. build and testing scripts).
*/
const read = require('read')
const Lexer = require('./Lexer')
const Interpreter = require('./Interpreter')
const lexer = new Lexer()
const interpreter = new Interpreter()
interpreter.registerBuiltIns(require('./repl-operators/io'))
interpreter.setTestReporter(require('./repl-operators/testReporter'))
if (process.argv[process.argv.length - 1] === '--') {
process.stdin.resume()
process.stdin.on('data', (buf) => lexer.put(buf.toString()))
process.stdin.on('end', async () => {
try {
await interpreter.run(lexer.getTokens()).promise
} catch (e) {
console.error(e.toString())
}
console.log(interpreter._stack._stack.map(obj => obj.toString()).join(', '))
})
} else {
repl()
}
/**
* The actual read-eval-print loop.
*/
async function repl () {
while (true) {
try {
const input = await new Promise((resolve, reject) => {
read({ prompt: '>' }, (err, input) => {
if (err) {
reject(err)
} else {
resolve(input)
}
})
})
lexer.put(input + '\n')
try {
await interpreter.run(lexer.getTokens()).promise
} catch (e) {
console.error(e.toString())
}
console.log(interpreter._stack._stack.map(obj => obj.toString()).join(', '))
} catch (e) {
console.log('')
return
}
}
}