From c378591e3f3061fa93149bb43ab285db0a8797b4 Mon Sep 17 00:00:00 2001 From: Aryadev Chavali Date: Thu, 25 Apr 2024 03:01:59 +0530 Subject: [PATCH] Simplify OP_JUMP_IF implementation Same method as when simplifying OP_POP's implementation: use the lookup table along with OPCODE_DATA_TYPE abuse. In this case I made a lookup table called OP_POP for this method to work, but it wasn't difficult. --- vm/runtime.c | 14 +++++++------- vm/runtime.h | 7 +++++++ 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/vm/runtime.c b/vm/runtime.c index 6f17e94..e235629 100644 --- a/vm/runtime.c +++ b/vm/runtime.c @@ -139,13 +139,13 @@ err_t vm_execute(vm_t *vm) else if (UNSIGNED_OPCODE_IS_TYPE(instruction.opcode, OP_JUMP_IF)) { data_t datum = {0}; - err_t err = ERR_OK; - if (instruction.opcode == OP_JUMP_IF_BYTE) - err = vm_pop_byte(vm, &datum); - else if (instruction.opcode == OP_JUMP_IF_HWORD) - err = vm_pop_hword(vm, &datum); - else if (instruction.opcode == OP_JUMP_IF_WORD) - err = vm_pop_word(vm, &datum); + + // Here we add OP_POP_BYTE and the data_type_t of the opcode to + // get the right typed OP_POP opcode. + opcode_t pop_opcode = + OPCODE_DATA_TYPE(instruction.opcode, OP_JUMP_IF) + OP_POP_BYTE; + + err_t err = POP_ROUTINES[pop_opcode](vm, &datum); if (err) return err; diff --git a/vm/runtime.h b/vm/runtime.h index eda35e1..c6b6669 100644 --- a/vm/runtime.h +++ b/vm/runtime.h @@ -89,6 +89,13 @@ err_t vm_pop_byte(vm_t *, data_t *); err_t vm_pop_hword(vm_t *, data_t *); err_t vm_pop_word(vm_t *, data_t *); +typedef err_t (*pop_f)(vm_t *, data_t *); +static const pop_f POP_ROUTINES[] = { + [OP_POP_BYTE] = vm_pop_byte, + [OP_POP_HWORD] = vm_pop_hword, + [OP_POP_WORD] = vm_pop_word, +}; + err_t vm_push_byte(vm_t *, data_t); err_t vm_push_hword(vm_t *, data_t); err_t vm_push_word(vm_t *, data_t);