From 7dcbac1a3ce1c6fd87d79a0b76cdb20c8f090184 Mon Sep 17 00:00:00 2001 From: ubq323 Date: Thu, 3 Aug 2023 21:08:03 +0100 Subject: add strings to parser --- ast.c | 21 ++++++++++++++------- ast.h | 3 ++- com.c | 4 ++++ g.peg | 2 ++ "test.b\303\276" | 5 +---- 5 files changed, 23 insertions(+), 12 deletions(-) diff --git a/ast.c b/ast.c index 2443283..d0a7ffe 100644 --- a/ast.c +++ b/ast.c @@ -57,6 +57,15 @@ AstNode astnode_new_symbol(char *s) { }; } +AstNode astnode_new_string(char *s) { + return (AstNode){ + .ty =AST_STRING, + .as = { + .str = s + } + }; +} + void astnode_disp(AstNode *a) { switch (a->ty) { case AST_NUM: @@ -70,20 +79,18 @@ void astnode_disp(AstNode *a) { } printf(")"); break; - case AST_SYMBOL:; + case AST_SYMBOL: + case AST_STRING: printf("%s:%s ",ast_ty_to_str(a->ty), a->as.str); break; + } } const char* ty_names[] = { - "list", "num", "symbol" + "list", "num", "symbol", "string" }; const char *ast_ty_to_str(AstTy ty) { - if (ty >= AST_TY_LAST || ty < 0) { - return "???"; - } else { - return ty_names[ty]; - } + return ty_names[ty]; } diff --git a/ast.h b/ast.h index b3e9d75..b1569c4 100644 --- a/ast.h +++ b/ast.h @@ -8,8 +8,8 @@ typedef enum { AST_LIST, AST_NUM, AST_SYMBOL, + AST_STRING, } AstTy; -#define AST_TY_LAST AST_SYMBOL+1 struct _astnode; typedef struct _astnode AstNode; @@ -37,6 +37,7 @@ void astnode_append(AstNode *l, AstNode val); AstNode astnode_new_num(int n); AstNode astnode_new_list(); AstNode astnode_new_symbol(char *s); +AstNode astnode_new_string(char *s); void astnode_disp(AstNode *a); diff --git a/com.c b/com.c index dc458f9..2c73d67 100644 --- a/com.c +++ b/com.c @@ -11,6 +11,10 @@ static void compile_node(Chunk *ch, AstNode a) { printf("can't compile symbol\n"); exit(1); break; + case AST_STRING: + printf("can't compile strings yet\n"); + exit(1); + break; case AST_NUM: chunk_wbc(ch, OP_LOADK); chunk_wbc(ch, chunk_wconst(ch, VAL_NUM(a.as.num))); diff --git a/g.peg b/g.peg index 3c75ab9..172938f 100644 --- a/g.peg +++ b/g.peg @@ -25,6 +25,7 @@ expr <- l:list { $$ = l; } / n:number { $$ = n; } / s:symbol { $$ = s; } + / t:string { $$ = t; } list <- { $$ = astnode_new_list(); } '(' @@ -34,6 +35,7 @@ list <- { $$ = astnode_new_list(); } number <- < [0-9]+ > (! ident_char) _ { $$ = astnode_new_num(atoi($1)); } symbol <- < ident_char+ > _ { $$ = astnode_new_symbol(strdup($1)); } +string <- '"' < [^"]+ > '"' { $$ = astnode_new_string(strdup($1)); } ident_char <- [-_a-zA-Z'+*0-9] _ <- [ \t\n]* diff --git "a/test.b\303\276" "b/test.b\303\276" index 78159de..f79fc6b 100644 --- "a/test.b\303\276" +++ "b/test.b\303\276" @@ -1,4 +1 @@ -(do - (set a 4) - (set b 5) - (print (+ a b))) +(+ 6 (* 9 25)) -- cgit v1.2.3