diff options
author | ubq323 <ubq323@ubq323.website> | 2023-08-01 22:37:26 +0100 |
---|---|---|
committer | ubq323 <ubq323@ubq323.website> | 2023-08-01 22:37:26 +0100 |
commit | 9e555bc2bf618148929e52ccd0efdb1b752bdcac (patch) | |
tree | 5e6f01123d795624c0093df6e08307be2b2c8cd0 /com.c | |
parent | 24fb17017e9d6238488c9827da0ee6d0f4f84356 (diff) |
compilation of basic arithmetic exprs to bytecode
Diffstat (limited to 'com.c')
-rw-r--r-- | com.c | 70 |
1 files changed, 70 insertions, 0 deletions
@@ -0,0 +1,70 @@ +#include <stdlib.h> +#include <stdio.h> + +#include "vm.h" +#include "ast.h" +#include "read.h" + +static void compile_node(Chunk *ch, AstNode a) { + switch (a.ty) { + case AST_SYMBOL: + printf("can't compile symbol\n"); + exit(1); + break; + case AST_NUM: + chunk_wbc(ch, OP_LOADK); + chunk_wbc(ch, chunk_wconst(ch, VAL_NUM(a.as.num))); + break; + case AST_LIST:; + AstVec l = a.as.list; + #define CK(cond, msg) if (!(cond)) { puts(msg); exit(1); } + CK(l.len == 3, "can only compile binary ops"); + CK(l.vals[0].ty == AST_SYMBOL, "can only call ops"); + #undef CK + char opchar = l.vals[0].as.str[0]; + Op op; + switch (opchar) { + #define OP(char, code) case char: op = code; break; + OP('+', OP_ADD) + OP('-', OP_SUB) + OP('*', OP_MUL) + OP('/', OP_DIV) + #undef OP + default: + printf("unkown op %s\n",l.vals[0].as.str); + exit(1); + break; + } + compile_node(ch, l.vals[1]); + compile_node(ch, l.vals[2]); + chunk_wbc(ch, op); + } +} + + + + + +int main() { + Chunk ch = chunk_new(); + AstNode an = read(); + compile_node(&ch, an); + + chunk_wbc(&ch, OP_PRINT); + chunk_wbc(&ch, OP_RET); + + + // chunk_wbc(&ch, OP_LOADK); + // chunk_wbc(&ch, chunk_wconst(&ch, VAL_NUM(5.0))); + // chunk_wbc(&ch, OP_LOADK); + // chunk_wbc(&ch, chunk_wconst(&ch, VAL_NUM(10.0))); + // chunk_wbc(&ch, OP_LOADK); + // chunk_wbc(&ch, chunk_wconst(&ch, VAL_NUM(2.0))); + // chunk_wbc(&ch, OP_MUL); + // chunk_wbc(&ch, OP_ADD); + // chunk_wbc(&ch, OP_PRINT); + // chunk_wbc(&ch, OP_RET); + + runvm(&ch); +} + |