Merge remote-tracking branch 'kanaka/master' into fsharp
[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): 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
167 def PRINT(exp):
168 return printer._pr_str(exp)
169
170 # repl
171 class MalEval(MalFunc):
172 def apply(self, args):
173 return self.EvalFunc(args[0], self.env)
174
175 def 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
191 REP("(def! *host-language* \"rpython\")", repl_env)
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)
195 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)
196
197 if len(argv) >= 2:
198 REP('(load-file "' + argv[1] + '")', repl_env)
199 return 0
200
201 REP("(println (str \"Mal [\" *host-language* \"]\"))", repl_env)
202 while True:
203 try:
204 line = mal_readline.readline("user> ")
205 if line == "": continue
206 print(REP(line, repl_env))
207 except EOFError as e:
208 break
209 except reader.Blank:
210 continue
211 except types.MalException as e:
212 print(u"Error: %s" % printer._pr_str(e.object, False))
213 except Exception as e:
214 print("Error: %s" % e)
215 if IS_RPYTHON:
216 llop.debug_print_traceback(lltype.Void)
217 else:
218 print("".join(traceback.format_exception(*sys.exc_info())))
219 return 0
220
221 # _____ Define and setup target ___
222 def target(*args):
223 return entry_point
224
225 # Just run entry_point if not RPython compilation
226 import sys
227 if not sys.argv[0].endswith('rpython'):
228 entry_point(sys.argv)