~deciduously/nlox

nlox/src/nloxpkg/lox.nim -rw-r--r-- 881 bytes
0f2f20d1Ben Lovy Scanner 5 months ago
                                                                                
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
#! The top-level of the Lox interpreter.

import loxerror, scanner, token

type
    Lox* = ref object of RootObj
        error_logger: LoxError

# Build a new interpreter
proc new_lox*(): Lox =
    var ret = new Lox
    ret.error_logger = new LoxError
    ret

# Interpret Lox input, results to stdout
method run(self: Lox, source: string) {.base.} =
    let scanner = new_scanner(source, self.error_logger)
    let tokens = scanner.scan_tokens()
    for token in tokens:
        echo $token

# Interpret a source file
method run_file*(self: Lox, path: string) {.base.} =
    self.run(readFile(path))
    if self.error_logger.had_error: quit(65)

# Open a REPL
method run_prompt*(self: Lox) {.base.} =
    while true:
        stdout.write("> ")
        let line = stdin.readLine()
        if line.len() == 0: break
        self.run(line)
        self.error_logger.had_error = false