2 * Copyright © 2016 Keith Packard <keithp@keithp.com>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
20 * Plan: walk actuals, construct formals
22 * stack > save > actuals > actual_1
24 * formals . > actual_2
27 static struct ao_lisp_cons *stack;
28 static struct ao_lisp_cons *actuals;
29 static struct ao_lisp_cons *formals;
30 static struct ao_lisp_cons *formals_tail;
31 static uint8_t been_here;
34 #define DBG(...) printf(__VA_ARGS__)
35 #define DBG_CONS(a) ao_lisp_cons_print(a)
36 #define DBG_POLY(a) ao_lisp_poly_print(a)
44 ao_lisp_eval(ao_lisp_poly v)
46 struct ao_lisp_cons *formal;
51 ao_lisp_root_add(&ao_lisp_cons_type, &stack);
52 ao_lisp_root_add(&ao_lisp_cons_type, &actuals);
53 ao_lisp_root_add(&ao_lisp_cons_type, &formals);
54 ao_lisp_root_add(&ao_lisp_cons_type, &formals_tail);
62 /* Build stack frames for each list */
63 while (ao_lisp_poly_type(v) == AO_LISP_CONS) {
67 /* Push existing frame on the stack */
69 struct ao_lisp_cons *frame;
71 frame = ao_lisp_cons(ao_lisp_cons_poly(actuals), formals);
72 stack = ao_lisp_cons(ao_lisp_cons_poly(frame), stack);
74 actuals = ao_lisp_poly_cons(v);
79 DBG("start: stack"); DBG_CONS(stack); DBG("\n");
80 DBG("start: actuals"); DBG_CONS(actuals); DBG("\n");
81 DBG("start: formals"); DBG_CONS(formals); DBG("\n");
84 /* Evaluate primitive types */
86 switch (ao_lisp_poly_type(v)) {
91 v = ao_lisp_poly_atom(v)->val;
96 DBG("add formal: "); DBG_POLY(v); DBG("\n");
98 formal = ao_lisp_cons(v, NULL);
100 formals_tail->cdr = formal;
103 formals_tail = formal;
104 actuals = actuals->cdr;
113 /* Process all of the arguments */
116 DBG ("actual: "); DBG_POLY(v); DBG("\n");
122 /* Evaluate the resulting list */
123 if (ao_lisp_poly_type(v) == AO_LISP_BUILTIN) {
124 struct ao_lisp_builtin *b = ao_lisp_poly_builtin(v);
126 v = b->func(formals->cdr);
134 DBG ("invalid eval\n");
138 struct ao_lisp_cons *frame;
140 /* Pop the previous frame off the stack */
141 frame = ao_lisp_poly_cons(stack->car);
142 actuals = ao_lisp_poly_cons(frame->car);
143 formals = frame->cdr;
145 /* Recompute the tail of the formals list */
146 for (formal = formals; formal->cdr != NULL; formal = formal->cdr);
147 formals_tail = formal;
150 DBG("stack pop: stack"); DBG_CONS(stack); DBG("\n");
151 DBG("stack pop: actuals"); DBG_CONS(actuals); DBG("\n");
152 DBG("stack pop: formals"); DBG_CONS(formals); DBG("\n");