-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathroadc.py
More file actions
executable file
·78 lines (67 loc) · 1.86 KB
/
roadc.py
File metadata and controls
executable file
·78 lines (67 loc) · 1.86 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
#!/usr/bin/env python3
"""
RoadC — The BlackRoad Language (Python interpreter)
Usage:
roadc.py run <file.road> Run a RoadC source file
roadc.py repl Interactive REPL
roadc.py parse <file.road> Parse and dump AST
roadc.py version Show version
"""
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from lexer import Lexer
from parser import Parser
from interpreter import Interpreter
VERSION = "0.1.0"
def run_code(code):
tokens = Lexer(code).tokenize()
ast = Parser(tokens).parse_program()
Interpreter().run(ast)
def run_file(path):
with open(path) as f:
run_code(f.read())
def parse_file(path):
with open(path) as f:
code = f.read()
tokens = Lexer(code).tokenize()
ast = Parser(tokens).parse_program()
for stmt in ast.statements:
print(stmt)
def repl():
print(f"RoadC {VERSION} — type 'exit' to quit")
interp = Interpreter()
while True:
try:
line = input("road> ")
except (EOFError, KeyboardInterrupt):
print()
break
if line.strip() in ('exit', 'quit'):
break
if not line.strip():
continue
try:
tokens = Lexer(line).tokenize()
ast = Parser(tokens).parse_program()
interp.run(ast)
except Exception as e:
print(f"Error: {e}")
def main():
if len(sys.argv) < 2:
print(__doc__.strip())
sys.exit(1)
cmd = sys.argv[1]
if cmd == 'version':
print(f"RoadC {VERSION}")
elif cmd == 'run' and len(sys.argv) > 2:
run_file(sys.argv[2])
elif cmd == 'parse' and len(sys.argv) > 2:
parse_file(sys.argv[2])
elif cmd == 'repl':
repl()
else:
print(__doc__.strip())
sys.exit(1)
if __name__ == '__main__':
main()