-
Notifications
You must be signed in to change notification settings - Fork 1
/
run.py
76 lines (66 loc) · 2.12 KB
/
run.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
import sys
import cfg
from execution import Program
def run_file(filename, environment=None, options=None):
if environment is None:
environment = Program(is_repl=False, options=options)
try:
with open(filename) as f:
code = f.read()
except FileNotFoundError:
cfg.error("could not find", filename)
return
except PermissionError:
cfg.error("insufficient permissions to read", filename)
return
except IOError:
cfg.error("could not read", filename)
return
# If file read was successful, execute the code
run_program(code, environment)
def run_program(code, environment=None, options=None):
if environment is None:
environment = Program(is_repl=False, options=options)
try:
environment.execute(code)
except KeyboardInterrupt:
cfg.interrupted_error()
except RecursionError:
cfg.recursion_error()
except Exception as err:
# Miscellaneous exception, probably indicates a bug in
# the interpreter
cfg.error(err)
finally:
sys.stdout.flush()
def repl(environment=None, options=None):
print("(tinylisp 2)")
if environment is None:
environment = Program(is_repl=True, options=options)
print("Type (help) for information")
instruction = input_instruction()
while True:
try:
last_value = environment.execute(instruction)
except KeyboardInterrupt:
cfg.interrupted_error()
except RecursionError:
cfg.recursion_error()
except cfg.UserQuit:
break
except Exception as err:
# Miscellaneous exception, probably indicates a bug in
# the interpreter
cfg.error(err)
break
else:
if last_value is not None:
environment.global_scope[cfg.Symbol("_")] = last_value
instruction = input_instruction()
print("Bye!")
def input_instruction():
try:
instruction = input(cfg.PROMPT)
except (EOFError, KeyboardInterrupt):
instruction = "(quit)"
return instruction