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)
81 print_atom_as_sexpr(expr.atom);
85 print_cons_as_sexpr(expr.cons);
90 void destroy_expr(struct Expr expr)
94 destroy_atom(expr.atom);
98 destroy_cons(expr.cons);
103 struct Cons *create_cons(struct Expr car, struct Expr cdr)
105 struct Cons *cons = malloc(sizeof(struct Cons));
116 void destroy_cons(struct Cons *cons)
118 destroy_expr(cons->car);
119 destroy_expr(cons->cdr);
123 struct Atom *create_number_atom(float num)
125 struct Atom *atom = malloc(sizeof(struct Atom));
129 atom->type = ATOM_NUMBER;
134 struct Atom *create_string_atom(const char *str, const char *str_end)
136 struct Atom *atom = malloc(sizeof(struct Atom));
140 atom->type = ATOM_STRING;
141 atom->str = string_duplicate(str, str_end);
142 if (atom->str == NULL) {
150 struct Atom *create_symbol_atom(const char *sym, const char *sym_end)
152 struct Atom *atom = malloc(sizeof(struct Atom));
156 atom->type = ATOM_SYMBOL;
157 atom->sym = string_duplicate(sym, sym_end);
158 if (atom->sym == NULL) {
166 void destroy_atom(struct Atom *atom)
168 switch (atom->type) {