8 #include "script/expr.h"
11 static char *string_duplicate(const char *str,
14 if (str_end != NULL && str > str_end) {
18 const size_t n = str_end == NULL ? strlen(str) : (size_t) (str_end - str);
19 char *dup_str = malloc(sizeof(char) * (n + 1));
20 if (dup_str == NULL) {
24 memcpy(dup_str, str, n);
30 struct Expr atom_as_expr(struct Atom *atom)
40 struct Expr cons_as_expr(struct Cons *cons)
50 struct Expr void_expr(void)
59 void print_atom_as_sexpr(struct Atom *atom)
65 printf("%s", atom->sym);
69 printf("%ld", atom->num);
73 printf("\"%s\"", atom->str);
78 void print_cons_as_sexpr(struct Cons *head)
82 struct Cons *cons = head;
85 print_expr_as_sexpr(cons->car);
87 while (cons->cdr.type == EXPR_CONS) {
88 cons = cons->cdr.cons;
90 print_expr_as_sexpr(cons->car);
93 if (cons->cdr.atom->type != ATOM_SYMBOL ||
94 strcmp("nil", cons->cdr.atom->sym) != 0) {
96 print_expr_as_sexpr(cons->cdr);
102 void print_expr_as_sexpr(struct Expr expr)
104 /* TODO(#296): print_expr_as_sexpr doesn't support lists */
107 print_atom_as_sexpr(expr.atom);
111 print_cons_as_sexpr(expr.cons);
119 void destroy_expr(struct Expr expr)
123 destroy_atom(expr.atom);
127 destroy_cons(expr.cons);
135 struct Cons *create_cons(Gc *gc, struct Expr car, struct Expr cdr)
137 struct Cons *cons = malloc(sizeof(struct Cons));
145 if (gc_add_expr(gc, cons_as_expr(cons)) < 0) {
153 void destroy_cons(struct Cons *cons)
158 struct Atom *create_number_atom(Gc *gc, long int num)
160 struct Atom *atom = malloc(sizeof(struct Atom));
164 atom->type = ATOM_NUMBER;
167 if (gc_add_expr(gc, atom_as_expr(atom)) < 0) {
175 struct Atom *create_string_atom(Gc *gc, const char *str, const char *str_end)
177 struct Atom *atom = malloc(sizeof(struct Atom));
183 atom->type = ATOM_STRING;
184 atom->str = string_duplicate(str, str_end);
186 if (atom->str == NULL) {
190 if (gc_add_expr(gc, atom_as_expr(atom)) < 0) {
198 if (atom->str != NULL) {
207 struct Atom *create_symbol_atom(Gc *gc, const char *sym, const char *sym_end)
209 struct Atom *atom = malloc(sizeof(struct Atom));
215 atom->type = ATOM_SYMBOL;
216 atom->sym = string_duplicate(sym, sym_end);
218 if (atom->sym == NULL) {
222 if (gc_add_expr(gc, atom_as_expr(atom)) < 0) {
230 if (atom->sym != NULL) {
239 void destroy_atom(struct Atom *atom)
241 switch (atom->type) {