summaryrefslogtreecommitdiff
path: root/src/arithm.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/arithm.c')
-rw-r--r--src/arithm.c51
1 files changed, 51 insertions, 0 deletions
diff --git a/src/arithm.c b/src/arithm.c
new file mode 100644
index 0000000..3f1e781
--- /dev/null
+++ b/src/arithm.c
@@ -0,0 +1,51 @@
+#include <stdlib.h>
+#include "syntax.h"
+#include "utils.h"
+
+
+int parse_num(char* str) {
+ // TODO: switch to dedicated Result type later
+ // TODO: add other bases (per bash arithmetic syntax)
+ char* endptr;
+ long n = strtol(str, &endptr, 10);
+ if (*endptr == '\0') {
+ return (int)n;
+ } else {
+ exit(42);
+ }
+}
+
+
+int eval_binop(BinOp op, int left, int right) {
+ switch (op) {
+ case PLUS:
+ return left+right;
+ case MULT:
+ return left*right;
+ default:
+ exit(99);
+ }
+}
+
+int eval_arithm_node(ArithmNode node, ShellState* shstate) {
+ char* num_str;
+ int left_val, right_val;
+
+ switch (node.kind) {
+ case ARITHM_INT_LIT:
+ return node.as.lit_val;
+ case ARITHM_VAR:
+ num_str = get_var(node.as.varname, shstate);
+ return parse_num(num_str);
+ case ARITHM_BINOP:
+ left_val = eval_arithm_node(*node.as.binop.left, shstate);
+ right_val = eval_arithm_node(*node.as.binop.right, shstate);
+ return eval_binop(node.as.binop.op, left_val, right_val);
+ }
+}
+
+
+int eval_arithm_ast(ArithmAst ast, ShellState* shstate) {
+ // TODO: clean up the tree
+ return eval_arithm_node(*ast.root, shstate);
+}