diff options
Diffstat (limited to 'ast.c')
-rw-r--r-- | ast.c | 127 |
1 files changed, 0 insertions, 127 deletions
@@ -1,127 +0,0 @@ -#include "ast.h" -#include <stdlib.h> -#include <stddef.h> -#include <stdio.h> -#include <assert.h> -#include <string.h> - -AstVec astvec_new() { - AstNode *vals = malloc(2 * sizeof(AstNode)); - return (AstVec){ - .len = 0, - .cap = 2, - vals = vals - }; -} - -void astvec_append(AstVec *v, AstNode val) { - if (v->len == v->cap) { - size_t newcap = v->cap * 2; - // printf("%ld to %ld\n", v->cap, newcap); - v->vals = realloc(v->vals, newcap * sizeof(AstNode)); - v->cap = newcap; - } - v->vals[v->len] = val; - v->len ++; -} - -void astnode_append(AstNode *l, AstNode val) { - // printf(" astnode_append: %d\n",l->ty); - assert(l->ty == AST_LIST || l->ty == AST_ARR); - astvec_append(&l->as.list, val); -} - -AstNode astnode_new_num(int n) { - return (AstNode){ - .ty = AST_NUM, - .as = { - .num = n, - }, - }; -} - -AstNode astnode_new_list() { - return (AstNode){ - .ty = AST_LIST, - .as = { - .list = astvec_new() - } - }; -} -AstNode astnode_new_arr() { - return (AstNode){ - .ty = AST_ARR, - .as = { - .list = astvec_new() - } - }; -} - -AstNode astnode_new_ident(const char *s) { - return (AstNode){ - .ty =AST_IDENT, - .as = { - .str = strdup(s) - } - }; -} - -AstNode astnode_new_string(const char *s) { - return (AstNode){ - .ty =AST_STRING, - .as = { - .str = strdup(s) - } - }; -} - -void astnode_free(AstNode *a) { - switch (a->ty) { - case AST_NUM: break; - case AST_IDENT: - case AST_STRING: - free(a->as.str); - break; - case AST_LIST: - case AST_ARR:; - AstVec *v = &a->as.list; - for (int i = 0; i < v->len; i++) { - astnode_free(&v->vals[i]); - } - free(v->vals); - v->vals = NULL; - v->len = 0; - v->cap = 0; - break; - } -} - -void astnode_disp(AstNode *a) { - switch (a->ty) { - case AST_NUM: - printf("%s:%d ",ast_ty_to_str(a->ty),a->as.num); - break; - case AST_LIST: - case AST_ARR:; - AstVec *v = &a->as.list; - printf("%s:(",ast_ty_to_str(a->ty)); - for (int i = 0; i < v->len; i++) { - astnode_disp(&v->vals[i]); - } - printf(")"); - break; - case AST_IDENT: - case AST_STRING: - printf("%s:%s ",ast_ty_to_str(a->ty), a->as.str); - break; - - } -} - -const char* ty_names[] = { - "list", "num", "ident", "string", "arr", -}; -const char *ast_ty_to_str(AstTy ty) { - return ty_names[ty]; -} - |