-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebscript.js
More file actions
111 lines (95 loc) · 3.02 KB
/
webscript.js
File metadata and controls
111 lines (95 loc) · 3.02 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
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
import fs from 'fs';
import readline from 'node:readline'
import { Lexer } from './lexer.js'
import { Parser } from './parser.js'
import { Interpreter } from './interpreter.js'
import stdlib, { WebScriptError } from './stdlib.js'
import { errorMonitor } from 'events';
const readFile = location =>
new Promise((resolve, reject) =>
fs.readFile(location, 'utf-8', (err, data) => {
if (err) return reject(err)
resolve(data.toString())
})
)
const writeFile = (location, data) =>
new Promise((resolve, reject) =>
fs.writeFile(location, data, err => {
if (err) return reject(err)
resolve()
})
)
;(async () => {
let argv = process.argv.slice(2)
const debug = argv.find(cmd => cmd === '--dbg') ? true : false
argv = argv.filter(arg => arg !== '--dbg')
const location = argv[0]
if (location) {
const program = await readFile(location)
const lexer = new Lexer(program)
try {
lexer.scanTokens()
} catch (err) {
console.log(err)
process.exit(1)
} finally {
if (debug) await writeFile('tokens.json', JSON.stringify(lexer.tokens, null, 2))
}
const parser = new Parser(lexer.tokens)
try {
parser.parse()
} catch (err) {
console.log(err)
} finally {
if (debug) await writeFile('ast.json', JSON.stringify(parser.ast, null, 2))
}
const interpreter = new Interpreter()
try {
interpreter.run(parser.ast, stdlib)
} catch (err) {
console.log(err)
}
} else {
const interpreter = new Interpreter()
let scope = {
...stdlib,
exit: () => process.exit(0)
}
const input = readline.createInterface({
input: process.stdin,
output: process.stdout
})
process.on('SIGINT', () => {
input.close()
})
const repl = line => {
let hadError = false
const lexer = new Lexer(line)
try {
lexer.scanTokens()
} catch (err) {
if (err instanceof WebScriptError) {
hadError = true
console.log(err.toString())
} else throw err
}
if (!hadError) {
const parser = new Parser(lexer.tokens)
try {
parser.parse()
} catch (err) {
if (err instanceof WebScriptError) console.log(err.toString())
else throw err
}
try {
scope = interpreter.run(parser.ast, scope)
} catch (err) {
if (err instanceof WebScriptError) console.log(err.toString())
else throw err
}
}
input.question('> ', repl)
}
input.question('> ', repl)
}
})()