// SPDX-License-Identifier: MIT // Copyright (c) 2023 John Watts and the LuminaSensum contributors #include "bytecode.h" #include "error.h" #include "number.h" #include <stddef.h> enum opcodes { OP_NUM = 0x01, OP_RET = 0x03, OP_CALL = 0x04, OP_NULL = 0x05, OP_GET = 0x06, OP_SET = 0x07, OP_DROP = 0x08, }; // clang-format off static const unsigned char bytecode[] = { 0x05, 0x05, 0x05, 0x01, 0x6a, 0x02, 0x00, 0x00, 0x07, 0x01, 0x05, 0x06, 0x01, 0x06, 0x01, 0x04, 0x02, 0x41, 0x64, 0x64, 0x00, 0x08, 0x01, 0x07, 0x02, 0x05, 0x01, 0x02, 0x00, 0x00, 0x00, 0x06, 0x02, 0x04, 0x02, 0x4d, 0x69, 0x6e, 0x75, 0x73, 0x00, 0x08, 0x01, 0x07, 0x03, 0x06, 0x03, 0x07, 0x00, 0x08, 0x03, 0x03, }; // clang-format on void bytecode_run(struct object **stack, int arg_count) { abort_if(!stack, "bytecode_run has no stack"); const unsigned char *pos_code = &bytecode[0]; struct object **pos_stack = stack + arg_count; unsigned char op = OP_RET; while ((op = *pos_code++) != OP_RET) { // Skip over NOP, ASCII and unknown OPs switch (op) { case OP_NUM: { int num = 0; num |= *pos_code++ << 0; num |= *pos_code++ << 8; num |= *pos_code++ << 16; num |= *pos_code++ << 24; *pos_stack++ = number_create(num); break; } case OP_CALL: { int arg_count = *pos_code++; const char *dispatch = (const char *)pos_code; struct object *obj = *--pos_stack; struct object **args = pos_stack - arg_count; dispatch_call(obj, dispatch, arg_count, args); *pos_stack = NULL; object_drop(&obj); break; } case OP_NULL: { *pos_stack++ = NULL; break; } case OP_GET: { struct object *obj = stack[*pos_code++]; object_hold(obj); *pos_stack++ = obj; break; } case OP_SET: { struct object **obj_old = &stack[*pos_code++]; struct object *obj_new = *--pos_stack; if (*obj_old != NULL) { object_drop(obj_old); } *obj_old = obj_new; // obj_new reference doesn't change break; } case OP_DROP: { unsigned char count = *pos_code++; while (count--) { object_drop(--pos_stack); } break; } } } }