Files
corelang/bytecode_codegen.cpp
2022-06-22 16:16:02 +02:00

67 lines
2.0 KiB
C++

function Register_Index
bc_emit_expr(Bc *b, Ast *ast){
if(!ast) return -1;
if(!is_flag_set(ast->flags, AST_EXPR))
compiler_error(ast->pos, "Internal compiler error: Trying to emit expression but it doesn't have appropriate flag");
switch(ast->kind){
// @todo pass type and figure out what to do with untyped ??
CASE(VALUE, Atom){
Register_Index dst = allocate_register(b);
switch(node->type->kind){
CASE_UINT: emit_load_constant_u64(b, dst, bigint_as_unsigned(&node->big_int_val)); break;
CASE_SINT: emit_load_constant_s64(b, dst, bigint_as_signed(&node->big_int_val)); break;
CASE_FLOAT: emit_load_constant_f64(b, dst, node->f64_val); break;
invalid_default_case;
}
return dst;
BREAK();
}
CASE(BINARY, Binary){
Register_Index left = bc_emit_expr(b, node->left);
Register_Index right = bc_emit_expr(b, node->right);
emit_arithmetic(b, BC_ADD_S64, left, right, left);
release_register(b, right);
return left;
BREAK();
}
default:{}
}
return -1;
}
function void
compile_to_bc(){
Bc bc = create_bytecode_interp();
Bc *b = &bc;
For_Named(pctx->ordered_decls, ast){
switch(ast->kind){
CASE(LAMBDA, Decl){
// node->bytecode_data_position = emit_lambda();
BREAK();
}
CASE(VAR, Decl){
node->bytecode_data_position = exp_alloc(&b->memory, node->type->size, AF_ZeroMemory);
if(node->expr){
Register_Index expression_index = bc_emit_expr(b, node->expr);
Register_Index address_index = allocate_register(b);
emit_load_constant_address(b, address_index, node->bytecode_data_position);
emit_memory(b, BC_STORE_TO_MEMORY64, address_index, expression_index);
release_register(b, expression_index);
release_register(b, address_index);
}
BREAK();
}
default: {}
}
}
emit_end(b);
run_bytecode_interp(b);
destroy_bytecode_interp(b);
}