From e05ebeef2a47baf0730be824fc7ee32cb747822f Mon Sep 17 00:00:00 2001 From: Jacob Date: Sat, 28 Dec 2024 18:59:04 -0500 Subject: [PATCH] Added the ability to call infix function backend. --- src/grammar.y | 12 ++++++++++++ src/lexer.c | 24 +++++++++++++++++++++--- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/src/grammar.y b/src/grammar.y index a6d7d32..878bc37 100644 --- a/src/grammar.y +++ b/src/grammar.y @@ -21,6 +21,10 @@ %define parse.error verbose +%token LGROUP +%token RGROUP +%token SEP + %token CALL %token NUM @@ -42,6 +46,14 @@ input: exp: NUM { $$ = ast_init(AST_TYPE_NUM, ast_num_data_init($1)); } | NEG NUM { $$ = ast_init(AST_TYPE_NUM, ast_num_data_init(-$2)); } + + | CALL LGROUP NUM SEP NUM RGROUP { + AST** argv = calloc(2, sizeof(AST*)); + argv[0] = ast_init(AST_TYPE_NUM, ast_num_data_init($3)); + argv[1] = ast_init(AST_TYPE_NUM, ast_num_data_init($5)); + $$ = ast_init(AST_TYPE_CALL, ast_call_data_init($1, 2, argv)); + } + | NUM PLUS NUM { AST** argv = calloc(2, sizeof(AST*)); argv[0] = ast_init(AST_TYPE_NUM, ast_num_data_init($1)); diff --git a/src/lexer.c b/src/lexer.c index 9943181..579b155 100644 --- a/src/lexer.c +++ b/src/lexer.c @@ -3,6 +3,7 @@ #include #include +#include "include/dstr.h" #include "include/lexer.h" int acc_int(int c) { @@ -37,6 +38,17 @@ double acc_float(int c) { return value; } +char* acc_word(int c) { + Dstr* val = dstr_init(); + do { + dstr_appendch(val, *(inp - 1)); + inp++; + } while (isalpha(*inp)); + dstr_appendch(val, *(inp - 1)); + + return val->buf; +} + int yylex() { if (*inp == '\0') return YYEOF; @@ -52,17 +64,23 @@ int yylex() { return NUM; } + if (isalpha(c)) { + yylval.strval = acc_word(c); + return CALL; + } + switch (c) { case '+': return PLUS; case '\n': return NL; case '-': return NEG; case '*': return MULT; case '/': return DIV; - default: return CALL; + case '(': return LGROUP; + case ')': return RGROUP; + case ',': return SEP; + default: fprintf(stderr, "Unexpected character: %c\n", c); } - fprintf(stderr, "Unexpected character: %c\n", c); - return 0; } void yyerror(char const* s) { fprintf(stderr, "Parse error: %s\n", s); }