ccm/lib/prog.c

66 lines
1.4 KiB
C

#include "prog.h"
void prog_init(prog_t* self)
{
assert(self);
vec_init(&self->instrs);
vec_init(&self->constants);
}
void prog_free(prog_t* self)
{
assert(self);
vec_free_elements(&self->instrs, NULL);
vec_free(&self->instrs);
vec_free(&self->constants);
}
size_t prog_add_instr(prog_t* self, Opcode opcode, int param)
{
assert(self);
instr_t* instr = malloc(sizeof(instr_t));
instr->opcode = opcode;
instr->param = param;
vec_push(&self->instrs, instr);
return self->instrs.size - 1;
}
size_t prog_add_new_constant(prog_t* self, CCM value)
{
assert(self);
vec_push(&self->constants, (void*) value);
return self->constants.size - 1;
}
size_t prog_str(prog_t* self, char* buffer, size_t size)
{
assert(self);
assert(buffer);
size_t sz = 0;
for (size_t i=0; i<self->instrs.size; i++)
{
instr_t const* instr = self->instrs.data[i];
if (instr->param == CCM_NO_PARAM)
{
sz += snprintf(buffer + sz, size - sz, "%zu\t%s\n",
i,
OpcodeStr[instr->opcode]
+ strlen("OP_"));
}
else
{
sz += snprintf(buffer + sz, size - sz, "%zu\t%s %d\n",
i,
OpcodeStr[instr->opcode] + strlen("OP_"),
instr->param);
}
}
return sz;
}