-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlang.py
More file actions
58 lines (47 loc) · 1.46 KB
/
lang.py
File metadata and controls
58 lines (47 loc) · 1.46 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
import sys
import argparse
from lang.lexer import Lexer
from lang.parser import Parser
from lang.interpreter import Interpreter
from classes.environment import Environment
import classes.errors as er
environment = Environment()
lexer = Lexer()
parser = Parser()
interpreter = Interpreter(environment)
argparser = argparse.ArgumentParser()
argparser.add_argument("--debug", "-d", type=bool, default=False)
args, uknownargs = argparser.parse_known_args()
def run_program(program, repl=False, debug_mode=False):
try:
tokens = lexer.get_tokens(program)
if debug_mode:
print(tokens)
parse_result = parser.parse(tokens)
if debug_mode:
print(parse_result)
results, printed_results = interpreter.interpret(parse_result)
if not repl:
results = printed_results
print(*results, sep='\n')
except Exception as e:
er.print_error(e)
except KeyboardInterrupt:
print("\nProgram ended by user.")
sys.exit()
except Exception as e:
raise Exception
if len(sys.argv) >= 2:
filename = sys.argv[1]
with open(filename, "r") as f:
lines = f.readlines()
program = ''.join(lines)
run_program(program, debug_mode=args.debug)
else:
while True:
try:
program = input(">>> ")
run_program(program, repl=True)
except KeyboardInterrupt:
print("\nProgram ended by user.")
break