-
Notifications
You must be signed in to change notification settings - Fork 5
/
schrodinger.py
85 lines (74 loc) · 1.85 KB
/
schrodinger.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
#### schrodinger.py
#
# Interface for the Schrodinger interpreter
import os
import sys
import traceback
import readline
import atexit
from seval import eval
from slexer import tokenize
from sparser import parse, to_string
from builtins import global_env
#### Load from a file and run
def load(filename):
print "Loading and executing %s" % filename
rps = 0
full_line = ""
line_num = 1
for line in open(filename, "r"):
line = line.strip()
full_line += line
rps += line.count("(")-line.count(")")
if rps == 0 and full_line.strip() != "":
try:
tokens = tokenize(full_line)
while len(tokens) > 0:
tree = parse(tokens)
if tree is not None:
eval(tree,global_env)
except SystemExit:
exit()
except Exception as e:
print "\nAn error occurred on line %d:\n\t%s\n" % (line_num,full_line)
print e.message
#traceback.print_exc()
break
full_line = ""
line_num += 1
#### repl
def repl(prompt='vau> '):
try:
while True:
full_line = raw_input(prompt)
rps = full_line.count("(")-full_line.count(")")
while rps != 0 or full_line == "":
line = raw_input(">\t")
full_line += line
rps += line.count("(")-line.count(")")
try:
tokens = tokenize(full_line)
while len(tokens) > 0:
tree = parse(tokens)
if tree is not None:
val = eval(tree,global_env)
if val is not None: print to_string(val)
except ValueError as e:
print e.message
except (KeyboardInterrupt, SystemExit):
pass
except:
print "\nFatal Error\n"
traceback.print_exc()
#### on startup from the command line
def main():
histfile = os.path.expanduser("~/.schrodinger-history")
try: readline.read_history_file(histfile)
except IOError: pass
atexit.register(readline.write_history_file, histfile)
load("./stdlib.sch")
if len(sys.argv) > 1:
load(sys.argv[1])
repl()
if __name__ == "__main__":
main()