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 def entry_point(argv
):
100 return PRINT(EVAL(READ(str), env
))
102 # core.py: defined using python
103 for k
, v
in core
.ns
.items():
104 repl_env
.set(_symbol(unicode(k
)), MalFunc(v
))
106 # core.mal: defined using the language itself
107 REP("(def! not (fn* (a) (if a false true)))", repl_env
)
111 line
= mal_readline
.readline("user> ")
112 if line
== "": continue
113 print(REP(line
, repl_env
))
114 except EOFError as e
:
118 except types
.MalException
as e
:
119 print(u
"Error: %s" % printer
._pr
_str
(e
.object, False))
120 except Exception as e
:
121 print("Error: %s" % e
)
122 #print("".join(traceback.format_exception(*sys.exc_info())))
125 # _____ Define and setup target ___
129 # Just run entry_point if not RPython compilation
131 if not sys
.argv
[0].endswith('rpython'):
132 entry_point(sys
.argv
)