Add first lisp bits
[fw/altos] / src / lisp / ao_lisp_cons.c
1 /*
2  * Copyright © 2016 Keith Packard <keithp@keithp.com>
3  *
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.
8  *
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.
13  */
14
15 #include "ao_lisp.h"
16
17 static void cons_mark(void *addr)
18 {
19         struct ao_lisp_cons     *cons = addr;
20
21         for (;;) {
22                 ao_lisp_poly_mark(cons->car);
23                 cons = cons->cdr;
24                 if (!cons)
25                         break;
26                 if (ao_lisp_mark_memory(cons, sizeof (struct ao_lisp_cons)))
27                         break;
28         }
29 }
30
31 static int cons_size(void *addr)
32 {
33         (void) addr;
34         return sizeof (struct ao_lisp_cons);
35 }
36
37 static void cons_move(void *addr)
38 {
39         struct ao_lisp_cons     *cons = addr;
40
41         for (;;) {
42                 struct ao_lisp_cons     *cdr;
43
44                 cons->car = ao_lisp_poly_move(cons->car);
45                 cdr = ao_lisp_move_memory(cons->cdr, sizeof (struct ao_lisp_cons));
46                 if (!cdr)
47                         break;
48                 cons->cdr = cdr;
49                 cons = cdr;
50         }
51 }
52
53 const struct ao_lisp_mem_type ao_lisp_cons_type = {
54         .mark = cons_mark,
55         .size = cons_size,
56         .move = cons_move,
57 };
58
59 struct ao_lisp_cons *
60 ao_lisp_cons(ao_lisp_poly car, struct ao_lisp_cons *cdr)
61 {
62         struct ao_lisp_cons     *cons = ao_lisp_alloc(sizeof (struct ao_lisp_cons));
63         if (!cons)
64                 return NULL;
65         cons->car = car;
66         cons->cdr = cdr;
67         return cons;
68 }
69
70 void
71 ao_lisp_cons_print(struct ao_lisp_cons *cons)
72 {
73         int     first = 1;
74         printf("(");
75         while (cons) {
76                 if (!first)
77                         printf(" ");
78                 fflush(stdout);
79                 ao_lisp_poly_print(cons->car);
80                 cons = cons->cdr;
81                 first = 0;
82         }
83         printf(")");
84 }