3 import mal_types
as types
4 from mal_types
import (MalSym
, MalInt
, MalStr
,
5 nil
, true
, false
, _symbol
, _keywordu
,
6 MalList
, _list
, MalVector
, MalHashMap
, MalFunc
)
13 return reader
.read_str(str)
16 def eval_ast(ast
, env
):
17 if types
._symbol
_Q
(ast
):
18 assert isinstance(ast
, MalSym
)
20 elif types
._list
_Q
(ast
):
23 res
.append(EVAL(a
, env
))
25 elif types
._vector
_Q
(ast
):
28 res
.append(EVAL(a
, env
))
30 elif types
._hash
_map
_Q
(ast
):
32 for k
in ast
.dct
.keys():
33 new_dct
[k
] = EVAL(ast
.dct
[k
], env
)
34 return MalHashMap(new_dct
)
36 return ast
# primitive value, return unchanged
40 #print("EVAL %s" % printer._pr_str(ast))
41 if not types
._list
_Q
(ast
):
42 return eval_ast(ast
, env
)
45 if len(ast
) == 0: return ast
47 if isinstance(a0
, MalSym
):
53 a1
, a2
= ast
[1], ast
[2]
55 return env
.set(a1
, res
)
56 elif u
"let*" == a0sym
:
57 a1
, a2
= ast
[1], ast
[2]
59 for i
in range(0, len(a1
), 2):
60 let_env
.set(a1
[i
], EVAL(a1
[i
+1], let_env
))
62 env
= let_env
# Continue loop (TCO)
67 eval_ast(ast
.slice2(1, len(ast
)-1), env
)
68 ast
= ast
[-1] # Continue loop (TCO)
70 a1
, a2
= ast
[1], ast
[2]
72 if cond
is nil
or cond
is false
:
73 if len(ast
) > 3: ast
= ast
[3] # Continue loop (TCO)
76 ast
= a2
# Continue loop (TCO)
78 a1
, a2
= ast
[1], ast
[2]
79 return MalFunc(None, a2
, env
, a1
, EVAL
)
81 el
= eval_ast(ast
, env
)
83 if isinstance(f
, MalFunc
):
86 env
= f
.gen_env(el
.rest()) # Continue loop (TCO)
88 return f
.apply(el
.rest())
90 raise Exception("%s is not callable" % f
)
94 return printer
._pr
_str
(exp
)
97 class MalEval(MalFunc
):
98 def apply(self
, args
):
99 return self
.EvalFunc(args
[0], self
.env
)
101 def entry_point(argv
):
104 return PRINT(EVAL(READ(str), env
))
106 # core.py: defined using python
107 for k
, v
in core
.ns
.items():
108 repl_env
.set(_symbol(unicode(k
)), MalFunc(v
))
109 repl_env
.set(types
._symbol
(u
'eval'),
110 MalEval(None, env
=repl_env
, EvalFunc
=EVAL
))
113 for a
in argv
[2:]: mal_args
.append(MalStr(unicode(a
)))
114 repl_env
.set(_symbol(u
'*ARGV*'), MalList(mal_args
))
116 # core.mal: defined using the language itself
117 REP("(def! not (fn* (a) (if a false true)))", repl_env
)
118 REP("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))", repl_env
)
121 REP('(load-file "' + argv
[1] + '")', repl_env
)
126 line
= mal_readline
.readline("user> ")
127 if line
== "": continue
128 print(REP(line
, repl_env
))
129 except EOFError as e
:
133 except types
.MalException
as e
:
134 print(u
"Error: %s" % printer
._pr
_str
(e
.object, False))
135 except Exception as e
:
136 print("Error: %s" % e
)
137 #print("".join(traceback.format_exception(*sys.exc_info())))
140 # _____ Define and setup target ___
144 # Just run entry_point if not RPython compilation
146 if not sys
.argv
[0].endswith('rpython'):
147 entry_point(sys
.argv
)