8 #include "script/expr.h"
12 struct Expr atom_as_expr(struct Atom *atom)
22 struct Expr cons_as_expr(struct Cons *cons)
32 struct Expr void_expr(void)
41 void print_atom_as_sexpr(struct Atom *atom)
47 printf("%s", atom->sym);
51 printf("%ld", atom->num);
55 printf("\"%s\"", atom->str);
64 void print_cons_as_sexpr(struct Cons *head)
68 struct Cons *cons = head;
71 print_expr_as_sexpr(cons->car);
73 while (cons->cdr.type == EXPR_CONS) {
74 cons = cons->cdr.cons;
76 print_expr_as_sexpr(cons->car);
79 if (cons->cdr.atom->type != ATOM_SYMBOL ||
80 strcmp("nil", cons->cdr.atom->sym) != 0) {
82 print_expr_as_sexpr(cons->cdr);
88 void print_expr_as_sexpr(struct Expr expr)
90 /* TODO(#296): print_expr_as_sexpr doesn't support lists */
93 print_atom_as_sexpr(expr.atom);
97 print_cons_as_sexpr(expr.cons);
105 void destroy_expr(struct Expr expr)
109 destroy_atom(expr.atom);
113 destroy_cons(expr.cons);
121 struct Cons *create_cons(Gc *gc, struct Expr car, struct Expr cdr)
123 struct Cons *cons = malloc(sizeof(struct Cons));
131 if (gc_add_expr(gc, cons_as_expr(cons)) < 0) {
139 void destroy_cons(struct Cons *cons)
144 struct Atom *create_number_atom(Gc *gc, long int num)
146 struct Atom *atom = malloc(sizeof(struct Atom));
150 atom->type = ATOM_NUMBER;
153 if (gc_add_expr(gc, atom_as_expr(atom)) < 0) {
161 struct Atom *create_string_atom(Gc *gc, const char *str, const char *str_end)
163 struct Atom *atom = malloc(sizeof(struct Atom));
169 atom->type = ATOM_STRING;
170 atom->str = string_duplicate(str, str_end);
172 if (atom->str == NULL) {
176 if (gc_add_expr(gc, atom_as_expr(atom)) < 0) {
184 if (atom->str != NULL) {
193 struct Atom *create_symbol_atom(Gc *gc, const char *sym, const char *sym_end)
195 struct Atom *atom = malloc(sizeof(struct Atom));
201 atom->type = ATOM_SYMBOL;
202 atom->sym = string_duplicate(sym, sym_end);
204 if (atom->sym == NULL) {
208 if (gc_add_expr(gc, atom_as_expr(atom)) < 0) {
216 if (atom->sym != NULL) {
225 struct Atom *create_native_atom(Gc *gc, NativeFunction fun, void *param)
227 struct Atom *atom = malloc(sizeof(struct Atom));
233 atom->type = ATOM_NATIVE;
234 atom->native.fun = fun;
235 atom->native.param = param;
237 if (gc_add_expr(gc, atom_as_expr(atom)) < 0) {
251 void destroy_atom(struct Atom *atom)
253 switch (atom->type) {