From 681e005a6833e2fa02663d247e3428ba213952bb Mon Sep 17 00:00:00 2001 From: Jacob Date: Sat, 11 Jan 2025 10:53:49 -0500 Subject: [PATCH] Generalized arithmetic functions to arbitrary arguments. --- src/exec.c | 57 +++++++++++++++++++++++++++++++++-------------------- src/lexer.c | 6 +++--- 2 files changed, 39 insertions(+), 24 deletions(-) diff --git a/src/exec.c b/src/exec.c index 9335ca5..d467ff6 100644 --- a/src/exec.c +++ b/src/exec.c @@ -1,3 +1,4 @@ +#include #include #include @@ -21,32 +22,46 @@ ASTNumData exec_call(AST* ast) { log_dbg("Started call execution."); fflush(stdout); ASTCallData* calldata = (ASTCallData*)ast->data; - if (!strcmp(calldata->to, "sum") && calldata->argc == 2) { - ASTNumData n1 = exec_expr(calldata->argv[0]); - ASTNumData n2 = exec_expr(calldata->argv[1]); + if (!strcmp(calldata->to, "sum")) { + double total = 0; - return n1 + n2; - } else if (!strcmp(calldata->to, "sub") && calldata->argc == 2) { - ASTNumData n1 = exec_expr(calldata->argv[0]); - ASTNumData n2 = exec_expr(calldata->argv[1]); + for ( + size_t i = 0; + i < calldata->argc; + total += exec_expr(calldata->argv[i++]) + ); - return n1 - n2; - } else if (!strcmp(calldata->to, "mul") && calldata->argc == 2) { - ASTNumData n1 = exec_expr(calldata->argv[0]); - ASTNumData n2 = exec_expr(calldata->argv[1]); + return total; + } else if (!strcmp(calldata->to, "sub")) { + double total = 0; - return n1 * n2; - } else if (!strcmp(calldata->to, "div") && calldata->argc == 2) { - ASTNumData n1 = exec_expr(calldata->argv[0]); - ASTNumData n2 = exec_expr(calldata->argv[1]); + for ( + size_t i = 0; + i < calldata->argc; + total -= exec_expr(calldata->argv[i++]) + ); - return n1 / n2; - } else if (!strcmp(calldata->to, "sum") && calldata->argc == 3) { - ASTNumData n1 = exec_expr(calldata->argv[0]); - ASTNumData n2 = exec_expr(calldata->argv[1]); - ASTNumData n3 = exec_expr(calldata->argv[2]); + return total; + } else if (!strcmp(calldata->to, "mul")) { + double total = 1; - return n1 + n2 + n3; + for ( + size_t i = 0; + i < calldata->argc; + total *= exec_expr(calldata->argv[i++]) + ); + + return total; + } else if (!strcmp(calldata->to, "div")) { + double total = 1; + + for ( + size_t i = 0; + i < calldata->argc; + total /= exec_expr(calldata->argv[i++]) + ); + + return total; } return -1000; } diff --git a/src/lexer.c b/src/lexer.c index 83be8da..3f3f065 100644 --- a/src/lexer.c +++ b/src/lexer.c @@ -11,9 +11,9 @@ ArgArr* argarr_init() { ArgArr* argarr = malloc(sizeof(ArgArr)); - argarr->sz = ARLN; + argarr->sz = ARLN * sizeof(AST*); argarr->ln = 0; - argarr->buf = malloc(ARLN); + argarr->buf = malloc(argarr->sz); return argarr; } @@ -24,7 +24,7 @@ void argarr_destroy(ArgArr* argarr) { } void argarr_add(ArgArr* argarr, AST* arg) { - if (argarr->ln + 1 > argarr->sz) { + if ((argarr->ln + 1) * argarr->sz > argarr->sz) { argarr->sz *= 2; argarr->buf = realloc(argarr->buf, argarr->sz); log_dbgf(