-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLox.py
executable file
·86 lines (66 loc) · 1.85 KB
/
Lox.py
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
#!/usr/bin/env python3.12
import sys
from Scanner import Scanner, TokenType
from Token import Token
from Parser import Parser, Stmt
from RuntimeError import RuntimeError
from Interpreter import Interpreter
from Resolver import Resolver
interpreter = Interpreter()
hadError = False
hadRuntimeError = False
args = sys.argv[1:]
def run(source: str) -> None:
scanner: Scanner = Scanner(source)
tokens: list[Token] = scanner.scanTokens()
parser: Parser = Parser(tokens)
stmts: list[Stmt] = parser.parse()
if hadError:
return
resolver: Resolver = Resolver(interpreter)
resolver.resolve(stmts)
if hadError:
return
interpreter.interpret(stmts)
def runFile(path: str) -> None:
with open(path) as f:
data = f.read()
run(data)
if hadError:
exit(65)
if hadRuntimeError:
exit(70)
def runPrompt() -> None:
global hadError
while True:
try:
line = input("> ")
except EOFError:
exit(0)
if line == '':
break
run(line)
hadError = False
def error(line: int, message: str) -> None:
report(line, "", message)
def parse_error(token: Token, message: str) -> None:
if token.token_type == TokenType.EOF:
report(token.line, " at end", message)
else:
report(token.line, f"at '{token.lexeme}'", message)
def runtime_error(err: RuntimeError) -> None:
print(f'{err.__str__()}\n[line: {err.token.line}]')
global hadRuntimeError
hadRuntimeError = True
def report(line: int, where: str, message: str) -> None:
print(f"[line {line}] Error {where}: {message}")
global hadError
hadError = True
if __name__ == '__main__':
if len(args) > 1:
print("Usage: pylox <script>")
exit(64)
elif len(args) == 1:
runFile(args[0])
else:
runPrompt()