moka/lib/compiler.c

75 lines
2.4 KiB
C

#include "compiler.h"
void compiler_init(struct compiler* self,
struct status* status)
{
assert(self);
self->status = status;
}
void compiler_free(struct compiler* self)
{
assert(self);
}
void compiler_compile(struct compiler* self,
struct node* node,
struct prog* prog)
{
assert(self); assert(node); assert(prog);
switch (node->kind)
{
case NODE_ROOT: {
for (size_t i=0; i<node->children.size; i++)
{
struct node* child = node->children.data[i];
compiler_compile(self, child, prog);
}
} break;
case NODE_INT: {
struct value* value = malloc(sizeof(struct value));
int val = atoi(node->token->value);
value_init_int(value, val, node->line);
ssize_t addr = prog_add_new_value(prog, value);
prog_add_instruction(prog, OP_PUSH, addr);
} break;
case NODE_FLOAT: {
struct value* value = malloc(sizeof(struct value));
float val = atof(node->token->value);
value_init_float(value, val, node->line);
ssize_t addr = prog_add_new_value(prog, value);
prog_add_instruction(prog, OP_PUSH, addr);
} break;
case NODE_BOOL: {
struct value* value = malloc(sizeof(struct value));
bool val = strcmp("true", node->token->value) == 0;
value_init_bool(value, val, node->line);
ssize_t addr = prog_add_new_value(prog, value);
prog_add_instruction(prog, OP_PUSH, addr);
} break;
case NODE_STRING: {
struct value* value = malloc(sizeof(struct value));
value_init_string(value, node->token->value, node->line);
ssize_t addr = prog_add_new_value(prog, value);
prog_add_instruction(prog, OP_PUSH, addr);
} break;
case NODE_SYMBOL: {
struct value* value = malloc(sizeof(struct value));
value_init_symbol(value, node->token->value, node->line);
ssize_t addr = prog_add_new_value(prog, value);
prog_add_instruction(prog, OP_PUSH, addr);
} break;
default: {
fprintf(stderr, "cannot compile node %s\n",
NodeKindStr[node->kind]);
abort();
} break;
}
}