8 #include "script/expr.h"
10 static char *string_duplicate(const char *str,
13 if (str_end != NULL && str > str_end) {
17 const size_t n = str_end == NULL ? strlen(str) : (size_t) (str_end - str);
18 char *dup_str = malloc(sizeof(char) * (n + 1));
19 if (dup_str == NULL) {
23 memcpy(dup_str, str, n);
27 struct Expr atom_as_expr(struct Atom *atom)
37 struct Expr cons_as_expr(struct Cons *cons)
47 void print_atom_as_sexpr(struct Atom *atom)
53 printf("%s", atom->sym);
57 printf("%f", atom->num);
61 printf("\"%s\"", atom->str);
66 void print_cons_as_sexpr(struct Cons *head)
70 struct Cons *cons = head;
73 print_expr_as_sexpr(cons->car);
75 while (cons->cdr.type == EXPR_CONS) {
76 cons = cons->cdr.cons;
78 print_expr_as_sexpr(cons->car);
81 if (cons->cdr.atom->type != ATOM_SYMBOL ||
82 strcmp("nil", cons->cdr.atom->sym) != 0) {
84 print_expr_as_sexpr(cons->cdr);
90 void print_expr_as_sexpr(struct Expr expr)
92 /* TODO(#296): print_expr_as_sexpr doesn't support lists */
95 print_atom_as_sexpr(expr.atom);
99 print_cons_as_sexpr(expr.cons);
104 void destroy_expr(struct Expr expr)
108 destroy_atom(expr.atom);
112 destroy_cons(expr.cons);
117 struct Cons *create_cons(struct Expr car, struct Expr cdr)
119 struct Cons *cons = malloc(sizeof(struct Cons));
130 void destroy_cons(struct Cons *cons)
132 destroy_expr(cons->car);
133 destroy_expr(cons->cdr);
137 struct Atom *create_number_atom(float num)
139 struct Atom *atom = malloc(sizeof(struct Atom));
143 atom->type = ATOM_NUMBER;
148 struct Atom *create_string_atom(const char *str, const char *str_end)
150 struct Atom *atom = malloc(sizeof(struct Atom));
154 atom->type = ATOM_STRING;
155 atom->str = string_duplicate(str, str_end);
156 if (atom->str == NULL) {
164 struct Atom *create_symbol_atom(const char *sym, const char *sym_end)
166 struct Atom *atom = malloc(sizeof(struct Atom));
170 atom->type = ATOM_SYMBOL;
171 atom->sym = string_duplicate(sym, sym_end);
172 if (atom->sym == NULL) {
180 void destroy_atom(struct Atom *atom)
182 switch (atom->type) {