Change quasiquote algorithm
[jackhill/mal.git] / impls / rpython / step7_quote.py
1 import sys, traceback
2 import mal_readline
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)
7 import reader, printer
8 from env import Env
9 import core
10
11 # read
12 def READ(str):
13 return reader.read_str(str)
14
15 # eval
16 def qq_loop(elt, acc):
17 if types._list_Q(elt) and len(elt) == 2:
18 fst = elt[0]
19 if isinstance(fst, MalSym) and fst.value == u"splice-unquote":
20 return _list(_symbol(u"concat"), elt[1], acc)
21 return _list(_symbol(u"cons"), quasiquote(elt), acc)
22
23 def qq_foldr(seq):
24 acc = _list()
25 for elt in reversed(seq):
26 acc = qq_loop (elt, acc)
27 return acc
28
29 def quasiquote(ast):
30 if types._list_Q(ast):
31 if len(ast) == 2:
32 fst = ast[0]
33 if isinstance(fst, MalSym) and fst.value == u"unquote":
34 return ast[1]
35 return qq_foldr(ast.values)
36 elif types._vector_Q(ast):
37 return _list(_symbol(u"vec"), qq_foldr(ast.values))
38 elif types._symbol_Q(ast) or types._hash_map_Q(ast):
39 return _list(_symbol(u"quote"), ast)
40 else:
41 return ast
42
43 def eval_ast(ast, env):
44 if types._symbol_Q(ast):
45 assert isinstance(ast, MalSym)
46 return env.get(ast)
47 elif types._list_Q(ast):
48 res = []
49 for a in ast.values:
50 res.append(EVAL(a, env))
51 return MalList(res)
52 elif types._vector_Q(ast):
53 res = []
54 for a in ast.values:
55 res.append(EVAL(a, env))
56 return MalVector(res)
57 elif types._hash_map_Q(ast):
58 new_dct = {}
59 for k in ast.dct.keys():
60 new_dct[k] = EVAL(ast.dct[k], env)
61 return MalHashMap(new_dct)
62 else:
63 return ast # primitive value, return unchanged
64
65 def EVAL(ast, env):
66 while True:
67 #print("EVAL %s" % printer._pr_str(ast))
68 if not types._list_Q(ast):
69 return eval_ast(ast, env)
70
71 # apply list
72 if len(ast) == 0: return ast
73 a0 = ast[0]
74 if isinstance(a0, MalSym):
75 a0sym = a0.value
76 else:
77 a0sym = u"__<*fn*>__"
78
79 if u"def!" == a0sym:
80 a1, a2 = ast[1], ast[2]
81 res = EVAL(a2, env)
82 return env.set(a1, res)
83 elif u"let*" == a0sym:
84 a1, a2 = ast[1], ast[2]
85 let_env = Env(env)
86 for i in range(0, len(a1), 2):
87 let_env.set(a1[i], EVAL(a1[i+1], let_env))
88 ast = a2
89 env = let_env # Continue loop (TCO)
90 elif u"quote" == a0sym:
91 return ast[1]
92 elif u"quasiquoteexpand" == a0sym:
93 return quasiquote(ast[1])
94 elif u"quasiquote" == a0sym:
95 ast = quasiquote(ast[1]) # Continue loop (TCO)
96 elif u"do" == a0sym:
97 if len(ast) == 0:
98 return nil
99 elif len(ast) > 1:
100 eval_ast(ast.slice2(1, len(ast)-1), env)
101 ast = ast[-1] # Continue loop (TCO)
102 elif u"if" == a0sym:
103 a1, a2 = ast[1], ast[2]
104 cond = EVAL(a1, env)
105 if cond is nil or cond is false:
106 if len(ast) > 3: ast = ast[3] # Continue loop (TCO)
107 else: return nil
108 else:
109 ast = a2 # Continue loop (TCO)
110 elif u"fn*" == a0sym:
111 a1, a2 = ast[1], ast[2]
112 return MalFunc(None, a2, env, a1, EVAL)
113 else:
114 el = eval_ast(ast, env)
115 f = el.values[0]
116 if isinstance(f, MalFunc):
117 if f.ast:
118 ast = f.ast
119 env = f.gen_env(el.rest()) # Continue loop (TCO)
120 else:
121 return f.apply(el.rest())
122 else:
123 raise Exception("%s is not callable" % f)
124
125 # print
126 def PRINT(exp):
127 return printer._pr_str(exp)
128
129 # repl
130 class MalEval(MalFunc):
131 def apply(self, args):
132 return self.EvalFunc(args[0], self.env)
133
134 def entry_point(argv):
135 repl_env = Env()
136 def REP(str, env):
137 return PRINT(EVAL(READ(str), env))
138
139 # core.py: defined using python
140 for k, v in core.ns.items():
141 repl_env.set(_symbol(unicode(k)), MalFunc(v))
142 repl_env.set(types._symbol(u'eval'),
143 MalEval(None, env=repl_env, EvalFunc=EVAL))
144 mal_args = []
145 if len(argv) >= 3:
146 for a in argv[2:]: mal_args.append(MalStr(unicode(a)))
147 repl_env.set(_symbol(u'*ARGV*'), MalList(mal_args))
148
149 # core.mal: defined using the language itself
150 REP("(def! not (fn* (a) (if a false true)))", repl_env)
151 REP("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \"\nnil)\")))))", repl_env)
152
153 if len(argv) >= 2:
154 REP('(load-file "' + argv[1] + '")', repl_env)
155 return 0
156
157 while True:
158 try:
159 line = mal_readline.readline("user> ")
160 if line == "": continue
161 print(REP(line, repl_env))
162 except EOFError as e:
163 break
164 except reader.Blank:
165 continue
166 except types.MalException as e:
167 print(u"Error: %s" % printer._pr_str(e.object, False))
168 except Exception as e:
169 print("Error: %s" % e)
170 #print("".join(traceback.format_exception(*sys.exc_info())))
171 return 0
172
173 # _____ Define and setup target ___
174 def target(*args):
175 return entry_point
176
177 # Just run entry_point if not RPython compilation
178 import sys
179 if not sys.argv[0].endswith('rpython'):
180 entry_point(sys.argv)