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