/
repl.py
43 lines (34 loc) · 928 Bytes
/
repl.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
import sptokenizer
import spparser
import environment
import traceback
prompt = 'pie > '
def read_input():
print(prompt, end="", flush=True)
indent = 0
unmatched_left = 0
lines = []
while True:
line = input(' ' * indent)
lines.append(line)
for c in line:
if c == '(':
unmatched_left += 1
elif c == ')':
unmatched_left -= 1
if unmatched_left <= 0:
return '\n'.join(lines)
indent = len(prompt)
def repl():
while True:
source = read_input()
try:
tokens = sptokenizer.tokenize(source)
ast = spparser.parse_program(tokens)
value = ast.eval(environment.Environment(environment.built_ins))
except Exception:
print(traceback.format_exc())
else:
if value is not None:
print(value)
repl()