#include "../include/compiler.h" #include "../include/parser.h" #include "../include/ssa/ssa.h" #include "../include/bytecode/bytecode.h" #include "../include/std/log.h" #include "../include/std/mem.h" #include "../include/std/hash.h" #include "../include/std/file.h" #include "../include/std/alloc.h" #include #include #include #include static void amal_compiler_deinit(amal_compiler *self); static usize strnlen(const char *str, usize max_length) { usize len; len = 0; while(len < max_length && *str != '\0') { ++len; ++str; } return len; } /* TODO: Allow to specify size and members? */ static CHECK_RESULT int create_default_type(amal_compiler *compiler, const char *name, u32 num_pointers, u32 fixed_size, amal_default_type **default_type) { StructDecl *struct_decl; Ast *expr; LhsExpr *lhs_expr; return_if_error(arena_allocator_alloc(&compiler->allocator, sizeof(StructDecl), (void**)&struct_decl)); return_if_error(structdecl_init(struct_decl, &compiler->root_scope, &compiler->allocator)); struct_decl->fields_num_pointers = num_pointers; struct_decl->fields_fixed_size_bytes = fixed_size; return_if_error(arena_allocator_alloc(&compiler->allocator, sizeof(amal_default_type), (void**)default_type)); lhs_expr = &(*default_type)->lhs_expr; lhsexpr_init(lhs_expr, DECL_FLAG_EXTERN | DECL_FLAG_PUB | DECL_FLAG_CONST, create_buffer_view(name, strnlen(name, PATH_MAX))); return_if_error(ast_create(&compiler->allocator, struct_decl, AST_STRUCT_DECL, &lhs_expr->rhs_expr)); return_if_error(ast_create(&compiler->allocator, lhs_expr, AST_LHS, &expr)); expr->resolve_data.type.type = RESOLVED_TYPE_LHS_EXPR; expr->resolve_data.type.value.lhs_expr = lhs_expr; expr->resolve_data.status = AST_RESOLVED; lhs_expr->rhs_expr->resolve_data = expr->resolve_data; return scope_add_child(&compiler->root_scope, expr); } static CHECK_RESULT int create_default_type_num_pointers(amal_compiler *compiler, const char *name, u32 num_pointers, amal_default_type **default_type) { return create_default_type(compiler, name, num_pointers, 0, default_type); } static CHECK_RESULT int create_default_type_fixed_size(amal_compiler *compiler, const char *name, u32 byte_size, amal_default_type **default_type) { return create_default_type(compiler, name, 0, byte_size, default_type); } static CHECK_RESULT int init_default_types(amal_compiler *compiler) { return_if_error(create_default_type_fixed_size(compiler, "i8", 1, &compiler->default_types.i8)); return_if_error(create_default_type_fixed_size(compiler, "i16", 2, &compiler->default_types.i16)); return_if_error(create_default_type_fixed_size(compiler, "i32", 4, &compiler->default_types.i32)); return_if_error(create_default_type_fixed_size(compiler, "i64", 8, &compiler->default_types.i64)); return_if_error(create_default_type_fixed_size(compiler, "u8", 1, &compiler->default_types.u8)); return_if_error(create_default_type_fixed_size(compiler, "u16", 2, &compiler->default_types.u16)); return_if_error(create_default_type_fixed_size(compiler, "u32", 4, &compiler->default_types.u32)); return_if_error(create_default_type_fixed_size(compiler, "u64", 8, &compiler->default_types.u64)); return_if_error(create_default_type_num_pointers(compiler, "isize", 1, &compiler->default_types.isize)); return_if_error(create_default_type_num_pointers(compiler, "usize", 1, &compiler->default_types.usize)); return_if_error(create_default_type_fixed_size(compiler, "f32", 4, &compiler->default_types.f32)); return_if_error(create_default_type_fixed_size(compiler, "f64", 8, &compiler->default_types.f64)); /* TODO: str should be a struct with the fields @data (ptr) and @size (usize) */ return_if_error(create_default_type_num_pointers(compiler, "str", 1, &compiler->default_types.str)); compiler->default_types.arithmetic_types[0] = compiler->default_types.i8; compiler->default_types.arithmetic_types[1] = compiler->default_types.u8; compiler->default_types.arithmetic_types[2] = compiler->default_types.i16; compiler->default_types.arithmetic_types[3] = compiler->default_types.u16; compiler->default_types.arithmetic_types[4] = compiler->default_types.i32; compiler->default_types.arithmetic_types[5] = compiler->default_types.u32; compiler->default_types.arithmetic_types[6] = compiler->default_types.i64; compiler->default_types.arithmetic_types[7] = compiler->default_types.u64; compiler->default_types.arithmetic_types[8] = compiler->default_types.isize; compiler->default_types.arithmetic_types[9] = compiler->default_types.usize; compiler->default_types.i8->is_signed = bool_true; compiler->default_types.u8->is_signed = bool_false; compiler->default_types.i16->is_signed = bool_true; compiler->default_types.u16->is_signed = bool_false; compiler->default_types.i32->is_signed = bool_true; compiler->default_types.u32->is_signed = bool_false; compiler->default_types.i64->is_signed = bool_true; compiler->default_types.u64->is_signed = bool_false; compiler->default_types.isize->is_signed = bool_true; compiler->default_types.usize->is_signed = bool_false; compiler->default_types.f32->is_signed = bool_true; compiler->default_types.f64->is_signed = bool_true; compiler->default_types.str->is_signed = bool_false; return 0; } bool is_arithmetic_type(LhsExpr *expr, amal_compiler *compiler) { usize i; const amal_default_types *default_types = &compiler->default_types; for(i = 0; i < NUM_ARITHMETIC_TYPES; ++i) { if(expr == &default_types->arithmetic_types[i]->lhs_expr) return bool_true; } return bool_false; } void amal_compiler_options_init(amal_compiler_options *self) { self->error_callback = NULL; self->error_callback_userdata = NULL; self->num_threads = 0; } static CHECK_RESULT int amal_compiler_init(amal_compiler *self, const amal_compiler_options *options, amal_program *program) { am_memset(&self->allocator, 0, sizeof(self->allocator)); am_memset(&self->root_scope, 0, sizeof(self->root_scope)); if(options) self->options = *options; else amal_compiler_options_init(&self->options); self->program = program; self->started = bool_false; return_if_error(thread_pool_init(&self->stage_task_thread_pool, options ? options->num_threads : 0)); return_if_error(amal_mutex_init(&self->mutex)); return_if_error(arena_allocator_init(&self->allocator)); cleanup_if_error(scope_init(&self->root_scope, NULL, &self->allocator)); cleanup_if_error(buffer_init(&self->parsers, &self->allocator)); cleanup_if_error(hash_map_init(&self->file_scopes, &self->allocator, sizeof(FileScopeReference*), hash_map_compare_string, amal_hash_string)); cleanup_if_error(init_default_types(self)); return AMAL_COMPILER_OK; cleanup: amal_compiler_deinit(self); return AMAL_COMPILER_ERR; } void amal_compiler_deinit(amal_compiler *self) { Parser **parser = buffer_begin(&self->parsers); Parser **parser_end = buffer_end(&self->parsers); for(; parser != parser_end; ++parser) { if((*parser)->allocator) arena_allocator_deinit((*parser)->allocator); } thread_pool_deinit(&self->stage_task_thread_pool); amal_mutex_deinit(&self->mutex); arena_allocator_deinit(&self->allocator); } typedef enum { THREAD_WORK_PARSE, THREAD_WORK_RESOLVE_AST, THREAD_WORK_GENERATE_SSA, THREAD_WORK_GENERATE_BYTECODE } ThreadWorkType; typedef struct { amal_compiler *compiler; FileScopeReference *file_scope; } CompilerParserThreadUserData; typedef struct { amal_compiler *compiler; Parser *parser; ThreadWorkType work_type; } CompilerGenericThreadUserData; typedef struct { union { FileScopeReference *file_scope; Parser *parser; } value; ThreadWorkType type; } ThreadWorkData; static CHECK_RESULT int amal_compiler_load_in_this_thread(amal_compiler *compiler, FileScopeReference *file_scope) { Parser *parser; int result; BufferView filepath; ArenaAllocator *parser_allocator; result = AMAL_COMPILER_ERR; cleanup_if_error(amal_mutex_lock(&compiler->mutex, "amal_compiler_load_in_this_thread, create arena allocator")); cleanup_if_error(arena_allocator_alloc(&compiler->allocator, sizeof(ArenaAllocator), (void**)&parser_allocator)); amal_mutex_tryunlock(&compiler->mutex); return_if_error(arena_allocator_init(parser_allocator)); filepath = create_buffer_view(file_scope->canonical_path.data, file_scope->canonical_path.size); amal_log_info("Started parsing %.*s", filepath.size, filepath.data); return_if_error(arena_allocator_alloc(parser_allocator, sizeof(Parser), (void**)&parser)); return_if_error(parser_init(parser, compiler, parser_allocator)); file_scope->parser = parser; return_if_error(parser_parse_file(parser, filepath)); cleanup_if_error(amal_mutex_lock(&compiler->mutex, "amal_compiler_load_in_this_thread, add parser")); parser->index = buffer_get_size(&compiler->parsers, Parser*); cleanup_if_error(buffer_append(&compiler->parsers, &parser, sizeof(parser))); amal_log_info("Finished parsing %.*s", filepath.size, filepath.data); result = AMAL_COMPILER_OK; cleanup: amal_mutex_tryunlock(&compiler->mutex); return result; } static int thread_callback_parse_file(void *userdata) { int result; CompilerParserThreadUserData *compiler_parser_userdata = userdata; result = amal_compiler_load_in_this_thread(compiler_parser_userdata->compiler, compiler_parser_userdata->file_scope); am_free(userdata); return result; } static CHECK_RESULT int thread_resolve_ast(amal_compiler *compiler, Parser *parser) { AstCompilerContext compiler_context; int result; compiler_context.compiler = compiler; compiler_context.parser = parser; compiler_context.scope = NULL; result = setjmp(compiler_context.env); if(result == 0) { amal_log_debug("Resolving AST for file: %.*s", parser->tokenizer.code_name.size, parser->tokenizer.code_name.data); scope_resolve(&parser->struct_decl.body, &compiler_context); } return result; } static CHECK_RESULT int thread_generate_ssa(Parser *parser) { SsaCompilerContext compiler_context; int result; return_if_error(arena_allocator_alloc(parser->allocator, sizeof(Ssa), (void**)&compiler_context.ssa)); return_if_error(ssa_init(compiler_context.ssa, parser)); compiler_context.compiler = parser->compiler; compiler_context.import_index = 0; parser->ssa = compiler_context.ssa; amal_log_debug("Generating SSA for file: %.*s", parser->tokenizer.code_name.size, parser->tokenizer.code_name.data); result = setjmp(compiler_context.env); if(result == 0) scope_generate_ssa(&parser->struct_decl.body, &compiler_context); return result; } static CHECK_RESULT int thread_generate_bytecode(Parser *parser) { BytecodeCompilerContext compiler_context; int result; return_if_error(arena_allocator_alloc(parser->allocator, sizeof(Bytecode), (void**)&compiler_context.bytecode)); return_if_error(bytecode_init(compiler_context.bytecode, parser->allocator)); compiler_context.parser = parser; amal_log_debug("Generating bytecode for file: %.*s", parser->tokenizer.code_name.size, parser->tokenizer.code_name.data); result = setjmp(compiler_context.env); if(result == 0) { generate_bytecode_from_ssa(&compiler_context); parser->bytecode = compiler_context.bytecode; } return result; } static int thread_callback_generic(void *userdata) { int result; CompilerGenericThreadUserData *compiler_userdata = userdata; switch(compiler_userdata->work_type) { case THREAD_WORK_PARSE: { assert(bool_false && "Thread work type can't be 'parse' for generic work"); break; } case THREAD_WORK_RESOLVE_AST: result = thread_resolve_ast(compiler_userdata->compiler, compiler_userdata->parser); break; case THREAD_WORK_GENERATE_SSA: result = thread_generate_ssa(compiler_userdata->parser); break; case THREAD_WORK_GENERATE_BYTECODE: result = thread_generate_bytecode(compiler_userdata->parser); break; } am_free(userdata); return result; } static CHECK_RESULT int amal_compiler_add_task(amal_compiler *self, ThreadWorkData work_data) { void *thread_user_data = NULL; int result = AMAL_COMPILER_OK; switch(work_data.type) { case THREAD_WORK_PARSE: { CompilerParserThreadUserData *userdata; cleanup_if_error(am_malloc(sizeof(CompilerParserThreadUserData), (void**)&userdata)); thread_user_data = userdata; userdata->compiler = self; userdata->file_scope = work_data.value.file_scope; result = thread_pool_add_task(&self->stage_task_thread_pool, thread_callback_parse_file, userdata); break; } case THREAD_WORK_RESOLVE_AST: case THREAD_WORK_GENERATE_SSA: case THREAD_WORK_GENERATE_BYTECODE: { CompilerGenericThreadUserData *userdata; cleanup_if_error(am_malloc(sizeof(CompilerGenericThreadUserData), (void**)&userdata)); thread_user_data = userdata; userdata->compiler = self; userdata->parser = work_data.value.parser; userdata->work_type = work_data.type; result = thread_pool_add_task(&self->stage_task_thread_pool, thread_callback_generic, userdata); break; } } cleanup: if(result != 0) am_free(thread_user_data); return result; } static CHECK_RESULT int amal_compiler_dispatch_generic(amal_compiler *self, ThreadWorkType work_type) { Parser **parser = buffer_begin(&self->parsers); Parser **parser_end = buffer_end(&self->parsers); for(; parser != parser_end; ++parser) { ThreadWorkData thread_work_data; thread_work_data.type = work_type; thread_work_data.value.parser = *parser; return_if_error(amal_compiler_add_task(self, thread_work_data)); } return thread_pool_join_all_tasks(&self->stage_task_thread_pool) ? 0 : -1; } static CHECK_RESULT int amal_compiler_generate_program(amal_compiler *self) { /* TODO: Copying the bytecode to the program can be done using multiple threads */ Parser **parser = buffer_begin(&self->parsers); Parser **parser_end = buffer_end(&self->parsers); for(; parser != parser_end; ++parser) { return_if_error(amal_program_append_bytecode(self->program, (*parser)->bytecode)); } return 0; } static CHECK_RESULT int try_create_file_scope(amal_compiler *compiler, const char *filepath, FileScopeReference **file_scope, bool *new_entry) { int ret; char *result_path; usize result_path_size; BufferView path_view; ret = -1; result_path = NULL; *new_entry = bool_false; /* TODO: Optimize. No need to allocate everytime... */ return_if_error(file_get_canonical_path(filepath, &result_path, &result_path_size)); path_view = create_buffer_view(result_path, result_path_size); cleanup_if_error(amal_mutex_lock(&compiler->mutex, "try_create_file_scope")); if(!hash_map_get(&compiler->file_scopes, path_view, file_scope)) { cleanup_if_error(arena_allocator_alloc(&compiler->allocator, sizeof(FileScopeReference), (void**)file_scope)); /* @(*file_scope)->canonical_path won't change after this, so it's fine if allocator belongs to non-thread safe compiler instance */ cleanup_if_error(file_scope_reference_init(*file_scope, path_view, &compiler->allocator)); cleanup_if_error(hash_map_insert(&compiler->file_scopes, path_view, file_scope)); *new_entry = bool_true; } ret = 0; cleanup: amal_mutex_tryunlock(&compiler->mutex); am_free(result_path); return ret; } int amal_compiler_load_file(amal_compiler_options *options, amal_program *program, const char *filepath) { amal_compiler compiler; FileScopeReference *file_scope; int result; assert(program); assert(filepath); return_if_error(amal_compiler_init(&compiler, options, program)); result = amal_compiler_internal_load_file(&compiler, filepath, &file_scope); amal_compiler_deinit(&compiler); return result; } /* TODO: Instead of using amal_log_error, print error message with tokenizer to show where the error is. This requires finding tokenizer by code reference. */ static CHECK_RESULT int validate_main_func(FileScopeReference *main_file_scope, LhsExpr **main_func) { const BufferView main_func_name = { "main", 4 }; LhsExpr *main_func_expr; main_func_expr = structdecl_get_field_by_name(&main_file_scope->parser->struct_decl, main_func_name); if(!main_func_expr) { amal_log_error("main function missing from start file \"%.*s\". Note: the main function has to be in the file scope.", main_file_scope->canonical_path.size, main_file_scope->canonical_path.data); return AMAL_COMPILER_ERR; } *main_func = main_func_expr; if(!main_func_expr->rhs_expr || main_func_expr->rhs_expr->type != AST_FUNCTION_DECL) { amal_log_error("main exists in start file \"%.*s\" but it's not an non-extern function", main_file_scope->canonical_path.size, main_file_scope->canonical_path.data); return AMAL_COMPILER_ERR; } if(!LHS_EXPR_IS_CONST(main_func_expr)) { amal_log_error("main function in start file \"%.*s\" has to be const", main_file_scope->canonical_path.size, main_file_scope->canonical_path.data); return AMAL_COMPILER_ERR; } if(LHS_EXPR_IS_EXTERN(main_func_expr)) { amal_log_error("main function in start file \"%.*s\" can't be declared as extern", main_file_scope->canonical_path.size, main_file_scope->canonical_path.data); return AMAL_COMPILER_ERR; } { const FunctionDecl *func_decl = main_func_expr->rhs_expr->value.func_decl; if(buffer_get_size(&func_decl->signature->parameters, FunctionParameter) != 0) { amal_log_error("main function in start file \"%.*s\" has to be a closure with no parameters", main_file_scope->canonical_path.size, main_file_scope->canonical_path.data); return AMAL_COMPILER_ERR; } if(buffer_get_size(&func_decl->signature->return_types, FunctionReturnType) != 0) { amal_log_error("main function in start file \"%.*s\" has to be a closure that doesn't return anything", main_file_scope->canonical_path.size, main_file_scope->canonical_path.data); return AMAL_COMPILER_ERR; } } return 0; } static void amal_compiler_parsers_set_bytecode_offsets(amal_compiler *self) { /* magic number + major version + minor version + patch version */ u32 offset = sizeof(u32) + sizeof(u8) + sizeof(u8) + sizeof(u8); Parser **parser = buffer_begin(&self->parsers); Parser **parser_end = buffer_end(&self->parsers); for(; parser != parser_end; ++parser) { (*parser)->bytecode->offset = offset; offset += (*parser)->bytecode->data.size; } } /* TODO: Parallelize this? */ static void amal_compiler_update_import_references(amal_compiler *self) { Parser **parser_start = buffer_begin(&self->parsers); Parser **parser = parser_start; Parser **parser_end = buffer_end(&self->parsers); amal_compiler_parsers_set_bytecode_offsets(self); for(; parser != parser_end; ++parser) { u8 *import_start = (u8*)(*parser)->bytecode->data.data + (*parser)->bytecode->import_index; u8 num_imports = *import_start; /* TODO: Remove these kinds of offset with sizeof. They are prone to hard-to-find bugs after code change */ BytecodeHeaderImport *header_import = (BytecodeHeaderImport*)(import_start + sizeof(u8) + sizeof(u32)); BytecodeHeaderImport *header_import_end = header_import + num_imports; /* The first import is the file itself and it already has function index, but the index is localized to the function itself, so we need to add the offset to the file itself as well. */ header_import->function_index += (*parser)->bytecode->offset; header_import->extern_function_index += (*parser)->bytecode->offset; ++header_import; for(; header_import != header_import_end; ++header_import) { Parser *imported_parser = *(parser_start + header_import->parser_index); header_import->function_index = imported_parser->bytecode->offset + imported_parser->bytecode->funcs_index; header_import->extern_function_index = imported_parser->bytecode->offset + imported_parser->bytecode->extern_funcs_index; } } } int amal_compiler_internal_load_file(amal_compiler *self, const char *filepath, FileScopeReference **file_scope) { ThreadWorkData thread_work_data; bool main_job; bool new_entry; return_if_error(try_create_file_scope(self, filepath, file_scope, &new_entry)); assert(file_scope && *file_scope && (*file_scope)->canonical_path.data); if(!new_entry) { amal_log_info("amal_compiler_load_file: file already parsed: %.*s", (*file_scope)->canonical_path.size, (*file_scope)->canonical_path.data); return 0; } thread_work_data.type = THREAD_WORK_PARSE; thread_work_data.value.file_scope = *file_scope; main_job = bool_false; /* The first time we get here, this will run single-threaded so this part doesn't need mutex */ if(!self->started) { self->started = bool_true; main_job = bool_true; } return_if_error(amal_compiler_add_task(self, thread_work_data)); if(main_job) { /*doc(Compiler flow) (Tokenize&parse -> Resolve AST -> Generate SSA -> Generate bytecode) -> Generate program\ Each step except the last is done using multiple threads in parallel and the output of each step is used in the next step. The last step is not done in parallel because the last step is combining all bytecode and writing it to a file, which is an IO bottlenecked operation and it won't benefit from multithreading and may even lose performance because of it. */ LhsExpr *main_func; /* Wait for all parsing to be done */ if(!thread_pool_join_all_tasks(&self->stage_task_thread_pool)) return -1; amal_log_info("Finished parsing all files, resolving AST"); return_if_error(validate_main_func(*file_scope, &main_func)); /* The main function is the start file needs to be exported, so it's accessible in the program execution to find the entry (main) function. */ main_func->decl_flags |= DECL_FLAG_EXPORT; return_if_error(amal_compiler_dispatch_generic(self, THREAD_WORK_RESOLVE_AST)); amal_log_info("Finished resolving AST, generating SSA"); return_if_error(amal_compiler_dispatch_generic(self, THREAD_WORK_GENERATE_SSA)); amal_log_info("Finished generating SSA"); return_if_error(amal_compiler_dispatch_generic(self, THREAD_WORK_GENERATE_BYTECODE)); amal_compiler_update_import_references(self); amal_log_info("Finished generating bytecode"); return_if_error(amal_compiler_generate_program(self)); amal_log_info("Finished generating program"); return AMAL_COMPILER_OK; } return 0; } Tokenizer* amal_compiler_find_tokenizer_by_code_reference(amal_compiler *self, const char *code_ref) { Parser **parser = buffer_begin(&self->parsers); Parser **parser_end = buffer_end(&self->parsers); for(; parser != parser_end; ++parser) { if(tokenizer_contains_code_reference(&(*parser)->tokenizer, code_ref)) return &(*parser)->tokenizer; } return NULL; }