2 IS_RPYTHON
= sys
.argv
[0].endswith('rpython')
5 #from rpython.rlib.debug import fatalerror
6 from rpython
.rtyper
.lltypesystem
import lltype
7 from rpython
.rtyper
.lltypesystem
.lloperation
import llop
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
22 return reader
.read_str(str)
26 return types
._sequential
_Q
(x
) and len(x
) > 0
30 return _list(_symbol(u
"quote"), ast
)
33 if isinstance(a0
, MalSym
):
34 if a0
.value
== u
'unquote':
36 if is_pair(a0
) and isinstance(a0
[0], MalSym
):
38 if (isinstance(a00
, MalSym
) and
39 a00
.value
== u
'splice-unquote'):
40 return _list(_symbol(u
"concat"),
42 quasiquote(ast
.rest()))
43 return _list(_symbol(u
"cons"),
45 quasiquote(ast
.rest()))
47 def is_macro_call(ast
, env
):
48 if types
._list
_Q
(ast
):
50 if isinstance(a0
, MalSym
):
51 if not env
.find(a0
) is None:
52 return env
.get(a0
).ismacro
55 def macroexpand(ast
, env
):
56 while is_macro_call(ast
, env
):
57 assert isinstance(ast
[0], MalSym
)
59 ast
= macroexpand(mac
.apply(ast
.rest()), env
)
62 def eval_ast(ast
, env
):
63 if types
._symbol
_Q
(ast
):
64 assert isinstance(ast
, MalSym
)
66 elif types
._list
_Q
(ast
):
69 res
.append(EVAL(a
, env
))
71 elif types
._vector
_Q
(ast
):
74 res
.append(EVAL(a
, env
))
76 elif types
._hash
_map
_Q
(ast
):
78 for k
in ast
.dct
.keys():
79 new_dct
[k
] = EVAL(ast
.dct
[k
], env
)
80 return MalHashMap(new_dct
)
82 return ast
# primitive value, return unchanged
86 #print("EVAL %s" % printer._pr_str(ast))
87 if not types
._list
_Q
(ast
):
88 return eval_ast(ast
, env
)
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
96 if isinstance(a0
, MalSym
):
102 a1
, a2
= ast
[1], ast
[2]
104 return env
.set(a1
, res
)
105 elif u
"let*" == a0sym
:
106 a1
, a2
= ast
[1], ast
[2]
108 for i
in range(0, len(a1
), 2):
109 let_env
.set(a1
[i
], EVAL(a1
[i
+1], let_env
))
111 env
= let_env
# Continue loop (TCO)
112 elif u
"quote" == a0sym
:
114 elif u
"quasiquote" == a0sym
:
115 ast
= quasiquote(ast
[1]) # Continue loop (TCO)
116 elif u
"defmacro!" == a0sym
:
117 func
= EVAL(ast
[2], env
)
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]
125 if isinstance(a20
, MalSym
):
126 if a20
.value
== u
"catch*":
128 return EVAL(a1
, env
);
129 except types
.MalException
as exc
:
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
);
142 eval_ast(ast
.slice2(1, len(ast
)-1), env
)
143 ast
= ast
[-1] # Continue loop (TCO)
145 a1
, a2
= ast
[1], ast
[2]
147 if cond
is nil
or cond
is false
:
148 if len(ast
) > 3: ast
= ast
[3] # Continue loop (TCO)
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
)
156 el
= eval_ast(ast
, env
)
158 if isinstance(f
, MalFunc
):
161 env
= f
.gen_env(el
.rest()) # Continue loop (TCO)
163 return f
.apply(el
.rest())
165 raise Exception("%s is not callable" % f
)
169 return printer
._pr
_str
(exp
)
172 class MalEval(MalFunc
):
173 def apply(self
, args
):
174 return self
.EvalFunc(args
[0], self
.env
)
176 def entry_point(argv
):
179 return PRINT(EVAL(READ(str), env
))
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
))
188 for a
in argv
[2:]: mal_args
.append(MalStr(unicode(a
)))
189 repl_env
.set(_symbol(u
'*ARGV*'), MalList(mal_args
))
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
)
201 REP('(load-file "' + argv
[1] + '")', repl_env
)
204 REP("(println (str \"Mal [\" *host-language* \"]\"))", repl_env
)
207 line
= mal_readline
.readline("user> ")
208 if line
== "": continue
209 print(REP(line
, repl_env
))
210 except EOFError as e
:
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
)
219 llop
.debug_print_traceback(lltype
.Void
)
221 print("".join(traceback
.format_exception(*sys
.exc_info())))
224 # _____ Define and setup target ___
228 # Just run entry_point if not RPython compilation
230 if not sys
.argv
[0].endswith('rpython'):
231 entry_point(sys
.argv
)