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 *cons)
71 print_expr_as_sexpr(cons->car);
73 print_expr_as_sexpr(cons->cdr);
77 void print_expr_as_sexpr(struct Expr expr)
79 /* TODO(#296): print_expr_as_sexpr doesn't support lists */
82 print_atom_as_sexpr(expr.atom);
86 print_cons_as_sexpr(expr.cons);
91 void destroy_expr(struct Expr expr)
95 destroy_atom(expr.atom);
99 destroy_cons(expr.cons);
104 struct Cons *create_cons(struct Expr car, struct Expr cdr)
106 struct Cons *cons = malloc(sizeof(struct Cons));
117 void destroy_cons(struct Cons *cons)
119 destroy_expr(cons->car);
120 destroy_expr(cons->cdr);
124 struct Atom *create_number_atom(float num)
126 struct Atom *atom = malloc(sizeof(struct Atom));
130 atom->type = ATOM_NUMBER;
135 struct Atom *create_string_atom(const char *str, const char *str_end)
137 struct Atom *atom = malloc(sizeof(struct Atom));
141 atom->type = ATOM_STRING;
142 atom->str = string_duplicate(str, str_end);
143 if (atom->str == NULL) {
151 struct Atom *create_symbol_atom(const char *sym, const char *sym_end)
153 struct Atom *atom = malloc(sizeof(struct Atom));
157 atom->type = ATOM_SYMBOL;
158 atom->sym = string_duplicate(sym, sym_end);
159 if (atom->sym == NULL) {
167 void destroy_atom(struct Atom *atom)
169 switch (atom->type) {