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