All: TCO let* and quasiquote.
[jackhill/mal.git] / c / step9_interop.c
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <unistd.h>
4
5 #include "types.h"
6 #include "readline.h"
7 #include "reader.h"
8 #include "core.h"
9 #include "interop.h"
10
11 // Declarations
12 MalVal *EVAL(MalVal *ast, Env *env);
13 MalVal *macroexpand(MalVal *ast, Env *env);
14
15 // read
16 MalVal *READ(char prompt[], char *str) {
17 char *line;
18 MalVal *ast;
19 if (str) {
20 line = str;
21 } else {
22 line = _readline(prompt);
23 if (!line) {
24 _error("EOF");
25 return NULL;
26 }
27 }
28 ast = read_str(line);
29 if (!str) { free(line); }
30 return ast;
31 }
32
33 // eval
34 int is_pair(MalVal *x) {
35 return _sequential_Q(x) && (_count(x) > 0);
36 }
37
38 MalVal *quasiquote(MalVal *ast) {
39 if (!is_pair(ast)) {
40 return _listX(2, malval_new_symbol("quote"), ast);
41 } else {
42 MalVal *a0 = _nth(ast, 0);
43 if ((a0->type & MAL_SYMBOL) &&
44 strcmp("unquote", a0->val.string) == 0) {
45 return _nth(ast, 1);
46 } else if (is_pair(a0)) {
47 MalVal *a00 = _nth(a0, 0);
48 if ((a00->type & MAL_SYMBOL) &&
49 strcmp("splice-unquote", a00->val.string) == 0) {
50 return _listX(3, malval_new_symbol("concat"),
51 _nth(a0, 1),
52 quasiquote(_rest(ast)));
53 }
54 }
55 return _listX(3, malval_new_symbol("cons"),
56 quasiquote(a0),
57 quasiquote(_rest(ast)));
58 }
59 }
60
61 int is_macro_call(MalVal *ast, Env *env) {
62 if (!ast || ast->type != MAL_LIST) { return 0; }
63 MalVal *a0 = _nth(ast, 0);
64 return (a0->type & MAL_SYMBOL) &&
65 env_find(env, a0->val.string) &&
66 env_get(env, a0->val.string)->ismacro;
67 }
68
69 MalVal *macroexpand(MalVal *ast, Env *env) {
70 if (!ast || mal_error) return NULL;
71 while (is_macro_call(ast, env)) {
72 MalVal *a0 = _nth(ast, 0);
73 MalVal *mac = env_get(env, a0->val.string);
74 // TODO: this is weird and limits it to 20. FIXME
75 ast = _apply(mac, _rest(ast));
76 }
77 return ast;
78 }
79
80 MalVal *eval_ast(MalVal *ast, Env *env) {
81 if (!ast || mal_error) return NULL;
82 if (ast->type == MAL_SYMBOL) {
83 //g_print("EVAL symbol: %s\n", ast->val.string);
84 return env_get(env, ast->val.string);
85 } else if ((ast->type == MAL_LIST) || (ast->type == MAL_VECTOR)) {
86 //g_print("EVAL sequential: %s\n", _pr_str(ast,1));
87 MalVal *el = _map2((MalVal *(*)(void*, void*))EVAL, ast, env);
88 if (!el || mal_error) return NULL;
89 el->type = ast->type;
90 return el;
91 } else if (ast->type == MAL_HASH_MAP) {
92 //g_print("EVAL hash_map: %s\n", _pr_str(ast,1));
93 GHashTableIter iter;
94 gpointer key, value;
95 MalVal *seq = malval_new_list(MAL_LIST,
96 g_array_sized_new(TRUE, TRUE, sizeof(MalVal*),
97 _count(ast)));
98 g_hash_table_iter_init (&iter, ast->val.hash_table);
99 while (g_hash_table_iter_next (&iter, &key, &value)) {
100 MalVal *kname = malval_new_string((char *)key);
101 g_array_append_val(seq->val.array, kname);
102 MalVal *new_val = EVAL((MalVal *)value, env);
103 g_array_append_val(seq->val.array, new_val);
104 }
105 return _hash_map(seq);
106 } else {
107 //g_print("EVAL scalar: %s\n", _pr_str(ast,1));
108 return ast;
109 }
110 }
111
112 MalVal *EVAL(MalVal *ast, Env *env) {
113 while (TRUE) {
114
115 if (!ast || mal_error) return NULL;
116 //g_print("EVAL: %s\n", _pr_str(ast,1));
117 if (ast->type != MAL_LIST) {
118 return eval_ast(ast, env);
119 }
120 if (!ast || mal_error) return NULL;
121
122 // apply list
123 //g_print("EVAL apply list: %s\n", _pr_str(ast,1));
124 ast = macroexpand(ast, env);
125 if (!ast || mal_error) return NULL;
126 if (ast->type != MAL_LIST) { return ast; }
127 if (_count(ast) == 0) { return ast; }
128
129 int i, len;
130 MalVal *a0 = _nth(ast, 0);
131 if ((a0->type & MAL_SYMBOL) &&
132 strcmp("def!", a0->val.string) == 0) {
133 //g_print("eval apply def!\n");
134 MalVal *a1 = _nth(ast, 1),
135 *a2 = _nth(ast, 2);
136 MalVal *res = EVAL(a2, env);
137 env_set(env, a1->val.string, res);
138 return res;
139 } else if ((a0->type & MAL_SYMBOL) &&
140 strcmp("let*", a0->val.string) == 0) {
141 //g_print("eval apply let*\n");
142 MalVal *a1 = _nth(ast, 1),
143 *a2 = _nth(ast, 2),
144 *key, *val;
145 assert_type(a1, MAL_LIST|MAL_VECTOR,
146 "let* bindings must be list or vector");
147 len = _count(a1);
148 assert((len % 2) == 0, "odd number of let* bindings forms");
149 Env *let_env = new_env(env, NULL, NULL);
150 for(i=0; i<len; i+=2) {
151 key = g_array_index(a1->val.array, MalVal*, i);
152 val = g_array_index(a1->val.array, MalVal*, i+1);
153 assert_type(key, MAL_SYMBOL, "let* bind to non-symbol");
154 env_set(let_env, key->val.string, EVAL(val, let_env));
155 }
156 ast = a2;
157 env = let_env;
158 // Continue loop
159 } else if ((a0->type & MAL_SYMBOL) &&
160 strcmp("quote", a0->val.string) == 0) {
161 //g_print("eval apply quote\n");
162 return _nth(ast, 1);
163 } else if ((a0->type & MAL_SYMBOL) &&
164 strcmp("quasiquote", a0->val.string) == 0) {
165 //g_print("eval apply quasiquote\n");
166 MalVal *a1 = _nth(ast, 1);
167 ast = quasiquote(a1);
168 // Continue loop
169 } else if ((a0->type & MAL_SYMBOL) &&
170 strcmp("defmacro!", a0->val.string) == 0) {
171 //g_print("eval apply defmacro!\n");
172 MalVal *a1 = _nth(ast, 1),
173 *a2 = _nth(ast, 2);
174 MalVal *res = EVAL(a2, env);
175 res->ismacro = TRUE;
176 env_set(env, a1->val.string, res);
177 return res;
178 } else if ((a0->type & MAL_SYMBOL) &&
179 strcmp("macroexpand", a0->val.string) == 0) {
180 //g_print("eval apply macroexpand\n");
181 MalVal *a1 = _nth(ast, 1);
182 return macroexpand(a1, env);
183 } else if ((a0->type & MAL_SYMBOL) &&
184 strcmp(".", a0->val.string) == 0) {
185 //g_print("eval apply .\n");
186 MalVal *el = eval_ast(_slice(ast, 1, _count(ast)), env);
187 return invoke_native(el);
188 } else if ((a0->type & MAL_SYMBOL) &&
189 strcmp("do", a0->val.string) == 0) {
190 //g_print("eval apply do\n");
191 eval_ast(_slice(ast, 1, _count(ast)-1), env);
192 ast = _last(ast);
193 // Continue loop
194 } else if ((a0->type & MAL_SYMBOL) &&
195 strcmp("if", a0->val.string) == 0) {
196 //g_print("eval apply if\n");
197 MalVal *a1 = _nth(ast, 1);
198 MalVal *cond = EVAL(a1, env);
199 if (!cond || mal_error) return NULL;
200 if (cond->type & (MAL_FALSE|MAL_NIL)) {
201 // eval false slot form
202 ast = _nth(ast, 3);
203 if (!ast) {
204 return &mal_nil;
205 }
206 } else {
207 // eval true slot form
208 ast = _nth(ast, 2);
209 }
210 // Continue loop
211 } else if ((a0->type & MAL_SYMBOL) &&
212 strcmp("fn*", a0->val.string) == 0) {
213 //g_print("eval apply fn*\n");
214 MalVal *mf = malval_new(MAL_FUNCTION_MAL, NULL);
215 mf->ismacro = FALSE;
216 mf->val.func.evaluator = EVAL;
217 mf->val.func.args = _nth(ast, 1);
218 mf->val.func.body = _nth(ast, 2);
219 mf->val.func.env = env;
220 return mf;
221 } else {
222 //g_print("eval apply\n");
223 MalVal *el = eval_ast(ast, env);
224 if (!el || mal_error) { return NULL; }
225 MalVal *f = _first(el),
226 *args = _rest(el);
227 assert_type(f, MAL_FUNCTION_C|MAL_FUNCTION_MAL,
228 "cannot apply '%s'", _pr_str(f,1));
229 if (f->type & MAL_FUNCTION_MAL) {
230 ast = f->val.func.body;
231 env = new_env(f->val.func.env, f->val.func.args, args);
232 // Continue loop
233 } else {
234 return _apply(f, args);
235 }
236 }
237
238 } // TCO while loop
239 }
240
241 // print
242 char *PRINT(MalVal *exp) {
243 if (mal_error) {
244 fprintf(stderr, "Error: %s\n", mal_error->val.string);
245 malval_free(mal_error);
246 mal_error = NULL;
247 return NULL;
248 }
249 return _pr_str(exp,1);
250 }
251
252 // repl
253
254 // read and eval
255 MalVal *RE(Env *env, char *prompt, char *str) {
256 MalVal *ast, *exp;
257 ast = READ(prompt, str);
258 if (!ast || mal_error) return NULL;
259 exp = EVAL(ast, env);
260 if (ast != exp) {
261 malval_free(ast); // Free input structure
262 }
263 return exp;
264 }
265
266 // Setup the initial REPL environment
267 Env *repl_env;
268
269 void init_repl_env(int argc, char *argv[]) {
270 repl_env = new_env(NULL, NULL, NULL);
271
272 // core.c: defined using C
273 int i;
274 for(i=0; i < (sizeof(core_ns) / sizeof(core_ns[0])); i++) {
275 env_set(repl_env, core_ns[i].name,
276 malval_new_function(core_ns[i].func, core_ns[i].arg_cnt));
277 }
278 MalVal *do_eval(MalVal *ast) { return EVAL(ast, repl_env); }
279 env_set(repl_env, "eval",
280 malval_new_function((void*(*)(void *))do_eval, 1));
281
282 MalVal *_argv = _listX(0);
283 for (i=2; i < argc; i++) {
284 MalVal *arg = malval_new_string(argv[i]);
285 g_array_append_val(_argv->val.array, arg);
286 }
287 env_set(repl_env, "*ARGV*", _argv);
288
289 // core.mal: defined using the language itself
290 RE(repl_env, "", "(def! not (fn* (a) (if a false true)))");
291 RE(repl_env, "",
292 "(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))");
293 RE(repl_env, "", "(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)))))))");
294 RE(repl_env, "", "(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))))))))");
295 }
296
297 int main(int argc, char *argv[])
298 {
299 MalVal *exp;
300 char *output;
301 char prompt[100];
302
303 // Set the initial prompt and environment
304 snprintf(prompt, sizeof(prompt), "user> ");
305 init_repl_env(argc, argv);
306
307 if (argc > 1) {
308 char *cmd = g_strdup_printf("(load-file \"%s\")", argv[1]);
309 RE(repl_env, "", cmd);
310 return 0;
311 }
312
313 // repl loop
314 for(;;) {
315 exp = RE(repl_env, prompt, NULL);
316 if (mal_error && strcmp("EOF", mal_error->val.string) == 0) {
317 return 0;
318 }
319 output = PRINT(exp);
320
321 if (output) {
322 g_print("%s\n", output);
323 free(output); // Free output string
324 }
325
326 //malval_free(exp); // Free evaluated expression
327 }
328 }