From eef7bf1aa2441824a99beb68a5d4282d7e990836 Mon Sep 17 00:00:00 2001 From: Tom-on64 Date: Thu, 30 May 2024 17:46:05 +0200 Subject: [PATCH] After all this time, I FINALLY implemented the calculator! --- src/calc.c | 109 +++++++++++++++++++++++++++++++++++++++++++--- src/filetable.asm | 2 +- 2 files changed, 105 insertions(+), 6 deletions(-) diff --git a/src/calc.c b/src/calc.c index 74212f2..425bc97 100644 --- a/src/calc.c +++ b/src/calc.c @@ -1,11 +1,110 @@ #include -#include +#include + +int evalExpr(char* expr, int* res); +int parseTerm(char** ptr); +int parseFactor(char** ptr); +int parseNumber(char** ptr); + +// TODO: Parsing doesn't account for addition/subtraction inside brackets, fix that __attribute__ ((section("entry"))) void main() { - print("Hello, World!\n"); - char in[32]; - read(in); - print(in); + printf("Welcome to calc.\n"); + char input[256]; + + while (1) { + printf("> "); + read(input); + *strchr(input, '\n') = '\0'; + + // Remove whitespace + char* old = input; + char* new = input; + while (*old != '\0') { + if (*old == ' ') old++; + *new++ = *old++; + } + *new = '\0'; + + if (strcmp(input, "exit") == 0) { + break; + } + + int res; + if (evalExpr(input, &res)) { + printf("%d\n", res); + } else { + printf("?\n"); + } + } + return; } + +int evalExpr(char* expr, int* res) { + char* ptr = expr; + *res = parseTerm(&ptr); + + while (*ptr != '\0') { + if (*ptr == '+') { + ptr++; + *res += parseTerm(&ptr); + } else if (*ptr == '-') { + ptr++; + *res -= parseTerm(&ptr); + } else { + return 0; // Invalid + } + } + + return 1; // Success +} + +int parseTerm(char** ptr) { + int res = parseFactor(ptr); + + while (**ptr == '*' || **ptr == '/') { + if (**ptr == '*') { + (*ptr)++; + res *= parseFactor(ptr); + } else if (**ptr == '/') { + (*ptr)++; + int div = parseFactor(ptr); + if (div != 0) { + res /= div; + } else { + return 0; + } + } + } + + return res; +} + +int parseFactor(char** ptr) { + if (**ptr == '(') { + (*ptr)++; + int res = parseTerm(ptr); + + if (**ptr == ')') { + (*ptr)++; + } else { + printf("Error: Missing ')'"); + return 0; + } + return res; + } else { + return parseNumber(ptr); + } +} +int parseNumber(char** ptr) { + int res = 0; + while (**ptr >= '0' && **ptr <= '9') { + res *= 10; + res += *(*ptr)++ - '0'; + } + + return res; +} + diff --git a/src/filetable.asm b/src/filetable.asm index c1e211c..b693d88 100644 --- a/src/filetable.asm +++ b/src/filetable.asm @@ -18,7 +18,7 @@ filetable: db "term16n",0,0,0, "fnt",0,56,4 db "testfont",0,0, "fnt",0,60,4 db "test",0,0,0,0,0,0, "txt",0,64,1 - db "calc",0,0,0,0,0,0, "bin",0,65,2 + db "calc",0,0,0,0,0,0, "bin",0,65,6 times 512-($-$$) db 0