summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/arithm.c51
-rw-r--r--src/syntax.h2
2 files changed, 52 insertions, 1 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);
+}
diff --git a/src/syntax.h b/src/syntax.h
index 0b5396c..9b34818 100644
--- a/src/syntax.h
+++ b/src/syntax.h
@@ -23,7 +23,7 @@ struct ArithmNode {
ArithmNodeKind kind;
union {
int lit_val;
- IntVec open_fds;
+ char* varname;
struct {
BinOp op;
ArithmNode* left;