Added NUMBER_OF_OPCODES which aids in compilation errors

If I add a new operand I want the build system to be more helpful in
finding the places I need to change to make it work.
This commit is contained in:
2023-10-22 20:27:09 +01:00
parent b20ad511a0
commit aa3d1cb85f
3 changed files with 12 additions and 1 deletions

View File

@@ -10,6 +10,7 @@
* Description: Implementation of bytecode for instructions
*/
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
@@ -116,6 +117,9 @@ const char *opcode_as_cstr(opcode_t code)
case OP_HALT:
return "HALT";
break;
case NUMBER_OF_OPCODES:
return "";
break;
}
return "";
}
@@ -201,6 +205,7 @@ void inst_print(inst_t instruction, FILE *fp)
size_t inst_bytecode_size(inst_t inst)
{
static_assert(NUMBER_OF_OPCODES == 31, "inst_bytecode_size: Out of date");
size_t size = 1; // for opcode
if (OPCODE_IS_TYPE(inst.opcode, OP_PUSH))
{
@@ -223,6 +228,7 @@ size_t inst_bytecode_size(inst_t inst)
void inst_write_bytecode(inst_t inst, darr_t *darr)
{
static_assert(NUMBER_OF_OPCODES == 31, "inst_write_bytecode: Out of date");
// Append opcode
darr_append_byte(darr, inst.opcode);
// Then append 0 or more operands
@@ -294,11 +300,12 @@ data_t read_type_from_darr(darr_t *darr, data_type_t type)
inst_t inst_read_bytecode(darr_t *darr)
{
static_assert(NUMBER_OF_OPCODES == 31, "inst_read_bytecode: Out of date");
if (darr->used >= darr->available)
return (inst_t){0};
inst_t inst = {0};
opcode_t opcode = darr->data[darr->used++];
if (opcode > OP_HALT)
if (opcode > OP_HALT || opcode == NUMBER_OF_OPCODES)
// Translate to NOOP
return inst;
// Read operands

View File

@@ -65,6 +65,8 @@ typedef enum
OP_EQ_HWORD,
OP_EQ_WORD,
// Should not be an opcode
NUMBER_OF_OPCODES,
OP_HALT = 0b11111111, // top of the byte is a HALT
} opcode_t;

View File

@@ -10,6 +10,7 @@
* Description: Virtual machine implementation
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -18,6 +19,7 @@
void vm_execute(vm_t *vm)
{
static_assert(NUMBER_OF_OPCODES == 31, "vm_execute: Out of date");
struct Program *prog = &vm->program;
if (prog->ptr >= prog->max)
// TODO: Error (Went past end of program)