Skip to content

Commit f765c11

Browse files
authored
Add Array and require to cli
Added `Array` class and `require` function to the node cli implementation
1 parent 309f6a2 commit f765c11

1 file changed

Lines changed: 38 additions & 3 deletions

File tree

cli.js

Lines changed: 38 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,46 @@ const getChar = () => {
3535
return cache.shift()
3636
}
3737

38-
const makeCLIEnvironment = () => {
38+
class LoxArray {
39+
init(_vars, args) {
40+
this.internalArray = Array(args[0] || 0).fill(null)
41+
}
42+
at(_vars, args) {
43+
return this.internalArray[args[0]] ?? null
44+
}
45+
get(_vars, args) {
46+
return this.internalArray[args[0]] ?? null
47+
}
48+
set(_vars, args) {
49+
// TODO: Throw error when set is incorrect
50+
if (args[0] > this.internalArray.length) return null
51+
this.internalArray[args[0]] = args[1]
52+
return args[1]
53+
}
54+
length() {
55+
return this.internalArray.length ?? null
56+
}
57+
}
58+
59+
const makeCLIEnvironment = (printfn, debug) => {
60+
const evalFile = (_vars, args) => {
61+
const code = fs.readFileSync(args[0], 'utf8')
62+
const newEnv = makeCLIEnvironment(printfn, debug)
63+
let lastLine
64+
try {
65+
lastLine = run(code, newEnv, printfn, debug)
66+
} catch (e) {
67+
console.log('Error importing', args[0], ':', e)
68+
}
69+
return newEnv
70+
}
3971
const env = new Environment()
4072
env.setBuiltin('readFile', (_vars, args) => fs.readFileSync(args[0], 'utf8'))
73+
env.setBuiltin('evalFile', (...args) => evalFile(...args) && null)
74+
env.setBuiltin('require', (...args) => evalFile(...args).map.get('exports'))
4175
env.setBuiltin('exit', (_vars, args) => process.exit(args[0] || 0))
4276
env.setBuiltin('chr', (_vars, args) => String.fromCharCode(args[0]))
77+
env.setBuiltinClass('Array', LoxArray)
4378
env.setBuiltin('getc', () => {
4479
const val = getChar()
4580
return val ? val.charCodeAt(0) : -1
@@ -57,7 +92,7 @@ const runPrompt = () => {
5792
prompt: prompt,
5893
historySize: +options.history
5994
})
60-
const env = makeCLIEnvironment()
95+
const env = makeCLIEnvironment(console.log, options.debug)
6196

6297
lineReader.on('line', line => {
6398
let code = line
@@ -76,7 +111,7 @@ const runPrompt = () => {
76111
const runFile = filename => {
77112
try {
78113
const file = fs.readFileSync(filename, 'utf8')
79-
const env = makeCLIEnvironment()
114+
const env = makeCLIEnvironment(console.log, options.debug)
80115
try {
81116
run(file, env, console.log, options.debug)
82117
} catch (e) {

0 commit comments

Comments
 (0)