All: move some fns to core. Major cleanup.
[jackhill/mal.git] / python / stepA_more.py
1 import sys, traceback
2 import mal_readline
3 import mal_types as types
4 import reader, printer
5 from env import Env
6 import core
7
8 # read
9 def READ(str):
10 return reader.read_str(str)
11
12 # eval
13 def is_pair(x):
14 return types._sequential_Q(x) and len(x) > 0
15
16 def quasiquote(ast):
17 if not is_pair(ast):
18 return types._list(types._symbol("quote"),
19 ast)
20 elif ast[0] == 'unquote':
21 return ast[1]
22 elif is_pair(ast[0]) and ast[0][0] == 'splice-unquote':
23 return types._list(types._symbol("concat"),
24 ast[0][1],
25 quasiquote(ast[1:]))
26 else:
27 return types._list(types._symbol("cons"),
28 quasiquote(ast[0]),
29 quasiquote(ast[1:]))
30
31 def is_macro_call(ast, env):
32 return (types._list_Q(ast) and
33 types._symbol_Q(ast[0]) and
34 env.find(ast[0]) and
35 hasattr(env.get(ast[0]), '_ismacro_'))
36
37 def macroexpand(ast, env):
38 while is_macro_call(ast, env):
39 mac = env.get(ast[0])
40 ast = macroexpand(mac(*ast[1:]), env)
41 return ast
42
43 def eval_ast(ast, env):
44 if types._symbol_Q(ast):
45 return env.get(ast)
46 elif types._list_Q(ast):
47 return types._list(*map(lambda a: EVAL(a, env), ast))
48 elif types._vector_Q(ast):
49 return types._vector(*map(lambda a: EVAL(a, env), ast))
50 elif types._hash_map_Q(ast):
51 keyvals = []
52 for k in ast.keys():
53 keyvals.append(EVAL(k, env))
54 keyvals.append(EVAL(ast[k], env))
55 return types._hash_map(*keyvals)
56 else:
57 return ast # primitive value, return unchanged
58
59 def EVAL(ast, env):
60 while True:
61 #print("EVAL %s" % ast)
62 if not types._list_Q(ast):
63 return eval_ast(ast, env)
64
65 # apply list
66 ast = macroexpand(ast, env)
67 if not types._list_Q(ast): return ast
68 if len(ast) == 0: return ast
69 a0 = ast[0]
70
71 if "def!" == a0:
72 a1, a2 = ast[1], ast[2]
73 res = EVAL(a2, env)
74 return env.set(a1, res)
75 elif "let*" == a0:
76 a1, a2 = ast[1], ast[2]
77 let_env = Env(env)
78 for i in range(0, len(a1), 2):
79 let_env.set(a1[i], EVAL(a1[i+1], let_env))
80 return EVAL(a2, let_env)
81 elif "quote" == a0:
82 return ast[1]
83 elif "quasiquote" == a0:
84 return EVAL(quasiquote(ast[1]), env)
85 elif 'defmacro!' == a0:
86 func = EVAL(ast[2], env)
87 func._ismacro_ = True
88 return env.set(ast[1], func)
89 elif 'macroexpand' == a0:
90 return macroexpand(ast[1], env)
91 elif "py!*" == a0:
92 if sys.version_info[0] >= 3:
93 exec(compile(ast[1], '', 'single'), globals())
94 else:
95 exec(compile(ast[1], '', 'single') in globals())
96 return None
97 elif "py*" == a0:
98 return eval(ast[1])
99 elif "." == a0:
100 el = eval_ast(ast[2:], env)
101 f = eval(ast[1])
102 return f(*el)
103 elif "try*" == a0:
104 a1, a2 = ast[1], ast[2]
105 if a2[0] == "catch*":
106 try:
107 return EVAL(a1, env);
108 except Exception as exc:
109 exc = exc.args[0]
110 catch_env = Env(env, [a2[1]], [exc])
111 return EVAL(a2[2], catch_env)
112 else:
113 return EVAL(a1, env);
114 elif "do" == a0:
115 eval_ast(ast[1:-1], env)
116 ast = ast[-1]
117 # Continue loop (TCO)
118 elif "if" == a0:
119 a1, a2 = ast[1], ast[2]
120 cond = EVAL(a1, env)
121 if cond is None or cond is False:
122 if len(ast) > 3: ast = ast[3]
123 else: ast = None
124 else:
125 ast = a2
126 # Continue loop (TCO)
127 elif "fn*" == a0:
128 a1, a2 = ast[1], ast[2]
129 return types._function(EVAL, Env, a2, env, a1)
130 else:
131 el = eval_ast(ast, env)
132 f = el[0]
133 if hasattr(f, '__ast__'):
134 ast = f.__ast__
135 env = f.__gen_env__(el[1:])
136 else:
137 return f(*el[1:])
138
139 # print
140 def PRINT(exp):
141 return printer._pr_str(exp)
142
143 # repl
144 repl_env = Env()
145 def REP(str):
146 return PRINT(EVAL(READ(str), repl_env))
147
148 # core.py: defined using python
149 for k, v in core.ns.items(): repl_env.set(k, v)
150 repl_env.set('eval', lambda ast: EVAL(ast, repl_env))
151
152 # core.mal: defined using the language itself
153 REP("(def! not (fn* (a) (if a false true)))")
154 REP("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))")
155 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)))))))")
156 REP("(defmacro! or (fn* (& xs) (if (empty? xs) nil (if (= 1 (count xs)) (first xs) `(let* (or_FIXME ~(first xs)) (if or_FIXME or_FIXME (or ~@(rest xs))))))))")
157
158 if len(sys.argv) >= 2:
159 REP('(load-file "' + sys.argv[1] + '")')
160 else:
161 while True:
162 try:
163 line = mal_readline.readline("user> ")
164 if line == None: break
165 if line == "": continue
166 print(REP(line))
167 except reader.Blank: continue
168 except Exception as e:
169 print("".join(traceback.format_exception(*sys.exc_info())))