Newer
Older
Tardis / lang / bytecode.c
// SPDX-License-Identifier: MIT
// Copyright (c) 2023 John Watts and the LuminaSensum contributors

#include "bytecode.h"
#include "error.h"
#include "number.h"

enum opcodes {
	OP_RET = 0x00,
	OP_NUM = 0x01,
	OP_DROP = 0x02,
};

// clang-format off
static const unsigned char bytecode[] = {
	OP_NUM, 0xaa, 0xaa, 0xaa, 0xaa,
	OP_DROP,
	OP_NUM, 0xbb, 0xbb, 0xbb, 0xbb,
	OP_DROP,
	OP_NUM, 0xcc, 0xcc, 0xcc, 0xcc,
	OP_DROP,
	OP_NUM, 0xd2, 0x04, 0x00, 0x00,
	OP_RET
};
// clang-format on

void bytecode_run(struct object **stack) {
	abort_if(!stack, "bytecode_run has no stack");
	const unsigned char *pos_code = &bytecode[0];
	struct object **pos_stack = stack;
	unsigned char op = OP_RET;
	while ((op = *pos_code++) != OP_RET) {
		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_DROP: {
			object_drop(--pos_stack);
			break;
		}
		}
	}
}