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);
82 void print_cons_as_sexpr(struct Cons *head)
86 struct Cons *cons = head;
89 print_expr_as_sexpr(cons->car);
91 while (cons->cdr.type == EXPR_CONS) {
92 cons = cons->cdr.cons;
94 print_expr_as_sexpr(cons->car);
97 if (cons->cdr.atom->type != ATOM_SYMBOL ||
98 strcmp("nil", cons->cdr.atom->sym) != 0) {
100 print_expr_as_sexpr(cons->cdr);
106 void print_expr_as_sexpr(struct Expr expr)
108 /* TODO(#296): print_expr_as_sexpr doesn't support lists */
111 print_atom_as_sexpr(expr.atom);
115 print_cons_as_sexpr(expr.cons);
123 void destroy_expr(struct Expr expr)
127 destroy_atom(expr.atom);
131 destroy_cons(expr.cons);
139 struct Cons *create_cons(Gc *gc, struct Expr car, struct Expr cdr)
141 struct Cons *cons = malloc(sizeof(struct Cons));
149 if (gc_add_expr(gc, cons_as_expr(cons)) < 0) {
157 void destroy_cons(struct Cons *cons)
162 struct Atom *create_number_atom(Gc *gc, long int num)
164 struct Atom *atom = malloc(sizeof(struct Atom));
168 atom->type = ATOM_NUMBER;
171 if (gc_add_expr(gc, atom_as_expr(atom)) < 0) {
179 struct Atom *create_string_atom(Gc *gc, const char *str, const char *str_end)
181 struct Atom *atom = malloc(sizeof(struct Atom));
187 atom->type = ATOM_STRING;
188 atom->str = string_duplicate(str, str_end);
190 if (atom->str == NULL) {
194 if (gc_add_expr(gc, atom_as_expr(atom)) < 0) {
202 if (atom->str != NULL) {
211 struct Atom *create_symbol_atom(Gc *gc, const char *sym, const char *sym_end)
213 struct Atom *atom = malloc(sizeof(struct Atom));
219 atom->type = ATOM_SYMBOL;
220 atom->sym = string_duplicate(sym, sym_end);
222 if (atom->sym == NULL) {
226 if (gc_add_expr(gc, atom_as_expr(atom)) < 0) {
234 if (atom->sym != NULL) {
243 struct Atom *create_native_atom(Gc *gc, NativeFunction fun)
245 struct Atom *atom = malloc(sizeof(struct Atom));
251 atom->type = ATOM_NATIVE;
254 if (gc_add_expr(gc, atom_as_expr(atom)) < 0) {
268 void destroy_atom(struct Atom *atom)
270 switch (atom->type) {