From c3fe9367986520b08a36bf693e6c74eb309377c5 Mon Sep 17 00:00:00 2001 From: Bad Diode Date: Sat, 23 Oct 2021 16:00:11 +0200 Subject: Cleanup macros for arithmetic ops --- src/bytecode/vm.h | 55 ++++++++++++++++++++++++++++--------------------------- 1 file changed, 28 insertions(+), 27 deletions(-) (limited to 'src/bytecode/vm.h') diff --git a/src/bytecode/vm.h b/src/bytecode/vm.h index 581f093..9b68fc1 100755 --- a/src/bytecode/vm.h +++ b/src/bytecode/vm.h @@ -40,6 +40,25 @@ vm_reset(VM *vm) { vm_init(vm); } +// Helper macros for a more clear VM switch. +#define FIXNUM_BINARY_OP(OP) \ + do { \ + Object a = array_pop(vm->stack); \ + Object b = array_pop(vm->stack); \ + if (!IS_FIXNUM(a) || !IS_FIXNUM(b)) { \ + error_push((Error){ \ + .type = ERR_TYPE_RUNTIME, \ + .value = ERR_WRONG_ARG_TYPE, \ + .line = vm->chunk->lines[vm->pc - vm->chunk->code - 1].line, \ + .col = vm->chunk->lines[vm->pc - vm->chunk->code - 1].col, \ + }); \ + return; \ + } \ + ssize_t x = AS_FIXNUM(a); \ + ssize_t y = AS_FIXNUM(b); \ + array_push(vm->stack, FIXNUM_VAL(y OP x)); \ + } while (false) + void vm_interpret(VM *vm, Chunk *chunk) { vm->chunk = chunk; @@ -73,31 +92,11 @@ vm_interpret(VM *vm, Chunk *chunk) { Object obj = vm->chunk->constants[constant]; array_push(vm->stack, obj); } break; - case OP_SUM: { - ssize_t a = AS_FIXNUM(array_pop(vm->stack)); - ssize_t b = AS_FIXNUM(array_pop(vm->stack)); - array_push(vm->stack, FIXNUM_VAL(a + b)); - } break; - case OP_SUB: { - ssize_t a = AS_FIXNUM(array_pop(vm->stack)); - ssize_t b = AS_FIXNUM(array_pop(vm->stack)); - array_push(vm->stack, FIXNUM_VAL(b - a)); - } break; - case OP_MUL: { - ssize_t a = AS_FIXNUM(array_pop(vm->stack)); - ssize_t b = AS_FIXNUM(array_pop(vm->stack)); - array_push(vm->stack, FIXNUM_VAL(a * b)); - } break; - case OP_DIV: { - ssize_t a = AS_FIXNUM(array_pop(vm->stack)); - ssize_t b = AS_FIXNUM(array_pop(vm->stack)); - array_push(vm->stack, FIXNUM_VAL(b / a)); - } break; - case OP_MOD: { - ssize_t a = AS_FIXNUM(array_pop(vm->stack)); - ssize_t b = AS_FIXNUM(array_pop(vm->stack)); - array_push(vm->stack, FIXNUM_VAL(a % b)); - } break; + case OP_SUM: { FIXNUM_BINARY_OP(+); } break; + case OP_SUB: { FIXNUM_BINARY_OP(-); } break; + case OP_MUL: { FIXNUM_BINARY_OP(*); } break; + case OP_DIV: { FIXNUM_BINARY_OP(/); } break; + case OP_MOD: { FIXNUM_BINARY_OP(%); } break; case OP_RETURN: { display(array_pop(vm->stack)); printf("\n"); @@ -107,8 +106,8 @@ vm_interpret(VM *vm, Chunk *chunk) { error_push((Error){ .type = ERR_TYPE_RUNTIME, .value = ERR_NOT_IMPLEMENTED, - .line = vm->chunk->lines[(vm->pc - vm->chunk->code) - 1].line, - .col = vm->chunk->lines[(vm->pc - vm->chunk->code) - 1].col, + .line = vm->chunk->lines[vm->pc - vm->chunk->code - 1].line, + .col = vm->chunk->lines[vm->pc - vm->chunk->code - 1].col, }); return; } break; @@ -123,4 +122,6 @@ vm_interpret(VM *vm, Chunk *chunk) { }); } +#undef FIXNUM_BINARY_OP + #endif // BDL_VM_H -- cgit v1.2.1