From 38c6a9113c1070da550f9f32e5832bbcbdea43f5 Mon Sep 17 00:00:00 2001 From: Jacob Signorovitch Date: Tue, 25 Feb 2025 08:04:43 -0500 Subject: [PATCH] Added sub to the builtin functions. --- src/builtin.c | 24 ++++++++++++++++++++++++ src/exec.c | 6 +++++- src/include/builtin.h | 7 ++++++- 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/src/builtin.c b/src/builtin.c index e7d7dbe..0ce39d3 100644 --- a/src/builtin.c +++ b/src/builtin.c @@ -21,3 +21,27 @@ AST* builtin_sum(size_t argc, AST** argv) { return ast_init(AST_TYPE_NUM, ast_num_data_init(total)); } + +AST* builtin_sub(size_t argc, AST** argv) { + log_dbg("Got here"); + AST* first = *argv; + if (first->type != AST_TYPE_NUM) + return ast_init( + AST_TYPE_EXC, ast_exc_data_init("Can't subtract non-num arguments.") + ); + + ASTNumData total = *(ASTNumData*)first->data; + + for (int i = 1; i < argc; i++) { + AST* arg = argv[i]; + if (arg->type != AST_TYPE_NUM) + return ast_init( + AST_TYPE_EXC, + ast_exc_data_init("Can't subtract non-num arguments.") + ); + + total -= *(ASTNumData*)arg->data; + } + + return ast_init(AST_TYPE_NUM, ast_num_data_init(total)); +} diff --git a/src/exec.c b/src/exec.c index 6009c58..58ccee7 100644 --- a/src/exec.c +++ b/src/exec.c @@ -22,6 +22,10 @@ AST* exec_start(AST* ast) { global, "sum", ast_init(AST_TYPE_BIF, ast_bif_data_init(builtin_sum)) ); + htab_ins( + global, "sub", ast_init(AST_TYPE_BIF, ast_bif_data_init(builtin_sub)) + ); + // Push global namespace to `scope`. stack_push(scope, global); @@ -74,7 +78,7 @@ AST* exec_call(AST* ast) { case AST_TYPE_BIF: ASTBIFData bifdata = fdef->data; return bifdata(argc, argv); - default: return ast_init(AST_TYPE_EXC, ast_exc_data_init("Good job")); + default: return ast_init(AST_TYPE_EXC, ast_exc_data_init("Good job!")); } } diff --git a/src/include/builtin.h b/src/include/builtin.h index 00d204b..7e37c4f 100644 --- a/src/include/builtin.h +++ b/src/include/builtin.h @@ -6,7 +6,12 @@ // Sum some nums. AST* builtin_sum(size_t argc, AST** argv); +// Subtract nums. +AST* builtin_sub(size_t argc, AST** argv); + // The list of built-in functions. -static AST* (*builtin_fns[])(size_t argc, AST** argv) = {builtin_sum}; +static AST* (*builtin_fns[])(size_t argc, AST** argv) = { + builtin_sum, builtin_sub +}; #endif