#include #include #include #include #include #include #include #include "node.h" void node_print(struct node *n, FILE *fp) { switch (n->ntype) { case N_EXPR: fprintf(fp, "\e[31m%s\e[0m", n->expr.func); break; case N_IDENT: fputs(n->ident.name, fp); break; case N_NUM: fprintf(fp, "%"PRId64, n->num.num); break; case N_STRING: fprintf(fp, "\"%s\"", n->string.data); break; default: fputs("", fp); } } struct node_dump_info { FILE *fp; int indent; }; int __node_dump_pre(struct node *n, void *_info) { struct node_dump_info *info = _info; struct node *arg; if (n->prev) fputc(' ', info->fp); if (node_is_block(n->up)) { info->indent += 4; fprintf(info->fp, "\n%*s", info->indent, ""); } if (n->ntype == N_EXPR) fputc('(', info->fp); node_print(n, info->fp); if ((n->ntype == N_EXPR) && n->expr.args) fputc(' ', info->fp); return 0; } int __node_dump_post(struct node *n, void *_info) { struct node_dump_info *info = _info; struct node *c; if (node_is_block(n)) fprintf(info->fp, "\n%*s", info->indent, ""); if (n->ntype == N_EXPR) fputc(')', info->fp); if (node_is_block(n->up)) info->indent -= 4; return 0; } void node_dump(struct node *n, FILE *fp) { struct node_dump_info info = { .fp = fp, }; node_walk(n, __node_dump_pre, __node_dump_post, &info); fputc('\n', fp); } int node_walk(struct node *n, int (*pre)(struct node *, void *), int (*post)(struct node *, void *), void *ctx) { int err = 0; if (pre && (err = pre(n, ctx))) return err; if (n->ntype == N_EXPR) { struct node *arg; node_expr_foreach(n, arg) { err = node_walk(arg, pre, post, ctx); if (err) return err; } } if (post && (err = post(n, ctx))) return err; return 0; } int node_replace(struct node *n, struct node *new) { new->up = n->up; if (n->prev) { new->prev = n->prev; n->prev->next = new; } if (n->next) { new->next = n->next; n->next->prev = new; } /* TODO: don't leak memory */ return 0; } /* constructors */ static struct node *node_new(enum ntype ntype) { struct node *n; n = calloc(1, sizeof(*n)); assert(n); n->ntype = ntype; return n; } struct node *node_string(char *data) { struct node *n = node_new(N_STRING); n->string.data = data; return n; } struct node *node_num(int64_t num) { struct node *n = node_new(N_NUM); n->num.num = num; return n; } struct node *node_ident(char *name) { struct node *n = node_new(N_IDENT); n->ident.name = name; return n; } struct node *node_append(struct node *n, struct node *arg) { struct node *last; assert(n->ntype == N_EXPR); arg->up = n; if (!n->expr.args) { n->expr.args = arg; return n; } for (last = n->expr.args; last->next; last = last->next); last->next = arg; arg->prev = last; return n; } struct node *node_expr(char *func, ...) { va_list ap; struct node *n, *arg; n = node_new(N_EXPR); n->expr.func = func; va_start(ap, func); while ((arg = va_arg(ap, struct node *))) node_append(n, arg); va_end(ap); return n; }