RPython: misc cleanup, step sync, stats target.
[jackhill/mal.git] / rpython / stepA_mal.py
CommitLineData
11b4be99
JM
1import sys, traceback
2import mal_readline
3import mal_types as types
8855a05a
JM
4from mal_types import (MalSym, MalInt, MalStr,
5 nil, true, false, _symbol, _keywordu,
6 MalList, _list, MalVector, MalHashMap, MalFunc)
11b4be99
JM
7import reader, printer
8from env import Env
9import core
10
11# read
12def READ(str):
13 return reader.read_str(str)
14
15# eval
16def is_pair(x):
17 return types._sequential_Q(x) and len(x) > 0
18
19def quasiquote(ast):
20 if not is_pair(ast):
21 return _list(_symbol(u"quote"), ast)
22 else:
23 a0 = ast[0]
24 if isinstance(a0, MalSym):
25 if a0.value == u'unquote':
26 return ast[1]
27 if is_pair(a0) and isinstance(a0[0], MalSym):
28 a00 = a0[0]
29 if (isinstance(a00, MalSym) and
30 a00.value == u'splice-unquote'):
31 return _list(_symbol(u"concat"),
32 a0[1],
33 quasiquote(ast.rest()))
34 return _list(_symbol(u"cons"),
35 quasiquote(a0),
36 quasiquote(ast.rest()))
37
38def is_macro_call(ast, env):
39 if types._list_Q(ast):
40 a0 = ast[0]
41 if isinstance(a0, MalSym):
42 if not env.find(a0) is None:
43 return env.get(a0).ismacro
44 return False
45
46def macroexpand(ast, env):
47 while is_macro_call(ast, env):
48 assert isinstance(ast[0], MalSym)
49 mac = env.get(ast[0])
50 ast = macroexpand(mac.apply(ast.rest()), env)
51 return ast
52
53def eval_ast(ast, env):
54 if types._symbol_Q(ast):
55 assert isinstance(ast, MalSym)
56 return env.get(ast)
57 elif types._list_Q(ast):
58 res = []
59 for a in ast.values:
60 res.append(EVAL(a, env))
61 return MalList(res)
8855a05a
JM
62 elif types._vector_Q(ast):
63 res = []
64 for a in ast.values:
65 res.append(EVAL(a, env))
66 return MalVector(res)
67 elif types._hash_map_Q(ast):
68 new_dct = {}
69 for k in ast.dct.keys():
70 new_dct[k] = EVAL(ast.dct[k], env)
71 return MalHashMap(new_dct)
11b4be99
JM
72 else:
73 return ast # primitive value, return unchanged
74
75def EVAL(ast, env):
76 while True:
77 #print("EVAL %s" % printer._pr_str(ast))
78 if not types._list_Q(ast):
79 return eval_ast(ast, env)
80
81 # apply list
82 ast = macroexpand(ast, env)
83 if not types._list_Q(ast): return ast
84 if len(ast) == 0: return ast
85 a0 = ast[0]
86 if isinstance(a0, MalSym):
87 a0sym = a0.value
88 else:
89 a0sym = u"__<*fn*>__"
90
91 if u"def!" == a0sym:
92 a1, a2 = ast[1], ast[2]
93 res = EVAL(a2, env)
94 return env.set(a1, res)
95 elif u"let*" == a0sym:
96 a1, a2 = ast[1], ast[2]
97 let_env = Env(env)
98 for i in range(0, len(a1), 2):
99 let_env.set(a1[i], EVAL(a1[i+1], let_env))
100 ast = a2
101 env = let_env # Continue loop (TCO)
102 elif u"quote" == a0sym:
103 return ast[1]
104 elif u"quasiquote" == a0sym:
105 ast = quasiquote(ast[1]) # Continue loop (TCO)
106 elif u"defmacro!" == a0sym:
107 func = EVAL(ast[2], env)
108 func.ismacro = True
109 return env.set(ast[1], func)
110 elif u"macroexpand" == a0sym:
111 return macroexpand(ast[1], env)
112 elif u"try*" == a0sym:
113 a1, a2 = ast[1], ast[2]
114 a20 = a2[0]
115 if isinstance(a20, MalSym):
116 if a20.value == u"catch*":
117 try:
118 return EVAL(a1, env);
119 except types.MalException as exc:
120 exc = exc.object
121 catch_env = Env(env, _list(a2[1]), _list(exc))
122 return EVAL(a2[2], catch_env)
123 except Exception as exc:
124 exc = MalStr(unicode("%s" % exc))
125 catch_env = Env(env, _list(a2[1]), _list(exc))
126 return EVAL(a2[2], catch_env)
127 return EVAL(a1, env);
128 elif u"do" == a0sym:
129 if len(ast) == 0:
130 return nil
131 elif len(ast) > 1:
132 eval_ast(ast.slice2(1, len(ast)-1), env)
133 ast = ast[-1] # Continue loop (TCO)
134 elif u"if" == a0sym:
135 a1, a2 = ast[1], ast[2]
136 cond = EVAL(a1, env)
137 if cond is nil or cond is false:
138 if len(ast) > 3: ast = ast[3] # Continue loop (TCO)
139 else: return nil
140 else:
141 ast = a2 # Continue loop (TCO)
142 elif u"fn*" == a0sym:
143 a1, a2 = ast[1], ast[2]
144 return MalFunc(None, a2, env, a1, EVAL)
145 else:
146 el = eval_ast(ast, env)
147 f = el.values[0]
148 if isinstance(f, MalFunc):
149 if f.ast:
150 ast = f.ast
151 env = f.gen_env(el.rest()) # Continue loop (TCO)
152 else:
153 return f.apply(el.rest())
154 else:
155 raise Exception("%s is not callable" % f)
156
157# print
158def PRINT(exp):
159 return printer._pr_str(exp)
160
161# repl
162class MalEval(MalFunc):
163 def apply(self, args):
164 return self.EvalFunc(args[0], self.env)
165
166def entry_point(argv):
167 repl_env = Env()
168 def REP(str, env):
169 return PRINT(EVAL(READ(str), env))
170
171 # core.py: defined using python
172 for k, v in core.ns.items():
173 repl_env.set(_symbol(unicode(k)), MalFunc(v))
174 repl_env.set(types._symbol(u'eval'),
175 MalEval(None, env=repl_env, EvalFunc=EVAL))
176 mal_args = []
177 if len(argv) >= 3:
178 for a in argv[2:]: mal_args.append(MalStr(unicode(a)))
179 repl_env.set(_symbol(u'*ARGV*'), MalList(mal_args))
180
181 # core.mal: defined using the language itself
7f714804 182 REP("(def! *host-language* \"rpython\")", repl_env)
11b4be99
JM
183 REP("(def! not (fn* (a) (if a false true)))", repl_env)
184 REP("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))", repl_env)
185 REP("(defmacro! cond (fn* (& xs) (if (> (count xs) 0) (list 'if (first xs) (if (> (count xs) 1) (nth xs 1) (throw \"odd number of forms to cond\")) (cons 'cond (rest (rest xs)))))))", repl_env)
186 REP("(defmacro! or (fn* (& xs) (if (empty? xs) nil (if (= 1 (count xs)) (first xs) `(let* (or_FIXME ~(first xs)) (if or_FIXME or_FIXME (or ~@(rest xs))))))))", repl_env)
187
188 if len(argv) >= 2:
189 REP('(load-file "' + argv[1] + '")', repl_env)
190 return 0
191
192 REP("(println (str \"Mal [\" *host-language* \"]\"))", repl_env)
193 while True:
194 try:
195 line = mal_readline.readline("user> ")
196 if line == "": continue
197 print(REP(line, repl_env))
198 except EOFError as e:
199 break
200 except reader.Blank:
201 continue
202 except types.MalException as e:
203 print(u"Error: %s" % printer._pr_str(e.object, False))
ab02c5bb
JM
204 except Exception as e:
205 print("Error: %s" % e)
11b4be99
JM
206 #print("".join(traceback.format_exception(*sys.exc_info())))
207 return 0
208
209# _____ Define and setup target ___
210def target(*args):
211 return entry_point
212
213# Just run entry_point if not RPython compilation
214import sys
215if not sys.argv[0].endswith('rpython'):
216 entry_point(sys.argv)