Merge pull request #143 from dubek/add-gensym
[jackhill/mal.git] / rpython / stepA_mal.py
CommitLineData
23fa1b11
JM
1import sys
2IS_RPYTHON = sys.argv[0].endswith('rpython')
3
4if IS_RPYTHON:
5 #from rpython.rlib.debug import fatalerror
6 from rpython.rtyper.lltypesystem import lltype
7 from rpython.rtyper.lltypesystem.lloperation import llop
8else:
9 import traceback
10
11b4be99
JM
11import mal_readline
12import mal_types as types
8855a05a
JM
13from mal_types import (MalSym, MalInt, MalStr,
14 nil, true, false, _symbol, _keywordu,
15 MalList, _list, MalVector, MalHashMap, MalFunc)
11b4be99
JM
16import reader, printer
17from env import Env
18import core
19
20# read
21def READ(str):
22 return reader.read_str(str)
23
24# eval
25def is_pair(x):
26 return types._sequential_Q(x) and len(x) > 0
27
28def 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
47def 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
55def 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
62def 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)
8855a05a
JM
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)
11b4be99
JM
81 else:
82 return ast # primitive value, return unchanged
83
84def 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): return ast
93 if len(ast) == 0: return ast
94 a0 = ast[0]
95 if isinstance(a0, MalSym):
96 a0sym = a0.value
97 else:
98 a0sym = u"__<*fn*>__"
99
100 if u"def!" == a0sym:
101 a1, a2 = ast[1], ast[2]
102 res = EVAL(a2, env)
103 return env.set(a1, res)
104 elif u"let*" == a0sym:
105 a1, a2 = ast[1], ast[2]
106 let_env = Env(env)
107 for i in range(0, len(a1), 2):
108 let_env.set(a1[i], EVAL(a1[i+1], let_env))
109 ast = a2
110 env = let_env # Continue loop (TCO)
111 elif u"quote" == a0sym:
112 return ast[1]
113 elif u"quasiquote" == a0sym:
114 ast = quasiquote(ast[1]) # Continue loop (TCO)
115 elif u"defmacro!" == a0sym:
116 func = EVAL(ast[2], env)
117 func.ismacro = True
118 return env.set(ast[1], func)
119 elif u"macroexpand" == a0sym:
120 return macroexpand(ast[1], env)
121 elif u"try*" == a0sym:
122 a1, a2 = ast[1], ast[2]
123 a20 = a2[0]
124 if isinstance(a20, MalSym):
125 if a20.value == u"catch*":
126 try:
127 return EVAL(a1, env);
128 except types.MalException as exc:
129 exc = exc.object
130 catch_env = Env(env, _list(a2[1]), _list(exc))
131 return EVAL(a2[2], catch_env)
132 except Exception as exc:
133 exc = MalStr(unicode("%s" % exc))
134 catch_env = Env(env, _list(a2[1]), _list(exc))
135 return EVAL(a2[2], catch_env)
136 return EVAL(a1, env);
137 elif u"do" == a0sym:
138 if len(ast) == 0:
139 return nil
140 elif len(ast) > 1:
141 eval_ast(ast.slice2(1, len(ast)-1), env)
142 ast = ast[-1] # Continue loop (TCO)
143 elif u"if" == a0sym:
144 a1, a2 = ast[1], ast[2]
145 cond = EVAL(a1, env)
146 if cond is nil or cond is false:
147 if len(ast) > 3: ast = ast[3] # Continue loop (TCO)
148 else: return nil
149 else:
150 ast = a2 # Continue loop (TCO)
151 elif u"fn*" == a0sym:
152 a1, a2 = ast[1], ast[2]
153 return MalFunc(None, a2, env, a1, EVAL)
154 else:
155 el = eval_ast(ast, env)
156 f = el.values[0]
157 if isinstance(f, MalFunc):
158 if f.ast:
159 ast = f.ast
160 env = f.gen_env(el.rest()) # Continue loop (TCO)
161 else:
162 return f.apply(el.rest())
163 else:
164 raise Exception("%s is not callable" % f)
165
166# print
167def PRINT(exp):
168 return printer._pr_str(exp)
169
170# repl
171class MalEval(MalFunc):
172 def apply(self, args):
173 return self.EvalFunc(args[0], self.env)
174
175def entry_point(argv):
176 repl_env = Env()
177 def REP(str, env):
178 return PRINT(EVAL(READ(str), env))
179
180 # core.py: defined using python
181 for k, v in core.ns.items():
182 repl_env.set(_symbol(unicode(k)), MalFunc(v))
183 repl_env.set(types._symbol(u'eval'),
184 MalEval(None, env=repl_env, EvalFunc=EVAL))
185 mal_args = []
186 if len(argv) >= 3:
187 for a in argv[2:]: mal_args.append(MalStr(unicode(a)))
188 repl_env.set(_symbol(u'*ARGV*'), MalList(mal_args))
189
190 # core.mal: defined using the language itself
7f714804 191 REP("(def! *host-language* \"rpython\")", repl_env)
11b4be99
JM
192 REP("(def! not (fn* (a) (if a false true)))", repl_env)
193 REP("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))", repl_env)
194 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)
29ba1fb6
DM
195 REP("(def! *gensym-counter* (atom 0))", repl_env)
196 REP("(def! gensym (fn* [] (symbol (str \"G__\" (swap! *gensym-counter* (fn* [x] (+ 1 x)))))))", repl_env)
197 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)
11b4be99
JM
198
199 if len(argv) >= 2:
200 REP('(load-file "' + argv[1] + '")', repl_env)
201 return 0
202
203 REP("(println (str \"Mal [\" *host-language* \"]\"))", repl_env)
204 while True:
205 try:
206 line = mal_readline.readline("user> ")
207 if line == "": continue
208 print(REP(line, repl_env))
209 except EOFError as e:
210 break
211 except reader.Blank:
212 continue
213 except types.MalException as e:
214 print(u"Error: %s" % printer._pr_str(e.object, False))
ab02c5bb
JM
215 except Exception as e:
216 print("Error: %s" % e)
23fa1b11
JM
217 if IS_RPYTHON:
218 llop.debug_print_traceback(lltype.Void)
219 else:
220 print("".join(traceback.format_exception(*sys.exc_info())))
11b4be99
JM
221 return 0
222
223# _____ Define and setup target ___
224def target(*args):
225 return entry_point
226
227# Just run entry_point if not RPython compilation
228import sys
229if not sys.argv[0].endswith('rpython'):
230 entry_point(sys.argv)