diff --git a/build.bat b/build.bat index b5ceccaf1..d50eb74bc 100644 --- a/build.bat +++ b/build.bat @@ -4,8 +4,8 @@ set exe_name=odin.exe :: Debug = 0, Release = 1 -set release_mode=1 -set compiler_flags= -nologo -Oi -TC -fp:fast -fp:except- -Gm- -MP -FC -GS- -EHsc- -GR- +set release_mode=0 +set compiler_flags= -nologo -Oi -TP -fp:fast -fp:except- -Gm- -MP -FC -GS- -EHsc- -GR- if %release_mode% EQU 0 ( rem Debug set compiler_flags=%compiler_flags% -Od -MDd -Z7 @@ -42,13 +42,10 @@ set linker_settings=%libs% %linker_flags% del *.pdb > NUL 2> NUL del *.ilk > NUL 2> NUL -odin run code/demo.odin -rem cl %compiler_settings% "src\main.c" ^ - rem /link %linker_settings% -OUT:%exe_name% ^ - rem && odin run code/demo.odin - rem && odin build code/metagen.odin ^ - rem && call "code\metagen.exe" "src\ast_nodes.metagen" - rem && odin run code/Jaze/src/main.odin +rem odin run code/demo.odin +cl %compiler_settings% "src\main.cpp" ^ + /link %linker_settings% -OUT:%exe_name% ^ + && odin run code/demo.odin del *.obj > NUL 2> NUL diff --git a/src/array.c b/src/array.cpp similarity index 99% rename from src/array.c rename to src/array.cpp index bb9e789db..a46ccc47f 100644 --- a/src/array.c +++ b/src/array.cpp @@ -1,98 +1,7 @@ #define ARRAY_GROW_FORMULA(x) (2*(x) + 8) GB_STATIC_ASSERT(ARRAY_GROW_FORMULA(0) > 0); -#define Array(Type_) struct { \ - gbAllocator allocator; \ - Type_ * e; \ - isize count; \ - isize capacity; \ -} - -typedef Array(void) ArrayVoid; - -#define array_init_reserve(x_, allocator_, init_capacity_) do { \ - void **e = cast(void **)&((x_)->e); \ - GB_ASSERT((x_) != NULL); \ - (x_)->allocator = (allocator_); \ - (x_)->count = 0; \ - (x_)->capacity = (init_capacity_); \ - *e = gb_alloc((allocator_), gb_size_of(*(x_)->e)*(init_capacity_)); \ -} while (0) - -#define array_init_count(x_, allocator_, init_count_) do { \ - void **e = cast(void **)&((x_)->e); \ - GB_ASSERT((x_) != NULL); \ - (x_)->allocator = (allocator_); \ - (x_)->count = (init_count_); \ - (x_)->capacity = (init_count_); \ - *e = gb_alloc((allocator_), gb_size_of(*(x_)->e)*(init_count_)); \ -} while (0) - -#define array_init(x_, allocator_) do { array_init_reserve(x_, allocator_, ARRAY_GROW_FORMULA(0)); } while (0) -#define array_free(x_) do { gb_free((x_)->allocator, (x_)->e); } while (0) -#define array_set_capacity(x_, capacity_) do { array__set_capacity((x_), (capacity_), gb_size_of(*(x_)->e)); } while (0) - -#define array_grow(x_, min_capacity_) do { \ - isize new_capacity = ARRAY_GROW_FORMULA((x_)->capacity); \ - if (new_capacity < (min_capacity_)) { \ - new_capacity = (min_capacity_); \ - } \ - array_set_capacity(x_, new_capacity); \ -} while (0) - -#define array_add(x_, item_) do { \ - if ((x_)->capacity < (x_)->count+1) { \ - array_grow(x_, 0); \ - } \ - (x_)->e[(x_)->count++] = item_; \ -} while (0) - -#define array_pop(x_) do { GB_ASSERT((x_)->count > 0); (x_)->count--; } while (0) -#define array_clear(x_) do { (x_)->count = 0; } while (0) - -#define array_resize(x_, new_count_) do { \ - if ((x_)->capacity < (new_count_)) { \ - array_grow((x_), (new_count_)); \ - } \ - (x_)->count = (new_count_); \ -} while (0) - -#define array_reserve(x_, new_capacity_) do { \ - if ((x_)->capacity < (new_capacity_)) { \ - array_set_capacity((x_), (new_capacity_)); \ - } \ -} while (0) - - - - -void array__set_capacity(void *ptr, isize capacity, isize element_size) { - ArrayVoid *x = cast(ArrayVoid *)ptr; - GB_ASSERT(ptr != NULL); - - GB_ASSERT(element_size > 0); - - if (capacity == x->capacity) { - return; - } - - if (capacity < x->count) { - if (x->capacity < capacity) { - isize new_capacity = ARRAY_GROW_FORMULA(x->capacity); - if (new_capacity < capacity) { - new_capacity = capacity; - } - array__set_capacity(ptr, new_capacity, element_size); - } - x->count = capacity; - } - - x->e = gb_resize(x->allocator, x->e, element_size*x->capacity, element_size*capacity); - x->capacity = capacity; -} - - -#if 0 +#if 1 template struct Array { gbAllocator allocator; @@ -224,6 +133,97 @@ void array_set_capacity(Array *array, isize capacity) { array->capacity = capacity; } - - #endif + +#if 0 +#define Array(Type_) struct { \ + gbAllocator allocator; \ + Type_ * e; \ + isize count; \ + isize capacity; \ +} + +typedef Array(void) ArrayVoid; + +#define array_init_reserve(x_, allocator_, init_capacity_) do { \ + void **e = cast(void **)&((x_)->e); \ + GB_ASSERT((x_) != NULL); \ + (x_)->allocator = (allocator_); \ + (x_)->count = 0; \ + (x_)->capacity = (init_capacity_); \ + *e = gb_alloc((allocator_), gb_size_of(*(x_)->e)*(init_capacity_)); \ +} while (0) + +#define array_init_count(x_, allocator_, init_count_) do { \ + void **e = cast(void **)&((x_)->e); \ + GB_ASSERT((x_) != NULL); \ + (x_)->allocator = (allocator_); \ + (x_)->count = (init_count_); \ + (x_)->capacity = (init_count_); \ + *e = gb_alloc((allocator_), gb_size_of(*(x_)->e)*(init_count_)); \ +} while (0) + +#define array_init(x_, allocator_) do { array_init_reserve(x_, allocator_, ARRAY_GROW_FORMULA(0)); } while (0) +#define array_free(x_) do { gb_free((x_)->allocator, (x_)->e); } while (0) +#define array_set_capacity(x_, capacity_) do { array__set_capacity((x_), (capacity_), gb_size_of(*(x_)->e)); } while (0) + +#define array_grow(x_, min_capacity_) do { \ + isize new_capacity = ARRAY_GROW_FORMULA((x_)->capacity); \ + if (new_capacity < (min_capacity_)) { \ + new_capacity = (min_capacity_); \ + } \ + array_set_capacity(x_, new_capacity); \ +} while (0) + +#define array_add(x_, item_) do { \ + if ((x_)->capacity < (x_)->count+1) { \ + array_grow(x_, 0); \ + } \ + (x_)->e[(x_)->count++] = item_; \ +} while (0) + +#define array_pop(x_) do { GB_ASSERT((x_)->count > 0); (x_)->count--; } while (0) +#define array_clear(x_) do { (x_)->count = 0; } while (0) + +#define array_resize(x_, new_count_) do { \ + if ((x_)->capacity < (new_count_)) { \ + array_grow((x_), (new_count_)); \ + } \ + (x_)->count = (new_count_); \ +} while (0) + +#define array_reserve(x_, new_capacity_) do { \ + if ((x_)->capacity < (new_capacity_)) { \ + array_set_capacity((x_), (new_capacity_)); \ + } \ +} while (0) + + + + +void array__set_capacity(void *ptr, isize capacity, isize element_size) { + ArrayVoid *x = cast(ArrayVoid *)ptr; + GB_ASSERT(ptr != NULL); + + GB_ASSERT(element_size > 0); + + if (capacity == x->capacity) { + return; + } + + if (capacity < x->count) { + if (x->capacity < capacity) { + isize new_capacity = ARRAY_GROW_FORMULA(x->capacity); + if (new_capacity < capacity) { + new_capacity = capacity; + } + array__set_capacity(ptr, new_capacity, element_size); + } + x->count = capacity; + } + + x->e = gb_resize(x->allocator, x->e, element_size*x->capacity, element_size*capacity); + x->capacity = capacity; +} +#endif + diff --git a/src/build_settings.c b/src/build_settings.cpp similarity index 88% rename from src/build_settings.c rename to src/build_settings.cpp index 0ba38e30f..eb8a50c6a 100644 --- a/src/build_settings.c +++ b/src/build_settings.cpp @@ -1,5 +1,5 @@ // This stores the information for the specify architecture of this build -typedef struct BuildContext { +struct BuildContext { // Constants String ODIN_OS; // target operating system String ODIN_ARCH; // target architecture @@ -15,7 +15,7 @@ typedef struct BuildContext { String llc_flags; String link_flags; bool is_dll; -} BuildContext; +}; gb_global BuildContext build_context = {0}; @@ -35,7 +35,7 @@ String const NIX_SEPARATOR_STRING = {cast(u8 *)"/", 1}; #if defined(GB_SYSTEM_WINDOWS) String odin_root_dir(void) { String path = global_module_path; - Array(wchar_t) path_buf; + Array path_buf; isize len, i; gbTempArenaMemory tmp; wchar_t *text; @@ -48,7 +48,7 @@ String odin_root_dir(void) { len = 0; for (;;) { - len = GetModuleFileNameW(NULL, &path_buf.e[0], path_buf.count); + len = GetModuleFileNameW(NULL, &path_buf[0], path_buf.count); if (len == 0) { return make_string(NULL, 0); } @@ -65,7 +65,7 @@ String odin_root_dir(void) { GetModuleFileNameW(NULL, text, len); path = string16_to_string(heap_allocator(), make_string16(text, len)); for (i = path.len-1; i >= 0; i--) { - u8 c = path.text[i]; + u8 c = path[i]; if (c == '/' || c == '\\') { break; } @@ -102,7 +102,7 @@ String odin_root_dir(void) { len = 0; for (;;) { int sz = path_buf.count; - int res = _NSGetExecutablePath(&path_buf.e[0], &sz); + int res = _NSGetExecutablePath(&path_buf[0], &sz); if(res == 0) { len = sz; break; @@ -114,11 +114,11 @@ String odin_root_dir(void) { tmp = gb_temp_arena_memory_begin(&string_buffer_arena); text = gb_alloc_array(string_buffer_allocator, u8, len + 1); - gb_memmove(text, &path_buf.e[0], len); + gb_memmove(text, &path_buf[0], len); path = make_string(text, len); for (i = path.len-1; i >= 0; i--) { - u8 c = path.text[i]; + u8 c = path[i]; if (c == '/' || c == '\\') { break; } @@ -158,7 +158,7 @@ String odin_root_dir(void) { // of this compiler, it should be _good enough_. // That said, there's no solid 100% method on Linux to get the program's // path without checking this link. Sorry. - len = readlink("/proc/self/exe", &path_buf.e[0], path_buf.count); + len = readlink("/proc/self/exe", &path_buf[0], path_buf.count); if(len == 0) { return make_string(NULL, 0); } @@ -171,11 +171,11 @@ String odin_root_dir(void) { tmp = gb_temp_arena_memory_begin(&string_buffer_arena); text = gb_alloc_array(string_buffer_allocator, u8, len + 1); - gb_memmove(text, &path_buf.e[0], len); + gb_memmove(text, &path_buf[0], len); path = make_string(text, len); for (i = path.len-1; i >= 0; i--) { - u8 c = path.text[i]; + u8 c = path[i]; if (c == '/' || c == '\\') { break; } @@ -200,10 +200,10 @@ String path_to_fullpath(gbAllocator a, String s) { String16 string16 = string_to_string16(string_buffer_allocator, s); String result = {0}; - DWORD len = GetFullPathNameW(string16.text, 0, NULL, NULL); + DWORD len = GetFullPathNameW(&string16[0], 0, NULL, NULL); if (len != 0) { wchar_t *text = gb_alloc_array(string_buffer_allocator, wchar_t, len+1); - GetFullPathNameW(string16.text, len, text, NULL); + GetFullPathNameW(&string16[0], len, text, NULL); text[len] = 0; result = string16_to_string(a, make_string16(text, len)); } @@ -212,7 +212,7 @@ String path_to_fullpath(gbAllocator a, String s) { } #elif defined(GB_SYSTEM_OSX) || defined(GB_SYSTEM_UNIX) String path_to_fullpath(gbAllocator a, String s) { - char *p = realpath(cast(char *)s.text, 0); + char *p = realpath(cast(char *)&s[0], 0); if(p == NULL) return make_string_c(""); return make_string_c(p); @@ -229,8 +229,8 @@ String get_fullpath_relative(gbAllocator a, String base_dir, String path) { u8 *str = gb_alloc_array(heap_allocator(), u8, str_len+1); isize i = 0; - gb_memmove(str+i, base_dir.text, base_dir.len); i += base_dir.len; - gb_memmove(str+i, path.text, path.len); + gb_memmove(str+i, &base_dir[0], base_dir.len); i += base_dir.len; + gb_memmove(str+i, &path[0], path.len); str[str_len] = '\0'; res = path_to_fullpath(a, make_string(str, str_len)); gb_free(heap_allocator(), str); @@ -247,9 +247,9 @@ String get_fullpath_core(gbAllocator a, String path) { isize str_len = module_dir.len + core_len + path.len; u8 *str = gb_alloc_array(heap_allocator(), u8, str_len+1); - gb_memmove(str, module_dir.text, module_dir.len); + gb_memmove(str, &module_dir[0], module_dir.len); gb_memmove(str+module_dir.len, core, core_len); - gb_memmove(str+module_dir.len+core_len, path.text, path.len); + gb_memmove(str+module_dir.len+core_len, &path[0], path.len); str[str_len] = '\0'; res = path_to_fullpath(a, make_string(str, str_len)); @@ -294,7 +294,7 @@ void init_build_context(void) { // NOTE(zangent): MacOS systems are x64 only, so ld doesn't have // an architecture option. All compilation done on MacOS must be x64. - GB_ASSERT(str_eq(bc->ODIN_ARCH, str_lit("amd64"))); + GB_ASSERT(bc->ODIN_ARCH == "amd64"); #define LINK_FLAG_X64 "" #define LINK_FLAG_X86 "" @@ -311,12 +311,12 @@ void init_build_context(void) { #define LINK_FLAG_X86 "-arch x86" #endif - if (str_eq(bc->ODIN_ARCH, str_lit("amd64"))) { + if (bc->ODIN_ARCH == "amd64") { bc->word_size = 8; bc->max_align = 16; bc->llc_flags = str_lit("-march=x86-64 "); bc->link_flags = str_lit(LINK_FLAG_X64 " "); - } else if (str_eq(bc->ODIN_ARCH, str_lit("x86"))) { + } else if (bc->ODIN_ARCH == "x86") { bc->word_size = 4; bc->max_align = 8; bc->llc_flags = str_lit("-march=x86 "); diff --git a/src/check_decl.c b/src/check_decl.cpp similarity index 92% rename from src/check_decl.c rename to src/check_decl.cpp index a14c79a20..57fb2c7f4 100644 --- a/src/check_decl.c +++ b/src/check_decl.cpp @@ -13,7 +13,7 @@ Type *check_init_variable(Checker *c, Entity *e, Operand *operand, String contex // TODO(bill): is this a good enough error message? // TODO(bill): Actually allow built in procedures to be passed around and thus be created on use error_node(operand->expr, - "Cannot assign builtin procedure `%s` in %.*s", + "Cannot assign built-in procedure `%s` in %.*s", expr_str, LIT(context_name)); @@ -58,7 +58,7 @@ Type *check_init_variable(Checker *c, Entity *e, Operand *operand, String contex return e->type; } -void check_init_variables(Checker *c, Entity **lhs, isize lhs_count, AstNodeArray inits, String context_name) { +void check_init_variables(Checker *c, Entity **lhs, isize lhs_count, Array inits, String context_name) { if ((lhs == NULL || lhs_count == 0) && inits.count == 0) { return; } @@ -67,20 +67,20 @@ void check_init_variables(Checker *c, Entity **lhs, isize lhs_count, AstNodeArra // NOTE(bill): If there is a bad syntax error, rhs > lhs which would mean there would need to be // an extra allocation - ArrayOperand operands = {0}; - array_init_reserve(&operands, c->tmp_allocator, 2*lhs_count); + Array operands = {}; + array_init(&operands, c->tmp_allocator, 2*lhs_count); check_unpack_arguments(c, lhs_count, &operands, inits, true); isize rhs_count = operands.count; for_array(i, operands) { - if (operands.e[i].mode == Addressing_Invalid) { + if (operands[i].mode == Addressing_Invalid) { rhs_count--; } } isize max = gb_min(lhs_count, rhs_count); for (isize i = 0; i < max; i++) { - check_init_variable(c, lhs[i], &operands.e[i], context_name); + check_init_variable(c, lhs[i], &operands[i], context_name); } if (rhs_count > 0 && lhs_count != rhs_count) { error(lhs[0]->token, "Assignment count mismatch `%td` = `%td`", lhs_count, rhs_count); @@ -145,7 +145,7 @@ void check_type_decl(Checker *c, Entity *e, AstNode *type_expr, Type *def) { // gb_printf_err("%.*s %p\n", LIT(e->token.string), e); - Type *bt = check_type_extra(c, type_expr, named); + Type *bt = check_type(c, type_expr, named); named->Named.base = base_type(bt); if (named->Named.base == t_invalid) { // gb_printf("check_type_decl: %s\n", type_to_string(named)); @@ -174,7 +174,7 @@ void check_const_decl(Checker *c, Entity *e, AstNode *type_expr, AstNode *init, e->type = t; } - Operand operand = {0}; + Operand operand = {}; if (init != NULL) { check_expr_or_type(c, &operand, init); } @@ -274,7 +274,7 @@ void check_proc_lit(Checker *c, Entity *e, DeclInfo *d) { bool is_require_results = (pd->tags & ProcTag_require_results) != 0; - if (d->scope->is_file && str_eq(e->token.string, str_lit("main"))) { + if (d->scope->is_file && e->token.string == "main") { if (proc_type != NULL) { TypeProc *pt = &proc_type->Proc; if (pt->param_count != 0 || @@ -319,7 +319,7 @@ void check_proc_lit(Checker *c, Entity *e, DeclInfo *d) { } if (is_foreign) { - MapEntity *fp = &c->info.foreigns; + auto *fp = &c->info.foreigns; String name = e->token.string; if (pd->foreign_name.len > 0) { name = pd->foreign_name; @@ -334,7 +334,7 @@ void check_proc_lit(Checker *c, Entity *e, DeclInfo *d) { String name = foreign_library->Ident.string; Entity *found = scope_lookup_entity(c->context.scope, name); if (found == NULL) { - if (str_eq(name, str_lit("_"))) { + if (name == "_") { error_node(foreign_library, "`_` cannot be used as a value type"); } else { error_node(foreign_library, "Undeclared name: %.*s", LIT(name)); @@ -352,7 +352,7 @@ void check_proc_lit(Checker *c, Entity *e, DeclInfo *d) { e->Procedure.foreign_name = name; HashKey key = hash_string(name); - Entity **found = map_entity_get(fp, key); + Entity **found = map_get(fp, key); if (found) { Entity *f = *found; TokenPos pos = f->token.pos; @@ -365,7 +365,7 @@ void check_proc_lit(Checker *c, Entity *e, DeclInfo *d) { LIT(name), LIT(pos.file), pos.line, pos.column); } } else { - map_entity_set(fp, key, e); + map_set(fp, key, e); } } else { String name = e->token.string; @@ -374,12 +374,12 @@ void check_proc_lit(Checker *c, Entity *e, DeclInfo *d) { } if (is_link_name || is_export) { - MapEntity *fp = &c->info.foreigns; + auto *fp = &c->info.foreigns; e->Procedure.link_name = name; HashKey key = hash_string(name); - Entity **found = map_entity_get(fp, key); + Entity **found = map_get(fp, key); if (found) { Entity *f = *found; TokenPos pos = f->token.pos; @@ -389,7 +389,7 @@ void check_proc_lit(Checker *c, Entity *e, DeclInfo *d) { "\tother at %.*s(%td:%td)", LIT(name), LIT(pos.file), pos.line, pos.column); } else { - map_entity_set(fp, key, e); + map_set(fp, key, e); } } } @@ -408,7 +408,7 @@ void check_var_decl(Checker *c, Entity *e, Entity **entities, isize entity_count e->flags |= EntityFlag_Visited; if (type_expr != NULL) { - e->type = check_type_extra(c, type_expr, NULL); + e->type = check_type(c, type_expr); } if (init_expr == NULL) { @@ -420,7 +420,7 @@ void check_var_decl(Checker *c, Entity *e, Entity **entities, isize entity_count if (entities == NULL || entity_count == 1) { GB_ASSERT(entities == NULL || entities[0] == e); - Operand operand = {0}; + Operand operand = {}; check_expr(c, &operand, init_expr); check_init_variable(c, e, &operand, str_lit("variable declaration")); } @@ -431,8 +431,8 @@ void check_var_decl(Checker *c, Entity *e, Entity **entities, isize entity_count } } - AstNodeArray inits; - array_init_reserve(&inits, c->allocator, 1); + Array inits; + array_init(&inits, c->allocator, 1); array_add(&inits, init_expr); check_init_variables(c, entities, entity_count, inits, str_lit("variable declaration")); } @@ -443,7 +443,7 @@ void check_entity_decl(Checker *c, Entity *e, DeclInfo *d, Type *named_type) { } if (d == NULL) { - DeclInfo **found = map_decl_info_get(&c->info.entities, hash_pointer(e)); + DeclInfo **found = map_get(&c->info.entities, hash_pointer(e)); if (found) { d = *found; } else { @@ -484,7 +484,7 @@ void check_entity_decl(Checker *c, Entity *e, DeclInfo *d, Type *named_type) { void check_proc_body(Checker *c, Token token, DeclInfo *decl, Type *type, AstNode *body) { GB_ASSERT(body->kind == AstNode_BlockStmt); - String proc_name = {0}; + String proc_name = {}; if (token.kind == Token_Ident) { proc_name = token.string; } else { @@ -511,10 +511,10 @@ void check_proc_body(Checker *c, Token token, DeclInfo *decl, Type *type, AstNod String name = e->token.string; Type *t = base_type(type_deref(e->type)); if (is_type_struct(t) || is_type_raw_union(t)) { - Scope **found = map_scope_get(&c->info.scopes, hash_pointer(t->Record.node)); + Scope **found = map_get(&c->info.scopes, hash_pointer(t->Record.node)); GB_ASSERT(found != NULL); for_array(i, (*found)->elements.entries) { - Entity *f = (*found)->elements.entries.e[i].value; + Entity *f = (*found)->elements.entries[i].value; if (f->kind == Entity_Variable) { Entity *uvar = make_entity_using_variable(c->allocator, e, f->token, f->type); uvar->Variable.is_immutable = is_immutable; @@ -555,9 +555,9 @@ void check_proc_body(Checker *c, Token token, DeclInfo *decl, Type *type, AstNod if (decl->parent != NULL) { // NOTE(bill): Add the dependencies from the procedure literal (lambda) for_array(i, decl->deps.entries) { - HashKey key = decl->deps.entries.e[i].key; + HashKey key = decl->deps.entries[i].key; Entity *e = cast(Entity *)key.ptr; - map_bool_set(&decl->parent->deps, key, true); + map_set(&decl->parent->deps, key, true); } } } diff --git a/src/check_expr.c b/src/check_expr.cpp similarity index 90% rename from src/check_expr.c rename to src/check_expr.cpp index 1ed7378e5..a8453f0cb 100644 --- a/src/check_expr.c +++ b/src/check_expr.cpp @@ -2,8 +2,7 @@ void check_expr (Checker *c, Operand *operand, AstNode * void check_multi_expr (Checker *c, Operand *operand, AstNode *expression); void check_expr_or_type (Checker *c, Operand *operand, AstNode *expression); ExprKind check_expr_base (Checker *c, Operand *operand, AstNode *expression, Type *type_hint); -Type * check_type_extra (Checker *c, AstNode *expression, Type *named_type); -Type * check_type (Checker *c, AstNode *expression); +Type * check_type (Checker *c, AstNode *expression, Type *named_type = NULL); void check_type_decl (Checker *c, Entity *e, AstNode *type_expr, Type *def); Entity * check_selector (Checker *c, Operand *operand, AstNode *node, Type *type_hint); void check_not_tuple (Checker *c, Operand *operand); @@ -16,17 +15,12 @@ void update_expr_type (Checker *c, AstNode *e, Type *type, boo bool check_is_terminating (AstNode *node); bool check_has_break (AstNode *stmt, bool implicit); void check_stmt (Checker *c, AstNode *node, u32 flags); -void check_stmt_list (Checker *c, AstNodeArray stmts, u32 flags); +void check_stmt_list (Checker *c, Array stmts, u32 flags); void check_init_constant (Checker *c, Entity *e, Operand *operand); bool check_representable_as_constant(Checker *c, ExactValue in_value, Type *type, ExactValue *out_value); Type * check_call_arguments (Checker *c, Operand *operand, Type *proc_type, AstNode *call); -gb_inline Type *check_type(Checker *c, AstNode *expression) { - return check_type_extra(c, expression, NULL); -} - - void error_operand_not_expression(Operand *o) { if (o->mode == Addressing_Type) { gbString err = expr_to_string(o->expr); @@ -46,14 +40,14 @@ void error_operand_no_value(Operand *o) { } -void check_scope_decls(Checker *c, AstNodeArray nodes, isize reserve_size) { +void check_scope_decls(Checker *c, Array nodes, isize reserve_size) { Scope *s = c->context.scope; GB_ASSERT(!s->is_file); check_collect_entities(c, nodes, false); for_array(i, s->elements.entries) { - Entity *e = s->elements.entries.e[i].value; + Entity *e = s->elements.entries[i].value; switch (e->kind) { case Entity_Constant: case Entity_TypeName: @@ -62,7 +56,7 @@ void check_scope_decls(Checker *c, AstNodeArray nodes, isize reserve_size) { default: continue; } - DeclInfo **found = map_decl_info_get(&c->info.entities, hash_pointer(e)); + DeclInfo **found = map_get(&c->info.entities, hash_pointer(e)); if (found != NULL) { DeclInfo *d = *found; check_entity_decl(c, e, d, NULL); @@ -70,7 +64,7 @@ void check_scope_decls(Checker *c, AstNodeArray nodes, isize reserve_size) { } for_array(i, s->elements.entries) { - Entity *e = s->elements.entries.e[i].value; + Entity *e = s->elements.entries[i].value; if (e->kind != Entity_Procedure) { continue; } @@ -261,13 +255,18 @@ i64 check_distance_between_types(Checker *c, Operand *operand, Type *type) { } +i64 assign_score_function(i64 distance) { + // TODO(bill): A decent score function + return gb_max(1000000 - distance*distance, 0); +} + + bool check_is_assignable_to_with_score(Checker *c, Operand *operand, Type *type, i64 *score_) { i64 score = 0; i64 distance = check_distance_between_types(c, operand, type); bool ok = distance >= 0; if (ok) { - // TODO(bill): A decent score function - score = gb_max(1000000 - distance*distance, 0); + score = assign_score_function(distance); } if (score_) *score_ = score; return ok; @@ -326,7 +325,7 @@ void check_assignment(Checker *c, Operand *operand, Type *type, String context_n // TODO(bill): is this a good enough error message? // TODO(bill): Actually allow built in procedures to be passed around and thus be created on use error_node(operand->expr, - "Cannot assign builtin procedure `%s` in %.*s", + "Cannot assign built-in procedure `%s` in %.*s", expr_str, LIT(context_name)); } else { @@ -348,7 +347,7 @@ void check_assignment(Checker *c, Operand *operand, Type *type, String context_n } -void populate_using_entity_map(Checker *c, AstNode *node, Type *t, MapEntity *entity_map) { +void populate_using_entity_map(Checker *c, AstNode *node, Type *t, Map *entity_map) { t = base_type(type_deref(t)); gbString str = NULL; if (node != NULL) { @@ -361,7 +360,7 @@ void populate_using_entity_map(Checker *c, AstNode *node, Type *t, MapEntity *en GB_ASSERT(f->kind == Entity_Variable); String name = f->token.string; HashKey key = hash_string(name); - Entity **found = map_entity_get(entity_map, key); + Entity **found = map_get(entity_map, key); if (found != NULL) { Entity *e = *found; // TODO(bill): Better type error @@ -371,7 +370,7 @@ void populate_using_entity_map(Checker *c, AstNode *node, Type *t, MapEntity *en error(e->token, "`%.*s` is already declared`", LIT(name)); } } else { - map_entity_set(entity_map, key, f); + map_set(entity_map, key, f); add_entity(c, c->context.scope, NULL, f); if (f->flags & EntityFlag_Using) { populate_using_entity_map(c, node, f->type, entity_map); @@ -385,13 +384,13 @@ void populate_using_entity_map(Checker *c, AstNode *node, Type *t, MapEntity *en // Returns filled field_count -isize check_fields(Checker *c, AstNode *node, AstNodeArray decls, +isize check_fields(Checker *c, AstNode *node, Array decls, Entity **fields, isize field_count, String context) { gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&c->tmp_arena); - MapEntity entity_map = {0}; - map_entity_init_with_reserve(&entity_map, c->tmp_allocator, 2*field_count); + Map entity_map = {}; + map_init_with_reserve(&entity_map, c->tmp_allocator, 2*field_count); Entity *using_index_expr = NULL; @@ -401,7 +400,7 @@ isize check_fields(Checker *c, AstNode *node, AstNodeArray decls, isize field_index = 0; for_array(decl_index, decls) { - AstNode *decl = decls.e[decl_index]; + AstNode *decl = decls[decl_index]; if (decl->kind != AstNode_Field) { continue; } @@ -412,13 +411,13 @@ isize check_fields(Checker *c, AstNode *node, AstNodeArray decls, if (is_using) { if (f->names.count > 1) { - error_node(f->names.e[0], "Cannot apply `using` to more than one of the same type"); + error_node(f->names[0], "Cannot apply `using` to more than one of the same type"); is_using = false; } } for_array(name_index, f->names) { - AstNode *name = f->names.e[name_index]; + AstNode *name = f->names[name_index]; if (!ast_node_expect(name, AstNode_Ident)) { continue; } @@ -427,13 +426,13 @@ isize check_fields(Checker *c, AstNode *node, AstNodeArray decls, Entity *e = make_entity_field(c->allocator, c->context.scope, name_token, type, is_using, cast(i32)field_index); e->identifier = name; - if (str_eq(name_token.string, str_lit("_"))) { + if (name_token.string == "_") { fields[field_index++] = e; - } else if (str_eq(name_token.string, str_lit("__tag"))) { + } else if (name_token.string == "__tag") { error_node(name, "`__tag` is a reserved identifier for fields"); } else { HashKey key = hash_string(name_token.string); - Entity **found = map_entity_get(&entity_map, key); + Entity **found = map_get(&entity_map, key); if (found != NULL) { Entity *e = *found; // NOTE(bill): Scope checking already checks the declaration but in many cases, this can happen so why not? @@ -441,7 +440,7 @@ isize check_fields(Checker *c, AstNode *node, AstNodeArray decls, error(name_token, "`%.*s` is already declared in this type", LIT(name_token.string)); error(e->token, "\tpreviously declared"); } else { - map_entity_set(&entity_map, key, e); + map_set(&entity_map, key, e); fields[field_index++] = e; add_entity(c, c->context.scope, name, e); } @@ -454,15 +453,15 @@ isize check_fields(Checker *c, AstNode *node, AstNodeArray decls, Type *t = base_type(type_deref(type)); if (!is_type_struct(t) && !is_type_raw_union(t) && !is_type_bit_field(t) && f->names.count >= 1 && - f->names.e[0]->kind == AstNode_Ident) { - Token name_token = f->names.e[0]->Ident; + f->names[0]->kind == AstNode_Ident) { + Token name_token = f->names[0]->Ident; if (is_type_indexable(t)) { bool ok = true; for_array(emi, entity_map.entries) { - Entity *e = entity_map.entries.e[emi].value; + Entity *e = entity_map.entries[emi].value; if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) { if (is_type_indexable(e->type)) { - if (e->identifier != f->names.e[0]) { + if (e->identifier != f->names[0]) { ok = false; using_index_expr = e; break; @@ -496,7 +495,7 @@ isize check_fields(Checker *c, AstNode *node, AstNodeArray decls, // TODO(bill): Cleanup struct field reordering // TODO(bill): Inline sorting procedure? -gb_global gbAllocator __checker_allocator = {0}; +gb_global gbAllocator __checker_allocator = {}; GB_COMPARE_PROC(cmp_reorder_struct_fields) { // Rule: @@ -545,7 +544,7 @@ void check_struct_type(Checker *c, Type *struct_type, AstNode *node) { isize field_count = 0; for_array(field_index, st->fields) { - AstNode *field = st->fields.e[field_index]; + AstNode *field = st->fields[field_index]; switch (field->kind) { case_ast_node(f, Field, field); field_count += f->names.count; @@ -600,7 +599,7 @@ void check_struct_type(Checker *c, Type *struct_type, AstNode *node) { return; } - Operand o = {0}; + Operand o = {}; check_expr(c, &o, st->align); if (o.mode != Addressing_Constant) { if (o.mode != Addressing_Invalid) { @@ -641,7 +640,7 @@ void check_union_type(Checker *c, Type *union_type, AstNode *node) { isize variant_count = ut->variants.count+1; isize field_count = 0; for_array(i, ut->fields) { - AstNode *field = ut->fields.e[i]; + AstNode *field = ut->fields[i]; if (field->kind == AstNode_Field) { ast_node(f, Field, field); field_count += f->names.count; @@ -650,8 +649,8 @@ void check_union_type(Checker *c, Type *union_type, AstNode *node) { gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&c->tmp_arena); - MapEntity entity_map = {0}; // Key: String - map_entity_init_with_reserve(&entity_map, c->tmp_allocator, 2*variant_count); + Map entity_map = {}; // Key: String + map_init_with_reserve(&entity_map, c->tmp_allocator, 2*variant_count); Entity *using_index_expr = NULL; @@ -666,7 +665,7 @@ void check_union_type(Checker *c, Type *union_type, AstNode *node) { for (isize i = 0; i < field_count; i++) { Entity *f = fields[i]; String name = f->token.string; - map_entity_set(&entity_map, hash_string(name), f); + map_set(&entity_map, hash_string(name), f); } union_type->Record.fields = fields; @@ -680,7 +679,7 @@ void check_union_type(Checker *c, Type *union_type, AstNode *node) { } for_array(i, ut->variants) { - AstNode *variant = ut->variants.e[i]; + AstNode *variant = ut->variants[i]; if (variant->kind != AstNode_UnionField) { continue; } @@ -692,14 +691,14 @@ void check_union_type(Checker *c, Type *union_type, AstNode *node) { ast_node(fl, FieldList, f->list); // NOTE(bill): Copy the contents for the common fields for now - AstNodeArray list = {0}; + Array list = {}; array_init_count(&list, c->allocator, ut->fields.count+fl->list.count); - gb_memmove_array(list.e, ut->fields.e, ut->fields.count); - gb_memmove_array(list.e+ut->fields.count, fl->list.e, fl->list.count); + gb_memmove_array(list.data, ut->fields.data, ut->fields.count); + gb_memmove_array(list.data+ut->fields.count, fl->list.data, fl->list.count); isize list_count = 0; for_array(j, list) { - ast_node(f, Field, list.e[j]); + ast_node(f, Field, list[j]); list_count += f->names.count; } @@ -729,17 +728,17 @@ void check_union_type(Checker *c, Type *union_type, AstNode *node) { type->Named.type_name = e; add_entity(c, c->context.scope, f->name, e); - if (str_eq(name_token.string, str_lit("_"))) { + if (name_token.string == "_") { error(name_token, "`_` cannot be used a union subtype"); continue; } HashKey key = hash_string(name_token.string); - if (map_entity_get(&entity_map, key) != NULL) { + if (map_get(&entity_map, key) != NULL) { // NOTE(bill): Scope checking already checks the declaration error(name_token, "`%.*s` is already declared in this union", LIT(name_token.string)); } else { - map_entity_set(&entity_map, key, e); + map_set(&entity_map, key, e); variants[variant_index++] = e; } add_entity_use(c, f->name, e); @@ -760,7 +759,7 @@ void check_raw_union_type(Checker *c, Type *union_type, AstNode *node) { isize field_count = 0; for_array(field_index, ut->fields) { - AstNode *field = ut->fields.e[field_index]; + AstNode *field = ut->fields[field_index]; switch (field->kind) { case_ast_node(f, Field, field); field_count += f->names.count; @@ -801,8 +800,8 @@ void check_enum_type(Checker *c, Type *enum_type, Type *named_type, AstNode *nod // NOTE(bill): Must be up here for the `check_init_constant` system enum_type->Record.enum_base_type = base_type; - MapEntity entity_map = {0}; // Key: String - map_entity_init_with_reserve(&entity_map, c->tmp_allocator, 2*(et->fields.count)); + Map entity_map = {}; // Key: String + map_init_with_reserve(&entity_map, c->tmp_allocator, 2*(et->fields.count)); Entity **fields = gb_alloc_array(c->allocator, Entity *, et->fields.count); isize field_count = 0; @@ -817,7 +816,7 @@ void check_enum_type(Checker *c, Type *enum_type, Type *named_type, AstNode *nod ExactValue max_value = exact_value_i64(0); for_array(i, et->fields) { - AstNode *field = et->fields.e[i]; + AstNode *field = et->fields[i]; AstNode *ident = NULL; AstNode *init = NULL; if (field->kind == AstNode_FieldValue) { @@ -837,7 +836,7 @@ void check_enum_type(Checker *c, Type *enum_type, Type *named_type, AstNode *nod String name = ident->Ident.string; if (init != NULL) { - Operand o = {0}; + Operand o = {}; check_expr(c, &o, init); if (o.mode != Addressing_Constant) { error_node(init, "Enumeration value must be a constant"); @@ -857,21 +856,21 @@ void check_enum_type(Checker *c, Type *enum_type, Type *named_type, AstNode *nod // NOTE(bill): Skip blank identifiers - if (str_eq(name, str_lit("_"))) { + if (name == "_") { continue; - } else if (str_eq(name, str_lit("count"))) { + } else if (name == "count") { error_node(field, "`count` is a reserved identifier for enumerations"); continue; - } else if (str_eq(name, str_lit("min_value"))) { + } else if (name == "min_value") { error_node(field, "`min_value` is a reserved identifier for enumerations"); continue; - } else if (str_eq(name, str_lit("max_value"))) { + } else if (name == "max_value") { error_node(field, "`max_value` is a reserved identifier for enumerations"); continue; - } else if (str_eq(name, str_lit("names"))) { + } else if (name == "names") { error_node(field, "`names` is a reserved identifier for enumerations"); continue; - }/* else if (str_eq(name, str_lit("base_type"))) { + }/* else if (name == "base_type") { error_node(field, "`base_type` is a reserved identifier for enumerations"); continue; } */ @@ -888,10 +887,10 @@ void check_enum_type(Checker *c, Type *enum_type, Type *named_type, AstNode *nod e->flags |= EntityFlag_Visited; HashKey key = hash_string(name); - if (map_entity_get(&entity_map, key) != NULL) { + if (map_get(&entity_map, key) != NULL) { error_node(ident, "`%.*s` is already declared in this enumeration", LIT(name)); } else { - map_entity_set(&entity_map, key, e); + map_set(&entity_map, key, e); add_entity(c, c->context.scope, NULL, e); fields[field_count++] = e; add_entity_use(c, field, e); @@ -922,8 +921,8 @@ void check_bit_field_type(Checker *c, Type *bit_field_type, Type *named_type, As gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&c->tmp_arena); - MapEntity entity_map = {0}; // Key: String - map_entity_init_with_reserve(&entity_map, c->tmp_allocator, 2*(bft->fields.count)); + Map entity_map = {}; // Key: String + map_init_with_reserve(&entity_map, c->tmp_allocator, 2*(bft->fields.count)); isize field_count = 0; Entity **fields = gb_alloc_array(c->allocator, Entity *, bft->fields.count); @@ -932,7 +931,7 @@ void check_bit_field_type(Checker *c, Type *bit_field_type, Type *named_type, As u32 curr_offset = 0; for_array(i, bft->fields) { - AstNode *field = bft->fields.e[i]; + AstNode *field = bft->fields[i]; GB_ASSERT(field->kind == AstNode_FieldValue); AstNode *ident = field->FieldValue.field; AstNode *value = field->FieldValue.value; @@ -943,7 +942,7 @@ void check_bit_field_type(Checker *c, Type *bit_field_type, Type *named_type, As } String name = ident->Ident.string; - Operand o = {0}; + Operand o = {}; check_expr(c, &o, value); if (o.mode != Addressing_Constant) { error_node(value, "Bit field bit size must be a constant"); @@ -966,11 +965,11 @@ void check_bit_field_type(Checker *c, Type *bit_field_type, Type *named_type, As e->flags |= EntityFlag_BitFieldValue; HashKey key = hash_string(name); - if (str_ne(name, str_lit("_")) && - map_entity_get(&entity_map, key) != NULL) { + if (name != "_" && + map_get(&entity_map, key) != NULL) { error_node(ident, "`%.*s` is already declared in this bit field", LIT(name)); } else { - map_entity_set(&entity_map, key, e); + map_set(&entity_map, key, e); add_entity(c, c->context.scope, NULL, e); add_entity_use(c, field, e); @@ -992,7 +991,7 @@ void check_bit_field_type(Checker *c, Type *bit_field_type, Type *named_type, As if (bft->align != NULL) { - Operand o = {0}; + Operand o = {}; check_expr(c, &o, bft->align); if (o.mode != Addressing_Constant) { if (o.mode != Addressing_Invalid) { @@ -1033,7 +1032,7 @@ Type *check_get_params(Checker *c, Scope *scope, AstNode *_params, bool *is_vari return NULL; } ast_node(field_list, FieldList, _params); - AstNodeArray params = field_list->list; + Array params = field_list->list; if (params.count == 0) { return NULL; @@ -1041,7 +1040,7 @@ Type *check_get_params(Checker *c, Scope *scope, AstNode *_params, bool *is_vari isize variable_count = 0; for_array(i, params) { - AstNode *field = params.e[i]; + AstNode *field = params[i]; if (ast_node_expect(field, AstNode_Field)) { ast_node(f, Field, field); variable_count += gb_max(f->names.count, 1); @@ -1052,43 +1051,79 @@ Type *check_get_params(Checker *c, Scope *scope, AstNode *_params, bool *is_vari Entity **variables = gb_alloc_array(c->allocator, Entity *, variable_count); isize variable_index = 0; for_array(i, params) { - if (params.e[i]->kind != AstNode_Field) { + if (params[i]->kind != AstNode_Field) { continue; } - ast_node(p, Field, params.e[i]); + ast_node(p, Field, params[i]); AstNode *type_expr = p->type; - if (type_expr) { + Type *type = NULL; + AstNode *default_value = p->default_value; + ExactValue value = {}; + + if (type_expr == NULL) { + Operand o = {}; + check_expr(c, &o, default_value); + + if (o.mode != Addressing_Constant) { + error_node(default_value, "Default parameter must be a constant"); + } else { + value = o.value; + } + + type = default_type(o.type); + } else { if (type_expr->kind == AstNode_Ellipsis) { type_expr = type_expr->Ellipsis.expr; if (i+1 == params.count) { is_variadic = true; } else { - error_node(params.e[i], "Invalid AST: Invalid variadic parameter"); + error_node(params[i], "Invalid AST: Invalid variadic parameter"); } } - Type *type = check_type(c, type_expr); - if (p->flags&FieldFlag_no_alias) { - if (!is_type_pointer(type)) { - error_node(params.e[i], "`no_alias` can only be applied to fields of pointer type"); - p->flags &= ~FieldFlag_no_alias; // Remove the flag + type = check_type(c, type_expr); + + if (default_value != NULL) { + Operand o = {}; + check_expr(c, &o, default_value); + + if (o.mode != Addressing_Constant) { + error_node(default_value, "Default parameter must be a constant"); + } else { + value = o.value; } + + check_is_assignable_to(c, &o, type); } - for_array(j, p->names) { - AstNode *name = p->names.e[j]; - if (ast_node_expect(name, AstNode_Ident)) { - Entity *param = make_entity_param(c->allocator, scope, name->Ident, type, - p->flags&FieldFlag_using, p->flags&FieldFlag_immutable); - if (p->flags&FieldFlag_no_alias) { - param->flags |= EntityFlag_NoAlias; - } - if (p->flags&FieldFlag_immutable) { - param->Variable.is_immutable = true; - } - add_entity(c, scope, name, param); - variables[variable_index++] = param; + } + if (type == NULL) { + error_node(params[i], "Invalid parameter type"); + type = t_invalid; + } + + if (p->flags&FieldFlag_no_alias) { + if (!is_type_pointer(type)) { + error_node(params[i], "`no_alias` can only be applied to fields of pointer type"); + p->flags &= ~FieldFlag_no_alias; // Remove the flag + } + } + + for_array(j, p->names) { + AstNode *name = p->names[j]; + if (ast_node_expect(name, AstNode_Ident)) { + Entity *param = make_entity_param(c->allocator, scope, name->Ident, type, + (p->flags&FieldFlag_using) != 0, (p->flags&FieldFlag_immutable) != 0); + if (p->flags&FieldFlag_no_alias) { + param->flags |= EntityFlag_NoAlias; } + if (p->flags&FieldFlag_immutable) { + param->Variable.is_immutable = true; + } + param->Variable.default_value = value; + + add_entity(c, scope, name, param); + variables[variable_index++] = param; } } } @@ -1118,7 +1153,7 @@ Type *check_get_results(Checker *c, Scope *scope, AstNode *_results) { return NULL; } ast_node(field_list, FieldList, _results); - AstNodeArray results = field_list->list; + Array results = field_list->list; if (results.count == 0) { return NULL; @@ -1127,7 +1162,7 @@ Type *check_get_results(Checker *c, Scope *scope, AstNode *_results) { isize variable_count = 0; for_array(i, results) { - AstNode *field = results.e[i]; + AstNode *field = results[i]; if (ast_node_expect(field, AstNode_Field)) { ast_node(f, Field, field); variable_count += gb_max(f->names.count, 1); @@ -1137,7 +1172,7 @@ Type *check_get_results(Checker *c, Scope *scope, AstNode *_results) { Entity **variables = gb_alloc_array(c->allocator, Entity *, variable_count); isize variable_index = 0; for_array(i, results) { - ast_node(field, Field, results.e[i]); + ast_node(field, Field, results[i]); Type *type = check_type(c, field->type); if (field->names.count == 0) { Token token = ast_node_token(field->type); @@ -1149,7 +1184,7 @@ Type *check_get_results(Checker *c, Scope *scope, AstNode *_results) { Token token = ast_node_token(field->type); token.string = str_lit(""); - AstNode *name = field->names.e[j]; + AstNode *name = field->names[j]; if (name->kind != AstNode_Ident) { error_node(name, "Expected an identifer for as the field name"); } else { @@ -1164,15 +1199,15 @@ Type *check_get_results(Checker *c, Scope *scope, AstNode *_results) { for (isize i = 0; i < variable_index; i++) { String x = variables[i]->token.string; - if (x.len == 0 || str_eq(x, str_lit("_"))) { + if (x.len == 0 || x == "_") { continue; } for (isize j = i+1; j < variable_index; j++) { String y = variables[j]->token.string; - if (y.len == 0 || str_eq(y, str_lit("_"))) { + if (y.len == 0 || y == "_") { continue; } - if (str_eq(x, y)) { + if (x == y) { error(variables[j]->token, "Duplicate return value name `%.*s`", LIT(y)); } } @@ -1187,7 +1222,7 @@ Type *check_get_results(Checker *c, Scope *scope, AstNode *_results) { Type *type_to_abi_compat_param_type(gbAllocator a, Type *original_type) { Type *new_type = original_type; - if (str_eq(build_context.ODIN_OS, str_lit("windows"))) { + if (build_context.ODIN_OS == "windows") { // NOTE(bill): Changing the passing parameter value type is to match C's ABI // IMPORTANT TODO(bill): This only matches the ABI on MSVC at the moment // SEE: https://msdn.microsoft.com/en-us/library/zthk2dkh.aspx @@ -1223,7 +1258,7 @@ Type *type_to_abi_compat_param_type(gbAllocator a, Type *original_type) { } } break; } - } else if (str_eq(build_context.ODIN_OS, str_lit("linux"))) { + } else if (build_context.ODIN_OS == "linux") { Type *bt = core_type(original_type); switch (bt->kind) { // Okay to pass by value @@ -1277,7 +1312,7 @@ Type *type_to_abi_compat_result_type(gbAllocator a, Type *original_type) { - if (str_eq(build_context.ODIN_OS, str_lit("windows"))) { + if (build_context.ODIN_OS == "windows") { Type *bt = core_type(reduce_tuple_to_single_type(original_type)); // NOTE(bill): This is just reversed engineered from LLVM IR output switch (bt->kind) { @@ -1301,7 +1336,7 @@ Type *type_to_abi_compat_result_type(gbAllocator a, Type *original_type) { } } break; } - } else if (str_eq(build_context.ODIN_OS, str_lit("linux"))) { + } else if (build_context.ODIN_OS == "linux") { } else { // IMPORTANT TODO(bill): figure out the ABI settings for Linux, OSX etc. for @@ -1330,7 +1365,7 @@ bool abi_compat_return_by_value(gbAllocator a, ProcCallingConvention cc, Type *a } - if (str_eq(build_context.ODIN_OS, str_lit("windows"))) { + if (build_context.ODIN_OS == "windows") { i64 size = 8*type_size_of(a, abi_return_type); switch (size) { case 0: @@ -1388,7 +1423,7 @@ Entity *check_ident(Checker *c, Operand *o, AstNode *n, Type *named_type, Type * Entity *e = scope_lookup_entity(c->context.scope, name); if (e == NULL) { - if (str_eq(name, str_lit("_"))) { + if (name == "_") { error(n->Ident, "`_` cannot be used as a value type"); } else { error(n->Ident, "Undeclared name: %.*s", LIT(name)); @@ -1418,7 +1453,7 @@ Entity *check_ident(Checker *c, Operand *o, AstNode *n, Type *named_type, Type * if (e->kind == Entity_Procedure) { // NOTE(bill): Overloads are only allowed with the same scope Scope *s = e->scope; - overload_count = map_entity_multi_count(&s->elements, key); + overload_count = multi_map_count(&s->elements, key); if (overload_count > 1) { is_overloaded = true; } @@ -1429,7 +1464,7 @@ Entity *check_ident(Checker *c, Operand *o, AstNode *n, Type *named_type, Type * bool skip = false; Entity **procs = gb_alloc_array(heap_allocator(), Entity *, overload_count); - map_entity_multi_get_all(&s->elements, key, procs); + multi_map_get_all(&s->elements, key, procs); if (type_hint != NULL) { gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&c->tmp_arena); // NOTE(bill): These should be done @@ -1438,7 +1473,7 @@ Entity *check_ident(Checker *c, Operand *o, AstNode *n, Type *named_type, Type * if (t == t_invalid) { continue; } - Operand x = {0}; + Operand x = {}; x.mode = Addressing_Value; x.type = t; if (check_is_assignable_to(c, &x, type_hint)) { @@ -1512,7 +1547,7 @@ Entity *check_ident(Checker *c, Operand *o, AstNode *n, Type *named_type, Type * break; case Entity_Builtin: - o->builtin_id = e->Builtin.id; + o->builtin_id = cast(BuiltinProcId)e->Builtin.id; o->mode = Addressing_Builtin; break; @@ -1546,7 +1581,7 @@ i64 check_array_or_map_count(Checker *c, AstNode *e, bool is_map) { if (e == NULL) { return 0; } - Operand o = {0}; + Operand o = {}; if (e->kind == AstNode_UnaryExpr && e->UnaryExpr.op.kind == Token_Ellipsis) { return -1; @@ -1605,8 +1640,8 @@ void check_map_type(Checker *c, Type *type, AstNode *node) { ast_node(mt, MapType, node); i64 count = check_array_or_map_count(c, mt->count, true); - Type *key = check_type_extra(c, mt->key, NULL); - Type *value = check_type_extra(c, mt->value, NULL); + Type *key = check_type(c, mt->key); + Type *value = check_type(c, mt->value); if (!is_type_valid_for_keys(key)) { if (is_type_boolean(key)) { @@ -1702,7 +1737,7 @@ void check_map_type(Checker *c, Type *type, AstNode *node) { // error_node(node, "`map` types are not yet implemented"); } -bool check_type_extra_internal(Checker *c, AstNode *e, Type **type, Type *named_type) { +bool check_type_internal(Checker *c, AstNode *e, Type **type, Type *named_type) { GB_ASSERT_NOT_NULL(type); if (e == NULL) { *type = t_invalid; @@ -1711,7 +1746,7 @@ bool check_type_extra_internal(Checker *c, AstNode *e, Type **type, Type *named_ switch (e->kind) { case_ast_node(i, Ident, e); - Operand o = {0}; + Operand o = {}; check_ident(c, &o, e, named_type, NULL, false); switch (o.mode) { @@ -1735,7 +1770,7 @@ bool check_type_extra_internal(Checker *c, AstNode *e, Type **type, Type *named_ case_end; case_ast_node(se, SelectorExpr, e); - Operand o = {0}; + Operand o = {}; check_selector(c, &o, e, NULL); switch (o.mode) { @@ -1759,7 +1794,7 @@ bool check_type_extra_internal(Checker *c, AstNode *e, Type **type, Type *named_ case_end; case_ast_node(pe, ParenExpr, e); - *type = check_type_extra(c, pe->expr, named_type); + *type = check_type(c, pe->expr, named_type); return true; case_end; @@ -1794,7 +1829,7 @@ bool check_type_extra_internal(Checker *c, AstNode *e, Type **type, Type *named_ case_ast_node(at, ArrayType, e); if (at->count != NULL) { - Type *elem = check_type_extra(c, at->elem, NULL); + Type *elem = check_type(c, at->elem, NULL); i64 count = check_array_or_map_count(c, at->count, false); if (count < 0) { error_node(at->count, ".. can only be used in conjuction with compound literals"); @@ -1825,7 +1860,7 @@ bool check_type_extra_internal(Checker *c, AstNode *e, Type **type, Type *named_ case_end; case_ast_node(dat, DynamicArrayType, e); - Type *elem = check_type_extra(c, dat->elem, NULL); + Type *elem = check_type(c, dat->elem); i64 esz = type_size_of(c->allocator, elem); #if 0 if (esz == 0) { @@ -1919,7 +1954,7 @@ bool check_type_extra_internal(Checker *c, AstNode *e, Type **type, Type *named_ case_end; case_ast_node(ce, CallExpr, e); - Operand o = {0}; + Operand o = {}; check_expr_or_type(c, &o, e); if (o.mode == Addressing_Type) { *type = o.type; @@ -1934,9 +1969,9 @@ bool check_type_extra_internal(Checker *c, AstNode *e, Type **type, Type *named_ -Type *check_type_extra(Checker *c, AstNode *e, Type *named_type) { +Type *check_type(Checker *c, AstNode *e, Type *named_type) { Type *type = NULL; - bool ok = check_type_extra_internal(c, e, &type, named_type); + bool ok = check_type_internal(c, e, &type, named_type); if (!ok) { gbString err_str = expr_to_string(e); @@ -1959,7 +1994,7 @@ Type *check_type_extra(Checker *c, AstNode *e, Type *named_type) { } if (is_type_typed(type)) { - add_type_and_value(&c->info, e, Addressing_Type, type, (ExactValue){0}); + add_type_and_value(&c->info, e, Addressing_Type, type, empty_exact_value); } else { gbString name = type_to_string(type); error_node(e, "Invalid type definition of %s", name); @@ -2213,8 +2248,8 @@ void check_is_expressible(Checker *c, Operand *o, Type *type) { if (!is_type_integer(o->type) && is_type_integer(type)) { error_node(o->expr, "`%s` truncated to `%s`", a, b); } else { - char buf[127] = {0}; - String str = {0}; + char buf[127] = {}; + String str = {}; i128 i = o->value.value_integer; if (is_type_unsigned(o->type)) { str = u128_to_string(*cast(u128 *)&i, buf, gb_size_of(buf)); @@ -2421,7 +2456,7 @@ void check_shift(Checker *c, Operand *x, Operand *y, AstNode *node) { GB_ASSERT(node->kind == AstNode_BinaryExpr); ast_node(be, BinaryExpr, node); - ExactValue x_val = {0}; + ExactValue x_val = {}; if (x->mode == Addressing_Constant) { x_val = exact_value_to_integer(x->value); } @@ -2488,7 +2523,7 @@ void check_shift(Checker *c, Operand *x, Operand *y, AstNode *node) { TokenPos pos = ast_node_token(x->expr).pos; if (x_is_untyped) { - ExprInfo *info = map_expr_info_get(&c->info.untyped, hash_pointer(x->expr)); + ExprInfo *info = map_get(&c->info.untyped, hash_pointer(x->expr)); if (info != NULL) { info->is_lhs = true; } @@ -2517,7 +2552,7 @@ void check_shift(Checker *c, Operand *x, Operand *y, AstNode *node) { String check_down_cast_name(Type *dst_, Type *src_) { - String result = {0}; + String result = {}; Type *dst = type_deref(dst_); Type *src = type_deref(src_); Type *dst_s = base_type(dst); @@ -2552,7 +2587,7 @@ Operand check_ptr_addition(Checker *c, TokenKind op, Operand *ptr, Operand *offs GB_ASSERT(is_type_integer(offset->type)); GB_ASSERT(op == Token_Add || op == Token_Sub); - Operand operand = {0}; + Operand operand = {}; operand.mode = Addressing_Value; operand.type = ptr->type; operand.expr = node; @@ -2764,7 +2799,7 @@ bool check_binary_vector_expr(Checker *c, Token op, Operand *x, Operand *y) { void check_binary_expr(Checker *c, Operand *x, AstNode *node) { GB_ASSERT(node->kind == AstNode_BinaryExpr); - Operand y_ = {0}, *y = &y_; + Operand y_ = {}, *y = &y_; ast_node(be, BinaryExpr, node); @@ -2944,7 +2979,7 @@ void check_binary_expr(Checker *c, Operand *x, AstNode *node) { void update_expr_type(Checker *c, AstNode *e, Type *type, bool final) { HashKey key = hash_pointer(e); - ExprInfo *found = map_expr_info_get(&c->info.untyped, key); + ExprInfo *found = map_get(&c->info.untyped, key); if (found == NULL) { return; } @@ -2983,12 +3018,12 @@ void update_expr_type(Checker *c, AstNode *e, Type *type, bool final) { if (!final && is_type_untyped(type)) { old.type = base_type(type); - map_expr_info_set(&c->info.untyped, key, old); + map_set(&c->info.untyped, key, old); return; } // We need to remove it and then give it a new one - map_expr_info_remove(&c->info.untyped, key); + map_remove(&c->info.untyped, key); if (old.is_lhs && !is_type_integer(type)) { gbString expr_str = expr_to_string(e); @@ -3003,7 +3038,7 @@ void update_expr_type(Checker *c, AstNode *e, Type *type, bool final) { } void update_expr_value(Checker *c, AstNode *e, ExactValue value) { - ExprInfo *found = map_expr_info_get(&c->info.untyped, hash_pointer(e)); + ExprInfo *found = map_get(&c->info.untyped, hash_pointer(e)); if (found) { found->value = value; } @@ -3016,7 +3051,7 @@ void convert_untyped_error(Checker *c, Operand *operand, Type *target_type) { if (operand->mode == Addressing_Constant) { if (i128_eq(operand->value.value_integer, I128_ZERO)) { - if (str_ne(make_string_c(expr_str), str_lit("nil"))) { // HACK NOTE(bill): Just in case + if (make_string_c(expr_str) != "nil") { // HACK NOTE(bill): Just in case // NOTE(bill): Doesn't matter what the type is as it's still zero in the union extra_text = " - Did you want `nil`?"; } @@ -3206,7 +3241,7 @@ isize entity_overload_count(Scope *s, String name) { } if (e->kind == Entity_Procedure) { // NOTE(bill): Overloads are only allowed with the same scope - return map_entity_multi_count(&s->elements, hash_string(e->token.string)); + return multi_map_count(&s->elements, hash_string(e->token.string)); } return 1; } @@ -3238,7 +3273,7 @@ Entity *check_selector(Checker *c, Operand *operand, AstNode *node, Type *type_h bool check_op_expr = true; Entity *expr_entity = NULL; Entity *entity = NULL; - Selection sel = {0}; // NOTE(bill): Not used if it's an import name + Selection sel = {}; // NOTE(bill): Not used if it's an import name operand->expr = node; @@ -3298,7 +3333,7 @@ Entity *check_selector(Checker *c, Operand *operand, AstNode *node, Type *type_h isize overload_count = entity_overload_count(import_scope, entity_name); bool is_overloaded = overload_count > 1; - bool implicit_is_found = map_bool_get(&e->ImportName.scope->implicit, hash_pointer(entity)) != NULL; + bool implicit_is_found = map_get(&e->ImportName.scope->implicit, hash_pointer(entity)) != NULL; bool is_not_exported = !is_entity_exported(entity); if (!implicit_is_found) { is_not_exported = false; @@ -3320,7 +3355,7 @@ Entity *check_selector(Checker *c, Operand *operand, AstNode *node, Type *type_h bool skip = false; Entity **procs = gb_alloc_array(heap_allocator(), Entity *, overload_count); - map_entity_multi_get_all(&import_scope->elements, key, procs); + multi_map_get_all(&import_scope->elements, key, procs); for (isize i = 0; i < overload_count; i++) { Type *t = base_type(procs[i]->type); @@ -3329,14 +3364,14 @@ Entity *check_selector(Checker *c, Operand *operand, AstNode *node, Type *type_h } // NOTE(bill): Check to see if it's imported - if (map_bool_get(&import_scope->implicit, hash_pointer(procs[i]))) { + if (map_get(&import_scope->implicit, hash_pointer(procs[i]))) { gb_swap(Entity *, procs[i], procs[overload_count-1]); overload_count--; i--; // NOTE(bill): Counteract the post event continue; } - Operand x = {0}; + Operand x = {}; x.mode = Addressing_Value; x.type = t; if (type_hint != NULL) { @@ -3390,7 +3425,7 @@ Entity *check_selector(Checker *c, Operand *operand, AstNode *node, Type *type_h if (entity == NULL && selector->kind == AstNode_BasicLit) { if (is_type_struct(operand->type) || is_type_tuple(operand->type)) { Type *type = base_type(operand->type); - Operand o = {0}; + Operand o = {}; check_expr(c, &o, selector); if (o.mode != Addressing_Constant || !is_type_integer(o.type)) { @@ -3496,7 +3531,7 @@ Entity *check_selector(Checker *c, Operand *operand, AstNode *node, Type *type_h break; case Entity_Builtin: operand->mode = Addressing_Builtin; - operand->builtin_id = entity->Builtin.id; + operand->builtin_id = cast(BuiltinProcId)entity->Builtin.id; break; // NOTE(bill): These cases should never be hit but are here for sanity reasons @@ -3533,6 +3568,14 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id } } + if (ce->args.count > 0) { + if (ce->args[0]->kind == AstNode_FieldValue) { + error_node(call, "`field = value` calling is not allowed on built-in procedures"); + return false; + } + } + + bool vari_expand = (ce->ellipsis.pos.line != 0); if (vari_expand && id != BuiltinProc_append) { error(ce->ellipsis, "Invalid use of `..` with built-in procedure `append`"); @@ -3551,12 +3594,12 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id // NOTE(bill): The first arg may be a Type, this will be checked case by case break; default: - check_multi_expr(c, operand, ce->args.e[0]); + check_multi_expr(c, operand, ce->args[0]); } switch (id) { default: - GB_PANIC("Implement builtin procedure: %.*s", LIT(builtin_procs[id].name)); + GB_PANIC("Implement built-in procedure: %.*s", LIT(builtin_procs[id].name)); break; case BuiltinProc_len: @@ -3566,7 +3609,7 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id Type *op_type = type_deref(operand->type); Type *type = t_int; AddressingMode mode = Addressing_Invalid; - ExactValue value = {0}; + ExactValue value = {}; if (is_type_string(op_type) && id == BuiltinProc_len) { if (operand->mode == Addressing_Constant) { mode = Addressing_Constant; @@ -3608,11 +3651,11 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id case BuiltinProc_new: { // new :: proc(Type) -> ^Type - Operand op = {0}; - check_expr_or_type(c, &op, ce->args.e[0]); + Operand op = {}; + check_expr_or_type(c, &op, ce->args[0]); Type *type = op.type; if ((op.mode != Addressing_Type && type == NULL) || type == t_invalid) { - error_node(ce->args.e[0], "Expected a type for `new`"); + error_node(ce->args[0], "Expected a type for `new`"); return false; } operand->mode = Addressing_Value; @@ -3622,25 +3665,25 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id case BuiltinProc_new_slice: { // new_slice :: proc(Type, len: int) -> []Type // new_slice :: proc(Type, len, cap: int) -> []Type - Operand op = {0}; - check_expr_or_type(c, &op, ce->args.e[0]); + Operand op = {}; + check_expr_or_type(c, &op, ce->args[0]); Type *type = op.type; if ((op.mode != Addressing_Type && type == NULL) || type == t_invalid) { - error_node(ce->args.e[0], "Expected a type for `new_slice`"); + error_node(ce->args[0], "Expected a type for `new_slice`"); return false; } isize arg_count = ce->args.count; if (arg_count < 2 || 3 < arg_count) { - error_node(ce->args.e[0], "`new_slice` expects 2 or 3 arguments, found %td", arg_count); + error_node(ce->args[0], "`new_slice` expects 2 or 3 arguments, found %td", arg_count); // NOTE(bill): Return the correct type to reduce errors } else { // If any are constant - i64 sizes[2] = {0}; + i64 sizes[2] = {}; isize size_count = 0; for (isize i = 1; i < arg_count; i++) { i64 val = 0; - bool ok = check_index_value(c, ce->args.e[i], -1, &val); + bool ok = check_index_value(c, ce->args[i], -1, &val); if (ok && val >= 0) { GB_ASSERT(size_count < gb_count_of(sizes)); sizes[size_count++] = val; @@ -3648,7 +3691,7 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id } if (size_count == 2 && sizes[0] > sizes[1]) { - error_node(ce->args.e[1], "`new_slice` count and capacity are swapped"); + error_node(ce->args[1], "`new_slice` count and capacity are swapped"); // No need quit } } @@ -3660,11 +3703,11 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id case BuiltinProc_make: { // make :: proc(Type, len: int) -> Type // make :: proc(Type, len, cap: int) -> Type - Operand op = {0}; - check_expr_or_type(c, &op, ce->args.e[0]); + Operand op = {}; + check_expr_or_type(c, &op, ce->args[0]); Type *type = op.type; if ((op.mode != Addressing_Type && type == NULL) || type == t_invalid) { - error_node(ce->args.e[0], "Expected a type for `make`"); + error_node(ce->args[0], "Expected a type for `make`"); return false; } @@ -3688,16 +3731,16 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id isize arg_count = ce->args.count; if (arg_count < min_args || max_args < arg_count) { - error_node(ce->args.e[0], "`make` expects %td or %d argument, found %td", min_args, max_args, arg_count); + error_node(ce->args[0], "`make` expects %td or %d argument, found %td", min_args, max_args, arg_count); return false; } // If any are constant - i64 sizes[4] = {0}; + i64 sizes[4] = {}; isize size_count = 0; for (isize i = 1; i < arg_count; i++) { i64 val = 0; - bool ok = check_index_value(c, false, ce->args.e[i], -1, &val); + bool ok = check_index_value(c, false, ce->args[i], -1, &val); if (ok && val >= 0) { GB_ASSERT(size_count < gb_count_of(sizes)); sizes[size_count++] = val; @@ -3705,7 +3748,7 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id } if (size_count == 2 && sizes[0] > sizes[1]) { - error_node(ce->args.e[1], "`make` count and capacity are swapped"); + error_node(ce->args[1], "`make` count and capacity are swapped"); // No need quit } @@ -3755,8 +3798,8 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id return false; } - AstNode *capacity = ce->args.e[1]; - Operand op = {0}; + AstNode *capacity = ce->args[1]; + Operand op = {}; check_expr(c, &op, capacity); if (op.mode == Addressing_Invalid) { return false; @@ -3846,8 +3889,8 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id Type *key = base_type(type)->Map.key; Operand x = {Addressing_Invalid}; - AstNode *key_node = ce->args.e[1]; - Operand op = {0}; + AstNode *key_node = ce->args[1]; + Operand op = {}; check_expr(c, &op, key_node); if (op.mode == Addressing_Invalid) { return false; @@ -3868,9 +3911,9 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id case BuiltinProc_size_of: { // size_of :: proc(Type) -> untyped int - Type *type = check_type(c, ce->args.e[0]); + Type *type = check_type(c, ce->args[0]); if (type == NULL || type == t_invalid) { - error_node(ce->args.e[0], "Expected a type for `size_of`"); + error_node(ce->args[0], "Expected a type for `size_of`"); return false; } @@ -3894,9 +3937,9 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id case BuiltinProc_align_of: { // align_of :: proc(Type) -> untyped int - Type *type = check_type(c, ce->args.e[0]); + Type *type = check_type(c, ce->args[0]); if (type == NULL || type == t_invalid) { - error_node(ce->args.e[0], "Expected a type for `align_of`"); + error_node(ce->args[0], "Expected a type for `align_of`"); return false; } operand->mode = Addressing_Constant; @@ -3918,15 +3961,15 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id case BuiltinProc_offset_of: { // offset_of :: proc(Type, field) -> untyped int - Operand op = {0}; - Type *bt = check_type(c, ce->args.e[0]); + Operand op = {}; + Type *bt = check_type(c, ce->args[0]); Type *type = base_type(bt); if (type == NULL || type == t_invalid) { - error_node(ce->args.e[0], "Expected a type for `offset_of`"); + error_node(ce->args[0], "Expected a type for `offset_of`"); return false; } - AstNode *field_arg = unparen_expr(ce->args.e[1]); + AstNode *field_arg = unparen_expr(ce->args[1]); if (field_arg == NULL || field_arg->kind != AstNode_Ident) { error_node(field_arg, "Expected an identifier for field argument"); @@ -3942,14 +3985,14 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id Selection sel = lookup_field(c->allocator, type, arg->string, operand->mode == Addressing_Type); if (sel.entity == NULL) { gbString type_str = type_to_string(bt); - error_node(ce->args.e[0], + error_node(ce->args[0], "`%s` has no field named `%.*s`", type_str, LIT(arg->string)); gb_string_free(type_str); return false; } if (sel.indirect) { gbString type_str = type_to_string(bt); - error_node(ce->args.e[0], + error_node(ce->args[0], "Field `%.*s` is embedded via a pointer in `%s`", LIT(arg->string), type_str); gb_string_free(type_str); return false; @@ -3962,7 +4005,7 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id case BuiltinProc_offset_of_val: { // offset_of_val :: proc(val: expression) -> untyped int - AstNode *arg = unparen_expr(ce->args.e[0]); + AstNode *arg = unparen_expr(ce->args[0]); if (arg->kind != AstNode_SelectorExpr) { gbString str = expr_to_string(arg); error_node(arg, "`%s` is not a selector expression", str); @@ -3997,7 +4040,7 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id } if (sel.indirect) { gbString type_str = type_to_string(type); - error_node(ce->args.e[0], + error_node(ce->args[0], "Field `%.*s` is embedded via a pointer in `%s`", LIT(i->string), type_str); gb_string_free(type_str); return false; @@ -4031,7 +4074,7 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id // NOTE(bill): The type information may not be setup yet init_preload(c); - AstNode *expr = ce->args.e[0]; + AstNode *expr = ce->args[0]; Type *type = check_type(c, expr); if (type == NULL || type == t_invalid) { error_node(expr, "Invalid argument to `type_info`"); @@ -4052,7 +4095,7 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id // NOTE(bill): The type information may not be setup yet init_preload(c); - AstNode *expr = ce->args.e[0]; + AstNode *expr = ce->args[0]; check_assignment(c, operand, NULL, str_lit("argument of `type_info_of_val`")); if (operand->mode == Addressing_Invalid || operand->mode == Addressing_Builtin) return false; @@ -4066,13 +4109,13 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id // compile_assert :: proc(cond: bool) -> bool if (!is_type_boolean(operand->type) && operand->mode != Addressing_Constant) { - gbString str = expr_to_string(ce->args.e[0]); + gbString str = expr_to_string(ce->args[0]); error_node(call, "`%s` is not a constant boolean", str); gb_string_free(str); return false; } if (!operand->value.value_bool) { - gbString str = expr_to_string(ce->args.e[0]); + gbString str = expr_to_string(ce->args[0]); error_node(call, "Compile time assertion: `%s`", str); gb_string_free(str); } @@ -4085,7 +4128,7 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id // assert :: proc(cond: bool) -> bool if (!is_type_boolean(operand->type)) { - gbString str = expr_to_string(ce->args.e[0]); + gbString str = expr_to_string(ce->args[0]); error_node(call, "`%s` is not a boolean", str); gb_string_free(str); return false; @@ -4099,7 +4142,7 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id // panic :: proc(msg: string) if (!is_type_string(operand->type)) { - gbString str = expr_to_string(ce->args.e[0]); + gbString str = expr_to_string(ce->args[0]); error_node(call, "`%s` is not a string", str); gb_string_free(str); return false; @@ -4116,8 +4159,8 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id if (d->kind == Type_Slice) { dest_type = d->Slice.elem; } - Operand op = {0}; - check_expr(c, &op, ce->args.e[1]); + Operand op = {}; + check_expr(c, &op, ce->args[1]); if (op.mode == Addressing_Invalid) { return false; } @@ -4132,8 +4175,8 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id } if (!are_types_identical(dest_type, src_type)) { - gbString d_arg = expr_to_string(ce->args.e[0]); - gbString s_arg = expr_to_string(ce->args.e[1]); + gbString d_arg = expr_to_string(ce->args[0]); + gbString s_arg = expr_to_string(ce->args[1]); gbString d_str = type_to_string(dest_type); gbString s_str = type_to_string(src_type); error_node(call, @@ -4169,8 +4212,8 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id if (i == 0) { continue; } - AstNode *arg = ce->args.e[i]; - Operand op = {0}; + AstNode *arg = ce->args[i]; + Operand op = {}; check_expr(c, &op, arg); if (op.mode == Addressing_Invalid) { return false; @@ -4207,13 +4250,13 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id case BuiltinProc_complex: { // complex :: proc(real, imag: float_type) -> complex_type Operand x = *operand; - Operand y = {0}; + Operand y = {}; // NOTE(bill): Invalid will be the default till fixed operand->type = t_invalid; operand->mode = Addressing_Invalid; - check_expr(c, &y, ce->args.e[1]); + check_expr(c, &y, ce->args[1]); if (y.mode == Addressing_Invalid) { return false; } @@ -4348,15 +4391,15 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id isize arg_count = ce->args.count; if (arg_count < 2 || 3 < arg_count) { - error_node(ce->args.e[0], "`slice_ptr` expects 2 or 3 arguments, found %td", arg_count); + error_node(ce->args[0], "`slice_ptr` expects 2 or 3 arguments, found %td", arg_count); // NOTE(bill): Return the correct type to reduce errors } else { // If any are constant - i64 sizes[2] = {0}; + i64 sizes[2] = {}; isize size_count = 0; for (isize i = 1; i < arg_count; i++) { i64 val = 0; - bool ok = check_index_value(c, false, ce->args.e[i], -1, &val); + bool ok = check_index_value(c, false, ce->args[i], -1, &val); if (ok && val >= 0) { GB_ASSERT(size_count < gb_count_of(sizes)); sizes[size_count++] = val; @@ -4364,7 +4407,7 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id } if (size_count == 2 && sizes[0] > sizes[1]) { - error_node(ce->args.e[1], "`slice_ptr` count and capacity are swapped"); + error_node(ce->args[1], "`slice_ptr` count and capacity are swapped"); // No need quit } } @@ -4396,9 +4439,9 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id return false; } - AstNode *other_arg = ce->args.e[1]; + AstNode *other_arg = ce->args[1]; Operand a = *operand; - Operand b = {0}; + Operand b = {}; check_expr(c, &b, other_arg); if (b.mode == Addressing_Invalid) { return false; @@ -4464,9 +4507,9 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id return false; } - AstNode *other_arg = ce->args.e[1]; + AstNode *other_arg = ce->args[1]; Operand a = *operand; - Operand b = {0}; + Operand b = {}; check_expr(c, &b, other_arg); if (b.mode == Addressing_Invalid) { return false; @@ -4566,11 +4609,11 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id return false; } - AstNode *min_arg = ce->args.e[1]; - AstNode *max_arg = ce->args.e[2]; + AstNode *min_arg = ce->args[1]; + AstNode *max_arg = ce->args[2]; Operand x = *operand; - Operand y = {0}; - Operand z = {0}; + Operand y = {}; + Operand z = {}; check_expr(c, &y, min_arg); if (y.mode == Addressing_Invalid) { @@ -4645,14 +4688,14 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id } break; case BuiltinProc_transmute: { - Operand op = {0}; - check_expr_or_type(c, &op, ce->args.e[0]); + Operand op = {}; + check_expr_or_type(c, &op, ce->args[0]); Type *t = op.type; if ((op.mode != Addressing_Type && t == NULL) || t == t_invalid) { - error_node(ce->args.e[0], "Expected a type for `transmute`"); + error_node(ce->args[0], "Expected a type for `transmute`"); return false; } - AstNode *expr = ce->args.e[1]; + AstNode *expr = ce->args[1]; Operand *o = operand; check_expr(c, o, expr); if (o->mode == Addressing_Invalid) { @@ -4698,7 +4741,7 @@ bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id return true; } -typedef enum CallArgumentError { +enum CallArgumentError { CallArgumentError_None, CallArgumentError_WrongTypes, CallArgumentError_NonVariadicExpand, @@ -4707,126 +4750,22 @@ typedef enum CallArgumentError { CallArgumentError_ArgumentCount, CallArgumentError_TooFewArguments, CallArgumentError_TooManyArguments, -} CallArgumentError; + CallArgumentError_InvalidFieldValue, + CallArgumentError_ParameterNotFound, + CallArgumentError_ParameterMissing, + CallArgumentError_DuplicateParameter, +}; -typedef enum CallArgumentErrorMode { +enum CallArgumentErrorMode { CallArgumentMode_NoErrors, CallArgumentMode_ShowErrors, -} CallArgumentErrorMode; +}; -CallArgumentError check_call_arguments_internal(Checker *c, AstNode *call, Type *proc_type, Operand *operands, isize operand_count, - CallArgumentErrorMode show_error_mode, i64 *score_) { - ast_node(ce, CallExpr, call); - isize param_count = 0; - bool variadic = proc_type->Proc.variadic; - bool vari_expand = (ce->ellipsis.pos.line != 0); - i64 score = 0; - bool show_error = show_error_mode == CallArgumentMode_ShowErrors; - if (proc_type->Proc.params != NULL) { - param_count = proc_type->Proc.params->Tuple.variable_count; - if (variadic) { - param_count--; - } - } - - if (vari_expand && !variadic) { - if (show_error) { - error(ce->ellipsis, - "Cannot use `..` in call to a non-variadic procedure: `%.*s`", - LIT(ce->proc->Ident.string)); - } - if (score_) *score_ = score; - return CallArgumentError_NonVariadicExpand; - } - - if (operand_count == 0 && param_count == 0) { - if (score_) *score_ = score; - return CallArgumentError_None; - } - - i32 error_code = 0; - if (operand_count < param_count) { - error_code = -1; - } else if (!variadic && operand_count > param_count) { - error_code = +1; - } - if (error_code != 0) { - CallArgumentError err = CallArgumentError_TooManyArguments; - char *err_fmt = "Too many arguments for `%s`, expected %td arguments"; - if (error_code < 0) { - err = CallArgumentError_TooFewArguments; - err_fmt = "Too few arguments for `%s`, expected %td arguments"; - } - - if (show_error) { - gbString proc_str = expr_to_string(ce->proc); - error_node(call, err_fmt, proc_str, param_count); - gb_string_free(proc_str); - } - if (score_) *score_ = score; - return err; - } - - bool err = CallArgumentError_None; - - GB_ASSERT(proc_type->Proc.params != NULL); - Entity **sig_params = proc_type->Proc.params->Tuple.variables; - isize operand_index = 0; - for (; operand_index < param_count; operand_index++) { - Type *t = sig_params[operand_index]->type; - Operand o = operands[operand_index]; - if (variadic) { - o = operands[operand_index]; - } - i64 s = 0; - if (!check_is_assignable_to_with_score(c, &o, t, &s)) { - if (show_error) { - check_assignment(c, &o, t, str_lit("argument")); - } - err = CallArgumentError_WrongTypes; - } - score += s; - } - - if (variadic) { - bool variadic_expand = false; - Type *slice = sig_params[param_count]->type; - GB_ASSERT(is_type_slice(slice)); - Type *elem = base_type(slice)->Slice.elem; - Type *t = elem; - for (; operand_index < operand_count; operand_index++) { - Operand o = operands[operand_index]; - if (vari_expand) { - variadic_expand = true; - t = slice; - if (operand_index != param_count) { - if (show_error) { - error_node(o.expr, "`..` in a variadic procedure can only have one variadic argument at the end"); - } - if (score_) *score_ = score; - return CallArgumentError_MultipleVariadicExpand; - } - } - i64 s = 0; - if (!check_is_assignable_to_with_score(c, &o, t, &s)) { - if (show_error) { - check_assignment(c, &o, t, str_lit("argument")); - } - err = CallArgumentError_WrongTypes; - } - score += s; - } - } - - if (score_) *score_ = score; - return err; -} - -typedef struct ValidProcAndScore { +struct ValidProcAndScore { isize index; i64 score; -} ValidProcAndScore; +}; int valid_proc_and_score_cmp(void const *a, void const *b) { i64 si = (cast(ValidProcAndScore const *)a)->score; @@ -4834,13 +4773,11 @@ int valid_proc_and_score_cmp(void const *a, void const *b) { return sj < si ? -1 : sj > si; } -typedef Array(Operand) ArrayOperand; - -bool check_unpack_arguments(Checker *c, isize lhs_count, ArrayOperand *operands, AstNodeArray rhs, bool allow_ok) { +bool check_unpack_arguments(Checker *c, isize lhs_count, Array *operands, Array rhs, bool allow_ok) { bool optional_ok = false; for_array(i, rhs) { - Operand o = {0}; - check_multi_expr(c, &o, rhs.e[i]); + Operand o = {}; + check_multi_expr(c, &o, rhs[i]); if (o.type == NULL || o.type->kind != Type_Tuple) { if (allow_ok && lhs_count == 2 && rhs.count == 1 && @@ -4872,29 +4809,294 @@ bool check_unpack_arguments(Checker *c, isize lhs_count, ArrayOperand *operands, return optional_ok; } -Type *check_call_arguments(Checker *c, Operand *operand, Type *proc_type, AstNode *call) { - GB_ASSERT(call->kind == AstNode_CallExpr); +#define CALL_ARGUMENT_CHECKER(name) CallArgumentError name(Checker *c, AstNode *call, Type *proc_type, Array operands, CallArgumentErrorMode show_error_mode, i64 *score_) +typedef CALL_ARGUMENT_CHECKER(CallArgumentCheckerType); + +CALL_ARGUMENT_CHECKER(check_call_arguments_internal) { + ast_node(ce, CallExpr, call); + isize param_count = 0; + isize param_count_excluding_defaults = 0; + bool variadic = proc_type->Proc.variadic; + bool vari_expand = (ce->ellipsis.pos.line != 0); + i64 score = 0; + bool show_error = show_error_mode == CallArgumentMode_ShowErrors; + + TypeTuple *param_tuple = NULL; + + if (proc_type->Proc.params != NULL) { + param_tuple = &proc_type->Proc.params->Tuple; + + param_count = param_tuple->variable_count; + if (variadic) { + param_count--; + } + } + + param_count_excluding_defaults = param_count; + if (param_tuple != NULL) { + for (isize i = param_count-1; i >= 0; i--) { + Entity *e = param_tuple->variables[i]; + GB_ASSERT(e->kind == Entity_Variable); + if (e->Variable.default_value.kind == ExactValue_Invalid) { + break; + } + param_count_excluding_defaults--; + } + } + + if (vari_expand && !variadic) { + if (show_error) { + error(ce->ellipsis, + "Cannot use `..` in call to a non-variadic procedure: `%.*s`", + LIT(ce->proc->Ident.string)); + } + if (score_) *score_ = score; + return CallArgumentError_NonVariadicExpand; + } + + if (operands.count == 0 && param_count_excluding_defaults == 0) { + if (score_) *score_ = score; + return CallArgumentError_None; + } + + i32 error_code = 0; + if (operands.count < param_count_excluding_defaults) { + error_code = -1; + } else if (!variadic && operands.count > param_count) { + error_code = +1; + } + if (error_code != 0) { + CallArgumentError err = CallArgumentError_TooManyArguments; + char *err_fmt = "Too many arguments for `%s`, expected %td arguments"; + if (error_code < 0) { + err = CallArgumentError_TooFewArguments; + err_fmt = "Too few arguments for `%s`, expected %td arguments"; + } + + if (show_error) { + gbString proc_str = expr_to_string(ce->proc); + error_node(call, err_fmt, proc_str, param_count_excluding_defaults); + gb_string_free(proc_str); + } + if (score_) *score_ = score; + return err; + } + + CallArgumentError err = CallArgumentError_None; + + GB_ASSERT(proc_type->Proc.params != NULL); + Entity **sig_params = param_tuple->variables; + isize operand_index = 0; + for (; operand_index < param_count_excluding_defaults; operand_index++) { + Type *t = sig_params[operand_index]->type; + Operand o = operands[operand_index]; + if (variadic) { + o = operands[operand_index]; + } + i64 s = 0; + if (!check_is_assignable_to_with_score(c, &o, t, &s)) { + if (show_error) { + check_assignment(c, &o, t, str_lit("argument")); + } + err = CallArgumentError_WrongTypes; + } + score += s; + } + + if (variadic) { + bool variadic_expand = false; + Type *slice = sig_params[param_count]->type; + GB_ASSERT(is_type_slice(slice)); + Type *elem = base_type(slice)->Slice.elem; + Type *t = elem; + for (; operand_index < operands.count; operand_index++) { + Operand o = operands[operand_index]; + if (vari_expand) { + variadic_expand = true; + t = slice; + if (operand_index != param_count) { + if (show_error) { + error_node(o.expr, "`..` in a variadic procedure can only have one variadic argument at the end"); + } + if (score_) *score_ = score; + return CallArgumentError_MultipleVariadicExpand; + } + } + i64 s = 0; + if (!check_is_assignable_to_with_score(c, &o, t, &s)) { + if (show_error) { + check_assignment(c, &o, t, str_lit("argument")); + } + err = CallArgumentError_WrongTypes; + } + score += s; + } + } + + if (score_) *score_ = score; + return err; +} + +bool is_call_expr_field_value(AstNodeCallExpr *ce) { + GB_ASSERT(ce != NULL); + + if (ce->args.count == 0) { + return false; + } + return ce->args[0]->kind == AstNode_FieldValue; +} + +isize lookup_procedure_parameter(TypeProc *pt, String parameter_name) { + isize param_count = pt->param_count; + for (isize i = 0; i < param_count; i++) { + Entity *e = pt->params->Tuple.variables[i]; + String name = e->token.string; + if (name == "_") { + continue; + } + if (name == parameter_name) { + return i; + } + } + return -1; +} + +CALL_ARGUMENT_CHECKER(check_named_call_arguments) { + ast_node(ce, CallExpr, call); + GB_ASSERT(is_type_proc(proc_type)); + TypeProc *pt = &base_type(proc_type)->Proc; + + i64 score = 0; + bool show_error = show_error_mode == CallArgumentMode_ShowErrors; + CallArgumentError err = CallArgumentError_None; + + isize param_count = pt->param_count; + bool *params_visited = gb_alloc_array(c->allocator, bool, param_count); + + for_array(i, ce->args) { + AstNode *arg = ce->args[i]; + ast_node(fv, FieldValue, arg); + if (fv->field->kind != AstNode_Ident) { + if (show_error) { + gbString expr_str = expr_to_string(fv->field); + error_node(arg, "Invalid parameter name `%s` in procedure call", expr_str); + gb_string_free(expr_str); + } + err = CallArgumentError_InvalidFieldValue; + continue; + } + String name = fv->field->Ident.string; + isize index = lookup_procedure_parameter(pt, name); + if (index < 0) { + if (show_error) { + error_node(arg, "No parameter named `%.*s` for this procedure type", LIT(name)); + } + err = CallArgumentError_ParameterNotFound; + continue; + } + if (params_visited[index]) { + if (show_error) { + error_node(arg, "Duplicate parameter `%.*s` in procedure call", LIT(name)); + } + err = CallArgumentError_DuplicateParameter; + continue; + } + + params_visited[index] = true; + Operand *o = &operands[i]; + + Type *param_type = pt->params->Tuple.variables[index]->type; + + i64 s = 0; + if (!check_is_assignable_to_with_score(c, o, param_type, &s)) { + if (show_error) { + check_assignment(c, o, param_type, str_lit("procedure argument")); + } + err = CallArgumentError_WrongTypes; + } + score += s; + } + + +#if 1 + isize param_count_to_check = param_count; + if (pt->variadic) { + param_count_to_check--; + } + for (isize i = 0; i < param_count_to_check; i++) { + if (!params_visited[i]) { + Entity *e = pt->params->Tuple.variables[i]; + if (e->token.string == "_") { + continue; + } + GB_ASSERT(e->kind == Entity_Variable); + if (e->Variable.default_value.kind != ExactValue_Invalid) { + score += assign_score_function(1); + continue; + } + + if (show_error) { + gbString str = type_to_string(e->type); + error_node(call, "Parameter `%.*s` of type `%s` is missing in procedure call", + LIT(e->token.string), str); + gb_string_free(str); + } + err = CallArgumentError_ParameterMissing; + } + } +#endif + + if (score_) *score_ = score; + + return err; +} + + +Type *check_call_arguments(Checker *c, Operand *operand, Type *proc_type, AstNode *call) { ast_node(ce, CallExpr, call); - ArrayOperand operands; - array_init_reserve(&operands, heap_allocator(), 2*ce->args.count); - check_unpack_arguments(c, -1, &operands, ce->args, false); + CallArgumentCheckerType *call_checker = check_call_arguments_internal; + Array operands = {}; + defer (array_free(&operands)); + + if (is_call_expr_field_value(ce)) { + call_checker = check_named_call_arguments; + + array_init_count(&operands, heap_allocator(), ce->args.count); + for_array(i, ce->args) { + AstNode *arg = ce->args[i]; + ast_node(fv, FieldValue, arg); + check_expr(c, &operands[i], fv->value); + } + + bool vari_expand = (ce->ellipsis.pos.line != 0); + if (vari_expand) { + error(ce->ellipsis, "Invalid use of `..` with `field = value` call`"); + } + + } else { + array_init(&operands, heap_allocator(), 2*ce->args.count); + check_unpack_arguments(c, -1, &operands, ce->args, false); + } if (operand->mode == Addressing_Overload) { GB_ASSERT(operand->overload_entities != NULL && - operand->overload_count > 0); + operand->overload_count > 1); isize overload_count = operand->overload_count; Entity ** procs = operand->overload_entities; ValidProcAndScore *valids = gb_alloc_array(heap_allocator(), ValidProcAndScore, overload_count); isize valid_count = 0; + defer (gb_free(heap_allocator(), procs)); + defer (gb_free(heap_allocator(), valids)); + String name = procs[0]->token.string; for (isize i = 0; i < overload_count; i++) { Entity *e = procs[i]; - DeclInfo **found = map_decl_info_get(&c->info.entities, hash_pointer(e)); + DeclInfo **found = map_get(&c->info.entities, hash_pointer(e)); GB_ASSERT(found != NULL); DeclInfo *d = *found; check_entity_decl(c, e, d, NULL); @@ -4905,7 +5107,7 @@ Type *check_call_arguments(Checker *c, Operand *operand, Type *proc_type, AstNod Type *proc_type = base_type(p->type); if (proc_type != NULL && is_type_proc(proc_type)) { i64 score = 0; - CallArgumentError err = check_call_arguments_internal(c, call, proc_type, operands.e, operands.count, CallArgumentMode_NoErrors, &score); + CallArgumentError err = call_checker(c, call, proc_type, operands, CallArgumentMode_NoErrors, &score); if (err == CallArgumentError_None) { valids[valid_count].index = i; valids[valid_count].score = score; @@ -4936,7 +5138,7 @@ Type *check_call_arguments(Checker *c, Operand *operand, Type *proc_type, AstNod Entity *proc = procs[valids[i].index]; TokenPos pos = proc->token.pos; gbString pt = type_to_string(proc->type); - gb_printf_err("\t%.*s :: %s at %.*s(%td:%td)\n", LIT(name), pt, LIT(pos.file), pos.line, pos.column); + gb_printf_err("\t%.*s :: %s at %.*s(%td:%td) with score %lld\n", LIT(name), pt, LIT(pos.file), pos.line, pos.column, valids[i].score); gb_string_free(pt); } proc_type = t_invalid; @@ -4950,16 +5152,14 @@ Type *check_call_arguments(Checker *c, Operand *operand, Type *proc_type, AstNod add_entity_use(c, expr, e); proc_type = e->type; i64 score = 0; - CallArgumentError err = check_call_arguments_internal(c, call, proc_type, operands.e, operands.count, CallArgumentMode_ShowErrors, &score); + CallArgumentError err = call_checker(c, call, proc_type, operands, CallArgumentMode_ShowErrors, &score); } - - gb_free(heap_allocator(), valids); - gb_free(heap_allocator(), procs); } else { i64 score = 0; - CallArgumentError err = check_call_arguments_internal(c, call, proc_type, operands.e, operands.count, CallArgumentMode_ShowErrors, &score); - array_free(&operands); + CallArgumentError err = call_checker(c, call, proc_type, operands, CallArgumentMode_ShowErrors, &score); } + + return proc_type; } @@ -4992,9 +5192,37 @@ ExprKind check_call_expr(Checker *c, Operand *operand, AstNode *call) { ast_node(ce, CallExpr, call); check_expr_or_type(c, operand, ce->proc); + if (ce->args.count > 0) { + bool fail = false; + bool first_is_field_value = (ce->args[0]->kind == AstNode_FieldValue); + for_array(i, ce->args) { + AstNode *arg = ce->args[i]; + bool mix = false; + if (first_is_field_value) { + mix = arg->kind != AstNode_FieldValue; + } else { + mix = arg->kind == AstNode_FieldValue; + } + if (mix) { + error_node(arg, "Mixture of `field = value` and value elements in a procedure all is not allowed"); + fail = true; + } + } + + if (fail) { + operand->mode = Addressing_Invalid; + operand->expr = call; + return Expr_Stmt; + } + } + if (operand->mode == Addressing_Invalid) { for_array(i, ce->args) { - check_expr_base(c, operand, ce->args.e[i], NULL); + AstNode *arg = ce->args[i]; + if (arg->kind == AstNode_FieldValue) { + arg = arg->FieldValue.value; + } + check_expr_base(c, operand, arg, NULL); } operand->mode = Addressing_Invalid; operand->expr = call; @@ -5007,14 +5235,20 @@ ExprKind check_call_expr(Checker *c, Operand *operand, AstNode *call) { operand->mode = Addressing_Invalid; isize arg_count = ce->args.count; switch (arg_count) { - case 0: error_node(call, "Missing argument in convertion to `%s`", str); break; - default: error_node(call, "Too many arguments in convertion to `%s`", str); break; - case 1: - check_expr(c, operand, ce->args.e[0]); + case 0: error_node(call, "Missing argument in conversion to `%s`", str); break; + default: error_node(call, "Too many arguments in conversion to `%s`", str); break; + case 1: { + AstNode *arg = ce->args[0]; + if (arg->kind == AstNode_FieldValue) { + error_node(call, "`field = value` cannot be used in a type conversion"); + arg = arg->FieldValue.value; + // NOTE(bill): Carry on the cast regardless + } + check_expr(c, operand, arg); if (operand->mode != Addressing_Invalid) { check_cast(c, operand, t); } - break; + } break; } gb_string_free(str); @@ -5213,7 +5447,7 @@ ExprKind check_expr_base_internal(Checker *c, Operand *o, AstNode *node, Type *t case Token_Rune: t = t_untyped_rune; break; case Token_Imag: { String s = bl->string; - Rune r = s.text[s.len-1]; + Rune r = s[s.len-1]; switch (r) { case 'i': t = t_untyped_complex; break; } @@ -5226,13 +5460,13 @@ ExprKind check_expr_base_internal(Checker *c, Operand *o, AstNode *node, Type *t case_end; case_ast_node(bd, BasicDirective, node); - if (str_eq(bd->name, str_lit("file"))) { + if (bd->name == "file") { o->type = t_untyped_string; o->value = exact_value_string(bd->token.pos.file); - } else if (str_eq(bd->name, str_lit("line"))) { + } else if (bd->name == "line") { o->type = t_untyped_integer; o->value = exact_value_i64(bd->token.pos.line); - } else if (str_eq(bd->name, str_lit("procedure"))) { + } else if (bd->name == "procedure") { if (c->proc_stack.count == 0) { error_node(node, "#procedure may only be used within procedures"); o->type = t_untyped_string; @@ -5388,11 +5622,11 @@ ExprKind check_expr_base_internal(Checker *c, Operand *o, AstNode *node, Type *t } { // Checker values isize field_count = t->Record.field_count; - if (cl->elems.e[0]->kind == AstNode_FieldValue) { + if (cl->elems[0]->kind == AstNode_FieldValue) { bool *fields_visited = gb_alloc_array(c->allocator, bool, field_count); for_array(i, cl->elems) { - AstNode *elem = cl->elems.e[i]; + AstNode *elem = cl->elems[i]; if (elem->kind != AstNode_FieldValue) { error_node(elem, "Mixture of `field = value` and value elements in a structure literal is not allowed"); continue; @@ -5423,15 +5657,15 @@ ExprKind check_expr_base_internal(Checker *c, Operand *o, AstNode *node, Type *t continue; } - Entity *field = t->Record.fields[sel.index.e[0]]; + Entity *field = t->Record.fields[sel.index[0]]; add_entity_use(c, fv->field, field); - if (fields_visited[sel.index.e[0]]) { + if (fields_visited[sel.index[0]]) { error_node(elem, "Duplicate field `%.*s` in structure literal", LIT(name)); continue; } - fields_visited[sel.index.e[0]] = true; + fields_visited[sel.index[0]] = true; check_expr(c, o, fv->value); if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type)) { @@ -5448,14 +5682,14 @@ ExprKind check_expr_base_internal(Checker *c, Operand *o, AstNode *node, Type *t bool all_fields_are_blank = true; for (isize i = 0; i < t->Record.field_count; i++) { Entity *field = t->Record.fields_in_src_order[i]; - if (str_ne(field->token.string, str_lit("_"))) { + if (field->token.string != "_") { all_fields_are_blank = false; break; } } for_array(index, cl->elems) { - AstNode *elem = cl->elems.e[index]; + AstNode *elem = cl->elems[index]; if (elem->kind == AstNode_FieldValue) { error_node(elem, "Mixture of `field = value` and value elements in a structure literal is not allowed"); continue; @@ -5466,7 +5700,7 @@ ExprKind check_expr_base_internal(Checker *c, Operand *o, AstNode *node, Type *t } Entity *field = t->Record.fields_in_src_order[index]; - if (!all_fields_are_blank && str_eq(field->token.string, str_lit("_"))) { + if (!all_fields_are_blank && field->token.string == "_") { // NOTE(bill): Ignore blank identifiers continue; } @@ -5502,7 +5736,7 @@ ExprKind check_expr_base_internal(Checker *c, Operand *o, AstNode *node, Type *t case Type_DynamicArray: { Type *elem_type = NULL; - String context_name = {0}; + String context_name = {}; i64 max_type_count = -1; if (t->kind == Type_Slice) { elem_type = t->Slice.elem; @@ -5533,8 +5767,8 @@ ExprKind check_expr_base_internal(Checker *c, Operand *o, AstNode *node, Type *t } for (; index < elem_count; index++) { - GB_ASSERT(cl->elems.e != NULL); - AstNode *e = cl->elems.e[index]; + GB_ASSERT(cl->elems.data != NULL); + AstNode *e = cl->elems[index]; if (e == NULL) { error_node(node, "Invalid literal element"); continue; @@ -5549,7 +5783,7 @@ ExprKind check_expr_base_internal(Checker *c, Operand *o, AstNode *node, Type *t error_node(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name)); } - Operand operand = {0}; + Operand operand = {}; check_expr_with_type_hint(c, &operand, e, elem_type); check_assignment(c, &operand, elem_type, context_name); @@ -5563,7 +5797,7 @@ ExprKind check_expr_base_internal(Checker *c, Operand *o, AstNode *node, Type *t if (t->kind == Type_Vector) { if (t->Vector.count > 1 && gb_is_between(index, 2, t->Vector.count-1)) { - error_node(cl->elems.e[0], "Expected either 1 (broadcast) or %td elements in vector literal, got %td", t->Vector.count, index); + error_node(cl->elems[0], "Expected either 1 (broadcast) or %td elements in vector literal, got %td", t->Vector.count, index); } } @@ -5585,11 +5819,11 @@ ExprKind check_expr_base_internal(Checker *c, Operand *o, AstNode *node, Type *t { // Checker values Type *field_types[2] = {t_rawptr, t_type_info_ptr}; isize field_count = 2; - if (cl->elems.e[0]->kind == AstNode_FieldValue) { - bool fields_visited[2] = {0}; + if (cl->elems[0]->kind == AstNode_FieldValue) { + bool fields_visited[2] = {}; for_array(i, cl->elems) { - AstNode *elem = cl->elems.e[i]; + AstNode *elem = cl->elems[i]; if (elem->kind != AstNode_FieldValue) { error_node(elem, "Mixture of `field = value` and value elements in a `any` literal is not allowed"); continue; @@ -5609,7 +5843,7 @@ ExprKind check_expr_base_internal(Checker *c, Operand *o, AstNode *node, Type *t continue; } - isize index = sel.index.e[0]; + isize index = sel.index[0]; if (fields_visited[index]) { error_node(elem, "Duplicate field `%.*s` in `any` literal", LIT(name)); @@ -5626,7 +5860,7 @@ ExprKind check_expr_base_internal(Checker *c, Operand *o, AstNode *node, Type *t } } else { for_array(index, cl->elems) { - AstNode *elem = cl->elems.e[index]; + AstNode *elem = cl->elems[index]; if (elem->kind == AstNode_FieldValue) { error_node(elem, "Mixture of `field = value` and value elements in a `any` literal is not allowed"); continue; @@ -5658,7 +5892,7 @@ ExprKind check_expr_base_internal(Checker *c, Operand *o, AstNode *node, Type *t is_constant = false; { // Checker values for_array(i, cl->elems) { - AstNode *elem = cl->elems.e[i]; + AstNode *elem = cl->elems[i]; if (elem->kind != AstNode_FieldValue) { error_node(elem, "Only `field = value` elements are allowed in a map literal"); continue; @@ -5839,7 +6073,7 @@ ExprKind check_expr_base_internal(Checker *c, Operand *o, AstNode *node, Type *t bool is_const = o->mode == Addressing_Constant; if (is_type_map(t)) { - Operand key = {0}; + Operand key = {}; check_expr(c, &key, ie->index); check_assignment(c, &key, t->Map.key, str_lit("map index")); if (key.mode == Addressing_Invalid) { @@ -5983,7 +6217,7 @@ ExprKind check_expr_base_internal(Checker *c, Operand *o, AstNode *node, Type *t TokenKind interval_kind = se->interval0.kind; - i64 indices[2] = {0}; + i64 indices[2] = {}; AstNode *nodes[3] = {se->low, se->high, se->max}; for (isize i = 0; i < gb_count_of(nodes); i++) { i64 index = max_count; @@ -6141,19 +6375,19 @@ void check_expr_or_type(Checker *c, Operand *o, AstNode *e) { gbString write_expr_to_string(gbString str, AstNode *node); -gbString write_record_fields_to_string(gbString str, AstNodeArray params) { +gbString write_record_fields_to_string(gbString str, Array params) { for_array(i, params) { if (i > 0) { str = gb_string_appendc(str, ", "); } - str = write_expr_to_string(str, params.e[i]); + str = write_expr_to_string(str, params[i]); } return str; } gbString string_append_token(gbString str, Token token) { if (token.string.len > 0) { - return gb_string_append_length(str, token.string.text, token.string.len); + return gb_string_append_length(str, &token.string[0], token.string.len); } return str; } @@ -6186,7 +6420,7 @@ gbString write_expr_to_string(gbString str, AstNode *node) { case_ast_node(bd, BasicDirective, node); str = gb_string_appendc(str, "#"); - str = gb_string_append_length(str, bd->name.text, bd->name.len); + str = gb_string_append_length(str, &bd->name[0], bd->name.len); case_end; case_ast_node(pl, ProcLit, node); @@ -6200,7 +6434,7 @@ gbString write_expr_to_string(gbString str, AstNode *node) { if (i > 0) { str = gb_string_appendc(str, ", "); } - str = write_expr_to_string(str, cl->elems.e[i]); + str = write_expr_to_string(str, cl->elems[i]); } str = gb_string_appendc(str, "}"); case_end; @@ -6321,7 +6555,7 @@ gbString write_expr_to_string(gbString str, AstNode *node) { } for_array(i, f->names) { - AstNode *name = f->names.e[i]; + AstNode *name = f->names[i]; if (i > 0) { str = gb_string_appendc(str, ", "); } @@ -6341,7 +6575,7 @@ gbString write_expr_to_string(gbString str, AstNode *node) { if (i > 0) { str = gb_string_appendc(str, ", "); } - str = write_expr_to_string(str, f->list.e[i]); + str = write_expr_to_string(str, f->list[i]); } case_end; @@ -6357,7 +6591,7 @@ gbString write_expr_to_string(gbString str, AstNode *node) { str = gb_string_appendc(str, "("); for_array(i, ce->args) { - AstNode *arg = ce->args.e[i]; + AstNode *arg = ce->args[i]; if (i > 0) { str = gb_string_appendc(str, ", "); } @@ -6406,7 +6640,7 @@ gbString write_expr_to_string(gbString str, AstNode *node) { if (i > 0) { str = gb_string_appendc(str, ", "); } - str = write_expr_to_string(str, et->fields.e[i]); + str = write_expr_to_string(str, et->fields[i]); } str = gb_string_appendc(str, "}"); case_end; diff --git a/src/check_stmt.c b/src/check_stmt.cpp similarity index 92% rename from src/check_stmt.c rename to src/check_stmt.cpp index d9639a11e..80233a38f 100644 --- a/src/check_stmt.c +++ b/src/check_stmt.cpp @@ -1,4 +1,4 @@ -void check_stmt_list(Checker *c, AstNodeArray stmts, u32 flags) { +void check_stmt_list(Checker *c, Array stmts, u32 flags) { if (stmts.count == 0) { return; } @@ -12,13 +12,13 @@ void check_stmt_list(Checker *c, AstNodeArray stmts, u32 flags) { isize max = stmts.count; for (isize i = stmts.count-1; i >= 0; i--) { - if (stmts.e[i]->kind != AstNode_EmptyStmt) { + if (stmts[i]->kind != AstNode_EmptyStmt) { break; } max--; } for (isize i = 0; i < max; i++) { - AstNode *n = stmts.e[i]; + AstNode *n = stmts[i]; if (n->kind == AstNode_EmptyStmt) { continue; } @@ -40,10 +40,10 @@ void check_stmt_list(Checker *c, AstNodeArray stmts, u32 flags) { } -bool check_is_terminating_list(AstNodeArray stmts) { +bool check_is_terminating_list(Array stmts) { // Iterate backwards for (isize n = stmts.count-1; n >= 0; n--) { - AstNode *stmt = stmts.e[n]; + AstNode *stmt = stmts[n]; if (stmt->kind != AstNode_EmptyStmt) { return check_is_terminating(stmt); } @@ -52,9 +52,9 @@ bool check_is_terminating_list(AstNodeArray stmts) { return false; } -bool check_has_break_list(AstNodeArray stmts, bool implicit) { +bool check_has_break_list(Array stmts, bool implicit) { for_array(i, stmts) { - AstNode *stmt = stmts.e[i]; + AstNode *stmt = stmts[i]; if (check_has_break(stmt, implicit)) { return true; } @@ -137,7 +137,7 @@ bool check_is_terminating(AstNode *node) { case_ast_node(ms, MatchStmt, node); bool has_default = false; for_array(i, ms->body->BlockStmt.stmts) { - AstNode *clause = ms->body->BlockStmt.stmts.e[i]; + AstNode *clause = ms->body->BlockStmt.stmts[i]; ast_node(cc, CaseClause, clause); if (cc->list.count == 0) { has_default = true; @@ -153,7 +153,7 @@ bool check_is_terminating(AstNode *node) { case_ast_node(ms, TypeMatchStmt, node); bool has_default = false; for_array(i, ms->body->BlockStmt.stmts) { - AstNode *clause = ms->body->BlockStmt.stmts.e[i]; + AstNode *clause = ms->body->BlockStmt.stmts[i]; ast_node(cc, CaseClause, clause); if (cc->list.count == 0) { has_default = true; @@ -187,7 +187,7 @@ Type *check_assignment_variable(Checker *c, Operand *rhs, AstNode *lhs_node) { // NOTE(bill): Ignore assignments to `_` if (node->kind == AstNode_Ident && - str_eq(node->Ident.string, str_lit("_"))) { + node->Ident.string == "_") { add_entity_definition(&c->info, node, NULL); check_assignment(c, rhs, NULL, str_lit("assignment to `_` identifier")); if (rhs->mode == Addressing_Invalid) { @@ -218,7 +218,7 @@ Type *check_assignment_variable(Checker *c, Operand *rhs, AstNode *lhs_node) { if (t == t_invalid) { continue; } - Operand x = {0}; + Operand x = {}; x.mode = Addressing_Value; x.type = t; if (check_is_assignable_to(c, &x, lhs.type)) { @@ -340,11 +340,11 @@ Type *check_assignment_variable(Checker *c, Operand *rhs, AstNode *lhs_node) { return rhs->type; } -typedef enum MatchTypeKind { +enum MatchTypeKind { MatchType_Invalid, MatchType_Union, MatchType_Any, -} MatchTypeKind; +}; MatchTypeKind check_valid_type_match_type(Type *type) { type = type_deref(type); @@ -384,15 +384,10 @@ void check_stmt(Checker *c, AstNode *node, u32 flags) { -typedef struct TypeAndToken { +struct TypeAndToken { Type *type; Token token; -} TypeAndToken; - -#define MAP_TYPE TypeAndToken -#define MAP_PROC map_type_and_token_ -#define MAP_NAME MapTypeAndToken -#include "map.c" +}; void check_when_stmt(Checker *c, AstNodeWhenStmt *ws, u32 flags) { flags &= ~Stmt_CheckScopeDecls; @@ -434,7 +429,7 @@ void check_label(Checker *c, AstNode *label) { return; } String name = l->name->Ident.string; - if (str_eq(name, str_lit("_"))) { + if (name == "_") { error_node(l->name, "A label's name cannot be a blank identifier"); return; } @@ -448,8 +443,8 @@ void check_label(Checker *c, AstNode *label) { bool ok = true; for_array(i, c->context.decl->labels) { - BlockLabel bl = c->context.decl->labels.e[i]; - if (str_eq(bl.name, name)) { + BlockLabel bl = c->context.decl->labels[i]; + if (bl.name == name) { error_node(label, "Duplicate label with the name `%.*s`", LIT(name)); ok = false; break; @@ -513,7 +508,7 @@ bool check_using_stmt_entity(Checker *c, AstNodeUsingStmt *us, AstNode *expr, bo case Entity_ImportName: { Scope *scope = e->ImportName.scope; for_array(i, scope->elements.entries) { - Entity *decl = scope->elements.entries.e[i].value; + Entity *decl = scope->elements.entries[i].value; Entity *found = scope_insert_entity(c->context.scope, decl); if (found != NULL) { gbString expr_str = expr_to_string(expr); @@ -535,11 +530,11 @@ bool check_using_stmt_entity(Checker *c, AstNodeUsingStmt *us, AstNode *expr, bo Type *t = base_type(type_deref(e->type)); if (is_type_struct(t) || is_type_raw_union(t) || is_type_union(t)) { // TODO(bill): Make it work for unions too - Scope **found_ = map_scope_get(&c->info.scopes, hash_pointer(t->Record.node)); + Scope **found_ = map_get(&c->info.scopes, hash_pointer(t->Record.node)); GB_ASSERT(found_ != NULL); Scope *found = *found_; for_array(i, found->elements.entries) { - Entity *f = found->elements.entries.e[i].value; + Entity *f = found->elements.entries[i].value; if (f->kind == Entity_Variable) { Entity *uvar = make_entity_using_variable(c->allocator, e, f->token, f->type); // if (is_selector) { @@ -645,7 +640,7 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { return; } - Operand x = {0}; + Operand x = {}; check_expr(c, &x, s->expr); if (x.mode == Addressing_Invalid) { return; @@ -693,23 +688,23 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { // NOTE(bill): If there is a bad syntax error, rhs > lhs which would mean there would need to be // an extra allocation - ArrayOperand operands = {0}; - array_init_reserve(&operands, c->tmp_allocator, 2 * lhs_count); + Array operands = {}; + array_init(&operands, c->tmp_allocator, 2 * lhs_count); check_unpack_arguments(c, lhs_count, &operands, as->rhs, true); isize rhs_count = operands.count; for_array(i, operands) { - if (operands.e[i].mode == Addressing_Invalid) { + if (operands[i].mode == Addressing_Invalid) { rhs_count--; } } isize max = gb_min(lhs_count, rhs_count); for (isize i = 0; i < max; i++) { - check_assignment_variable(c, &operands.e[i], as->lhs.e[i]); + check_assignment_variable(c, &operands[i], as->lhs[i]); } if (lhs_count != rhs_count) { - error_node(as->lhs.e[0], "Assignment count mismatch `%td` = `%td`", lhs_count, rhs_count); + error_node(as->lhs[0], "Assignment count mismatch `%td` = `%td`", lhs_count, rhs_count); } gb_temp_arena_memory_end(tmp); @@ -732,15 +727,15 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { be->op = op; be->op.kind = cast(TokenKind)(cast(i32)be->op.kind - (Token_AddEq - Token_Add)); // NOTE(bill): Only use the first one will be used - be->left = as->lhs.e[0]; - be->right = as->rhs.e[0]; + be->left = as->lhs[0]; + be->right = as->rhs[0]; check_binary_expr(c, &operand, &binary_expr); if (operand.mode == Addressing_Invalid) { return; } // NOTE(bill): Only use the first one will be used - check_assignment_variable(c, &operand, as->lhs.e[0]); + check_assignment_variable(c, &operand, as->lhs[0]); } break; } case_end; @@ -794,7 +789,7 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { } - Type *proc_type = c->proc_stack.e[c->proc_stack.count-1]; + Type *proc_type = c->proc_stack[c->proc_stack.count-1]; isize result_count = 0; if (proc_type->Proc.results) { result_count = proc_type->Proc.results->Tuple.variable_count; @@ -816,13 +811,13 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { check_init_variables(c, variables, result_count, rs->results, str_lit("return statement")); // if (pos.line == 10) { - // AstNode *x = rs->results.e[0]; + // AstNode *x = rs->results[0]; // gb_printf_err("%s\n", expr_to_string(x)); // gb_printf_err("%s\n", type_to_string(type_of_expr(&c->info, x))); // } } } else if (rs->results.count > 0) { - error_node(rs->results.e[0], "No return values expected"); + error_node(rs->results[0], "No return values expected"); } case_end; @@ -863,7 +858,7 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { Type *val = NULL; Type *idx = NULL; - Entity *entities[2] = {0}; + Entity *entities[2] = {}; isize entity_count = 0; AstNode *expr = unparen_expr(rs->expr); @@ -943,10 +938,10 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { } if (x.mode != Addressing_Constant) { - x.value = (ExactValue){0}; + x.value = empty_exact_value; } if (y.mode != Addressing_Constant) { - y.value = (ExactValue){0}; + y.value = empty_exact_value; } @@ -1032,7 +1027,7 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { String str = token.string; Entity *found = NULL; - if (str_ne(str, str_lit("_"))) { + if (str != "_") { found = current_scope_lookup_entity(c->context.scope, str); } if (found == NULL) { @@ -1072,7 +1067,7 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { case_end; case_ast_node(ms, MatchStmt, node); - Operand x = {0}; + Operand x = {}; mod_flags |= Stmt_BreakAllowed; check_open_scope(c, node); @@ -1089,7 +1084,7 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { x.type = t_bool; x.value = exact_value_bool(true); - Token token = {0}; + Token token = {}; token.pos = ast_node_token(ms->body).pos; token.string = str_lit("true"); x.expr = ast_ident(c->curr_ast_file, token); @@ -1106,7 +1101,7 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { AstNode *first_default = NULL; ast_node(bs, BlockStmt, ms->body); for_array(i, bs->stmts) { - AstNode *stmt = bs->stmts.e[i]; + AstNode *stmt = bs->stmts[i]; AstNode *default_stmt = NULL; if (stmt->kind == AstNode_CaseClause) { ast_node(cc, CaseClause, stmt); @@ -1130,11 +1125,11 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { } } - MapTypeAndToken seen = {0}; // NOTE(bill): Multimap - map_type_and_token_init(&seen, heap_allocator()); + Map seen = {}; // NOTE(bill): Multimap + map_init(&seen, heap_allocator()); for_array(i, bs->stmts) { - AstNode *stmt = bs->stmts.e[i]; + AstNode *stmt = bs->stmts[i]; if (stmt->kind != AstNode_CaseClause) { // NOTE(bill): error handled by above multiple default checker continue; @@ -1142,12 +1137,12 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { ast_node(cc, CaseClause, stmt); for_array(j, cc->list) { - AstNode *expr = unparen_expr(cc->list.e[j]); + AstNode *expr = unparen_expr(cc->list[j]); if (is_ast_node_a_range(expr)) { ast_node(ie, BinaryExpr, expr); - Operand lhs = {0}; - Operand rhs = {0}; + Operand lhs = {}; + Operand rhs = {}; check_expr(c, &lhs, ie->left); if (x.mode == Addressing_Invalid) { continue; @@ -1168,7 +1163,7 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { } - TokenKind op = {0}; + TokenKind op = {}; Operand a = lhs; Operand b = rhs; @@ -1197,7 +1192,7 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { Operand b1 = rhs; check_comparison(c, &a1, &b1, op); } else { - Operand y = {0}; + Operand y = {}; check_expr(c, &y, expr); if (x.mode == Addressing_Invalid || y.mode == Addressing_Invalid) { @@ -1222,13 +1217,13 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { if (y.value.kind != ExactValue_Invalid) { HashKey key = hash_exact_value(y.value); - TypeAndToken *found = map_type_and_token_get(&seen, key); + TypeAndToken *found = map_get(&seen, key); if (found != NULL) { gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&c->tmp_arena); - isize count = map_type_and_token_multi_count(&seen, key); + isize count = multi_map_count(&seen, key); TypeAndToken *taps = gb_alloc_array(c->tmp_allocator, TypeAndToken, count); - map_type_and_token_multi_get_all(&seen, key, taps); + multi_map_get_all(&seen, key, taps); bool continue_outer = false; for (isize i = 0; i < count; i++) { @@ -1254,7 +1249,7 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { } } TypeAndToken tap = {y.type, ast_node_token(y.expr)}; - map_type_and_token_multi_insert(&seen, key, tap); + multi_map_insert(&seen, key, tap); } } } @@ -1268,13 +1263,13 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { check_close_scope(c); } - map_type_and_token_destroy(&seen); + map_destroy(&seen); check_close_scope(c); case_end; case_ast_node(ms, TypeMatchStmt, node); - Operand x = {0}; + Operand x = {}; mod_flags |= Stmt_BreakAllowed; check_open_scope(c, node); @@ -1297,8 +1292,8 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { syntax_error(as_token, "Expected 1 expression after `in`"); break; } - AstNode *lhs = as->lhs.e[0]; - AstNode *rhs = as->rhs.e[0]; + AstNode *lhs = as->lhs[0]; + AstNode *rhs = as->rhs[0]; check_expr(c, &x, rhs); check_assignment(c, &x, NULL, str_lit("type match expression")); @@ -1316,7 +1311,7 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { AstNode *first_default = NULL; ast_node(bs, BlockStmt, ms->body); for_array(i, bs->stmts) { - AstNode *stmt = bs->stmts.e[i]; + AstNode *stmt = bs->stmts[i]; AstNode *default_stmt = NULL; if (stmt->kind == AstNode_CaseClause) { ast_node(cc, CaseClause, stmt); @@ -1346,11 +1341,11 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { } - MapBool seen = {0}; // Multimap - map_bool_init(&seen, heap_allocator()); + Map seen = {}; // Multimap + map_init(&seen, heap_allocator()); for_array(i, bs->stmts) { - AstNode *stmt = bs->stmts.e[i]; + AstNode *stmt = bs->stmts[i]; if (stmt->kind != AstNode_CaseClause) { // NOTE(bill): error handled by above multiple default checker continue; @@ -1362,9 +1357,9 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { Type *case_type = NULL; for_array(type_index, cc->list) { - AstNode *type_expr = cc->list.e[type_index]; + AstNode *type_expr = cc->list[type_index]; if (type_expr != NULL) { // Otherwise it's a default expression - Operand y = {0}; + Operand y = {}; check_expr_or_type(c, &y, type_expr); if (match_type_kind == MatchType_Union) { @@ -1391,7 +1386,7 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { } HashKey key = hash_pointer(y.type); - bool *found = map_bool_get(&seen, key); + bool *found = map_get(&seen, key); if (found) { TokenPos pos = cc->token.pos; gbString expr_str = expr_to_string(y.expr); @@ -1403,7 +1398,7 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { gb_string_free(expr_str); break; } - map_bool_set(&seen, key, cast(bool)true); + map_set(&seen, key, cast(bool)true); } } @@ -1434,7 +1429,7 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { check_stmt_list(c, cc->stmts, mod_flags); check_close_scope(c); } - map_bool_destroy(&seen); + map_destroy(&seen); check_close_scope(c); case_end; @@ -1481,7 +1476,7 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { } AstNode *ident = bs->label; String name = ident->Ident.string; - Operand o = {0}; + Operand o = {}; Entity *e = check_ident(c, &o, ident, NULL, NULL, false); if (e == NULL) { error_node(ident, "Undeclared label name: %.*s", LIT(name)); @@ -1502,15 +1497,15 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { return; } for_array(i, us->list) { - AstNode *expr = unparen_expr(us->list.e[0]); + AstNode *expr = unparen_expr(us->list[0]); Entity *e = NULL; bool is_selector = false; if (expr->kind == AstNode_Ident) { - Operand o = {0}; + Operand o = {}; e = check_ident(c, &o, expr, NULL, NULL, true); } else if (expr->kind == AstNode_SelectorExpr) { - Operand o = {0}; + Operand o = {}; e = check_selector(c, &o, expr, NULL); is_selector = true; } else if (expr->kind == AstNode_Implicit) { @@ -1526,7 +1521,7 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { case_ast_node(pa, PushAllocator, node); - Operand op = {0}; + Operand op = {}; check_expr(c, &op, pa->expr); check_assignment(c, &op, t_allocator, str_lit("argument to push_allocator")); check_stmt(c, pa->body, mod_flags); @@ -1534,7 +1529,7 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { case_ast_node(pa, PushContext, node); - Operand op = {0}; + Operand op = {}; check_expr(c, &op, pa->expr); check_assignment(c, &op, t_context, str_lit("argument to push_context")); check_stmt(c, pa->body, mod_flags); @@ -1555,7 +1550,7 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { } for_array(i, vd->names) { - AstNode *name = vd->names.e[i]; + AstNode *name = vd->names[i]; Entity *entity = NULL; if (name->kind != AstNode_Ident) { error_node(name, "A variable declaration must be an identifier"); @@ -1564,11 +1559,11 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { String str = token.string; Entity *found = NULL; // NOTE(bill): Ignore assignments to `_` - if (str_ne(str, str_lit("_"))) { + if (str != "_") { found = current_scope_lookup_entity(c->context.scope, str); } if (found == NULL) { - entity = make_entity_variable(c->allocator, c->context.scope, token, NULL, vd->flags&VarDeclFlag_immutable); + entity = make_entity_variable(c->allocator, c->context.scope, token, NULL, (vd->flags&VarDeclFlag_immutable) != 0); entity->identifier = name; } else { TokenPos pos = found->token.pos; @@ -1588,7 +1583,7 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { Type *init_type = NULL; if (vd->type) { - init_type = check_type_extra(c, vd->type, NULL); + init_type = check_type(c, vd->type, NULL); if (init_type == NULL) { init_type = t_invalid; } @@ -1635,10 +1630,10 @@ void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { Type *t = base_type(type_deref(e->type)); if (is_type_struct(t) || is_type_raw_union(t)) { - Scope **found = map_scope_get(&c->info.scopes, hash_pointer(t->Record.node)); + Scope **found = map_get(&c->info.scopes, hash_pointer(t->Record.node)); GB_ASSERT(found != NULL); for_array(i, (*found)->elements.entries) { - Entity *f = (*found)->elements.entries.e[i].value; + Entity *f = (*found)->elements.entries[i].value; if (f->kind == Entity_Variable) { Entity *uvar = make_entity_using_variable(c->allocator, e, f->token, f->type); uvar->Variable.is_immutable = is_immutable; diff --git a/src/checker.c b/src/checker.cpp similarity index 84% rename from src/checker.c rename to src/checker.cpp index b416a6871..05503c608 100644 --- a/src/checker.c +++ b/src/checker.cpp @@ -1,27 +1,27 @@ -#include "exact_value.c" -#include "entity.c" +#include "exact_value.cpp" +#include "entity.cpp" -typedef enum ExprKind { +enum ExprKind { Expr_Expr, Expr_Stmt, -} ExprKind; +}; // Statements and Declarations -typedef enum StmtFlag { +enum StmtFlag { Stmt_BreakAllowed = 1<<0, Stmt_ContinueAllowed = 1<<1, Stmt_FallthroughAllowed = 1<<2, Stmt_CheckScopeDecls = 1<<5, -} StmtFlag; +}; -typedef struct BuiltinProc { +struct BuiltinProc { String name; isize arg_count; bool variadic; ExprKind kind; -} BuiltinProc; -typedef enum BuiltinProcId { +}; +enum BuiltinProcId { BuiltinProc_Invalid, BuiltinProc_len, @@ -71,7 +71,7 @@ typedef enum BuiltinProcId { BuiltinProc_transmute, BuiltinProc_Count, -} BuiltinProcId; +}; gb_global BuiltinProc builtin_procs[BuiltinProc_Count] = { {STR_LIT(""), 0, false, Expr_Stmt}, @@ -123,9 +123,9 @@ gb_global BuiltinProc builtin_procs[BuiltinProc_Count] = { }; -#include "types.c" +#include "types.cpp" -typedef enum AddressingMode { +enum AddressingMode { Addressing_Invalid, // invalid addressing mode Addressing_NoValue, // no value (void in C) Addressing_Value, // computed value (rvalue) @@ -139,14 +139,14 @@ typedef enum AddressingMode { // lhs: acts like a Variable // rhs: acts like OptionalOk Addressing_OptionalOk, // rhs: acts like a value with an optional boolean part (for existence check) -} AddressingMode; +}; // Operand is used as an intermediate value whilst checking // Operands store an addressing mode, the expression being evaluated, // its type and node, and other specific information for certain // addressing modes // Its zero-value is a valid "invalid operand" -typedef struct Operand { +struct Operand { AddressingMode mode; Type * type; ExactValue value; @@ -154,13 +154,13 @@ typedef struct Operand { BuiltinProcId builtin_id; isize overload_count; Entity ** overload_entities; -} Operand; +}; -typedef struct TypeAndValue { +struct TypeAndValue { AddressingMode mode; Type * type; ExactValue value; -} TypeAndValue; +}; bool is_operand_value(Operand o) { switch (o.mode) { @@ -178,13 +178,12 @@ bool is_operand_nil(Operand o) { } -typedef struct BlockLabel { +struct BlockLabel { String name; AstNode *label; // AstNode_Label; -} BlockLabel; +}; // DeclInfo is used to store information of certain declarations to allow for "any order" usage -typedef struct DeclInfo DeclInfo; struct DeclInfo { DeclInfo * parent; // NOTE(bill): only used for procedure literals at the moment Scope * scope; @@ -196,29 +195,29 @@ struct DeclInfo { AstNode * init_expr; AstNode * proc_lit; // AstNode_ProcLit - MapBool deps; // Key: Entity * - Array(BlockLabel) labels; + Map deps; // Key: Entity * + Array labels; }; // ProcedureInfo stores the information needed for checking a procedure -typedef struct ProcedureInfo { +struct ProcedureInfo { AstFile * file; Token token; DeclInfo * decl; Type * type; // Type_Procedure AstNode * body; // AstNode_BlockStmt u32 tags; -} ProcedureInfo; +}; // ExprInfo stores information used for "untyped" expressions -typedef struct ExprInfo { +struct ExprInfo { bool is_lhs; // Debug info AddressingMode mode; Type * type; // Type_Basic ExactValue value; -} ExprInfo; +}; ExprInfo make_expr_info(bool is_lhs, AddressingMode mode, Type *type, ExactValue value) { ExprInfo ei = {is_lhs, mode, type, value}; @@ -227,72 +226,42 @@ ExprInfo make_expr_info(bool is_lhs, AddressingMode mode, Type *type, ExactValue -#define MAP_TYPE Entity * -#define MAP_PROC map_entity_ -#define MAP_NAME MapEntity -#include "map.c" - -typedef struct Scope { +struct Scope { Scope * parent; Scope * prev, *next; Scope * first_child; Scope * last_child; - MapEntity elements; // Key: String - MapBool implicit; // Key: Entity * + Map elements; // Key: String + Map implicit; // Key: Entity * - Array(Scope *) shared; - Array(Scope *) imported; + Array shared; + Array imported; bool is_proc; bool is_global; bool is_file; bool is_init; bool has_been_imported; // This is only applicable to file scopes AstFile * file; -} Scope; +}; gb_global Scope *universal_scope = NULL; -#define MAP_TYPE TypeAndValue -#define MAP_PROC map_tav_ -#define MAP_NAME MapTypeAndValue -#include "map.c" - -#define MAP_TYPE Scope * -#define MAP_PROC map_scope_ -#define MAP_NAME MapScope -#include "map.c" - -#define MAP_TYPE DeclInfo * -#define MAP_PROC map_decl_info_ -#define MAP_NAME MapDeclInfo -#include "map.c" - -#define MAP_TYPE AstFile * -#define MAP_PROC map_ast_file_ -#define MAP_NAME MapAstFile -#include "map.c" - -#define MAP_TYPE ExprInfo -#define MAP_PROC map_expr_info_ -#define MAP_NAME MapExprInfo -#include "map.c" - -typedef struct DelayedDecl { +struct DelayedDecl { Scope * parent; AstNode *decl; -} DelayedDecl; +}; -typedef struct CheckerFileNode { - i32 id; - Array_i32 wheres; - Array_i32 whats; - i32 score; // Higher the score, the better -} CheckerFileNode; +struct CheckerFileNode { + i32 id; + Array wheres; + Array whats; + i32 score; // Higher the score, the better +}; -typedef struct CheckerContext { +struct CheckerContext { Scope * file_scope; Scope * scope; DeclInfo * decl; @@ -301,33 +270,33 @@ typedef struct CheckerContext { String proc_name; Type * type_hint; DeclInfo * curr_proc_decl; -} CheckerContext; +}; // CheckerInfo stores all the symbol information for a type-checked program -typedef struct CheckerInfo { - MapTypeAndValue types; // Key: AstNode * | Expression -> Type (and value) - MapEntity definitions; // Key: AstNode * | Identifier -> Entity - MapEntity uses; // Key: AstNode * | Identifier -> Entity - MapScope scopes; // Key: AstNode * | Node -> Scope - MapExprInfo untyped; // Key: AstNode * | Expression -> ExprInfo - MapEntity implicits; // Key: AstNode * - MapDeclInfo entities; // Key: Entity * - MapEntity foreigns; // Key: String - MapAstFile files; // Key: String (full path) - MapIsize type_info_map; // Key: Type * +struct CheckerInfo { + Map types; // Key: AstNode * | Expression -> Type (and value) + Map definitions; // Key: AstNode * | Identifier -> Entity + Map uses; // Key: AstNode * | Identifier -> Entity + Map scopes; // Key: AstNode * | Node -> Scope + Map untyped; // Key: AstNode * | Expression -> ExprInfo + Map implicits; // Key: AstNode * + Map entities; // Key: Entity * + Map foreigns; // Key: String + Map files; // Key: String (full path) + Map type_info_map; // Key: Type * isize type_info_count; -} CheckerInfo; +}; -typedef struct Checker { +struct Checker { Parser * parser; CheckerInfo info; AstFile * curr_ast_file; Scope * global_scope; - Array(ProcedureInfo) procs; // NOTE(bill): Procedures to check - Array(DelayedDecl) delayed_imports; - Array(DelayedDecl) delayed_foreign_libraries; - Array(CheckerFileNode) file_nodes; + Array procs; // NOTE(bill): Procedures to check + Array delayed_imports; + Array delayed_foreign_libraries; + Array file_nodes; gbArena arena; gbArena tmp_arena; @@ -336,18 +305,16 @@ typedef struct Checker { CheckerContext context; - Array(Type *) proc_stack; + Array proc_stack; bool done_preload; -} Checker; +}; -typedef struct DelayedEntity { +struct DelayedEntity { AstNode * ident; Entity * entity; DeclInfo * decl; -} DelayedEntity; - -typedef Array(DelayedEntity) DelayedEntities; +}; @@ -355,7 +322,7 @@ typedef Array(DelayedEntity) DelayedEntities; void init_declaration_info(DeclInfo *d, Scope *scope, DeclInfo *parent) { d->parent = parent; d->scope = scope; - map_bool_init(&d->deps, heap_allocator()); + map_init(&d->deps, heap_allocator()); array_init(&d->labels, heap_allocator()); } @@ -366,7 +333,7 @@ DeclInfo *make_declaration_info(gbAllocator a, Scope *scope, DeclInfo *parent) { } void destroy_declaration_info(DeclInfo *d) { - map_bool_destroy(&d->deps); + map_destroy(&d->deps); } bool decl_info_has_init(DeclInfo *d) { @@ -393,8 +360,8 @@ bool decl_info_has_init(DeclInfo *d) { Scope *make_scope(Scope *parent, gbAllocator allocator) { Scope *s = gb_alloc_item(allocator, Scope); s->parent = parent; - map_entity_init(&s->elements, heap_allocator()); - map_bool_init(&s->implicit, heap_allocator()); + map_init(&s->elements, heap_allocator()); + map_init(&s->implicit, heap_allocator()); array_init(&s->shared, heap_allocator()); array_init(&s->imported, heap_allocator()); @@ -406,7 +373,7 @@ Scope *make_scope(Scope *parent, gbAllocator allocator) { void destroy_scope(Scope *scope) { for_array(i, scope->elements.entries) { - Entity *e =scope->elements.entries.e[i].value; + Entity *e =scope->elements.entries[i].value; if (e->kind == Entity_Variable) { if (!(e->flags & EntityFlag_Used)) { #if 0 @@ -420,8 +387,8 @@ void destroy_scope(Scope *scope) { destroy_scope(child); } - map_entity_destroy(&scope->elements); - map_bool_destroy(&scope->implicit); + map_destroy(&scope->elements); + map_destroy(&scope->implicit); array_free(&scope->shared); array_free(&scope->imported); @@ -431,7 +398,7 @@ void destroy_scope(Scope *scope) { void add_scope(Checker *c, AstNode *node, Scope *scope) { GB_ASSERT(node != NULL); GB_ASSERT(scope != NULL); - map_scope_set(&c->info.scopes, hash_pointer(node), scope); + map_set(&c->info.scopes, hash_pointer(node), scope); } @@ -457,13 +424,13 @@ void check_close_scope(Checker *c) { Entity *current_scope_lookup_entity(Scope *s, String name) { HashKey key = hash_string(name); - Entity **found = map_entity_get(&s->elements, key); + Entity **found = map_get(&s->elements, key); if (found) { return *found; } for_array(i, s->shared) { - Scope *shared = s->shared.e[i]; - Entity **found = map_entity_get(&shared->elements, key); + Scope *shared = s->shared[i]; + Entity **found = map_get(&shared->elements, key); if (found) { Entity *e = *found; if (e->kind == Entity_Variable && @@ -488,7 +455,7 @@ void scope_lookup_parent_entity(Scope *scope, String name, Scope **scope_, Entit bool gone_thru_file = false; HashKey key = hash_string(name); for (Scope *s = scope; s != NULL; s = s->parent) { - Entity **found = map_entity_get(&s->elements, key); + Entity **found = map_get(&s->elements, key); if (found) { Entity *e = *found; if (gone_thru_proc) { @@ -512,8 +479,8 @@ void scope_lookup_parent_entity(Scope *scope, String name, Scope **scope_, Entit } else { // Check shared scopes - i.e. other files @ global scope for_array(i, s->shared) { - Scope *shared = s->shared.e[i]; - Entity **found = map_entity_get(&shared->elements, key); + Scope *shared = s->shared[i]; + Entity **found = map_get(&shared->elements, key); if (found) { Entity *e = *found; if (e->kind == Entity_Variable && @@ -561,7 +528,7 @@ Entity *scope_lookup_entity(Scope *s, String name) { Entity *scope_insert_entity(Scope *s, Entity *entity) { String name = entity->token.string; HashKey key = hash_string(name); - Entity **found = map_entity_get(&s->elements, key); + Entity **found = map_get(&s->elements, key); #if 1 // IMPORTANT NOTE(bill): Procedure overloading code @@ -579,15 +546,15 @@ Entity *scope_insert_entity(Scope *s, Entity *entity) { if (s->is_global) { return prev; } - map_entity_multi_insert(&s->elements, key, entity); + multi_map_insert(&s->elements, key, entity); } else { - map_entity_set(&s->elements, key, entity); + map_set(&s->elements, key, entity); } #else if (found) { return *found; } - map_entity_set(&s->elements, key, entity); + map_set(&s->elements, key, entity); #endif if (entity->scope == NULL) { entity->scope = s; @@ -602,7 +569,7 @@ void check_scope_usage(Checker *c, Scope *scope) { void add_dependency(DeclInfo *d, Entity *e) { - map_bool_set(&d->deps, hash_pointer(e), cast(bool)true); + map_set(&d->deps, hash_pointer(e), cast(bool)true); } void add_declaration_dependency(Checker *c, Entity *e) { @@ -610,7 +577,7 @@ void add_declaration_dependency(Checker *c, Entity *e) { return; } if (c->context.decl != NULL) { - DeclInfo **found = map_decl_info_get(&c->info.entities, hash_pointer(e)); + DeclInfo **found = map_get(&c->info.entities, hash_pointer(e)); if (found) { add_dependency(c->context.decl, e); } @@ -708,31 +675,31 @@ void init_universal_scope(void) { void init_checker_info(CheckerInfo *i) { gbAllocator a = heap_allocator(); - map_tav_init(&i->types, a); - map_entity_init(&i->definitions, a); - map_entity_init(&i->uses, a); - map_scope_init(&i->scopes, a); - map_decl_info_init(&i->entities, a); - map_expr_info_init(&i->untyped, a); - map_entity_init(&i->foreigns, a); - map_entity_init(&i->implicits, a); - map_isize_init(&i->type_info_map, a); - map_ast_file_init(&i->files, a); + map_init(&i->types, a); + map_init(&i->definitions, a); + map_init(&i->uses, a); + map_init(&i->scopes, a); + map_init(&i->entities, a); + map_init(&i->untyped, a); + map_init(&i->foreigns, a); + map_init(&i->implicits, a); + map_init(&i->type_info_map, a); + map_init(&i->files, a); i->type_info_count = 0; } void destroy_checker_info(CheckerInfo *i) { - map_tav_destroy(&i->types); - map_entity_destroy(&i->definitions); - map_entity_destroy(&i->uses); - map_scope_destroy(&i->scopes); - map_decl_info_destroy(&i->entities); - map_expr_info_destroy(&i->untyped); - map_entity_destroy(&i->foreigns); - map_entity_destroy(&i->implicits); - map_isize_destroy(&i->type_info_map); - map_ast_file_destroy(&i->files); + map_destroy(&i->types); + map_destroy(&i->definitions); + map_destroy(&i->uses); + map_destroy(&i->scopes); + map_destroy(&i->entities); + map_destroy(&i->untyped); + map_destroy(&i->foreigns); + map_destroy(&i->implicits); + map_destroy(&i->type_info_map); + map_destroy(&i->files); } @@ -753,8 +720,8 @@ void init_checker(Checker *c, Parser *parser, BuildContext *bc) { array_init(&c->file_nodes, a); for_array(i, parser->files) { - AstFile *file = &parser->files.e[i]; - CheckerFileNode node = {0}; + AstFile *file = &parser->files[i]; + CheckerFileNode node = {}; node.id = file->id; array_init(&node.whats, a); array_init(&node.wheres, a); @@ -765,7 +732,7 @@ void init_checker(Checker *c, Parser *parser, BuildContext *bc) { isize item_size = gb_max3(gb_size_of(Entity), gb_size_of(Type), gb_size_of(Scope)); isize total_token_count = 0; for_array(i, c->parser->files) { - AstFile *f = &c->parser->files.e[i]; + AstFile *f = &c->parser->files[i]; total_token_count += f->tokens.count; } isize arena_size = 2 * item_size * total_token_count; @@ -796,11 +763,11 @@ void destroy_checker(Checker *c) { Entity *entity_of_ident(CheckerInfo *i, AstNode *identifier) { if (identifier->kind == AstNode_Ident) { - Entity **found = map_entity_get(&i->definitions, hash_pointer(identifier)); + Entity **found = map_get(&i->definitions, hash_pointer(identifier)); if (found) { return *found; } - found = map_entity_get(&i->uses, hash_pointer(identifier)); + found = map_get(&i->uses, hash_pointer(identifier)); if (found) { return *found; } @@ -810,8 +777,8 @@ Entity *entity_of_ident(CheckerInfo *i, AstNode *identifier) { TypeAndValue type_and_value_of_expr(CheckerInfo *i, AstNode *expression) { - TypeAndValue result = {0}; - TypeAndValue *found = map_tav_get(&i->types, hash_pointer(expression)); + TypeAndValue result = {}; + TypeAndValue *found = map_get(&i->types, hash_pointer(expression)); if (found) result = *found; return result; } @@ -834,7 +801,7 @@ Type *type_of_expr(CheckerInfo *i, AstNode *expr) { void add_untyped(CheckerInfo *i, AstNode *expression, bool lhs, AddressingMode mode, Type *basic_type, ExactValue value) { - map_expr_info_set(&i->untyped, hash_pointer(expression), make_expr_info(lhs, mode, basic_type, value)); + map_set(&i->untyped, hash_pointer(expression), make_expr_info(lhs, mode, basic_type, value)); } void add_type_and_value(CheckerInfo *i, AstNode *expression, AddressingMode mode, Type *type, ExactValue value) { @@ -857,21 +824,21 @@ void add_type_and_value(CheckerInfo *i, AstNode *expression, AddressingMode mode } } - TypeAndValue tv = {0}; + TypeAndValue tv = {}; tv.type = type; tv.value = value; tv.mode = mode; - map_tav_set(&i->types, hash_pointer(expression), tv); + map_set(&i->types, hash_pointer(expression), tv); } void add_entity_definition(CheckerInfo *i, AstNode *identifier, Entity *entity) { GB_ASSERT(identifier != NULL); if (identifier->kind == AstNode_Ident) { - if (str_eq(identifier->Ident.string, str_lit("_"))) { + if (identifier->Ident.string == "_") { return; } HashKey key = hash_pointer(identifier); - map_entity_set(&i->definitions, key, entity); + map_set(&i->definitions, key, entity); } else { // NOTE(bill): Error should handled elsewhere } @@ -879,7 +846,7 @@ void add_entity_definition(CheckerInfo *i, AstNode *identifier, Entity *entity) bool add_entity(Checker *c, Scope *scope, AstNode *identifier, Entity *entity) { String name = entity->token.string; - if (!str_eq(name, str_lit("_"))) { + if (name != "_") { Entity *ie = scope_insert_entity(scope, entity); if (ie) { TokenPos pos = ie->token.pos; @@ -921,7 +888,7 @@ void add_entity_use(Checker *c, AstNode *identifier, Entity *entity) { return; } HashKey key = hash_pointer(identifier); - map_entity_set(&c->info.uses, key, entity); + map_set(&c->info.uses, key, entity); add_declaration_dependency(c, entity); // TODO(bill): Should this be here? } @@ -929,16 +896,16 @@ void add_entity_use(Checker *c, AstNode *identifier, Entity *entity) { void add_entity_and_decl_info(Checker *c, AstNode *identifier, Entity *e, DeclInfo *d) { GB_ASSERT(identifier->kind == AstNode_Ident); GB_ASSERT(e != NULL && d != NULL); - GB_ASSERT(str_eq(identifier->Ident.string, e->token.string)); + GB_ASSERT(identifier->Ident.string == e->token.string); add_entity(c, e->scope, identifier, e); - map_decl_info_set(&c->info.entities, hash_pointer(e), d); + map_set(&c->info.entities, hash_pointer(e), d); } void add_implicit_entity(Checker *c, AstNode *node, Entity *e) { GB_ASSERT(node != NULL); GB_ASSERT(e != NULL); - map_entity_set(&c->info.implicits, hash_pointer(node), e); + map_set(&c->info.implicits, hash_pointer(node), e); } @@ -954,14 +921,14 @@ void add_type_info_type(Checker *c, Type *t) { return; // Could be nil } - if (map_isize_get(&c->info.type_info_map, hash_pointer(t)) != NULL) { + if (map_get(&c->info.type_info_map, hash_pointer(t)) != NULL) { // Types have already been added return; } isize ti_index = -1; for_array(i, c->info.type_info_map.entries) { - MapIsizeEntry *e = &c->info.type_info_map.entries.e[i]; + auto *e = &c->info.type_info_map.entries[i]; Type *prev_type = cast(Type *)e->key.ptr; if (are_types_identical(t, prev_type)) { // Duplicate entry @@ -975,7 +942,7 @@ void add_type_info_type(Checker *c, Type *t) { ti_index = c->info.type_info_count; c->info.type_info_count++; } - map_isize_set(&c->info.type_info_map, hash_pointer(t), ti_index); + map_set(&c->info.type_info_map, hash_pointer(t), ti_index); @@ -1086,7 +1053,7 @@ void add_type_info_type(Checker *c, Type *t) { void check_procedure_later(Checker *c, AstFile *file, Token token, DeclInfo *decl, Type *type, AstNode *body, u32 tags) { - ProcedureInfo info = {0}; + ProcedureInfo info = {}; info.file = file; info.token = token; info.decl = decl; @@ -1107,14 +1074,14 @@ void pop_procedure(Checker *c) { Type *const curr_procedure_type(Checker *c) { isize count = c->proc_stack.count; if (count > 0) { - return c->proc_stack.e[count-1]; + return c->proc_stack[count-1]; } return NULL; } void add_curr_ast_file(Checker *c, AstFile *file) { if (file != NULL) { - TokenPos zero_pos = {0}; + TokenPos zero_pos = {}; global_error_collector.prev = zero_pos; c->curr_ast_file = file; c->context.decl = file->decl_info; @@ -1126,34 +1093,34 @@ void add_curr_ast_file(Checker *c, AstFile *file) { -void add_dependency_to_map(MapEntity *map, CheckerInfo *info, Entity *node) { +void add_dependency_to_map(Map *map, CheckerInfo *info, Entity *node) { if (node == NULL) { return; } - if (map_entity_get(map, hash_pointer(node)) != NULL) { + if (map_get(map, hash_pointer(node)) != NULL) { return; } - map_entity_set(map, hash_pointer(node), node); + map_set(map, hash_pointer(node), node); - DeclInfo **found = map_decl_info_get(&info->entities, hash_pointer(node)); + DeclInfo **found = map_get(&info->entities, hash_pointer(node)); if (found == NULL) { return; } DeclInfo *decl = *found; for_array(i, decl->deps.entries) { - Entity *e = cast(Entity *)decl->deps.entries.e[i].key.ptr; + Entity *e = cast(Entity *)decl->deps.entries[i].key.ptr; add_dependency_to_map(map, info, e); } } -MapEntity generate_minimum_dependency_map(CheckerInfo *info, Entity *start) { - MapEntity map = {0}; // Key: Entity * - map_entity_init(&map, heap_allocator()); +Map generate_minimum_dependency_map(CheckerInfo *info, Entity *start) { + Map map = {}; // Key: Entity * + map_init(&map, heap_allocator()); for_array(i, info->definitions.entries) { - Entity *e = info->definitions.entries.e[i].value; + Entity *e = info->definitions.entries[i].value; if (e->scope->is_global) { // NOTE(bill): Require runtime stuff add_dependency_to_map(&map, info, e); @@ -1283,7 +1250,7 @@ void init_preload(Checker *c) { bool check_arity_match(Checker *c, AstNodeValueDecl *d); -void check_collect_entities(Checker *c, AstNodeArray nodes, bool is_file_scope); +void check_collect_entities(Checker *c, Array nodes, bool is_file_scope); void check_collect_entities_from_when_stmt(Checker *c, AstNodeWhenStmt *ws, bool is_file_scope); bool check_is_entity_overloaded(Entity *e) { @@ -1292,7 +1259,7 @@ bool check_is_entity_overloaded(Entity *e) { } Scope *s = e->scope; HashKey key = hash_string(e->token.string); - isize overload_count = map_entity_multi_count(&s->elements, key); + isize overload_count = multi_map_count(&s->elements, key); return overload_count > 1; } @@ -1312,7 +1279,7 @@ void check_procedure_overloading(Checker *c, Entity *e) { String name = e->token.string; HashKey key = hash_string(name); Scope *s = e->scope; - isize overload_count = map_entity_multi_count(&s->elements, key); + isize overload_count = multi_map_count(&s->elements, key); GB_ASSERT(overload_count >= 1); if (overload_count == 1) { e->Procedure.overload_kind = Overload_No; @@ -1323,7 +1290,7 @@ void check_procedure_overloading(Checker *c, Entity *e) { gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&c->tmp_arena); Entity **procs = gb_alloc_array(c->tmp_allocator, Entity *, overload_count); - map_entity_multi_get_all(&s->elements, key, procs); + multi_map_get_all(&s->elements, key, procs); for (isize j = 0; j < overload_count; j++) { Entity *p = procs[j]; @@ -1388,9 +1355,9 @@ void check_procedure_overloading(Checker *c, Entity *e) { } -#include "check_expr.c" -#include "check_decl.c" -#include "check_stmt.c" +#include "check_expr.cpp" +#include "check_decl.cpp" +#include "check_stmt.cpp" @@ -1401,21 +1368,21 @@ bool check_arity_match(Checker *c, AstNodeValueDecl *d) { if (rhs == 0) { if (d->type == NULL) { - error_node(d->names.e[0], "Missing type or initial expression"); + error_node(d->names[0], "Missing type or initial expression"); return false; } } else if (lhs < rhs) { if (lhs < d->values.count) { - AstNode *n = d->values.e[lhs]; + AstNode *n = d->values[lhs]; gbString str = expr_to_string(n); error_node(n, "Extra initial expression `%s`", str); gb_string_free(str); } else { - error_node(d->names.e[0], "Extra initial expression"); + error_node(d->names[0], "Extra initial expression"); } return false; } else if (lhs > rhs && rhs != 1) { - AstNode *n = d->names.e[rhs]; + AstNode *n = d->names[rhs]; gbString str = expr_to_string(n); error_node(n, "Missing expression for `%s`", str); gb_string_free(str); @@ -1457,7 +1424,7 @@ void check_collect_entities_from_when_stmt(Checker *c, AstNodeWhenStmt *ws, bool } // NOTE(bill): If file_scopes == NULL, this will act like a local scope -void check_collect_entities(Checker *c, AstNodeArray nodes, bool is_file_scope) { +void check_collect_entities(Checker *c, Array nodes, bool is_file_scope) { // NOTE(bill): File scope and local scope are different kinds of scopes if (is_file_scope) { GB_ASSERT(c->context.scope->is_file); @@ -1466,7 +1433,7 @@ void check_collect_entities(Checker *c, AstNodeArray nodes, bool is_file_scope) } for_array(decl_index, nodes) { - AstNode *decl = nodes.e[decl_index]; + AstNode *decl = nodes[decl_index]; if (!is_ast_node_decl(decl) && !is_ast_node_when_stmt(decl)) { continue; } @@ -1498,7 +1465,7 @@ void check_collect_entities(Checker *c, AstNodeArray nodes, bool is_file_scope) di = make_declaration_info(heap_allocator(), c->context.scope, c->context.decl); di->entities = entities; di->type_expr = vd->type; - di->init_expr = vd->values.e[0]; + di->init_expr = vd->values[0]; if (vd->flags & VarDeclFlag_thread_local) { @@ -1508,16 +1475,16 @@ void check_collect_entities(Checker *c, AstNodeArray nodes, bool is_file_scope) for_array(i, vd->names) { - AstNode *name = vd->names.e[i]; + AstNode *name = vd->names[i]; AstNode *value = NULL; if (i < vd->values.count) { - value = vd->values.e[i]; + value = vd->values[i]; } if (name->kind != AstNode_Ident) { error_node(name, "A declaration's name must be an identifier, got %.*s", LIT(ast_node_strings[name->kind])); continue; } - Entity *e = make_entity_variable(c->allocator, c->context.scope, name->Ident, NULL, vd->flags & VarDeclFlag_immutable); + Entity *e = make_entity_variable(c->allocator, c->context.scope, name->Ident, NULL, (vd->flags&VarDeclFlag_immutable) != 0); e->Variable.is_thread_local = (vd->flags & VarDeclFlag_thread_local) != 0; e->identifier = name; @@ -1545,7 +1512,7 @@ void check_collect_entities(Checker *c, AstNodeArray nodes, bool is_file_scope) check_arity_match(c, vd); } else { for_array(i, vd->names) { - AstNode *name = vd->names.e[i]; + AstNode *name = vd->names[i]; if (name->kind != AstNode_Ident) { error_node(name, "A declaration's name must be an identifier, got %.*s", LIT(ast_node_strings[name->kind])); continue; @@ -1553,7 +1520,7 @@ void check_collect_entities(Checker *c, AstNodeArray nodes, bool is_file_scope) AstNode *init = NULL; if (i < vd->values.count) { - init = vd->values.e[i]; + init = vd->values[i]; } DeclInfo *d = make_declaration_info(c->allocator, c->context.scope, c->context.decl); @@ -1580,7 +1547,7 @@ void check_collect_entities(Checker *c, AstNodeArray nodes, bool is_file_scope) d->proc_lit = up_init; d->type_expr = vd->type; } else { - e = make_entity_constant(c->allocator, d->scope, name->Ident, NULL, (ExactValue){0}); + e = make_entity_constant(c->allocator, d->scope, name->Ident, NULL, empty_exact_value); d->type_expr = vd->type; d->init_expr = init; } @@ -1648,7 +1615,7 @@ void check_collect_entities(Checker *c, AstNodeArray nodes, bool is_file_scope) // NOTE(bill): `when` stmts need to be handled after the other as the condition may refer to something // declared after this stmt in source for_array(i, nodes) { - AstNode *node = nodes.e[i]; + AstNode *node = nodes[i]; switch (node->kind) { case_ast_node(ws, WhenStmt, node); check_collect_entities_from_when_stmt(c, ws, is_file_scope); @@ -1660,11 +1627,11 @@ void check_collect_entities(Checker *c, AstNodeArray nodes, bool is_file_scope) void check_all_global_entities(Checker *c) { - Scope *prev_file = {0}; + Scope *prev_file = {}; for_array(i, c->info.entities.entries) { - MapDeclInfoEntry *entry = &c->info.entities.entries.e[i]; - Entity *e = cast(Entity *)cast(uintptr)entry->key.key; + auto *entry = &c->info.entities.entries[i]; + Entity *e = cast(Entity *)entry->key.ptr; DeclInfo *d = entry->value; if (d->scope != e->scope) { @@ -1678,12 +1645,12 @@ void check_all_global_entities(Checker *c) { continue; } - if (e->kind != Entity_Procedure && str_eq(e->token.string, str_lit("main"))) { + if (e->kind != Entity_Procedure && e->token.string == "main") { if (e->scope->is_init) { error(e->token, "`main` is reserved as the entry point procedure in the initial scope"); continue; } - } else if (e->scope->is_global && str_eq(e->token.string, str_lit("main"))) { + } else if (e->scope->is_global && e->token.string == "main") { error(e->token, "`main` is reserved as the entry point procedure in the initial scope"); continue; } @@ -1701,8 +1668,8 @@ void check_all_global_entities(Checker *c) { } for_array(i, c->info.entities.entries) { - MapDeclInfoEntry *entry = &c->info.entities.entries.e[i]; - Entity *e = cast(Entity *)cast(uintptr)entry->key.key; + auto *entry = &c->info.entities.entries[i]; + Entity *e = cast(Entity *)entry->key.ptr; if (e->kind != Entity_Procedure) { continue; } @@ -1745,7 +1712,7 @@ String path_to_entity_name(String name, String fullpath) { isize slash = 0; isize dot = 0; for (isize i = filename.len-1; i >= 0; i--) { - u8 c = filename.text[i]; + u8 c = filename[i]; if (c == '/' || c == '\\') { break; } @@ -1757,7 +1724,7 @@ String path_to_entity_name(String name, String fullpath) { dot = filename.len; while (dot --> 0) { - u8 c = filename.text[dot]; + u8 c = filename[dot]; if (c == '.') { break; } @@ -1772,15 +1739,15 @@ String path_to_entity_name(String name, String fullpath) { } } -void check_import_entities(Checker *c, MapScope *file_scopes) { +void check_import_entities(Checker *c, Map *file_scopes) { #if 0 // TODO(bill): Dependency ordering for imports { - Array_i32 shared_global_file_ids = {0}; + Array_i32 shared_global_file_ids = {}; array_init_reserve(&shared_global_file_ids, heap_allocator(), c->file_nodes.count); for_array(i, c->file_nodes) { - CheckerFileNode *node = &c->file_nodes.e[i]; - AstFile *f = &c->parser->files.e[node->id]; + CheckerFileNode *node = &c->file_nodes[i]; + AstFile *f = &c->parser->files[node->id]; GB_ASSERT(f->id == node->id); if (f->scope->is_global) { array_add(&shared_global_file_ids, f->id); @@ -1788,11 +1755,11 @@ void check_import_entities(Checker *c, MapScope *file_scopes) { } for_array(i, c->file_nodes) { - CheckerFileNode *node = &c->file_nodes.e[i]; - AstFile *f = &c->parser->files.e[node->id]; + CheckerFileNode *node = &c->file_nodes[i]; + AstFile *f = &c->parser->files[node->id]; if (!f->scope->is_global) { for_array(j, shared_global_file_ids) { - array_add(&node->whats, shared_global_file_ids.e[j]); + array_add(&node->whats, shared_global_file_ids[j]); } } } @@ -1801,8 +1768,8 @@ void check_import_entities(Checker *c, MapScope *file_scopes) { } for_array(i, c->delayed_imports) { - Scope *parent_scope = c->delayed_imports.e[i].parent; - AstNode *decl = c->delayed_imports.e[i].decl; + Scope *parent_scope = c->delayed_imports[i].parent; + AstNode *decl = c->delayed_imports[i].decl; ast_node(id, ImportDecl, decl); Token token = id->relpath; @@ -1813,10 +1780,10 @@ void check_import_entities(Checker *c, MapScope *file_scopes) { } HashKey key = hash_string(id->fullpath); - Scope **found = map_scope_get(file_scopes, key); + Scope **found = map_get(file_scopes, key); if (found == NULL) { for_array(scope_index, file_scopes->entries) { - Scope *scope = file_scopes->entries.e[scope_index].value; + Scope *scope = file_scopes->entries[scope_index].value; gb_printf_err("%.*s\n", LIT(scope->file->tokenizer.fullpath)); } gb_printf_err("%.*s(%td:%td)\n", LIT(token.pos.file), token.pos.line, token.pos.column); @@ -1832,10 +1799,10 @@ void check_import_entities(Checker *c, MapScope *file_scopes) { i32 child_id = scope->file->id; // TODO(bill): Very slow - CheckerFileNode *parent_node = &c->file_nodes.e[parent_id]; + CheckerFileNode *parent_node = &c->file_nodes[parent_id]; bool add_child = true; for_array(j, parent_node->whats) { - if (parent_node->whats.e[j] == child_id) { + if (parent_node->whats[j] == child_id) { add_child = false; break; } @@ -1844,10 +1811,10 @@ void check_import_entities(Checker *c, MapScope *file_scopes) { array_add(&parent_node->whats, child_id); } - CheckerFileNode *child_node = &c->file_nodes.e[child_id]; + CheckerFileNode *child_node = &c->file_nodes[child_id]; bool add_parent = true; for_array(j, parent_node->wheres) { - if (parent_node->wheres.e[j] == parent_id) { + if (parent_node->wheres[j] == parent_id) { add_parent = false; break; } @@ -1858,24 +1825,24 @@ void check_import_entities(Checker *c, MapScope *file_scopes) { } for_array(i, c->file_nodes) { - CheckerFileNode *node = &c->file_nodes.e[i]; - AstFile *f = &c->parser->files.e[node->id]; + CheckerFileNode *node = &c->file_nodes[i]; + AstFile *f = &c->parser->files[node->id]; gb_printf_err("File %d %.*s", node->id, LIT(f->tokenizer.fullpath)); gb_printf_err("\n wheres:"); for_array(j, node->wheres) { - gb_printf_err(" %d", node->wheres.e[j]); + gb_printf_err(" %d", node->wheres[j]); } gb_printf_err("\n whats:"); for_array(j, node->whats) { - gb_printf_err(" %d", node->whats.e[j]); + gb_printf_err(" %d", node->whats[j]); } gb_printf_err("\n"); } #endif for_array(i, c->delayed_imports) { - Scope *parent_scope = c->delayed_imports.e[i].parent; - AstNode *decl = c->delayed_imports.e[i].decl; + Scope *parent_scope = c->delayed_imports[i].parent; + AstNode *decl = c->delayed_imports[i].decl; ast_node(id, ImportDecl, decl); Token token = id->relpath; @@ -1886,10 +1853,10 @@ void check_import_entities(Checker *c, MapScope *file_scopes) { } HashKey key = hash_string(id->fullpath); - Scope **found = map_scope_get(file_scopes, key); + Scope **found = map_get(file_scopes, key); if (found == NULL) { for_array(scope_index, file_scopes->entries) { - Scope *scope = file_scopes->entries.e[scope_index].value; + Scope *scope = file_scopes->entries[scope_index].value; gb_printf_err("%.*s\n", LIT(scope->file->tokenizer.fullpath)); } gb_printf_err("%.*s(%td:%td)\n", LIT(token.pos.file), token.pos.line, token.pos.column); @@ -1917,7 +1884,7 @@ void check_import_entities(Checker *c, MapScope *file_scopes) { bool previously_added = false; for_array(import_index, parent_scope->imported) { - Scope *prev = parent_scope->imported.e[import_index]; + Scope *prev = parent_scope->imported[import_index]; if (prev == scope) { previously_added = true; break; @@ -1932,10 +1899,10 @@ void check_import_entities(Checker *c, MapScope *file_scopes) { scope->has_been_imported = true; - if (str_eq(id->import_name.string, str_lit("."))) { + if (id->import_name.string == ".") { // NOTE(bill): Add imported entities to this file's scope for_array(elem_index, scope->elements.entries) { - Entity *e = scope->elements.entries.e[elem_index].value; + Entity *e = scope->elements.entries[elem_index].value; if (e->scope == parent_scope) { continue; } @@ -1949,7 +1916,7 @@ void check_import_entities(Checker *c, MapScope *file_scopes) { // TODO(bill): Should these entities be imported but cause an error when used? bool ok = add_entity(c, parent_scope, e->identifier, e); if (ok) { - map_bool_set(&parent_scope->implicit, hash_pointer(e), true); + map_set(&parent_scope->implicit, hash_pointer(e), true); } } } else { @@ -1958,7 +1925,7 @@ void check_import_entities(Checker *c, MapScope *file_scopes) { } } else { String import_name = path_to_entity_name(id->import_name.string, id->fullpath); - if (str_eq(import_name, str_lit("_"))) { + if (import_name == "_") { error(token, "File name, %.*s, cannot be as an import name as it is not a valid identifier", LIT(id->import_name.string)); } else { GB_ASSERT(id->import_name.pos.line != 0); @@ -1974,8 +1941,8 @@ void check_import_entities(Checker *c, MapScope *file_scopes) { } for_array(i, c->delayed_foreign_libraries) { - Scope *parent_scope = c->delayed_foreign_libraries.e[i].parent; - AstNode *decl = c->delayed_foreign_libraries.e[i].decl; + Scope *parent_scope = c->delayed_foreign_libraries[i].parent; + AstNode *decl = c->delayed_foreign_libraries[i].decl; ast_node(fl, ForeignLibrary, decl); String file_str = fl->filepath.string; @@ -2010,7 +1977,7 @@ void check_import_entities(Checker *c, MapScope *file_scopes) { String library_name = path_to_entity_name(fl->library_name.string, file_str); - if (str_eq(library_name, str_lit("_"))) { + if (library_name == "_") { error(fl->token, "File name, %.*s, cannot be as a library name as it is not a valid identifier", LIT(fl->library_name.string)); } else { GB_ASSERT(fl->library_name.pos.line != 0); @@ -2024,18 +1991,18 @@ void check_import_entities(Checker *c, MapScope *file_scopes) { void check_parsed_files(Checker *c) { - MapScope file_scopes; // Key: String (fullpath) - map_scope_init(&file_scopes, heap_allocator()); + Map file_scopes; // Key: String (fullpath) + map_init(&file_scopes, heap_allocator()); // Map full filepaths to Scopes for_array(i, c->parser->files) { - AstFile *f = &c->parser->files.e[i]; + AstFile *f = &c->parser->files[i]; Scope *scope = NULL; scope = make_scope(c->global_scope, c->allocator); scope->is_global = f->is_global_scope; scope->is_file = true; scope->file = f; - if (str_eq(f->tokenizer.fullpath, c->parser->init_fullpath)) { + if (f->tokenizer.fullpath == c->parser->init_fullpath) { scope->is_init = true; } @@ -2050,13 +2017,13 @@ void check_parsed_files(Checker *c) { f->scope = scope; f->decl_info = make_declaration_info(c->allocator, f->scope, c->context.decl); HashKey key = hash_string(f->tokenizer.fullpath); - map_scope_set(&file_scopes, key, scope); - map_ast_file_set(&c->info.files, key, f); + map_set(&file_scopes, key, scope); + map_set(&c->info.files, key, f); } // Collect Entities for_array(i, c->parser->files) { - AstFile *f = &c->parser->files.e[i]; + AstFile *f = &c->parser->files[i]; CheckerContext prev_context = c->context; add_curr_ast_file(c, f); check_collect_entities(c, f->decls, true); @@ -2071,7 +2038,7 @@ void check_parsed_files(Checker *c) { // Check procedure bodies // NOTE(bill): Nested procedures bodies will be added to this "queue" for_array(i, c->procs) { - ProcedureInfo *pi = &c->procs.e[i]; + ProcedureInfo *pi = &c->procs[i]; CheckerContext prev_context = c->context; add_curr_ast_file(c, pi->file); @@ -2094,9 +2061,9 @@ void check_parsed_files(Checker *c) { // Add untyped expression values for_array(i, c->info.untyped.entries) { - MapExprInfoEntry *entry = &c->info.untyped.entries.e[i]; + auto *entry = &c->info.untyped.entries[i]; HashKey key = entry->key; - AstNode *expr = cast(AstNode *)cast(uintptr)key.key; + AstNode *expr = cast(AstNode *)key.ptr; ExprInfo *info = &entry->value; if (info != NULL && expr != NULL) { if (is_type_typed(info->type)) { @@ -2132,7 +2099,7 @@ void check_parsed_files(Checker *c) { // NOTE(bill): Check for illegal cyclic type declarations for_array(i, c->info.definitions.entries) { - Entity *e = c->info.definitions.entries.e[i].value; + Entity *e = c->info.definitions.entries[i].value; if (e->kind == Entity_TypeName) { if (e->type != NULL) { // i64 size = type_size_of(c->sizes, c->allocator, e->type); @@ -2148,13 +2115,13 @@ void check_parsed_files(Checker *c) { if (!build_context.is_dll) { for_array(i, file_scopes.entries) { - Scope *s = file_scopes.entries.e[i].value; + Scope *s = file_scopes.entries[i].value; if (s->is_init) { Entity *e = current_scope_lookup_entity(s, str_lit("main")); if (e == NULL) { - Token token = {0}; + Token token = {}; if (s->file->tokens.count > 0) { - token = s->file->tokens.e[0]; + token = s->file->tokens[0]; } else { token.pos.file = s->file->tokenizer.fullpath; token.pos.line = 1; @@ -2169,6 +2136,6 @@ void check_parsed_files(Checker *c) { } } - map_scope_destroy(&file_scopes); + map_destroy(&file_scopes); } diff --git a/src/common.c b/src/common.cpp similarity index 85% rename from src/common.c rename to src/common.cpp index 54d938c92..0c096a40d 100644 --- a/src/common.c +++ b/src/common.cpp @@ -3,7 +3,7 @@ #include #endif -#define GB_NO_DEFER +// #define GB_NO_DEFER #define GB_IMPLEMENTATION #include "gb/gb.h" @@ -13,22 +13,27 @@ gbAllocator heap_allocator(void) { return gb_heap_allocator(); } -#include "unicode.c" -#include "string.c" -#include "array.c" -#include "integer128.c" -#include "murmurhash3.c" +#include "unicode.cpp" +#include "string.cpp" +#include "array.cpp" +#include "integer128.cpp" +#include "murmurhash3.cpp" u128 fnv128a(void const *data, isize len) { u128 o = u128_lo_hi(0x13bull, 0x1000000ull); u128 h = u128_lo_hi(0x62b821756295c58dull, 0x6c62272e07bb0142ull); u8 const *bytes = cast(u8 const *)data; for (isize i = 0; i < len; i++) { - h = u128_mul(u128_xor(h, u128_from_u64(bytes[i])), o); + h.lo ^= bytes[i]; + h = h * o; } return h; } +#include "map.cpp" + + + gb_global String global_module_path = {0}; gb_global bool global_module_path_set = false; @@ -43,8 +48,6 @@ gbAllocator scratch_allocator(void) { return gb_scratch_allocator(&scratch_memory); } -typedef struct DynamicArenaBlock DynamicArenaBlock; -typedef struct DynamicArena DynamicArena; struct DynamicArenaBlock { DynamicArenaBlock *prev; @@ -236,27 +239,4 @@ f64 gb_sqrt(f64 x) { } \ } while (0) -//////////////////////////////////////////////////////////////// -// -// Generic Data Structures -// -//////////////////////////////////////////////////////////////// -typedef Array(i32) Array_i32; -typedef Array(isize) Array_isize; - - -#define MAP_TYPE String -#define MAP_PROC map_string_ -#define MAP_NAME MapString -#include "map.c" - -#define MAP_TYPE bool -#define MAP_PROC map_bool_ -#define MAP_NAME MapBool -#include "map.c" - -#define MAP_TYPE isize -#define MAP_PROC map_isize_ -#define MAP_NAME MapIsize -#include "map.c" diff --git a/src/entity.c b/src/entity.cpp similarity index 94% rename from src/entity.c rename to src/entity.cpp index f029685c3..26e94dbf1 100644 --- a/src/entity.c +++ b/src/entity.cpp @@ -1,7 +1,7 @@ -typedef struct Scope Scope; -typedef struct Checker Checker; -typedef struct Type Type; -typedef struct DeclInfo DeclInfo; +struct Scope; +struct Checker; +struct Type; +struct DeclInfo; // typedef enum BuiltinProcId BuiltinProcId; @@ -19,12 +19,12 @@ typedef struct DeclInfo DeclInfo; ENTITY_KIND(Nil) \ ENTITY_KIND(Label) -typedef enum EntityKind { +enum EntityKind { #define ENTITY_KIND(k) GB_JOIN2(Entity_, k), ENTITY_KINDS #undef ENTITY_KIND Entity_Count, -} EntityKind; +}; String const entity_strings[] = { #define ENTITY_KIND(k) {cast(u8 *)#k, gb_size_of(#k)-1}, @@ -32,7 +32,7 @@ String const entity_strings[] = { #undef ENTITY_KIND }; -typedef enum EntityFlag { +enum EntityFlag { EntityFlag_Visited = 1<<0, EntityFlag_Used = 1<<1, EntityFlag_Using = 1<<2, @@ -45,24 +45,23 @@ typedef enum EntityFlag { EntityFlag_Value = 1<<9, EntityFlag_Sret = 1<<10, EntityFlag_BitFieldValue = 1<<11, -} EntityFlag; +}; // Zero value means the overloading process is not yet done -typedef enum OverloadKind { +enum OverloadKind { Overload_Unknown, Overload_No, Overload_Yes, -} OverloadKind; +}; -typedef enum EntityAliasKind { +enum EntityAliasKind { EntityAlias_Invalid, EntityAlias_Type, EntityAlias_Entity, -} EntityAliasKind; +}; // An Entity is a named "thing" in the language -typedef struct Entity Entity; struct Entity { EntityKind kind; u64 id; @@ -82,10 +81,11 @@ struct Entity { ExactValue value; } Constant; struct { - i32 field_index; - i32 field_src_index; - bool is_immutable; - bool is_thread_local; + i32 field_index; + i32 field_src_index; + bool is_immutable; + bool is_thread_local; + ExactValue default_value; } Variable; struct { bool is_type_alias; @@ -148,7 +148,7 @@ bool is_entity_exported(Entity *e) { if (name.len == 0) { return false; } - return name.text[0] != '_'; + return name[0] != '_'; } gb_global u64 global_entity_id = 0; diff --git a/src/exact_value.c b/src/exact_value.cpp similarity index 86% rename from src/exact_value.c rename to src/exact_value.cpp index 8261d8a1f..ff740a057 100644 --- a/src/exact_value.c +++ b/src/exact_value.cpp @@ -3,13 +3,14 @@ // TODO(bill): Big numbers // IMPORTANT TODO(bill): This needs to be completely fixed!!!!!!!! -typedef struct AstNode AstNode; +struct AstNode; +struct HashKey; -typedef struct Complex128 { +struct Complex128 { f64 real, imag; -} Complex128; +}; -typedef enum ExactValueKind { +enum ExactValueKind { ExactValue_Invalid, ExactValue_Bool, @@ -21,9 +22,9 @@ typedef enum ExactValueKind { ExactValue_Compound, // TODO(bill): Is this good enough? ExactValue_Count, -} ExactValueKind; +}; -typedef struct ExactValue { +struct ExactValue { ExactValueKind kind; union { bool value_bool; @@ -34,7 +35,9 @@ typedef struct ExactValue { Complex128 value_complex; AstNode * value_compound; }; -} ExactValue; +}; + +gb_global ExactValue const empty_exact_value = {}; HashKey hash_exact_value(ExactValue v) { return hashing_proc(&v, gb_size_of(ExactValue)); @@ -191,7 +194,7 @@ ExactValue exact_value_from_basic_literal(Token token) { case Token_Float: return exact_value_float_from_string(token.string); case Token_Imag: { String str = token.string; - Rune last_rune = cast(Rune)str.text[str.len-1]; + Rune last_rune = cast(Rune)str[str.len-1]; str.len--; // Ignore the `i|j|k` f64 imag = float_from_string(str); @@ -314,7 +317,7 @@ ExactValue exact_unary_operator_value(TokenKind op, ExactValue v, i32 precision) return v; case ExactValue_Integer: { ExactValue i = v; - i.value_integer = i128_neg(i.value_integer); + i.value_integer = -i.value_integer; return i; } case ExactValue_Float: { @@ -336,7 +339,7 @@ ExactValue exact_unary_operator_value(TokenKind op, ExactValue v, i32 precision) case ExactValue_Invalid: return v; case ExactValue_Integer: - i = i128_not(v.value_integer); + i = ~v.value_integer; break; default: goto failure; @@ -346,7 +349,7 @@ ExactValue exact_unary_operator_value(TokenKind op, ExactValue v, i32 precision) // limited to the types precision // IMPORTANT NOTE(bill): Max precision is 64 bits as that's how integers are stored if (0 < precision && precision < 128) { - i = i128_and(i, i128_not(i128_shl(I128_NEG_ONE, precision))); + i = i & ~(I128_NEG_ONE << precision); } return exact_value_i128(i); @@ -364,7 +367,7 @@ ExactValue exact_unary_operator_value(TokenKind op, ExactValue v, i32 precision) failure: GB_PANIC("Invalid unary operation, %.*s", LIT(token_strings[op])); - ExactValue error_value = {0}; + ExactValue error_value = {}; return error_value; } @@ -458,19 +461,19 @@ ExactValue exact_binary_operator_value(TokenKind op, ExactValue x, ExactValue y) i128 b = y.value_integer; i128 c = I128_ZERO; switch (op) { - case Token_Add: c = i128_add(a, b); break; - case Token_Sub: c = i128_sub(a, b); break; - case Token_Mul: c = i128_mul(a, b); break; + case Token_Add: c = a + b; break; + case Token_Sub: c = a - b; break; + case Token_Mul: c = a * b; break; case Token_Quo: return exact_value_float(fmod(i128_to_f64(a), i128_to_f64(b))); - case Token_QuoEq: c = i128_quo(a, b); break; // NOTE(bill): Integer division - case Token_Mod: c = i128_mod(a, b); break; - case Token_ModMod: c = i128_mod(i128_add(i128_mod(a, b), b), b); break; - case Token_And: c = i128_and (a, b); break; - case Token_Or: c = i128_or (a, b); break; - case Token_Xor: c = i128_xor (a, b); break; - case Token_AndNot: c = i128_and_not(a, b); break; - case Token_Shl: c = i128_shl (a, i128_to_u64(b)); break; - case Token_Shr: c = i128_shr (a, i128_to_u64(b)); break; + case Token_QuoEq: c = a / b; break; // NOTE(bill): Integer division + case Token_Mod: c = a % b; break; + case Token_ModMod: c = ((a % b) + b) % b; break; + case Token_And: c = a & b; break; + case Token_Or: c = a | b; break; + case Token_Xor: c = a ^ b; break; + case Token_AndNot: c = i128_and_not(a, b); break; + case Token_Shl: c = a << i128_to_u64(b); break; + case Token_Shr: c = a >> i128_to_u64(b); break; default: goto error; } @@ -523,7 +526,7 @@ ExactValue exact_binary_operator_value(TokenKind op, ExactValue x, ExactValue y) error: ; // MSVC accepts this??? apparently you cannot declare variables immediately after labels... - ExactValue error_value = {0}; + ExactValue error_value = {}; // gb_printf_err("Invalid binary operation: %s\n", token_kind_to_string(op)); return error_value; } @@ -557,12 +560,12 @@ bool compare_exact_values(TokenKind op, ExactValue x, ExactValue y) { i128 a = x.value_integer; i128 b = y.value_integer; switch (op) { - case Token_CmpEq: return i128_eq(a, b); - case Token_NotEq: return i128_ne(a, b); - case Token_Lt: return i128_lt(a, b); - case Token_LtEq: return i128_le(a, b); - case Token_Gt: return i128_gt(a, b); - case Token_GtEq: return i128_ge(a, b); + case Token_CmpEq: return a == b; + case Token_NotEq: return a != b; + case Token_Lt: return a < b; + case Token_LtEq: return a <= b; + case Token_Gt: return a > b; + case Token_GtEq: return a >= b; } } break; @@ -593,15 +596,14 @@ bool compare_exact_values(TokenKind op, ExactValue x, ExactValue y) { case ExactValue_String: { String a = x.value_string; String b = y.value_string; - isize len = gb_min(a.len, b.len); // TODO(bill): gb_memcompare is used because the strings are UTF-8 switch (op) { - case Token_CmpEq: return gb_memcompare(a.text, b.text, len) == 0; - case Token_NotEq: return gb_memcompare(a.text, b.text, len) != 0; - case Token_Lt: return gb_memcompare(a.text, b.text, len) < 0; - case Token_LtEq: return gb_memcompare(a.text, b.text, len) <= 0; - case Token_Gt: return gb_memcompare(a.text, b.text, len) > 0; - case Token_GtEq: return gb_memcompare(a.text, b.text, len) >= 0; + case Token_CmpEq: return a == b; + case Token_NotEq: return a != b; + case Token_Lt: return a < b; + case Token_LtEq: return a <= b; + case Token_Gt: return a > b; + case Token_GtEq: return a >= b; } } break; } diff --git a/src/integer128.c b/src/integer128.cpp similarity index 78% rename from src/integer128.c rename to src/integer128.cpp index 6cce03143..35023a220 100644 --- a/src/integer128.c +++ b/src/integer128.cpp @@ -1,16 +1,25 @@ -typedef struct u128 {u64 lo; u64 hi;} u128; -typedef struct i128 {u64 lo; i64 hi;} i128; -#define BIT128_U64_HIGHBIT 0x8000000000000000ul -#define BIT128_U64_BITS62 0x7ffffffffffffffful -#define BIT128_U64_ALLBITS 0xfffffffffffffffful +#if defined(GB_COMPILER_MSVC) && defined(GB_ARCH_64_BIT) && defined(GB_CPU_X86) + #define MSVC_AMD64_INTRINSICS + #include + #pragma intrinsic(_mul128) +#endif + +#define BIT128_U64_HIGHBIT 0x8000000000000000ull +#define BIT128_U64_BITS62 0x7fffffffffffffffull +#define BIT128_U64_ALLBITS 0xffffffffffffffffull + + +typedef struct u128 { u64 lo; u64 hi; } u128; +typedef struct i128 { u64 lo; i64 hi; } i128; + static u128 const U128_ZERO = {0, 0}; static u128 const U128_ONE = {1, 0}; static i128 const I128_ZERO = {0, 0}; static i128 const I128_ONE = {1, 0}; static u128 const U128_NEG_ONE = {BIT128_U64_ALLBITS, BIT128_U64_ALLBITS}; -static i128 const I128_NEG_ONE = {BIT128_U64_ALLBITS, BIT128_U64_ALLBITS}; +static i128 const I128_NEG_ONE = {BIT128_U64_ALLBITS, cast(i64)BIT128_U64_ALLBITS}; u128 u128_lo_hi (u64 lo, u64 hi); u128 u128_from_u32 (u32 u); @@ -84,6 +93,48 @@ void i128_divide (i128 num, i128 den, i128 *quo, i128 *rem); i128 i128_quo (i128 a, i128 b); i128 i128_mod (i128 a, i128 b); +bool operator==(u128 a, u128 b) { return u128_eq(a, b); } +bool operator!=(u128 a, u128 b) { return u128_ne(a, b); } +bool operator< (u128 a, u128 b) { return u128_lt(a, b); } +bool operator> (u128 a, u128 b) { return u128_gt(a, b); } +bool operator<=(u128 a, u128 b) { return u128_le(a, b); } +bool operator>=(u128 a, u128 b) { return u128_ge(a, b); } + +u128 operator+(u128 a, u128 b) { return u128_add(a, b); } +u128 operator-(u128 a, u128 b) { return u128_sub(a, b); } +u128 operator*(u128 a, u128 b) { return u128_mul(a, b); } +u128 operator/(u128 a, u128 b) { return u128_quo(a, b); } +u128 operator%(u128 a, u128 b) { return u128_mod(a, b); } +u128 operator&(u128 a, u128 b) { return u128_and(a, b); } +u128 operator|(u128 a, u128 b) { return u128_or (a, b); } +u128 operator^(u128 a, u128 b) { return u128_xor(a, b); } +u128 operator~(u128 a) { return u128_not(a); } +u128 operator+(u128 a) { return a; } +u128 operator-(u128 a) { return u128_neg(a); } +u128 operator<<(u128 a, u32 b) { return u128_shl(a, b); } +u128 operator>>(u128 a, u32 b) { return u128_shr(a, b); } + + +bool operator==(i128 a, i128 b) { return i128_eq(a, b); } +bool operator!=(i128 a, i128 b) { return i128_ne(a, b); } +bool operator< (i128 a, i128 b) { return i128_lt(a, b); } +bool operator> (i128 a, i128 b) { return i128_gt(a, b); } +bool operator<=(i128 a, i128 b) { return i128_le(a, b); } +bool operator>=(i128 a, i128 b) { return i128_ge(a, b); } + +i128 operator+(i128 a, i128 b) { return i128_add(a, b); } +i128 operator-(i128 a, i128 b) { return i128_sub(a, b); } +i128 operator*(i128 a, i128 b) { return i128_mul(a, b); } +i128 operator/(i128 a, i128 b) { return i128_quo(a, b); } +i128 operator%(i128 a, i128 b) { return i128_mod(a, b); } +i128 operator&(i128 a, i128 b) { return i128_and(a, b); } +i128 operator|(i128 a, i128 b) { return i128_or (a, b); } +i128 operator^(i128 a, i128 b) { return i128_xor(a, b); } +i128 operator~(i128 a) { return i128_not(a); } +i128 operator+(i128 a) { return a; } +i128 operator-(i128 a) { return i128_neg(a); } +i128 operator<<(i128 a, u32 b) { return i128_shl(a, b); } +i128 operator>>(i128 a, u32 b) { return i128_shr(a, b); } //////////////////////////////////////////////////////////////// @@ -99,7 +150,7 @@ u64 bit128__digit_value(Rune r) { return 16; // NOTE(bill): Larger than highest possible } -u128 u128_lo_hi(u64 lo, u64 hi) { return (u128){lo, hi}; } +u128 u128_lo_hi(u64 lo, u64 hi) { return u128{lo, hi}; } u128 u128_from_u32(u32 u) { return u128_lo_hi(cast(u64)u, 0); } u128 u128_from_u64(u64 u) { return u128_lo_hi(cast(u64)u, 0); } u128 u128_from_i64(i64 u) { return u128_lo_hi(cast(u64)u, u < 0 ? -1 : 0); } @@ -109,8 +160,8 @@ u128 u128_from_string(String string) { // TODO(bill): Allow for numbers with underscores in them u64 base = 10; bool has_prefix = false; - if (string.len > 2 && string.text[0] == '0') { - switch (string.text[1]) { + if (string.len > 2 && string[0] == '0') { + switch (string[1]) { case 'b': base = 2; has_prefix = true; break; case 'o': base = 8; has_prefix = true; break; case 'd': base = 10; has_prefix = true; break; @@ -160,8 +211,8 @@ i128 i128_from_string(String string) { // TODO(bill): Allow for numbers with underscores in them u64 base = 10; bool has_prefix = false; - if (string.len > 2 && string.text[0] == '0') { - switch (string.text[1]) { + if (string.len > 2 && string[0] == '0') { + switch (string[1]) { case 'b': base = 2; has_prefix = true; break; case 'o': base = 8; has_prefix = true; break; case 'd': base = 10; has_prefix = true; break; @@ -332,7 +383,11 @@ u128 u128_shl(u128 a, u32 n) { if (n >= 128) { return u128_lo_hi(0, 0); } - +#if 0 && defined(MSVC_AMD64_INTRINSICS) + a.hi = __shiftleft128(a.lo, a.hi, n); + a.lo = a.lo << n; + return a; +#else if (n >= 64) { n -= 64; a.hi = a.lo; @@ -347,13 +402,18 @@ u128 u128_shl(u128 a, u32 n) { a.lo <<= n; } return a; +#endif } u128 u128_shr(u128 a, u32 n) { if (n >= 128) { return u128_lo_hi(0, 0); } - +#if 0 && defined(MSVC_AMD64_INTRINSICS) + a.lo = __shiftright128(a.lo, a.hi, n); + a.hi = a.hi >> n; + return a; +#else if (n >= 64) { n -= 64; a.lo = a.hi; @@ -367,6 +427,7 @@ u128 u128_shr(u128 a, u32 n) { a.hi >>= n; } return a; +#endif } @@ -383,6 +444,14 @@ u128 u128_mul(u128 a, u128 b) { return a; } + +#if defined(MSVC_AMD64_INTRINSICS) + if (a.hi == 0 && b.hi == 0) { + a.lo = _umul128(a.lo, b.lo, &a.hi); + return a; + } +#endif + u128 res = {0}; u128 t = b; for (u32 i = 0; i < 128; i++) { @@ -396,6 +465,8 @@ u128 u128_mul(u128 a, u128 b) { return res; } +bool u128_hibit(u128 *d) { return (d->hi & BIT128_U64_HIGHBIT) != 0; } + void u128_divide(u128 num, u128 den, u128 *quo, u128 *rem) { if (u128_eq(den, U128_ZERO)) { if (quo) *quo = u128_from_u64(num.lo/den.lo); @@ -406,7 +477,7 @@ void u128_divide(u128 num, u128 den, u128 *quo, u128 *rem) { u128 x = U128_ONE; u128 r = U128_ZERO; - while (u128_ge(n, d) && ((u128_shr(d, 128-1).lo&1) == 0)) { + while (u128_ge(n, d) && !u128_hibit(&d)) { x = u128_shl(x, 1); d = u128_shl(d, 1); } @@ -427,11 +498,18 @@ void u128_divide(u128 num, u128 den, u128 *quo, u128 *rem) { } u128 u128_quo(u128 a, u128 b) { + if (a.hi == 0 && b.hi == 0) { + return u128_from_u64(a.lo/b.lo); + } + u128 res = {0}; u128_divide(a, b, &res, NULL); return res; } u128 u128_mod(u128 a, u128 b) { + if (a.hi == 0 && b.hi == 0) { + return u128_from_u64(a.lo%b.lo); + } u128 res = {0}; u128_divide(a, b, NULL, &res); return res; @@ -491,6 +569,11 @@ i128 i128_shl(i128 a, u32 n) { return i128_lo_hi(0, 0); } +#if 0 && defined(MSVC_AMD64_INTRINSICS) + a.hi = __shiftleft128(a.lo, a.hi, n); + a.lo = a.lo << n; + return a; +#else if (n >= 64) { n -= 64; a.hi = a.lo; @@ -505,6 +588,7 @@ i128 i128_shl(i128 a, u32 n) { a.lo <<= n; } return a; +#endif } i128 i128_shr(i128 a, u32 n) { @@ -512,6 +596,11 @@ i128 i128_shr(i128 a, u32 n) { return i128_lo_hi(0, 0); } +#if 0 && defined(MSVC_AMD64_INTRINSICS) + a.lo = __shiftright128(a.lo, a.hi, n); + a.hi = a.hi >> n; + return a; +#else if (n >= 64) { n -= 64; a.lo = a.hi; @@ -525,6 +614,7 @@ i128 i128_shr(i128 a, u32 n) { a.hi >>= n; } return a; +#endif } @@ -541,6 +631,13 @@ i128 i128_mul(i128 a, i128 b) { return a; } +#if defined(MSVC_AMD64_INTRINSICS) + if (a.hi == 0 && b.hi == 0) { + a.lo = _mul128(a.lo, b.lo, &a.hi); + return a; + } +#endif + i128 res = {0}; i128 t = b; for (u32 i = 0; i < 128; i++) { diff --git a/src/ir.c b/src/ir.cpp similarity index 93% rename from src/ir.c rename to src/ir.cpp index 3acc78afe..95c277f59 100644 --- a/src/ir.c +++ b/src/ir.cpp @@ -1,22 +1,11 @@ -typedef struct irProcedure irProcedure; -typedef struct irBlock irBlock; -typedef struct irValue irValue; -typedef struct irDebugInfo irDebugInfo; - -typedef Array(irValue *) irValueArray; - -#define MAP_TYPE irValue * -#define MAP_PROC map_ir_value_ -#define MAP_NAME MapIrValue -#include "map.c" - -#define MAP_TYPE irDebugInfo * -#define MAP_PROC map_ir_debug_info_ -#define MAP_NAME MapIrDebugInfo -#include "map.c" +struct irProcedure; +struct irBlock; +struct irValue; +struct irDebugInfo; -typedef struct irModule { + +struct irModule { CheckerInfo * info; gbArena arena; gbArena tmp_arena; @@ -30,32 +19,32 @@ typedef struct irModule { String layout; // String triple; - MapEntity min_dep_map; // Key: Entity * - MapIrValue values; // Key: Entity * - MapIrValue members; // Key: String - MapString entity_names; // Key: Entity * of the typename - MapIrDebugInfo debug_info; // Key: Unique pointer + Map min_dep_map; // Key: Entity * + Map values; // Key: Entity * + Map members; // Key: String + Map entity_names; // Key: Entity * of the typename + Map debug_info; // Key: Unique pointer i32 global_string_index; i32 global_array_index; // For ConstantSlice i32 global_generated_index; Entity * entry_point_entity; - Array(irProcedure *) procs; // NOTE(bill): All procedures with bodies - irValueArray procs_to_generate; // NOTE(bill): Procedures to generate + Array procs; // NOTE(bill): All procedures with bodies + Array procs_to_generate; // NOTE(bill): Procedures to generate - Array(String) foreign_library_paths; // Only the ones that were used -} irModule; + Array foreign_library_paths; // Only the ones that were used +}; // NOTE(bill): For more info, see https://en.wikipedia.org/wiki/Dominator_(graph_theory) -typedef struct irDomNode { +struct irDomNode { irBlock * idom; // Parent (Immediate Dominator) - Array(irBlock *) children; + Array children; i32 pre, post; // Ordering in tree -} irDomNode; +}; -typedef struct irBlock { +struct irBlock { i32 index; String label; irProcedure *parent; @@ -65,14 +54,13 @@ typedef struct irBlock { irDomNode dom; i32 gaps; - irValueArray instrs; - irValueArray locals; + Array instrs; + Array locals; - Array(irBlock *) preds; - Array(irBlock *) succs; -} irBlock; + Array preds; + Array succs; +}; -typedef struct irTargetList irTargetList; struct irTargetList { irTargetList *prev; irBlock * break_; @@ -80,17 +68,17 @@ struct irTargetList { irBlock * fallthrough_; }; -typedef enum irDeferExitKind { +enum irDeferExitKind { irDeferExit_Default, irDeferExit_Return, irDeferExit_Branch, -} irDeferExitKind; -typedef enum irDeferKind { +}; +enum irDeferKind { irDefer_Node, irDefer_Instr, -} irDeferKind; +}; -typedef struct irDefer { +struct irDefer { irDeferKind kind; isize scope_index; irBlock * block; @@ -99,19 +87,19 @@ typedef struct irDefer { // NOTE(bill): `instr` will be copied every time to create a new one irValue *instr; }; -} irDefer; +}; -typedef struct irBranchBlocks { +struct irBranchBlocks { AstNode *label; irBlock *break_; irBlock *continue_; -} irBranchBlocks; +}; struct irProcedure { irProcedure * parent; - Array(irProcedure *) children; + Array children; Entity * entity; irModule * module; @@ -122,17 +110,17 @@ struct irProcedure { u64 tags; irValue * return_ptr; - irValueArray params; - Array(irDefer) defer_stmts; - Array(irBlock *) blocks; + Array params; + Array defer_stmts; + Array blocks; i32 scope_index; irBlock * decl_block; irBlock * entry_block; irBlock * curr_block; irTargetList * target_list; - irValueArray referrers; + Array referrers; - Array(irBranchBlocks) branch_blocks; + Array branch_blocks; i32 local_count; i32 instr_count; @@ -153,7 +141,7 @@ struct irProcedure { Entity * entity; \ Type * type; \ bool zero_initialized; \ - irValueArray referrers; \ + Array referrers; \ i64 alignment; \ }) \ IR_INSTR_KIND(ZeroInit, struct { irValue *address; }) \ @@ -205,7 +193,7 @@ struct irProcedure { irValue *true_value; \ irValue *false_value; \ }) \ - IR_INSTR_KIND(Phi, struct { irValueArray edges; Type *type; }) \ + IR_INSTR_KIND(Phi, struct { Array edges; Type *type; }) \ IR_INSTR_KIND(Unreachable, i32) \ IR_INSTR_KIND(UnaryOp, struct { \ Type * type; \ @@ -261,12 +249,12 @@ struct irProcedure { IR_CONV_KIND(inttoptr) \ IR_CONV_KIND(bitcast) -typedef enum irInstrKind { +enum irInstrKind { irInstr_Invalid, #define IR_INSTR_KIND(x, ...) GB_JOIN2(irInstr_, x), IR_INSTR_KINDS #undef IR_INSTR_KIND -} irInstrKind; +}; String const ir_instr_strings[] = { {cast(u8 *)"Invalid", gb_size_of("Invalid")-1}, @@ -275,12 +263,12 @@ String const ir_instr_strings[] = { #undef IR_INSTR_KIND }; -typedef enum irConvKind { +enum irConvKind { irConv_Invalid, #define IR_CONV_KIND(x) GB_JOIN2(irConv_, x), IR_CONV_KINDS #undef IR_CONV_KIND -} irConvKind; +}; String const ir_conv_strings[] = { {cast(u8 *)"Invalid", gb_size_of("Invalid")-1}, @@ -293,7 +281,6 @@ String const ir_conv_strings[] = { IR_INSTR_KINDS #undef IR_INSTR_KIND -typedef struct irInstr irInstr; struct irInstr { irInstrKind kind; @@ -308,7 +295,7 @@ struct irInstr { }; -typedef enum irValueKind { +enum irValueKind { irValue_Invalid, irValue_Constant, @@ -323,58 +310,58 @@ typedef enum irValueKind { irValue_Instr, irValue_Count, -} irValueKind; +}; -typedef struct irValueConstant { +struct irValueConstant { Type * type; ExactValue value; -} irValueConstant; +}; -typedef struct irValueConstantSlice { +struct irValueConstantSlice { Type * type; irValue *backing_array; i64 count; -} irValueConstantSlice; +}; -typedef struct irValueNil { +struct irValueNil { Type *type; -} irValueNil; +}; -typedef struct irValueTypeName { +struct irValueTypeName { Type * type; String name; -} irValueTypeName; +}; -typedef struct irValueGlobal { +struct irValueGlobal { String name; Entity * entity; Type * type; irValue * value; - irValueArray referrers; + Array referrers; bool is_constant; bool is_private; bool is_thread_local; bool is_foreign; bool is_unnamed_addr; -} irValueGlobal; +}; -typedef enum irParamPasskind { +enum irParamPasskind { irParamPass_Value, // Pass by value irParamPass_Pointer, // Pass as a pointer rather than by value irParamPass_Integer, // Pass as an integer of the same size -} irParamPasskind; +}; -typedef struct irValueParam { +struct irValueParam { irParamPasskind kind; irProcedure * parent; Entity * entity; Type * type; Type * original_type; - irValueArray referrers; -} irValueParam; + Array referrers; +}; -typedef struct irValue { +struct irValue { irValueKind kind; i32 index; bool index_set; @@ -389,7 +376,7 @@ typedef struct irValue { irBlock Block; irInstr Instr; }; -} irValue; +}; gb_global irValue *v_zero = NULL; gb_global irValue *v_one = NULL; @@ -400,14 +387,14 @@ gb_global irValue *v_false = NULL; gb_global irValue *v_true = NULL; gb_global irValue *v_raw_nil = NULL; -typedef enum irAddrKind { +enum irAddrKind { irAddr_Default, // irAddr_Vector, irAddr_Map, irAddr_BitField, -} irAddrKind; +}; -typedef struct irAddr { +struct irAddr { irAddrKind kind; irValue * addr; union { @@ -423,7 +410,7 @@ typedef struct irAddr { // union { // struct { irValue *index; } Vector; // }; -} irAddr; +}; irAddr ir_addr(irValue *addr) { irAddr v = {irAddr_Default, addr}; @@ -444,7 +431,7 @@ irAddr ir_addr_bit_field(irValue *addr, isize bit_field_value_index) { return v; } -typedef enum irDebugEncoding { +enum irDebugEncoding { irDebugBasicEncoding_Invalid = 0, irDebugBasicEncoding_address = 1, @@ -464,9 +451,9 @@ typedef enum irDebugEncoding { irDebugBasicEncoding_structure_type = 19, irDebugBasicEncoding_union_type = 23, -} irDebugEncoding; +}; -typedef enum irDebugInfoKind { +enum irDebugInfoKind { irDebugInfo_Invalid, irDebugInfo_CompileUnit, @@ -485,9 +472,8 @@ typedef enum irDebugInfoKind { irDebugInfo_Count, -} irDebugInfoKind; +}; -typedef struct irDebugInfo irDebugInfo; struct irDebugInfo { irDebugInfoKind kind; i32 id; @@ -516,7 +502,7 @@ struct irDebugInfo { TokenPos pos; } Proc; struct { - Array(irDebugInfo *) procs; + Array procs; } AllProcs; @@ -528,7 +514,7 @@ struct irDebugInfo { } BasicType; struct { irDebugInfo * return_type; - Array(irDebugInfo *) param_types; + Array param_types; } ProcType; struct { irDebugInfo * base_type; @@ -542,7 +528,7 @@ struct irDebugInfo { TokenPos pos; i32 size; i32 align; - Array(irDebugInfo *) elements; + Array elements; } CompositeType; struct { String name; @@ -569,14 +555,13 @@ struct irDebugInfo { }; - -typedef struct irGen { +struct irGen { irModule module; gbFile output_file; bool opt_called; String output_base; String output_name; -} irGen; +}; @@ -662,7 +647,7 @@ irInstr *ir_get_last_instr(irBlock *block) { if (block != NULL) { isize len = block->instrs.count; if (len > 0) { - irValue *v = block->instrs.e[len-1]; + irValue *v = block->instrs[len-1]; GB_ASSERT(v->kind == irValue_Instr); return &v->Instr; } @@ -698,7 +683,7 @@ void ir_set_instr_parent(irValue *instr, irBlock *parent) { } } -irValueArray *ir_value_referrers(irValue *v) { +Array *ir_value_referrers(irValue *v) { switch (v->kind) { case irValue_Global: return &v->Global.referrers; @@ -817,7 +802,7 @@ String ir_get_global_name(irModule *m, irValue *v) { irValueGlobal *g = &v->Global; Entity *e = g->entity; String name = e->token.string; - String *found = map_string_get(&m->entity_names, hash_pointer(e)); + String *found = map_get(&m->entity_names, hash_pointer(e)); if (found != NULL) { name = *found; } @@ -969,7 +954,7 @@ irValue *ir_instr_if(irProcedure *p, irValue *cond, irBlock *true_block, irBlock } -irValue *ir_instr_phi(irProcedure *p, irValueArray edges, Type *type) { +irValue *ir_instr_phi(irProcedure *p, Array edges, Type *type) { irValue *v = ir_alloc_instr(p, irInstr_Phi); irInstr *i = &v->Instr; i->Phi.edges = edges; @@ -1125,7 +1110,7 @@ irValue *ir_value_procedure(gbAllocator a, irModule *m, Entity *entity, Type *ty Type *t = base_type(type); GB_ASSERT(is_type_proc(t)); - array_init_reserve(&v->Proc.params, heap_allocator(), t->Proc.param_count); + array_init(&v->Proc.params, heap_allocator(), t->Proc.param_count); return v; } @@ -1142,14 +1127,14 @@ irValue *ir_generate_array(irModule *m, Type *elem_type, i64 count, String prefi irValue *value = ir_value_global(a, e, NULL); value->Global.is_private = true; ir_module_add_value(m, e, value); - map_ir_value_set(&m->members, hash_string(token.string), value); + map_set(&m->members, hash_string(token.string), value); return value; } irBlock *ir_new_block(irProcedure *proc, AstNode *node, char *label) { Scope *scope = NULL; if (node != NULL) { - Scope **found = map_scope_get(&proc->module->info->scopes, hash_pointer(node)); + Scope **found = map_get(&proc->module->info->scopes, hash_pointer(node)); if (found) { scope = *found; } else { @@ -1177,7 +1162,7 @@ irBlock *ir_new_block(irProcedure *proc, AstNode *node, char *label) { void ir_add_block_to_proc(irProcedure *proc, irBlock *b) { for_array(i, proc->blocks) { - if (proc->blocks.e[i] == b) { + if (proc->blocks[i] == b) { return; } } @@ -1245,7 +1230,7 @@ irValue *ir_add_module_constant(irModule *m, Type *type, ExactValue value) { Entity *e = make_entity_constant(a, NULL, make_token_ident(name), t, value); irValue *g = ir_value_global(a, e, backing_array); ir_module_add_value(m, e, g); - map_ir_value_set(&m->members, hash_string(name), g); + map_set(&m->members, hash_string(name), g); return ir_value_constant_slice(a, type, g, count); } @@ -1276,7 +1261,7 @@ irValue *ir_add_global_string_array(irModule *m, String string) { // g->Global.is_constant = true; ir_module_add_value(m, entity, g); - map_ir_value_set(&m->members, hash_string(name), g); + map_set(&m->members, hash_string(name), g); return g; } @@ -1297,7 +1282,7 @@ irValue *ir_add_local(irProcedure *proc, Entity *e, AstNode *expr) { // } if (expr != NULL && proc->entity != NULL) { - irDebugInfo *di = *map_ir_debug_info_get(&proc->module->debug_info, hash_pointer(proc->entity)); + irDebugInfo *di = *map_get(&proc->module->debug_info, hash_pointer(proc->entity)); ir_emit(proc, ir_instr_debug_declare(proc, di, expr, e, true, instr)); } @@ -1305,7 +1290,7 @@ irValue *ir_add_local(irProcedure *proc, Entity *e, AstNode *expr) { } irValue *ir_add_local_for_identifier(irProcedure *proc, AstNode *name, bool zero_initialized) { - Entity **found = map_entity_get(&proc->module->info->definitions, hash_pointer(name)); + Entity **found = map_get(&proc->module->info->definitions, hash_pointer(name)); if (found) { Entity *e = *found; ir_emit_comment(proc, e->token.string); @@ -1347,7 +1332,7 @@ irValue *ir_add_global_generated(irModule *m, Type *type, irValue *value) { irValue *g = ir_value_global(a, e, value); ir_module_add_value(m, e, g); - map_ir_value_set(&m->members, hash_string(name), g); + map_set(&m->members, hash_string(name), g); return g; } @@ -1399,8 +1384,8 @@ irDebugInfo *ir_add_debug_info_file(irProcedure *proc, AstFile *file) { String directory = filename; isize slash_index = 0; for (isize i = filename.len-1; i >= 0; i--) { - if (filename.text[i] == '\\' || - filename.text[i] == '/') { + if (filename[i] == '\\' || + filename[i] == '/') { break; } slash_index = i; @@ -1413,7 +1398,7 @@ irDebugInfo *ir_add_debug_info_file(irProcedure *proc, AstFile *file) { di->File.filename = filename; di->File.directory = directory; - map_ir_debug_info_set(&proc->module->debug_info, hash_pointer(file), di); + map_set(&proc->module->debug_info, hash_pointer(file), di); return di; } @@ -1430,7 +1415,7 @@ irDebugInfo *ir_add_debug_info_proc(irProcedure *proc, Entity *entity, String na di->Proc.file = file; di->Proc.pos = entity->token.pos; - map_ir_debug_info_set(&proc->module->debug_info, hash_pointer(entity), di); + map_set(&proc->module->debug_info, hash_pointer(entity), di); return di; } @@ -1523,7 +1508,7 @@ irValue *ir_emit_call(irProcedure *p, irValue *value, irValue **args, isize arg_ irValue *ir_emit_global_call(irProcedure *proc, char *name_, irValue **args, isize arg_count) { String name = make_string_c(name_); - irValue **found = map_ir_value_get(&proc->module->members, hash_string(name)); + irValue **found = map_get(&proc->module->members, hash_string(name)); GB_ASSERT_MSG(found != NULL, "%.*s", LIT(name)); irValue *gp = *found; return ir_emit_call(proc, gp, args, arg_count); @@ -1535,7 +1520,7 @@ void ir_emit_defer_stmts(irProcedure *proc, irDeferExitKind kind, irBlock *block isize count = proc->defer_stmts.count; isize i = count; while (i --> 0) { - irDefer d = proc->defer_stmts.e[i]; + irDefer d = proc->defer_stmts[i]; if (kind == irDeferExit_Default) { if (proc->scope_index == d.scope_index && d.scope_index > 1) { @@ -1612,7 +1597,7 @@ void ir_emit_if(irProcedure *proc, irValue *cond, irBlock *true_block, irBlock * } void ir_emit_startup_runtime(irProcedure *proc) { - GB_ASSERT(proc->parent == NULL && str_eq(proc->name, str_lit("main"))); + GB_ASSERT(proc->parent == NULL && proc->name == "main"); ir_emit(proc, ir_alloc_instr(proc, irInstr_StartupRuntime)); } @@ -1917,12 +1902,14 @@ irValue *ir_addr_load(irProcedure *proc, irAddr addr) { return v; } + GB_ASSERT(8 > bit_inset); + irValue *shift_amount = ir_value_constant(a, int_type, exact_value_i64(bit_inset)); irValue *first_byte = ir_emit_load(proc, bytes); - irValue *res = ir_emit_arith(proc, Token_Shr, first_byte, ir_const_int(a, 8 - bit_inset), int_type); + irValue *res = ir_emit_arith(proc, Token_Shr, first_byte, shift_amount, int_type); irValue *remaining_bytes = ir_emit_load(proc, ir_emit_conv(proc, ir_emit_ptr_offset(proc, bytes, v_one), int_ptr)); - remaining_bytes = ir_emit_arith(proc, Token_Shl, remaining_bytes, ir_const_int(a, bit_inset), int_type); + remaining_bytes = ir_emit_arith(proc, Token_Shl, remaining_bytes, shift_amount, int_type); return ir_emit_arith(proc, Token_Or, res, remaining_bytes, int_type); } @@ -2446,7 +2433,7 @@ irValue *ir_emit_deep_field_gep(irProcedure *proc, irValue *e, Selection sel) { Type *type = type_deref(ir_type(e)); for_array(i, sel.index) { - i32 index = cast(i32)sel.index.e[i]; + i32 index = cast(i32)sel.index[i]; if (is_type_pointer(type)) { type = type_deref(type); e = ir_emit_load(proc, e); @@ -2516,7 +2503,7 @@ irValue *ir_emit_deep_field_ev(irProcedure *proc, irValue *e, Selection sel) { Type *type = ir_type(e); for_array(i, sel.index) { - i32 index = cast(i32)sel.index.e[i]; + i32 index = cast(i32)sel.index[i]; if (is_type_pointer(type)) { type = type_deref(type); e = ir_emit_load(proc, e); @@ -3286,7 +3273,7 @@ isize ir_type_info_index(CheckerInfo *info, Type *type) { isize entry_index = -1; HashKey key = hash_pointer(type); - isize *found_entry_index = map_isize_get(&info->type_info_map, key); + isize *found_entry_index = map_get(&info->type_info_map, key); if (found_entry_index) { entry_index = *found_entry_index; } @@ -3294,12 +3281,12 @@ isize ir_type_info_index(CheckerInfo *info, Type *type) { // NOTE(bill): Do manual search // TODO(bill): This is O(n) and can be very slow for_array(i, info->type_info_map.entries){ - MapIsizeEntry *e = &info->type_info_map.entries.e[i]; + auto *e = &info->type_info_map.entries[i]; Type *prev_type = cast(Type *)e->key.ptr; if (are_types_identical(prev_type, type)) { entry_index = e->value; // NOTE(bill): Add it to the search map - map_isize_set(&info->type_info_map, key, entry_index); + map_set(&info->type_info_map, key, entry_index); break; } } @@ -3387,8 +3374,8 @@ irValue *ir_emit_logical_binary_expr(irProcedure *proc, AstNode *expr) { return ir_build_expr(proc, be->right); } - irValueArray edges = {0}; - array_init_reserve(&edges, proc->module->allocator, done->preds.count+1); + Array edges = {}; + array_init(&edges, proc->module->allocator, done->preds.count+1); for_array(i, done->preds) { array_add(&edges, short_circuit); } @@ -3440,7 +3427,7 @@ String ir_mangle_name(irGen *s, String path, Entity *e) { irModule *m = &s->module; CheckerInfo *info = m->info; gbAllocator a = m->allocator; - AstFile *file = *map_ast_file_get(&info->files, hash_string(path)); + AstFile *file = *map_get(&info->files, hash_string(path)); char *str = gb_alloc_array(a, char, path.len+1); gb_memmove(str, path.text, path.len); @@ -3502,26 +3489,26 @@ void ir_mangle_add_sub_type_name(irModule *m, Entity *field, String parent) { "%.*s.%.*s", LIT(parent), LIT(cn)); String child = {text, new_name_len-1}; - map_string_set(&m->entity_names, hash_pointer(field), child); + map_set(&m->entity_names, hash_pointer(field), child); ir_gen_global_type_name(m, field, child); } irBranchBlocks ir_lookup_branch_blocks(irProcedure *proc, AstNode *ident) { GB_ASSERT(ident->kind == AstNode_Ident); - Entity **found = map_entity_get(&proc->module->info->uses, hash_pointer(ident)); + Entity **found = map_get(&proc->module->info->uses, hash_pointer(ident)); GB_ASSERT(found != NULL); Entity *e = *found; GB_ASSERT(e->kind == Entity_Label); for_array(i, proc->branch_blocks) { - irBranchBlocks *b = &proc->branch_blocks.e[i]; + irBranchBlocks *b = &proc->branch_blocks[i]; if (b->label == e->Label.node) { return *b; } } GB_PANIC("Unreachable"); - return (irBranchBlocks){0}; + return irBranchBlocks{}; } @@ -3537,7 +3524,7 @@ void ir_push_target_list(irProcedure *proc, AstNode *label, irBlock *break_, irB GB_ASSERT(label->kind == AstNode_Label); for_array(i, proc->branch_blocks) { - irBranchBlocks *b = &proc->branch_blocks.e[i]; + irBranchBlocks *b = &proc->branch_blocks[i]; GB_ASSERT(b->label != NULL && label != NULL); GB_ASSERT(b->label->kind == AstNode_Label); if (b->label == label) { @@ -3559,7 +3546,7 @@ void ir_pop_target_list(irProcedure *proc) { void ir_gen_global_type_name(irModule *m, Entity *e, String name) { irValue *t = ir_value_type_name(m->allocator, name, e->type); ir_module_add_value(m, e, t); - map_ir_value_set(&m->members, hash_string(name), t); + map_set(&m->members, hash_string(name), t); if (is_type_union(e->type)) { Type *bt = base_type(e->type); @@ -3608,12 +3595,12 @@ irValue *ir_emit_clamp(irProcedure *proc, Type *t, irValue *x, irValue *min, irV irValue *ir_find_global_variable(irProcedure *proc, String name) { - irValue **value = map_ir_value_get(&proc->module->members, hash_string(name)); + irValue **value = map_get(&proc->module->members, hash_string(name)); GB_ASSERT_MSG(value != NULL, "Unable to find global variable `%.*s`", LIT(name)); return *value; } -void ir_build_stmt_list(irProcedure *proc, AstNodeArray stmts); +void ir_build_stmt_list(irProcedure *proc, Array stmts); bool is_double_pointer(Type *t) { @@ -3666,7 +3653,7 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { case_end; case_ast_node(i, Ident, expr); - Entity *e = *map_entity_get(&proc->module->info->uses, hash_pointer(expr)); + Entity *e = *map_get(&proc->module->info->uses, hash_pointer(expr)); if (e->kind == Entity_Builtin) { Token token = ast_node_token(expr); GB_PANIC("TODO(bill): ir_build_single_expr Entity_Builtin `%.*s`\n" @@ -3677,7 +3664,7 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { return ir_value_nil(proc->module->allocator, tv.type); } - irValue **found = map_ir_value_get(&proc->module->values, hash_pointer(e)); + irValue **found = map_get(&proc->module->values, hash_pointer(e)); if (found) { irValue *v = *found; if (v->kind == irValue_Proc) { @@ -3712,8 +3699,8 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { case_ast_node(te, TernaryExpr, expr); ir_emit_comment(proc, str_lit("TernaryExpr")); - irValueArray edges = {0}; - array_init_reserve(&edges, proc->module->allocator, 2); + Array edges = {}; + array_init(&edges, proc->module->allocator, 2); GB_ASSERT(te->y != NULL); irBlock *then = ir_new_block(proc, NULL, "if.then"); @@ -3752,8 +3739,8 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { ir_build_stmt(proc, ie->init); } - irValueArray edges = {0}; - array_init_reserve(&edges, proc->module->allocator, 2); + Array edges = {}; + array_init(&edges, proc->module->allocator, 2); GB_ASSERT(ie->else_expr != NULL); irBlock *then = ir_new_block(proc, expr, "if.then"); @@ -3879,35 +3866,35 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { case_ast_node(ce, CallExpr, expr); - if (map_tav_get(&proc->module->info->types, hash_pointer(ce->proc))->mode == Addressing_Type) { + if (map_get(&proc->module->info->types, hash_pointer(ce->proc))->mode == Addressing_Type) { GB_ASSERT(ce->args.count == 1); - irValue *x = ir_build_expr(proc, ce->args.e[0]); + irValue *x = ir_build_expr(proc, ce->args[0]); irValue *y = ir_emit_conv(proc, x, tv.type); return y; } AstNode *p = unparen_expr(ce->proc); if (p->kind == AstNode_Ident) { - Entity **found = map_entity_get(&proc->module->info->uses, hash_pointer(p)); + Entity **found = map_get(&proc->module->info->uses, hash_pointer(p)); if (found && (*found)->kind == Entity_Builtin) { Entity *e = *found; switch (e->Builtin.id) { case BuiltinProc_type_info: { - Type *t = default_type(type_of_expr(proc->module->info, ce->args.e[0])); + Type *t = default_type(type_of_expr(proc->module->info, ce->args[0])); return ir_type_info(proc, t); } break; case BuiltinProc_type_info_of_val: { - Type *t = default_type(type_of_expr(proc->module->info, ce->args.e[0])); + Type *t = default_type(type_of_expr(proc->module->info, ce->args[0])); return ir_type_info(proc, t); } break; case BuiltinProc_transmute: { - irValue *x = ir_build_expr(proc, ce->args.e[1]); + irValue *x = ir_build_expr(proc, ce->args[1]); return ir_emit_transmute(proc, x, tv.type); } case BuiltinProc_len: { - irValue *v = ir_build_expr(proc, ce->args.e[0]); + irValue *v = ir_build_expr(proc, ce->args[0]); Type *t = base_type(ir_type(v)); if (is_type_pointer(t)) { // IMPORTANT TODO(bill): Should there be a nil pointer check? @@ -3934,7 +3921,7 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { } break; case BuiltinProc_cap: { - irValue *v = ir_build_expr(proc, ce->args.e[0]); + irValue *v = ir_build_expr(proc, ce->args[0]); Type *t = base_type(ir_type(v)); if (is_type_pointer(t)) { // IMPORTANT TODO(bill): Should there be a nil pointer check? @@ -3965,7 +3952,7 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { // new :: proc(Type) -> ^Type gbAllocator allocator = proc->module->allocator; - Type *type = type_of_expr(proc->module->info, ce->args.e[0]); + Type *type = type_of_expr(proc->module->info, ce->args[0]); Type *ptr_type = make_type_pointer(allocator, type); i64 s = type_size_of(allocator, type); @@ -3986,7 +3973,7 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { // new_slice :: proc(Type, len, cap: int) -> []Type gbAllocator allocator = proc->module->allocator; - Type *type = type_of_expr(proc->module->info, ce->args.e[0]); + Type *type = type_of_expr(proc->module->info, ce->args[0]); Type *ptr_type = make_type_pointer(allocator, type); Type *slice_type = make_type_slice(allocator, type); @@ -3996,14 +3983,14 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { irValue *elem_size = ir_const_int(allocator, s); irValue *elem_align = ir_const_int(allocator, a); - irValue *count = ir_emit_conv(proc, ir_build_expr(proc, ce->args.e[1]), t_int); + irValue *count = ir_emit_conv(proc, ir_build_expr(proc, ce->args[1]), t_int); irValue *capacity = count; if (ce->args.count == 3) { - capacity = ir_emit_conv(proc, ir_build_expr(proc, ce->args.e[2]), t_int); + capacity = ir_emit_conv(proc, ir_build_expr(proc, ce->args[2]), t_int); } - ir_emit_slice_bounds_check(proc, ast_node_token(ce->args.e[1]), v_zero, count, capacity, false); + ir_emit_slice_bounds_check(proc, ast_node_token(ce->args[1]), v_zero, count, capacity, false); irValue *slice_size = ir_emit_arith(proc, Token_Mul, elem_size, capacity, t_int); @@ -4022,7 +4009,7 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { case BuiltinProc_make: { ir_emit_comment(proc, str_lit("make")); gbAllocator a = proc->module->allocator; - Type *type = type_of_expr(proc->module->info, ce->args.e[0]); + Type *type = type_of_expr(proc->module->info, ce->args[0]); if (is_type_slice(type)) { Type *elem_type = core_type(type)->Slice.elem; @@ -4031,14 +4018,14 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { irValue *elem_size = ir_const_int(a, type_size_of(a, elem_type)); irValue *elem_align = ir_const_int(a, type_align_of(a, elem_type)); - irValue *count = ir_emit_conv(proc, ir_build_expr(proc, ce->args.e[1]), t_int); + irValue *count = ir_emit_conv(proc, ir_build_expr(proc, ce->args[1]), t_int); irValue *capacity = count; if (ce->args.count == 3) { - capacity = ir_emit_conv(proc, ir_build_expr(proc, ce->args.e[2]), t_int); + capacity = ir_emit_conv(proc, ir_build_expr(proc, ce->args[2]), t_int); } - ir_emit_slice_bounds_check(proc, ast_node_token(ce->args.e[1]), v_zero, count, capacity, false); + ir_emit_slice_bounds_check(proc, ast_node_token(ce->args[1]), v_zero, count, capacity, false); irValue *slice_size = ir_emit_arith(proc, Token_Mul, elem_size, capacity, t_int); @@ -4056,7 +4043,7 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { irValue *int_16 = ir_const_int(a, 16); irValue *cap = int_16; if (ce->args.count == 2) { - cap = ir_emit_conv(proc, ir_build_expr(proc, ce->args.e[1]), t_int); + cap = ir_emit_conv(proc, ir_build_expr(proc, ce->args[1]), t_int); } irValue *cond = ir_emit_comp(proc, Token_Gt, cap, v_zero); @@ -4074,14 +4061,14 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { Type *elem_type = base_type(type)->DynamicArray.elem; irValue *len = v_zero; if (ce->args.count > 1) { - len = ir_emit_conv(proc, ir_build_expr(proc, ce->args.e[1]), t_int); + len = ir_emit_conv(proc, ir_build_expr(proc, ce->args[1]), t_int); } irValue *cap = len; if (ce->args.count > 2) { - cap = ir_emit_conv(proc, ir_build_expr(proc, ce->args.e[2]), t_int); + cap = ir_emit_conv(proc, ir_build_expr(proc, ce->args[2]), t_int); } - ir_emit_slice_bounds_check(proc, ast_node_token(ce->args.e[0]), v_zero, len, cap, false); + ir_emit_slice_bounds_check(proc, ast_node_token(ce->args[0]), v_zero, len, cap, false); irValue *array = ir_add_local_generated(proc, type); irValue **args = gb_alloc_array(a, irValue *, 5); @@ -4101,7 +4088,7 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { gbAllocator a = proc->module->allocator; - AstNode *node = ce->args.e[0]; + AstNode *node = ce->args[0]; TypeAndValue tav = type_and_value_of_expr(proc->module->info, node); Type *type = base_type(tav.type); @@ -4174,12 +4161,12 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { ir_emit_comment(proc, str_lit("reserve")); gbAllocator a = proc->module->allocator; - irValue *ptr = ir_build_addr(proc, ce->args.e[0]).addr; + irValue *ptr = ir_build_addr(proc, ce->args[0]).addr; Type *type = ir_type(ptr); GB_ASSERT(is_type_pointer(type)); type = base_type(type_deref(type)); - irValue *capacity = ir_emit_conv(proc, ir_build_expr(proc, ce->args.e[1]), t_int); + irValue *capacity = ir_emit_conv(proc, ir_build_expr(proc, ce->args[1]), t_int); if (is_type_dynamic_array(type)) { Type *elem = type->DynamicArray.elem; @@ -4207,8 +4194,8 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { case BuiltinProc_clear: { ir_emit_comment(proc, str_lit("clear")); - Type *original_type = type_of_expr(proc->module->info, ce->args.e[0]); - irAddr addr = ir_build_addr(proc, ce->args.e[0]); + Type *original_type = type_of_expr(proc->module->info, ce->args[0]); + irAddr addr = ir_build_addr(proc, ce->args[0]); irValue *ptr = addr.addr; if (is_double_pointer(ir_type(ptr))) { ptr = ir_addr_load(proc, addr); @@ -4235,15 +4222,15 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { ir_emit_comment(proc, str_lit("append")); gbAllocator a = proc->module->allocator; - Type *value_type = type_of_expr(proc->module->info, ce->args.e[0]); - irAddr array_addr = ir_build_addr(proc, ce->args.e[0]); + Type *value_type = type_of_expr(proc->module->info, ce->args[0]); + irAddr array_addr = ir_build_addr(proc, ce->args[0]); irValue *array_ptr = array_addr.addr; if (is_double_pointer(ir_type(array_ptr))) { array_ptr = ir_addr_load(proc, array_addr); } Type *type = ir_type(array_ptr); { - TokenPos pos = ast_node_token(ce->args.e[0]).pos; + TokenPos pos = ast_node_token(ce->args[0]).pos; GB_ASSERT_MSG(is_type_pointer(type), "%.*s(%td) %s", LIT(pos.file), pos.line, type_to_string(type)); @@ -4268,7 +4255,7 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { isize arg_index = 0; isize arg_count = 0; for_array(i, ce->args) { - AstNode *a = ce->args.e[i]; + AstNode *a = ce->args[i]; Type *at = base_type(type_of_expr(proc->module->info, a)); if (at->kind == Type_Tuple) { arg_count += at->Tuple.variable_count; @@ -4281,7 +4268,7 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { bool vari_expand = ce->ellipsis.pos.line != 0; for_array(i, ce->args) { - irValue *a = ir_build_expr(proc, ce->args.e[i]); + irValue *a = ir_build_expr(proc, ce->args[i]); Type *at = ir_type(a); if (at->kind == Type_Tuple) { for (isize i = 0; i < at->Tuple.variable_count; i++) { @@ -4342,8 +4329,8 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { case BuiltinProc_delete: { ir_emit_comment(proc, str_lit("delete")); - irValue *map = ir_build_expr(proc, ce->args.e[0]); - irValue *key = ir_build_expr(proc, ce->args.e[1]); + irValue *map = ir_build_expr(proc, ce->args[0]); + irValue *key = ir_build_expr(proc, ce->args[1]); Type *map_type = ir_type(map); GB_ASSERT(is_type_dynamic_map(map_type)); Type *key_type = base_type(map_type)->Map.key; @@ -4360,7 +4347,7 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { case BuiltinProc_assert: { ir_emit_comment(proc, str_lit("assert")); - irValue *cond = ir_build_expr(proc, ce->args.e[0]); + irValue *cond = ir_build_expr(proc, ce->args[0]); GB_ASSERT(is_type_boolean(ir_type(cond))); cond = ir_emit_comp(proc, Token_CmpEq, cond, v_false); @@ -4371,11 +4358,11 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { ir_start_block(proc, err); // TODO(bill): Cleanup allocations here - Token token = ast_node_token(ce->args.e[0]); + Token token = ast_node_token(ce->args[0]); TokenPos pos = token.pos; - gbString expr = expr_to_string(ce->args.e[0]); + gbString expr = expr_to_string(ce->args[0]); isize expr_len = gb_string_length(expr); - String expr_str = {0}; + String expr_str = {}; expr_str.text = cast(u8 *)gb_alloc_copy_align(proc->module->allocator, expr, expr_len, 1); expr_str.len = expr_len; gb_string_free(expr); @@ -4396,10 +4383,10 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { case BuiltinProc_panic: { ir_emit_comment(proc, str_lit("panic")); - irValue *msg = ir_build_expr(proc, ce->args.e[0]); + irValue *msg = ir_build_expr(proc, ce->args[0]); GB_ASSERT(is_type_string(ir_type(msg))); - Token token = ast_node_token(ce->args.e[0]); + Token token = ast_node_token(ce->args[0]); TokenPos pos = token.pos; irValue **args = gb_alloc_array(proc->module->allocator, irValue *, 4); @@ -4416,8 +4403,8 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { case BuiltinProc_copy: { ir_emit_comment(proc, str_lit("copy")); // copy :: proc(dst, src: []Type) -> int - AstNode *dst_node = ce->args.e[0]; - AstNode *src_node = ce->args.e[1]; + AstNode *dst_node = ce->args[0]; + AstNode *src_node = ce->args[1]; irValue *dst_slice = ir_build_expr(proc, dst_node); irValue *src_slice = ir_build_expr(proc, src_node); Type *slice_type = base_type(ir_type(dst_slice)); @@ -4448,7 +4435,7 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { } break; case BuiltinProc_swizzle: { ir_emit_comment(proc, str_lit("swizzle.begin")); - irAddr vector_addr = ir_build_addr(proc, ce->args.e[0]); + irAddr vector_addr = ir_build_addr(proc, ce->args[0]); isize index_count = ce->args.count-1; if (index_count == 0) { return ir_addr_load(proc, vector_addr); @@ -4457,7 +4444,7 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { irValue *dst = ir_add_local_generated(proc, tv.type); for (i32 i = 1; i < ce->args.count; i++) { - TypeAndValue tv = type_and_value_of_expr(proc->module->info, ce->args.e[i]); + TypeAndValue tv = type_and_value_of_expr(proc->module->info, ce->args[i]); GB_ASSERT(is_type_integer(tv.type)); GB_ASSERT(tv.value.kind == ExactValue_Integer); @@ -4476,8 +4463,8 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { case BuiltinProc_complex: { ir_emit_comment(proc, str_lit("complex")); - irValue *real = ir_build_expr(proc, ce->args.e[0]); - irValue *imag = ir_build_expr(proc, ce->args.e[1]); + irValue *real = ir_build_expr(proc, ce->args[0]); + irValue *imag = ir_build_expr(proc, ce->args[1]); irValue *dst = ir_add_local_generated(proc, tv.type); Type *ft = base_complex_elem_type(tv.type); @@ -4491,20 +4478,20 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { case BuiltinProc_real: { ir_emit_comment(proc, str_lit("real")); - irValue *val = ir_build_expr(proc, ce->args.e[0]); + irValue *val = ir_build_expr(proc, ce->args[0]); irValue *real = ir_emit_struct_ev(proc, val, 0); return ir_emit_conv(proc, real, tv.type); } break; case BuiltinProc_imag: { ir_emit_comment(proc, str_lit("imag")); - irValue *val = ir_build_expr(proc, ce->args.e[0]); + irValue *val = ir_build_expr(proc, ce->args[0]); irValue *imag = ir_emit_struct_ev(proc, val, 1); return ir_emit_conv(proc, imag, tv.type); } break; case BuiltinProc_conj: { ir_emit_comment(proc, str_lit("conj")); - irValue *val = ir_build_expr(proc, ce->args.e[0]); + irValue *val = ir_build_expr(proc, ce->args[0]); irValue *res = NULL; Type *t = ir_type(val); if (is_type_complex(t)) { @@ -4520,12 +4507,12 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { case BuiltinProc_slice_ptr: { ir_emit_comment(proc, str_lit("slice_ptr")); - irValue *ptr = ir_build_expr(proc, ce->args.e[0]); - irValue *count = ir_build_expr(proc, ce->args.e[1]); + irValue *ptr = ir_build_expr(proc, ce->args[0]); + irValue *count = ir_build_expr(proc, ce->args[1]); count = ir_emit_conv(proc, count, t_int); irValue *capacity = count; if (ce->args.count > 2) { - capacity = ir_build_expr(proc, ce->args.e[2]); + capacity = ir_build_expr(proc, ce->args[2]); capacity = ir_emit_conv(proc, capacity, t_int); } @@ -4537,7 +4524,7 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { case BuiltinProc_slice_to_bytes: { ir_emit_comment(proc, str_lit("slice_to_bytes")); - irValue *s = ir_build_expr(proc, ce->args.e[0]); + irValue *s = ir_build_expr(proc, ce->args[0]); Type *t = base_type(ir_type(s)); if (is_type_u8_slice(t)) { return ir_emit_conv(proc, s, tv.type); @@ -4557,8 +4544,8 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { case BuiltinProc_min: { ir_emit_comment(proc, str_lit("min")); Type *t = type_of_expr(proc->module->info, expr); - irValue *x = ir_emit_conv(proc, ir_build_expr(proc, ce->args.e[0]), t); - irValue *y = ir_emit_conv(proc, ir_build_expr(proc, ce->args.e[1]), t); + irValue *x = ir_emit_conv(proc, ir_build_expr(proc, ce->args[0]), t); + irValue *y = ir_emit_conv(proc, ir_build_expr(proc, ce->args[1]), t); irValue *cond = ir_emit_comp(proc, Token_Lt, x, y); return ir_emit_select(proc, cond, x, y); } break; @@ -4566,15 +4553,15 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { case BuiltinProc_max: { ir_emit_comment(proc, str_lit("max")); Type *t = type_of_expr(proc->module->info, expr); - irValue *x = ir_emit_conv(proc, ir_build_expr(proc, ce->args.e[0]), t); - irValue *y = ir_emit_conv(proc, ir_build_expr(proc, ce->args.e[1]), t); + irValue *x = ir_emit_conv(proc, ir_build_expr(proc, ce->args[0]), t); + irValue *y = ir_emit_conv(proc, ir_build_expr(proc, ce->args[1]), t); irValue *cond = ir_emit_comp(proc, Token_Gt, x, y); return ir_emit_select(proc, cond, x, y); } break; case BuiltinProc_abs: { ir_emit_comment(proc, str_lit("abs")); - irValue *x = ir_build_expr(proc, ce->args.e[0]); + irValue *x = ir_build_expr(proc, ce->args[0]); Type *t = ir_type(x); if (is_type_complex(t)) { gbAllocator a = proc->module->allocator; @@ -4597,9 +4584,9 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { ir_emit_comment(proc, str_lit("clamp")); Type *t = type_of_expr(proc->module->info, expr); return ir_emit_clamp(proc, t, - ir_build_expr(proc, ce->args.e[0]), - ir_build_expr(proc, ce->args.e[1]), - ir_build_expr(proc, ce->args.e[2])); + ir_build_expr(proc, ce->args[0]), + ir_build_expr(proc, ce->args[1]), + ir_build_expr(proc, ce->args[2])); } break; } } @@ -4612,11 +4599,44 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { GB_ASSERT(proc_type_->kind == Type_Proc); TypeProc *type = &proc_type_->Proc; + if (is_call_expr_field_value(ce)) { + isize param_count = type->param_count; + irValue **args = gb_alloc_array(proc->module->allocator, irValue *, param_count); + + for_array(arg_index, ce->args) { + AstNode *arg = ce->args[arg_index]; + ast_node(fv, FieldValue, arg); + GB_ASSERT(fv->field->kind == AstNode_Ident); + String name = fv->field->Ident.string; + isize index = lookup_procedure_parameter(type, name); + GB_ASSERT(index >= 0); + irValue *expr = ir_build_expr(proc, fv->value); + args[index] = expr; + + } + TypeTuple *pt = &type->params->Tuple; + for (isize i = 0; i < param_count; i++) { + Entity *e = pt->variables[i]; + GB_ASSERT(e->kind == Entity_Variable); + if (args[i] == NULL) { + if (e->Variable.default_value.kind != ExactValue_Invalid) { + args[i] = ir_value_constant(proc->module->allocator, e->type, e->Variable.default_value); + } else { + args[i] = ir_value_nil(proc->module->allocator, e->type); + } + } else { + args[i] = ir_emit_conv(proc, args[i], e->type); + } + } + + return ir_emit_call(proc, value, args, param_count); + } + isize arg_index = 0; isize arg_count = 0; for_array(i, ce->args) { - AstNode *a = ce->args.e[i]; + AstNode *a = ce->args[i]; Type *at = base_type(type_of_expr(proc->module->info, a)); if (at->kind == Type_Tuple) { arg_count += at->Tuple.variable_count; @@ -4624,12 +4644,14 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { arg_count++; } } - irValue **args = gb_alloc_array(proc->module->allocator, irValue *, arg_count); - bool variadic = proc_type_->Proc.variadic; + + + irValue **args = gb_alloc_array(proc->module->allocator, irValue *, gb_max(type->param_count, arg_count)); + bool variadic = type->variadic; bool vari_expand = ce->ellipsis.pos.line != 0; for_array(i, ce->args) { - irValue *a = ir_build_expr(proc, ce->args.e[i]); + irValue *a = ir_build_expr(proc, ce->args[i]); Type *at = ir_type(a); if (at->kind == Type_Tuple) { for (isize i = 0; i < at->Tuple.variable_count; i++) { @@ -4644,6 +4666,23 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { TypeTuple *pt = &type->params->Tuple; + if (arg_count < type->param_count) { + isize end = type->param_count; + if (variadic) { + end--; + } + while (arg_index < end) { + Entity *e = pt->variables[arg_index]; + GB_ASSERT(e->kind == Entity_Variable); + if (e->Variable.default_value.kind != ExactValue_Invalid) { + args[arg_index++] = ir_value_constant(proc->module->allocator, e->type, e->Variable.default_value); + } else { + args[arg_index++] = ir_value_nil(proc->module->allocator, e->type); + } + } + } + + if (variadic) { isize i = 0; for (; i < type->param_count-1; i++) { @@ -4658,7 +4697,7 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { } } } else { - for (isize i = 0; i < arg_count; i++) { + for (isize i = 0; i < type->param_count; i++) { args[i] = ir_emit_conv(proc, args[i], pt->variables[i]->type); } } @@ -4688,7 +4727,7 @@ irValue *ir_build_expr(irProcedure *proc, AstNode *expr) { args[arg_count-1] = ir_emit_load(proc, slice); } - return ir_emit_call(proc, value, args, arg_count); + return ir_emit_call(proc, value, args, type->param_count); case_end; case_ast_node(se, SliceExpr, expr); @@ -4710,7 +4749,7 @@ irValue *ir_get_using_variable(irProcedure *proc, Entity *e) { Entity *parent = e->using_parent; Selection sel = lookup_field(proc->module->allocator, parent->type, name, false); GB_ASSERT(sel.entity != NULL); - irValue **pv = map_ir_value_get(&proc->module->values, hash_pointer(parent)); + irValue **pv = map_get(&proc->module->values, hash_pointer(parent)); irValue *v = NULL; if (pv != NULL) { v = *pv; @@ -4725,7 +4764,7 @@ irValue *ir_get_using_variable(irProcedure *proc, Entity *e) { // irValue *ir_add_using_variable(irProcedure *proc, Entity *e) { // irValue *var = ir_get_using_variable(proc, e); -// map_ir_value_set(&proc->module->values, hash_pointer(e), var); +// map_set(&proc->module->values, hash_pointer(e), var); // return var; // } @@ -4747,7 +4786,7 @@ irAddr ir_build_addr_from_entity(irProcedure *proc, Entity *e, AstNode *expr) { GB_ASSERT(e->kind != Entity_Constant); irValue *v = NULL; - irValue **found = map_ir_value_get(&proc->module->values, hash_pointer(e)); + irValue **found = map_get(&proc->module->values, hash_pointer(e)); if (found) { v = *found; } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) { @@ -4778,7 +4817,7 @@ irAddr ir_build_addr(irProcedure *proc, AstNode *expr) { case_ast_node(i, Ident, expr); if (ir_is_blank_ident(expr)) { - irAddr val = {0}; + irAddr val = {}; return val; } Entity *e = entity_of_ident(proc->module->info, expr); @@ -4813,7 +4852,7 @@ irAddr ir_build_addr(irProcedure *proc, AstNode *expr) { GB_ASSERT(e->kind == Entity_Variable); GB_ASSERT(e->flags & EntityFlag_TypeField); String name = e->token.string; - if (str_eq(name, str_lit("names"))) { + if (name == "names") { irValue *ti_ptr = ir_type_info(proc, type); irValue *names_ptr = NULL; @@ -4840,12 +4879,12 @@ irAddr ir_build_addr(irProcedure *proc, AstNode *expr) { Type *bft = type_deref(ir_addr_type(addr)); if (sel.index.count == 1) { GB_ASSERT(is_type_bit_field(bft)); - i32 index = sel.index.e[0]; + i32 index = sel.index[0]; return ir_addr_bit_field(addr.addr, index); } else { Selection s = sel; s.index.count--; - i32 index = s.index.e[s.index.count-1]; + i32 index = s.index[s.index.count-1]; irValue *a = addr.addr; a = ir_emit_deep_field_gep(proc, a, s); return ir_addr_bit_field(a, index); @@ -4902,27 +4941,7 @@ irAddr ir_build_addr(irProcedure *proc, AstNode *expr) { case_end; case_ast_node(be, BinaryExpr, expr); - switch (be->op.kind) { - // case Token_as: { - // ir_emit_comment(proc, str_lit("Cast - as")); - // // NOTE(bill): Needed for dereference of pointer conversion - // Type *type = type_of_expr(proc->module->info, expr); - // irValue *v = ir_add_local_generated(proc, type); - // ir_emit_store(proc, v, ir_emit_conv(proc, ir_build_expr(proc, be->left), type)); - // return ir_addr(v); - // } - // case Token_transmute: { - // ir_emit_comment(proc, str_lit("Cast - transmute")); - // // NOTE(bill): Needed for dereference of pointer conversion - // Type *type = type_of_expr(proc->module->info, expr); - // irValue *v = ir_add_local_generated(proc, type); - // ir_emit_store(proc, v, ir_emit_transmute(proc, ir_build_expr(proc, be->left), type)); - // return ir_addr(v); - // } - default: - GB_PANIC("Invalid binary expression for ir_build_addr: %.*s\n", LIT(be->op.string)); - break; - } + GB_PANIC("Invalid binary expression for ir_build_addr: %.*s\n", LIT(be->op.string)); case_end; case_ast_node(ie, IndexExpr, expr); @@ -5191,14 +5210,14 @@ irAddr ir_build_addr(irProcedure *proc, AstNode *expr) { case Type_Vector: { if (cl->elems.count == 1 && bt->Vector.count > 1) { isize index_count = bt->Vector.count; - irValue *elem_val = ir_build_expr(proc, cl->elems.e[0]); + irValue *elem_val = ir_build_expr(proc, cl->elems[0]); for (isize i = 0; i < index_count; i++) { ir_emit_store(proc, ir_emit_array_epi(proc, v, i), elem_val); } } else if (cl->elems.count > 0) { ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr))); for_array(i, cl->elems) { - AstNode *elem = cl->elems.e[i]; + AstNode *elem = cl->elems[i]; if (ir_is_elem_const(proc->module, elem, et)) { continue; } @@ -5221,7 +5240,7 @@ irAddr ir_build_addr(irProcedure *proc, AstNode *expr) { if (cl->elems.count > 0) { ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr))); for_array(field_index, cl->elems) { - AstNode *elem = cl->elems.e[field_index]; + AstNode *elem = cl->elems[field_index]; irValue *field_expr = NULL; Entity *field = NULL; @@ -5231,12 +5250,12 @@ irAddr ir_build_addr(irProcedure *proc, AstNode *expr) { ast_node(fv, FieldValue, elem); String name = fv->field->Ident.string; Selection sel = lookup_field(proc->module->allocator, bt, name, false); - index = sel.index.e[0]; + index = sel.index[0]; elem = fv->value; } else { TypeAndValue tav = type_and_value_of_expr(proc->module->info, elem); Selection sel = lookup_field_from_index(proc->module->allocator, bt, st->fields_in_src_order[field_index]->Variable.field_index); - index = sel.index.e[0]; + index = sel.index[0]; } field = st->fields[index]; @@ -5278,7 +5297,7 @@ irAddr ir_build_addr(irProcedure *proc, AstNode *expr) { irValue *items = ir_generate_array(proc->module, elem, item_count, str_lit("__dacl$"), cast(i64)cast(intptr)expr); for_array(field_index, cl->elems) { - AstNode *f = cl->elems.e[field_index]; + AstNode *f = cl->elems[field_index]; irValue *value = ir_emit_conv(proc, ir_build_expr(proc, f), elem); irValue *ep = ir_emit_array_epi(proc, items, field_index); ir_emit_store(proc, ep, value); @@ -5307,7 +5326,7 @@ irAddr ir_build_addr(irProcedure *proc, AstNode *expr) { ir_emit_global_call(proc, "__dynamic_map_reserve", args, 2); } for_array(field_index, cl->elems) { - AstNode *elem = cl->elems.e[field_index]; + AstNode *elem = cl->elems[field_index]; ast_node(fv, FieldValue, elem); irValue *key = ir_build_expr(proc, fv->field); @@ -5320,7 +5339,7 @@ irAddr ir_build_addr(irProcedure *proc, AstNode *expr) { if (cl->elems.count > 0) { ir_emit_store(proc, v, ir_add_module_constant(proc->module, type, exact_value_compound(expr))); for_array(i, cl->elems) { - AstNode *elem = cl->elems.e[i]; + AstNode *elem = cl->elems[i]; if (ir_is_elem_const(proc->module, elem, et)) { continue; } @@ -5344,7 +5363,7 @@ irAddr ir_build_addr(irProcedure *proc, AstNode *expr) { irValue *data = ir_emit_array_ep(proc, slice->ConstantSlice.backing_array, v_zero32); for_array(i, cl->elems) { - AstNode *elem = cl->elems.e[i]; + AstNode *elem = cl->elems[i]; if (ir_is_elem_const(proc->module, elem, et)) { continue; } @@ -5376,7 +5395,7 @@ irAddr ir_build_addr(irProcedure *proc, AstNode *expr) { }; for_array(field_index, cl->elems) { - AstNode *elem = cl->elems.e[field_index]; + AstNode *elem = cl->elems[field_index]; irValue *field_expr = NULL; isize index = field_index; @@ -5384,12 +5403,12 @@ irAddr ir_build_addr(irProcedure *proc, AstNode *expr) { if (elem->kind == AstNode_FieldValue) { ast_node(fv, FieldValue, elem); Selection sel = lookup_field(proc->module->allocator, bt, fv->field->Ident.string, false); - index = sel.index.e[0]; + index = sel.index[0]; elem = fv->value; } else { TypeAndValue tav = type_and_value_of_expr(proc->module->info, elem); Selection sel = lookup_field(proc->module->allocator, bt, field_names[field_index], false); - index = sel.index.e[0]; + index = sel.index[0]; } field_expr = ir_build_expr(proc, elem); @@ -5470,9 +5489,9 @@ irValue *ir_build_cond(irProcedure *proc, AstNode *cond, irBlock *true_block, ir -void ir_build_stmt_list(irProcedure *proc, AstNodeArray stmts) { +void ir_build_stmt_list(irProcedure *proc, Array stmts) { for_array(i, stmts) { - ir_build_stmt(proc, stmts.e[i]); + ir_build_stmt(proc, stmts[i]); } } @@ -5746,7 +5765,7 @@ void ir_build_range_interval(irProcedure *proc, AstNodeBinaryExpr *node, Type *v } void ir_store_type_case_implicit(irProcedure *proc, AstNode *clause, irValue *value) { - Entity **found = map_entity_get(&proc->module->info->implicits, hash_pointer(clause)); + Entity **found = map_get(&proc->module->info->implicits, hash_pointer(clause)); GB_ASSERT(found != NULL); Entity *e = *found; GB_ASSERT(e != NULL); irValue *x = ir_add_local(proc, e, NULL); @@ -5773,7 +5792,7 @@ void ir_build_stmt_internal(irProcedure *proc, AstNode *node) { case_ast_node(us, UsingStmt, node); for_array(i, us->list) { - AstNode *decl = unparen_expr(us->list.e[i]); + AstNode *decl = unparen_expr(us->list[i]); if (decl->kind == AstNode_ValueDecl) { ir_build_stmt(proc, decl); } @@ -5800,19 +5819,19 @@ void ir_build_stmt_internal(irProcedure *proc, AstNode *node) { if (vd->values.count == 0) { // declared and zero-initialized for_array(i, vd->names) { - AstNode *name = vd->names.e[i]; + AstNode *name = vd->names[i]; if (!ir_is_blank_ident(name)) { ir_add_local_for_identifier(proc, name, true); } } } else { // Tuple(s) - Array(irAddr) lvals = {0}; - irValueArray inits = {0}; - array_init_reserve(&lvals, m->tmp_allocator, vd->names.count); - array_init_reserve(&inits, m->tmp_allocator, vd->names.count); + Array lvals = {}; + Array inits = {}; + array_init(&lvals, m->tmp_allocator, vd->names.count); + array_init(&inits, m->tmp_allocator, vd->names.count); for_array(i, vd->names) { - AstNode *name = vd->names.e[i]; + AstNode *name = vd->names[i]; irAddr lval = ir_addr(NULL); if (!ir_is_blank_ident(name)) { ir_add_local_for_identifier(proc, name, false); @@ -5823,7 +5842,7 @@ void ir_build_stmt_internal(irProcedure *proc, AstNode *node) { } for_array(i, vd->values) { - irValue *init = ir_build_expr(proc, vd->values.e[i]); + irValue *init = ir_build_expr(proc, vd->values[i]); Type *t = ir_type(init); if (t->kind == Type_Tuple) { for (isize i = 0; i < t->Tuple.variable_count; i++) { @@ -5838,14 +5857,14 @@ void ir_build_stmt_internal(irProcedure *proc, AstNode *node) { for_array(i, inits) { - ir_addr_store(proc, lvals.e[i], inits.e[i]); + ir_addr_store(proc, lvals[i], inits[i]); } } gb_temp_arena_memory_end(tmp); } else { for_array(i, vd->names) { - AstNode *ident = vd->names.e[i]; + AstNode *ident = vd->names[i]; GB_ASSERT(ident->kind == AstNode_Ident); Entity *e = entity_of_ident(proc->module->info, ident); GB_ASSERT(e != NULL); @@ -5862,18 +5881,18 @@ void ir_build_stmt_internal(irProcedure *proc, AstNode *node) { irValue *value = ir_value_type_name(proc->module->allocator, name, e->type); - map_string_set(&proc->module->entity_names, hash_pointer(e), name); + map_set(&proc->module->entity_names, hash_pointer(e), name); ir_gen_global_type_name(proc->module, e, name); } break; case Entity_Procedure: { - DeclInfo **decl_info = map_decl_info_get(&proc->module->info->entities, hash_pointer(e)); + DeclInfo **decl_info = map_get(&proc->module->info->entities, hash_pointer(e)); GB_ASSERT(decl_info != NULL); DeclInfo *dl = *decl_info; ast_node(pd, ProcLit, dl->proc_lit); if (pd->body != NULL) { CheckerInfo *info = proc->module->info; - if (map_entity_get(&proc->module->min_dep_map, hash_pointer(e)) == NULL) { + if (map_get(&proc->module->min_dep_map, hash_pointer(e)) == NULL) { // NOTE(bill): Nothing depends upon it so doesn't need to be built break; } @@ -5922,10 +5941,10 @@ void ir_build_stmt_internal(irProcedure *proc, AstNode *node) { if (value->Proc.tags & ProcTag_foreign) { HashKey key = hash_string(name); - irValue **prev_value = map_ir_value_get(&proc->module->members, key); + irValue **prev_value = map_get(&proc->module->members, key); if (prev_value == NULL) { // NOTE(bill): Don't do mutliple declarations in the IR - map_ir_value_set(&proc->module->members, key, value); + map_set(&proc->module->members, key, value); } } else { array_add(&proc->children, &value->Proc); @@ -5945,12 +5964,12 @@ void ir_build_stmt_internal(irProcedure *proc, AstNode *node) { switch (as->op.kind) { case Token_Eq: { - Array(irAddr) lvals; + Array lvals; array_init(&lvals, m->tmp_allocator); for_array(i, as->lhs) { - AstNode *lhs = as->lhs.e[i]; - irAddr lval = {0}; + AstNode *lhs = as->lhs[i]; + irAddr lval = {}; if (!ir_is_blank_ident(lhs)) { lval = ir_build_addr(proc, lhs); } @@ -5959,28 +5978,28 @@ void ir_build_stmt_internal(irProcedure *proc, AstNode *node) { if (as->lhs.count == as->rhs.count) { if (as->lhs.count == 1) { - AstNode *rhs = as->rhs.e[0]; + AstNode *rhs = as->rhs[0]; irValue *init = ir_build_expr(proc, rhs); - ir_addr_store(proc, lvals.e[0], init); + ir_addr_store(proc, lvals[0], init); } else { - irValueArray inits; - array_init_reserve(&inits, m->tmp_allocator, lvals.count); + Array inits; + array_init(&inits, m->tmp_allocator, lvals.count); for_array(i, as->rhs) { - irValue *init = ir_build_expr(proc, as->rhs.e[i]); + irValue *init = ir_build_expr(proc, as->rhs[i]); array_add(&inits, init); } for_array(i, inits) { - ir_addr_store(proc, lvals.e[i], inits.e[i]); + ir_addr_store(proc, lvals[i], inits[i]); } } } else { - irValueArray inits; - array_init_reserve(&inits, m->tmp_allocator, lvals.count); + Array inits; + array_init(&inits, m->tmp_allocator, lvals.count); for_array(i, as->rhs) { - irValue *init = ir_build_expr(proc, as->rhs.e[i]); + irValue *init = ir_build_expr(proc, as->rhs[i]); Type *t = ir_type(init); // TODO(bill): refactor for code reuse as this is repeated a bit if (t->kind == Type_Tuple) { @@ -5995,7 +6014,7 @@ void ir_build_stmt_internal(irProcedure *proc, AstNode *node) { } for_array(i, inits) { - ir_addr_store(proc, lvals.e[i], inits.e[i]); + ir_addr_store(proc, lvals[i], inits[i]); } } @@ -6006,8 +6025,8 @@ void ir_build_stmt_internal(irProcedure *proc, AstNode *node) { // +=, -=, etc i32 op = cast(i32)as->op.kind; op += Token_Add - Token_AddEq; // Convert += to + - irAddr lhs = ir_build_addr(proc, as->lhs.e[0]); - irValue *value = ir_build_expr(proc, as->rhs.e[0]); + irAddr lhs = ir_build_addr(proc, as->lhs[0]); + irValue *value = ir_build_expr(proc, as->rhs[0]); ir_build_assign_op(proc, lhs, value, cast(TokenKind)op); } break; } @@ -6044,16 +6063,16 @@ void ir_build_stmt_internal(irProcedure *proc, AstNode *node) { // No return values } else if (return_count == 1) { Entity *e = return_type_tuple->variables[0]; - v = ir_build_expr(proc, rs->results.e[0]); + v = ir_build_expr(proc, rs->results[0]); v = ir_emit_conv(proc, v, e->type); } else { gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&proc->module->tmp_arena); - irValueArray results; - array_init_reserve(&results, proc->module->tmp_allocator, return_count); + Array results; + array_init(&results, proc->module->tmp_allocator, return_count); for_array(res_index, rs->results) { - irValue *res = ir_build_expr(proc, rs->results.e[res_index]); + irValue *res = ir_build_expr(proc, rs->results[res_index]); Type *t = ir_type(res); if (t->kind == Type_Tuple) { for (isize i = 0; i < t->Tuple.variable_count; i++) { @@ -6070,7 +6089,7 @@ void ir_build_stmt_internal(irProcedure *proc, AstNode *node) { v = ir_add_local_generated(proc, ret_type); for_array(i, results) { Entity *e = return_type_tuple->variables[i]; - irValue *res = ir_emit_conv(proc, results.e[i], e->type); + irValue *res = ir_emit_conv(proc, results[i], e->type); irValue *field = ir_emit_struct_ep(proc, v, i); ir_emit_store(proc, field, res); } @@ -6319,8 +6338,8 @@ void ir_build_stmt_internal(irProcedure *proc, AstNode *node) { } } - irAddr val_addr = {0}; - irAddr idx_addr = {0}; + irAddr val_addr = {}; + irAddr idx_addr = {}; if (val_type != NULL) { val_addr = ir_build_addr(proc, rs->value); } @@ -6358,7 +6377,7 @@ void ir_build_stmt_internal(irProcedure *proc, AstNode *node) { ast_node(body, BlockStmt, ms->body); - AstNodeArray default_stmts = {0}; + Array default_stmts = {}; irBlock *default_fall = NULL; irBlock *default_block = NULL; @@ -6367,7 +6386,7 @@ void ir_build_stmt_internal(irProcedure *proc, AstNode *node) { isize case_count = body->stmts.count; for_array(i, body->stmts) { - AstNode *clause = body->stmts.e[i]; + AstNode *clause = body->stmts[i]; irBlock *body = fall; ast_node(cc, CaseClause, clause); @@ -6399,12 +6418,12 @@ void ir_build_stmt_internal(irProcedure *proc, AstNode *node) { irBlock *next_cond = NULL; for_array(j, cc->list) { - AstNode *expr = unparen_expr(cc->list.e[j]); + AstNode *expr = unparen_expr(cc->list[j]); next_cond = ir_new_block(proc, clause, "match.case.next"); irValue *cond = v_false; if (is_ast_node_a_range(expr)) { ast_node(ie, BinaryExpr, expr); - TokenKind op = {0}; + TokenKind op = {}; switch (ie->op.kind) { case Token_Ellipsis: op = Token_LtEq; break; case Token_HalfClosed: op = Token_Lt; break; @@ -6459,7 +6478,7 @@ void ir_build_stmt_internal(irProcedure *proc, AstNode *node) { GB_ASSERT(as->lhs.count == 1); GB_ASSERT(as->rhs.count == 1); - irValue *parent = ir_build_expr(proc, as->rhs.e[0]); + irValue *parent = ir_build_expr(proc, as->rhs[0]); Type *parent_type = ir_type(parent); bool is_parent_ptr = is_type_pointer(ir_type(parent)); @@ -6494,7 +6513,7 @@ void ir_build_stmt_internal(irProcedure *proc, AstNode *node) { gb_local_persist i32 weird_count = 0; for_array(i, body->stmts) { - AstNode *clause = body->stmts.e[i]; + AstNode *clause = body->stmts[i]; ast_node(cc, CaseClause, clause); if (cc->list.count == 0) { default_ = clause; @@ -6506,7 +6525,7 @@ void ir_build_stmt_internal(irProcedure *proc, AstNode *node) { Type *case_type = NULL; for_array(type_index, cc->list) { next = ir_new_block(proc, NULL, "typematch.next"); - case_type = type_of_expr(proc->module->info, cc->list.e[type_index]); + case_type = type_of_expr(proc->module->info, cc->list[type_index]); irValue *cond = NULL; if (match_type_kind == MatchType_Union) { Type *bt = type_deref(case_type); @@ -6535,7 +6554,7 @@ void ir_build_stmt_internal(irProcedure *proc, AstNode *node) { Entity *case_entity = NULL; { - Entity **found = map_entity_get(&proc->module->info->implicits, hash_pointer(clause)); + Entity **found = map_get(&proc->module->info->implicits, hash_pointer(clause)); GB_ASSERT(found != NULL); case_entity = *found; } @@ -6680,11 +6699,11 @@ void ir_build_stmt_internal(irProcedure *proc, AstNode *node) { void ir_number_proc_registers(irProcedure *proc) { i32 reg_index = 0; for_array(i, proc->blocks) { - irBlock *b = proc->blocks.e[i]; + irBlock *b = proc->blocks[i]; b->index = i; for_array(j, b->instrs) { - irValue *value = b->instrs.e[j]; - GB_ASSERT(value->kind == irValue_Instr); + irValue *value = b->instrs[j]; + GB_ASSERT_MSG(value->kind == irValue_Instr, "%.*s", LIT(proc->name)); irInstr *instr = &value->Instr; if (ir_instr_type(instr) == NULL) { // NOTE(bill): Ignore non-returning instructions value->index = -1; @@ -6705,11 +6724,11 @@ void ir_begin_procedure_body(irProcedure *proc) { array_init(&proc->children, heap_allocator()); array_init(&proc->branch_blocks, heap_allocator()); - DeclInfo **found = map_decl_info_get(&proc->module->info->entities, hash_pointer(proc->entity)); + DeclInfo **found = map_get(&proc->module->info->entities, hash_pointer(proc->entity)); if (found != NULL) { DeclInfo *decl = *found; for_array(i, decl->labels) { - BlockLabel bl = decl->labels.e[i]; + BlockLabel bl = decl->labels[i]; irBranchBlocks bb = {bl.label, NULL, NULL}; array_add(&proc->branch_blocks, bb); } @@ -6743,18 +6762,18 @@ void ir_begin_procedure_body(irProcedure *proc) { for (isize i = 0; i < params->variable_count; i++) { ast_node(fl, FieldList, pt->params); GB_ASSERT(fl->list.count > 0); - GB_ASSERT(fl->list.e[0]->kind == AstNode_Field); - if (q_index == fl->list.e[param_index]->Field.names.count) { + GB_ASSERT(fl->list[0]->kind == AstNode_Field); + if (q_index == fl->list[param_index]->Field.names.count) { q_index = 0; param_index++; } - ast_node(field, Field, fl->list.e[param_index]); - AstNode *name = field->names.e[q_index++]; + ast_node(field, Field, fl->list[param_index]); + AstNode *name = field->names[q_index++]; Entity *e = params->variables[i]; Type *abi_type = proc->type->Proc.abi_compat_params[i]; - if (!str_eq(e->token.string, str_lit("")) && - !str_eq(e->token.string, str_lit("_"))) { + if (e->token.string != "" && + e->token.string != "_") { irValue *param = ir_add_param(proc, e, name, abi_type); array_add(&proc->params, param); } @@ -6784,7 +6803,7 @@ void ir_end_procedure_body(irProcedure *proc) { void ir_insert_code_before_proc(irProcedure* proc, irProcedure *parent) { if (parent == NULL) { - if (str_eq(proc->name, str_lit("main"))) { + if (proc->name == "main") { ir_emit_startup_runtime(proc); } } @@ -6800,12 +6819,12 @@ void ir_build_proc(irValue *value, irProcedure *parent) { CheckerInfo *info = m->info; Entity *e = proc->entity; String filename = e->token.pos.file; - AstFile **found = map_ast_file_get(&info->files, hash_string(filename)); + AstFile **found = map_get(&info->files, hash_string(filename)); GB_ASSERT(found != NULL); AstFile *f = *found; irDebugInfo *di_file = NULL; - irDebugInfo **di_file_found = map_ir_debug_info_get(&m->debug_info, hash_pointer(f)); + irDebugInfo **di_file_found = map_get(&m->debug_info, hash_pointer(f)); if (di_file_found) { di_file = *di_file_found; GB_ASSERT(di_file->kind == irDebugInfo_File); @@ -6857,7 +6876,7 @@ void ir_build_proc(irValue *value, irProcedure *parent) { void ir_module_add_value(irModule *m, Entity *e, irValue *v) { - map_ir_value_set(&m->values, hash_pointer(e), v); + map_set(&m->values, hash_pointer(e), v); } void ir_init_module(irModule *m, Checker *c) { @@ -6870,10 +6889,10 @@ void ir_init_module(irModule *m, Checker *c) { m->tmp_allocator = gb_arena_allocator(&m->tmp_arena); m->info = &c->info; - map_ir_value_init(&m->values, heap_allocator()); - map_ir_value_init(&m->members, heap_allocator()); - map_ir_debug_info_init(&m->debug_info, heap_allocator()); - map_string_init(&m->entity_names, heap_allocator()); + map_init(&m->values, heap_allocator()); + map_init(&m->members, heap_allocator()); + map_init(&m->debug_info, heap_allocator()); + map_init(&m->entity_names, heap_allocator()); array_init(&m->procs, heap_allocator()); array_init(&m->procs_to_generate, heap_allocator()); array_init(&m->foreign_library_paths, heap_allocator()); @@ -6887,8 +6906,8 @@ void ir_init_module(irModule *m, Checker *c) { { isize max_index = -1; for_array(type_info_map_index, m->info->type_info_map.entries) { - MapIsizeEntry *entry = &m->info->type_info_map.entries.e[type_info_map_index]; - Type *t = cast(Type *)cast(uintptr)entry->key.key; + auto *entry = &m->info->type_info_map.entries[type_info_map_index]; + Type *t = cast(Type *)entry->key.ptr; t = default_type(t); isize entry_index = ir_type_info_index(m->info, t); if (max_index < entry_index) { @@ -6902,7 +6921,7 @@ void ir_init_module(irModule *m, Checker *c) { irValue *g = ir_value_global(m->allocator, e, NULL); g->Global.is_private = true; ir_module_add_value(m, e, g); - map_ir_value_set(&m->members, hash_string(name), g); + map_set(&m->members, hash_string(name), g); ir_global_type_info_data = g; } @@ -6912,8 +6931,8 @@ void ir_init_module(irModule *m, Checker *c) { isize count = 0; for_array(entry_index, m->info->type_info_map.entries) { - MapIsizeEntry *entry = &m->info->type_info_map.entries.e[entry_index]; - Type *t = cast(Type *)cast(uintptr)entry->key.key; + auto *entry = &m->info->type_info_map.entries[entry_index]; + Type *t = cast(Type *)entry->key.ptr; switch (t->kind) { case Type_Record: @@ -6940,7 +6959,7 @@ void ir_init_module(irModule *m, Checker *c) { make_type_array(m->allocator, t_type_info_ptr, count), false); irValue *g = ir_value_global(m->allocator, e, NULL); ir_module_add_value(m, e, g); - map_ir_value_set(&m->members, hash_string(name), g); + map_set(&m->members, hash_string(name), g); ir_global_type_info_member_types = g; } { @@ -6949,7 +6968,7 @@ void ir_init_module(irModule *m, Checker *c) { make_type_array(m->allocator, t_string, count), false); irValue *g = ir_value_global(m->allocator, e, NULL); ir_module_add_value(m, e, g); - map_ir_value_set(&m->members, hash_string(name), g); + map_set(&m->members, hash_string(name), g); ir_global_type_info_member_names = g; } { @@ -6958,7 +6977,7 @@ void ir_init_module(irModule *m, Checker *c) { make_type_array(m->allocator, t_int, count), false); irValue *g = ir_value_global(m->allocator, e, NULL); ir_module_add_value(m, e, g); - map_ir_value_set(&m->members, hash_string(name), g); + map_set(&m->members, hash_string(name), g); ir_global_type_info_member_offsets = g; } @@ -6968,7 +6987,7 @@ void ir_init_module(irModule *m, Checker *c) { make_type_array(m->allocator, t_bool, count), false); irValue *g = ir_value_global(m->allocator, e, NULL); ir_module_add_value(m, e, g); - map_ir_value_set(&m->members, hash_string(name), g); + map_set(&m->members, hash_string(name), g); ir_global_type_info_member_usings = g; } } @@ -6976,18 +6995,18 @@ void ir_init_module(irModule *m, Checker *c) { { irDebugInfo *di = ir_alloc_debug_info(m->allocator, irDebugInfo_CompileUnit); - di->CompileUnit.file = m->info->files.entries.e[0].value; // Zeroth is the init file + di->CompileUnit.file = m->info->files.entries[0].value; // Zeroth is the init file di->CompileUnit.producer = str_lit("odin"); - map_ir_debug_info_set(&m->debug_info, hash_pointer(m), di); + map_set(&m->debug_info, hash_pointer(m), di); } } void ir_destroy_module(irModule *m) { - map_ir_value_destroy(&m->values); - map_ir_value_destroy(&m->members); - map_string_destroy(&m->entity_names); - map_ir_debug_info_destroy(&m->debug_info); + map_destroy(&m->values); + map_destroy(&m->members); + map_destroy(&m->entity_names); + map_destroy(&m->debug_info); array_free(&m->procs); array_free(&m->procs_to_generate); array_free(&m->foreign_library_paths); @@ -7080,7 +7099,7 @@ void ir_add_foreign_library_path(irModule *m, Entity *e) { } for_array(path_index, m->foreign_library_paths) { - String path = m->foreign_library_paths.e[path_index]; + String path = m->foreign_library_paths[path_index]; #if defined(GB_SYSTEM_WINDOWS) if (str_eq_ignore_case(path, library_path)) { #else @@ -7115,39 +7134,39 @@ void ir_gen_tree(irGen *s) { bool has_win_main = false; for_array(i, info->entities.entries) { - MapDeclInfoEntry *entry = &info->entities.entries.e[i]; - Entity *e = cast(Entity *)cast(uintptr)entry->key.key; + auto *entry = &info->entities.entries[i]; + Entity *e = cast(Entity *)entry->key.ptr; String name = e->token.string; if (e->kind == Entity_Variable) { global_variable_max_count++; } else if (e->kind == Entity_Procedure && !e->scope->is_global) { - if (e->scope->is_init && str_eq(name, str_lit("main"))) { + if (e->scope->is_init && name == "main") { entry_point = e; } if ((e->Procedure.tags & ProcTag_export) != 0 || (e->Procedure.link_name.len > 0) || (e->scope->is_file && e->Procedure.link_name.len > 0)) { - if (!has_dll_main && str_eq(name, str_lit("DllMain"))) { + if (!has_dll_main && name == "DllMain") { has_dll_main = true; - } else if (!has_win_main && str_eq(name, str_lit("WinMain"))) { + } else if (!has_win_main && name == "WinMain") { has_win_main = true; } } } } - typedef struct irGlobalVariable { + struct irGlobalVariable { irValue *var, *init; DeclInfo *decl; - } irGlobalVariable; - Array(irGlobalVariable) global_variables; - array_init_reserve(&global_variables, m->tmp_allocator, global_variable_max_count); + }; + Array global_variables; + array_init(&global_variables, m->tmp_allocator, global_variable_max_count); m->entry_point_entity = entry_point; m->min_dep_map = generate_minimum_dependency_map(info, entry_point); for_array(i, info->entities.entries) { - MapDeclInfoEntry *entry = &info->entities.entries.e[i]; + auto *entry = &info->entities.entries[i]; Entity *e = cast(Entity *)entry->key.ptr; String name = e->token.string; DeclInfo *decl = entry->value; @@ -7157,7 +7176,7 @@ void ir_gen_tree(irGen *s) { continue; } - if (map_entity_get(&m->min_dep_map, hash_pointer(e)) == NULL) { + if (map_get(&m->min_dep_map, hash_pointer(e)) == NULL) { // NOTE(bill): Nothing depends upon it so doesn't need to be built continue; } @@ -7166,12 +7185,12 @@ void ir_gen_tree(irGen *s) { if (e->kind == Entity_Procedure && (e->Procedure.tags & ProcTag_export) != 0) { } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) { // Handle later - } else if (scope->is_init && e->kind == Entity_Procedure && str_eq(name, str_lit("main"))) { + } else if (scope->is_init && e->kind == Entity_Procedure && name == "main") { } else { name = ir_mangle_name(s, e->token.pos.file, e); } } - map_string_set(&m->entity_names, hash_pointer(e), name); + map_set(&m->entity_names, hash_pointer(e), name); switch (e->kind) { case Entity_TypeName: @@ -7184,7 +7203,7 @@ void ir_gen_tree(irGen *s) { g->Global.name = name; g->Global.is_thread_local = e->Variable.is_thread_local; - irGlobalVariable var = {0}; + irGlobalVariable var = {}; var.var = g; var.decl = decl; @@ -7209,7 +7228,7 @@ void ir_gen_tree(irGen *s) { } ir_module_add_value(m, e, g); - map_ir_value_set(&m->members, hash_string(name), g); + map_set(&m->members, hash_string(name), g); } break; case Entity_Procedure: { @@ -7233,28 +7252,28 @@ void ir_gen_tree(irGen *s) { ir_module_add_value(m, e, p); HashKey hash_name = hash_string(name); - if (map_ir_value_get(&m->members, hash_name) == NULL) { - map_ir_value_multi_insert(&m->members, hash_name, p); + if (map_get(&m->members, hash_name) == NULL) { + multi_map_insert(&m->members, hash_name, p); } } break; } } for_array(i, m->members.entries) { - MapIrValueEntry *entry = &m->members.entries.e[i]; + auto *entry = &m->members.entries[i]; irValue *v = entry->value; if (v->kind == irValue_Proc) { ir_build_proc(v, NULL); } } - irDebugInfo *compile_unit = m->debug_info.entries.e[0].value; + irDebugInfo *compile_unit = m->debug_info.entries[0].value; GB_ASSERT(compile_unit->kind == irDebugInfo_CompileUnit); irDebugInfo *all_procs = ir_alloc_debug_info(m->allocator, irDebugInfo_AllProcs); isize all_proc_max_count = 0; for_array(i, m->debug_info.entries) { - MapIrDebugInfoEntry *entry = &m->debug_info.entries.e[i]; + auto *entry = &m->debug_info.entries[i]; irDebugInfo *di = entry->value; di->id = i; if (di->kind == irDebugInfo_Proc) { @@ -7262,13 +7281,13 @@ void ir_gen_tree(irGen *s) { } } - array_init_reserve(&all_procs->AllProcs.procs, m->allocator, all_proc_max_count); - map_ir_debug_info_set(&m->debug_info, hash_pointer(all_procs), all_procs); // NOTE(bill): This doesn't need to be mapped + array_init(&all_procs->AllProcs.procs, m->allocator, all_proc_max_count); + map_set(&m->debug_info, hash_pointer(all_procs), all_procs); // NOTE(bill): This doesn't need to be mapped compile_unit->CompileUnit.all_procs = all_procs; for_array(i, m->debug_info.entries) { - MapIrDebugInfoEntry *entry = &m->debug_info.entries.e[i]; + auto *entry = &m->debug_info.entries[i]; irDebugInfo *di = entry->value; if (di->kind == irDebugInfo_Proc) { array_add(&all_procs->AllProcs.procs, di); @@ -7305,8 +7324,8 @@ void ir_gen_tree(irGen *s) { Entity *e = make_entity_procedure(a, NULL, make_token_ident(name), proc_type, 0); irValue *p = ir_value_procedure(a, m, e, proc_type, NULL, body, name); - map_ir_value_set(&m->values, hash_pointer(e), p); - map_ir_value_set(&m->members, hash_string(name), p); + map_set(&m->values, hash_pointer(e), p); + map_set(&m->members, hash_string(name), p); irProcedure *proc = &p->Proc; proc->tags = ProcTag_no_inline; // TODO(bill): is no_inline a good idea? @@ -7326,7 +7345,7 @@ void ir_gen_tree(irGen *s) { { String main_name = str_lit("main"); - irValue **found = map_ir_value_get(&m->members, hash_string(main_name)); + irValue **found = map_get(&m->members, hash_string(main_name)); if (found != NULL) { ir_emit_call(proc, *found, NULL, 0); } else { @@ -7376,8 +7395,8 @@ void ir_gen_tree(irGen *s) { m->entry_point_entity = e; - map_ir_value_set(&m->values, hash_pointer(e), p); - map_ir_value_set(&m->members, hash_string(name), p); + map_set(&m->values, hash_pointer(e), p); + map_set(&m->members, hash_string(name), p); irProcedure *proc = &p->Proc; proc->tags = ProcTag_no_inline; // TODO(bill): is no_inline a good idea? @@ -7399,8 +7418,8 @@ void ir_gen_tree(irGen *s) { Entity *e = make_entity_procedure(a, NULL, make_token_ident(name), proc_type, 0); irValue *p = ir_value_procedure(a, m, e, proc_type, NULL, body, name); - map_ir_value_set(&m->values, hash_pointer(e), p); - map_ir_value_set(&m->members, hash_string(name), p); + map_set(&m->values, hash_pointer(e), p); + map_set(&m->members, hash_string(name), p); irProcedure *proc = &p->Proc; @@ -7410,7 +7429,7 @@ void ir_gen_tree(irGen *s) { // TODO(bill): Should do a dependency graph do check which order to initialize them in? for_array(i, global_variables) { - irGlobalVariable *var = &global_variables.e[i]; + irGlobalVariable *var = &global_variables[i]; if (var->decl->init_expr != NULL) { var->init = ir_build_expr(proc, var->decl->init_expr); } @@ -7418,7 +7437,7 @@ void ir_gen_tree(irGen *s) { // NOTE(bill): Initialize constants first for_array(i, global_variables) { - irGlobalVariable *var = &global_variables.e[i]; + irGlobalVariable *var = &global_variables[i]; if (var->init != NULL && var->init->kind == irValue_Constant) { Type *t = type_deref(ir_type(var->var)); if (is_type_any(t)) { @@ -7436,7 +7455,7 @@ void ir_gen_tree(irGen *s) { } for_array(i, global_variables) { - irGlobalVariable *var = &global_variables.e[i]; + irGlobalVariable *var = &global_variables[i]; if (var->init != NULL && var->init->kind != irValue_Constant) { Type *t = type_deref(ir_type(var->var)); if (is_type_any(t)) { @@ -7478,8 +7497,8 @@ void ir_gen_tree(irGen *s) { i32 type_info_member_offsets_index = 0; for_array(type_info_map_index, info->type_info_map.entries) { - MapIsizeEntry *entry = &info->type_info_map.entries.e[type_info_map_index]; - Type *t = cast(Type *)cast(uintptr)entry->key.key; + auto *entry = &info->type_info_map.entries[type_info_map_index]; + Type *t = cast(Type *)entry->key.ptr; t = default_type(t); isize entry_index = ir_type_info_index(info, t); @@ -7670,7 +7689,7 @@ void ir_gen_tree(irGen *s) { { irValue *packed = ir_const_bool(a, t->Record.is_packed); irValue *ordered = ir_const_bool(a, t->Record.is_ordered); - irValue *custom_align = ir_const_bool(a, t->Record.custom_align); + irValue *custom_align = ir_const_bool(a, t->Record.custom_align != 0); ir_emit_store(proc, ir_emit_struct_ep(proc, record, 4), packed); ir_emit_store(proc, ir_emit_struct_ep(proc, record, 5), ordered); ir_emit_store(proc, ir_emit_struct_ep(proc, record, 6), custom_align); @@ -7700,7 +7719,7 @@ void ir_gen_tree(irGen *s) { ir_emit_store(proc, name, ir_const_string(a, f->token.string)); } ir_emit_store(proc, offset, ir_const_int(a, foffset)); - ir_emit_store(proc, is_using, ir_const_bool(a, f->flags&EntityFlag_Using)); + ir_emit_store(proc, is_using, ir_const_bool(a, (f->flags&EntityFlag_Using) != 0)); } irValue *count = ir_const_int(a, t->Record.field_count); @@ -7941,8 +7960,8 @@ void ir_gen_tree(irGen *s) { } for_array(type_info_map_index, info->type_info_map.entries) { - MapIsizeEntry *entry = &info->type_info_map.entries.e[type_info_map_index]; - Type *t = cast(Type *)cast(uintptr)entry->key.key; + auto *entry = &info->type_info_map.entries[type_info_map_index]; + Type *t = cast(Type *)entry->key.ptr; t = default_type(t); isize entry_index = entry->value; @@ -7955,12 +7974,12 @@ void ir_gen_tree(irGen *s) { for_array(i, m->procs_to_generate) { - ir_build_proc(m->procs_to_generate.e[i], m->procs_to_generate.e[i]->Proc.parent); + ir_build_proc(m->procs_to_generate[i], m->procs_to_generate[i]->Proc.parent); } // Number debug info for_array(i, m->debug_info.entries) { - MapIrDebugInfoEntry *entry = &m->debug_info.entries.e[i]; + auto *entry = &m->debug_info.entries[i]; irDebugInfo *di = entry->value; di->id = i; } diff --git a/src/ir_opt.c b/src/ir_opt.cpp similarity index 84% rename from src/ir_opt.c rename to src/ir_opt.cpp index e9d83941d..c2c952b87 100644 --- a/src/ir_opt.c +++ b/src/ir_opt.cpp @@ -1,6 +1,6 @@ // Optimizations for the IR code -void ir_opt_add_operands(irValueArray *ops, irInstr *i) { +void ir_opt_add_operands(Array *ops, irInstr *i) { switch (i->kind) { case irInstr_Comment: break; @@ -48,7 +48,7 @@ void ir_opt_add_operands(irValueArray *ops, irInstr *i) { break; case irInstr_Phi: for_array(j, i->Phi.edges) { - array_add(ops, i->Phi.edges.e[j]); + array_add(ops, i->Phi.edges[j]); } break; case irInstr_Unreachable: @@ -97,24 +97,24 @@ void ir_opt_add_operands(irValueArray *ops, irInstr *i) { void ir_opt_block_replace_pred(irBlock *b, irBlock *from, irBlock *to) { for_array(i, b->preds) { - irBlock *pred = b->preds.e[i]; + irBlock *pred = b->preds[i]; if (pred == from) { - b->preds.e[i] = to; + b->preds[i] = to; } } } void ir_opt_block_replace_succ(irBlock *b, irBlock *from, irBlock *to) { for_array(i, b->succs) { - irBlock *succ = b->succs.e[i]; + irBlock *succ = b->succs[i]; if (succ == from) { - b->succs.e[i] = to; + b->succs[i] = to; } } } bool ir_opt_block_has_phi(irBlock *b) { - return b->instrs.e[0]->Instr.kind == irInstr_Phi; + return b->instrs[0]->Instr.kind == irInstr_Phi; } @@ -126,10 +126,10 @@ bool ir_opt_block_has_phi(irBlock *b) { -irValueArray ir_get_block_phi_nodes(irBlock *b) { - irValueArray phis = {0}; +Array ir_get_block_phi_nodes(irBlock *b) { + Array phis = {0}; for_array(i, b->instrs) { - irInstr *instr = &b->instrs.e[i]->Instr; + irInstr *instr = &b->instrs[i]->Instr; if (instr->kind != irInstr_Phi) { phis = b->instrs; phis.count = i; @@ -140,22 +140,22 @@ irValueArray ir_get_block_phi_nodes(irBlock *b) { } void ir_remove_pred(irBlock *b, irBlock *p) { - irValueArray phis = ir_get_block_phi_nodes(b); + Array phis = ir_get_block_phi_nodes(b); isize i = 0; for_array(j, b->preds) { - irBlock *pred = b->preds.e[j]; + irBlock *pred = b->preds[j]; if (pred != p) { - b->preds.e[i] = b->preds.e[j]; + b->preds[i] = b->preds[j]; for_array(k, phis) { - irInstrPhi *phi = &phis.e[k]->Instr.Phi; - phi->edges.e[i] = phi->edges.e[j]; + irInstrPhi *phi = &phis[k]->Instr.Phi; + phi->edges[i] = phi->edges[j]; } i++; } } b->preds.count = i; for_array(k, phis) { - irInstrPhi *phi = &phis.e[k]->Instr.Phi; + irInstrPhi *phi = &phis[k]->Instr.Phi; phi->edges.count = i; } @@ -164,13 +164,13 @@ void ir_remove_pred(irBlock *b, irBlock *p) { void ir_remove_dead_blocks(irProcedure *proc) { isize j = 0; for_array(i, proc->blocks) { - irBlock *b = proc->blocks.e[i]; + irBlock *b = proc->blocks[i]; if (b == NULL) { continue; } // NOTE(bill): Swap order b->index = j; - proc->blocks.e[j++] = b; + proc->blocks[j++] = b; } proc->blocks.count = j; } @@ -180,7 +180,7 @@ void ir_mark_reachable(irBlock *b) { isize const BLACK = -1; b->index = BLACK; for_array(i, b->succs) { - irBlock *succ = b->succs.e[i]; + irBlock *succ = b->succs[i]; if (succ->index == WHITE) { ir_mark_reachable(succ); } @@ -191,23 +191,23 @@ void ir_remove_unreachable_blocks(irProcedure *proc) { isize const WHITE = 0; isize const BLACK = -1; for_array(i, proc->blocks) { - proc->blocks.e[i]->index = WHITE; + proc->blocks[i]->index = WHITE; } - ir_mark_reachable(proc->blocks.e[0]); + ir_mark_reachable(proc->blocks[0]); for_array(i, proc->blocks) { - irBlock *b = proc->blocks.e[i]; + irBlock *b = proc->blocks[i]; if (b->index == WHITE) { for_array(j, b->succs) { - irBlock *c = b->succs.e[j]; + irBlock *c = b->succs[j]; if (c->index == BLACK) { ir_remove_pred(c, b); } } // NOTE(bill): Mark as empty but don't actually free it // As it's been allocated with an arena - proc->blocks.e[i] = NULL; + proc->blocks[i] = NULL; } } ir_remove_dead_blocks(proc); @@ -217,7 +217,7 @@ bool ir_opt_block_fusion(irProcedure *proc, irBlock *a) { if (a->succs.count != 1) { return false; } - irBlock *b = a->succs.e[0]; + irBlock *b = a->succs[0]; if (b->preds.count != 1) { return false; } @@ -228,21 +228,21 @@ bool ir_opt_block_fusion(irProcedure *proc, irBlock *a) { array_pop(&a->instrs); // Remove branch at end for_array(i, b->instrs) { - array_add(&a->instrs, b->instrs.e[i]); - ir_set_instr_parent(b->instrs.e[i], a); + array_add(&a->instrs, b->instrs[i]); + ir_set_instr_parent(b->instrs[i], a); } array_clear(&a->succs); for_array(i, b->succs) { - array_add(&a->succs, b->succs.e[i]); + array_add(&a->succs, b->succs[i]); } // Fix preds links for_array(i, b->succs) { - ir_opt_block_replace_pred(b->succs.e[i], b, a); + ir_opt_block_replace_pred(b->succs[i], b, a); } - proc->blocks.e[b->index] = NULL; + proc->blocks[b->index] = NULL; return true; } @@ -254,7 +254,7 @@ void ir_opt_blocks(irProcedure *proc) { while (changed) { changed = false; for_array(i, proc->blocks) { - irBlock *b = proc->blocks.e[i]; + irBlock *b = proc->blocks[i]; if (b == NULL) { continue; } @@ -273,20 +273,20 @@ void ir_opt_blocks(irProcedure *proc) { void ir_opt_build_referrers(irProcedure *proc) { gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&proc->module->tmp_arena); - irValueArray ops = {0}; // NOTE(bill): Act as a buffer - array_init_reserve(&ops, proc->module->tmp_allocator, 64); // HACK(bill): This _could_ overflow the temp arena + Array ops = {0}; // NOTE(bill): Act as a buffer + array_init(&ops, proc->module->tmp_allocator, 64); // HACK(bill): This _could_ overflow the temp arena for_array(i, proc->blocks) { - irBlock *b = proc->blocks.e[i]; + irBlock *b = proc->blocks[i]; for_array(j, b->instrs) { - irValue *instr = b->instrs.e[j]; + irValue *instr = b->instrs[j]; array_clear(&ops); ir_opt_add_operands(&ops, &instr->Instr); for_array(k, ops) { - irValue *op = ops.e[k]; + irValue *op = ops[k]; if (op == NULL) { continue; } - irValueArray *refs = ir_value_referrers(op); + Array *refs = ir_value_referrers(op); if (refs != NULL) { array_add(refs, instr); } @@ -324,7 +324,7 @@ i32 ir_lt_depth_first_search(irLTState *lt, irBlock *p, i32 i, irBlock **preorde lt->sdom[p->index] = p; ir_lt_link(lt, NULL, p); for_array(index, p->succs) { - irBlock *q = p->succs.e[index]; + irBlock *q = p->succs[index]; if (lt->sdom[q->index] == NULL) { lt->parent[q->index] = p; i = ir_lt_depth_first_search(lt, q, i, preorder); @@ -354,7 +354,7 @@ irDomPrePost ir_opt_number_dom_tree(irBlock *v, i32 pre, i32 post) { v->dom.pre = pre++; for_array(i, v->dom.children) { - result = ir_opt_number_dom_tree(v->dom.children.e[i], result.pre, result.post); + result = ir_opt_number_dom_tree(v->dom.children[i], result.pre, result.post); } v->dom.post = post++; @@ -381,7 +381,7 @@ void ir_opt_build_dom_tree(irProcedure *proc) { irBlock **preorder = &buf[3*n]; irBlock **buckets = &buf[4*n]; - irBlock *root = proc->blocks.e[0]; + irBlock *root = proc->blocks[0]; // Step 1 - number vertices i32 pre_num = ir_lt_depth_first_search(<, root, 0, preorder); @@ -403,7 +403,7 @@ void ir_opt_build_dom_tree(irProcedure *proc) { // Step 2 - Compute all sdoms lt.sdom[w->index] = lt.parent[w->index]; for_array(pred_index, w->preds) { - irBlock *v = w->preds.e[pred_index]; + irBlock *v = w->preds[pred_index]; irBlock *u = ir_lt_eval(<, v); if (lt.sdom[u->index]->dom.pre < lt.sdom[w->index]->dom.pre) { lt.sdom[w->index] = lt.sdom[u->index]; @@ -438,7 +438,7 @@ void ir_opt_build_dom_tree(irProcedure *proc) { } // Calculate children relation as inverse of idom - if (w->dom.idom->dom.children.e == NULL) { + if (w->dom.idom->dom.children.data == NULL) { // TODO(bill): Is this good enough for memory allocations? array_init(&w->dom.idom->dom.children, heap_allocator()); } @@ -461,7 +461,7 @@ void ir_opt_tree(irGen *s) { s->opt_called = true; for_array(member_index, s->module.procs) { - irProcedure *proc = s->module.procs.e[member_index]; + irProcedure *proc = s->module.procs[member_index]; if (proc->blocks.count == 0) { // Prototype/external procedure continue; } diff --git a/src/ir_print.c b/src/ir_print.cpp similarity index 97% rename from src/ir_print.c rename to src/ir_print.cpp index c7dec10cb..cc008f4a1 100644 --- a/src/ir_print.c +++ b/src/ir_print.cpp @@ -1,8 +1,8 @@ -typedef struct irFileBuffer { +struct irFileBuffer { gbVirtualMemory vm; isize offset; gbFile * output; -} irFileBuffer; +}; void ir_file_buffer_init(irFileBuffer *f, gbFile *output) { isize size = 8*gb_virtual_memory_page_size(NULL); @@ -39,7 +39,7 @@ void ir_file_buffer_write(irFileBuffer *f, void *data, isize len) { void ir_fprintf(irFileBuffer *f, char *fmt, ...) { va_list va; va_start(va, fmt); - char buf[4096] = {0}; + char buf[4096] = {}; isize len = gb_snprintf_va(buf, gb_size_of(buf), fmt, va); ir_file_buffer_write(f, buf, len-1); va_end(va); @@ -48,7 +48,7 @@ void ir_fprint_string(irFileBuffer *f, String s) { ir_file_buffer_write(f, s.text, s.len); } void ir_fprint_i128(irFileBuffer *f, i128 i) { - char buf[200] = {0}; + char buf[200] = {}; String str = i128_to_string(i, buf, gb_size_of(buf)-1); ir_fprint_string(f, str); } @@ -81,7 +81,7 @@ bool ir_valid_char(u8 c) { void ir_print_escape_string(irFileBuffer *f, String name, bool print_quotes, bool prefix_with_dot) { isize extra = 0; for (isize i = 0; i < name.len; i++) { - u8 c = name.text[i]; + u8 c = name[i]; if (!ir_valid_char(c)) { extra += 2; } @@ -111,7 +111,7 @@ void ir_print_escape_string(irFileBuffer *f, String name, bool print_quotes, boo } for (isize i = 0; i < name.len; i++) { - u8 c = name.text[i]; + u8 c = name[i]; if (ir_valid_char(c)) { buf[j++] = c; } else { @@ -306,7 +306,7 @@ void ir_print_type(irFileBuffer *f, irModule *m, Type *t) { case Type_Named: if (is_type_struct(t) || is_type_union(t)) { - String *name = map_string_get(&m->entity_names, hash_pointer(t->Named.type_name)); + String *name = map_get(&m->entity_names, hash_pointer(t->Named.type_name)); GB_ASSERT_MSG(name != NULL, "%.*s", LIT(t->Named.name)); ir_print_encoded_local(f, *name); } else { @@ -497,7 +497,7 @@ void ir_print_exact_value(irFileBuffer *f, irModule *m, ExactValue value, Type * if (i > 0) { ir_fprintf(f, ", "); } - TypeAndValue tav = type_and_value_of_expr(m->info, cl->elems.e[i]); + TypeAndValue tav = type_and_value_of_expr(m->info, cl->elems[i]); GB_ASSERT(tav.mode != Addressing_Invalid); ir_print_compound_element(f, m, tav.value, elem_type); } @@ -527,7 +527,7 @@ void ir_print_exact_value(irFileBuffer *f, irModule *m, ExactValue value, Type * ir_fprintf(f, "]["); if (elem_count == 1 && type->Vector.count > 1) { - TypeAndValue tav = type_and_value_of_expr(m->info, cl->elems.e[0]); + TypeAndValue tav = type_and_value_of_expr(m->info, cl->elems[0]); GB_ASSERT(tav.mode != Addressing_Invalid); for (isize i = 0; i < type->Vector.count; i++) { @@ -541,7 +541,7 @@ void ir_print_exact_value(irFileBuffer *f, irModule *m, ExactValue value, Type * if (i > 0) { ir_fprintf(f, ", "); } - TypeAndValue tav = type_and_value_of_expr(m->info, cl->elems.e[i]); + TypeAndValue tav = type_and_value_of_expr(m->info, cl->elems[i]); GB_ASSERT(tav.mode != Addressing_Invalid); ir_print_compound_element(f, m, tav.value, elem_type); } @@ -563,25 +563,25 @@ void ir_print_exact_value(irFileBuffer *f, irModule *m, ExactValue value, Type * ExactValue *values = gb_alloc_array(m->tmp_allocator, ExactValue, value_count); - if (cl->elems.e[0]->kind == AstNode_FieldValue) { + if (cl->elems[0]->kind == AstNode_FieldValue) { isize elem_count = cl->elems.count; for (isize i = 0; i < elem_count; i++) { - ast_node(fv, FieldValue, cl->elems.e[i]); + ast_node(fv, FieldValue, cl->elems[i]); String name = fv->field->Ident.string; TypeAndValue tav = type_and_value_of_expr(m->info, fv->value); GB_ASSERT(tav.mode != Addressing_Invalid); Selection sel = lookup_field(m->allocator, type, name, false); - Entity *f = type->Record.fields[sel.index.e[0]]; + Entity *f = type->Record.fields[sel.index[0]]; values[f->Variable.field_index] = tav.value; } } else { for (isize i = 0; i < value_count; i++) { Entity *f = type->Record.fields_in_src_order[i]; - TypeAndValue tav = type_and_value_of_expr(m->info, cl->elems.e[i]); - ExactValue val = {0}; + TypeAndValue tav = type_and_value_of_expr(m->info, cl->elems[i]); + ExactValue val = {}; if (tav.mode != Addressing_Invalid) { val = tav.value; } @@ -891,11 +891,11 @@ void ir_print_instr(irFileBuffer *f, irModule *m, irValue *value) { ir_fprintf(f, ", "); } - irValue *edge = instr->Phi.edges.e[i]; + irValue *edge = instr->Phi.edges[i]; irBlock *block = NULL; if (instr->parent != NULL && i < instr->parent->preds.count) { - block = instr->parent->preds.e[i]; + block = instr->parent->preds[i]; } ir_fprintf(f, "[ "); @@ -1500,8 +1500,8 @@ void ir_print_proc(irFileBuffer *f, irModule *m, irProcedure *proc) { ir_fprintf(f, " noalias"); } if (proc->body != NULL) { - if (!str_eq(e->token.string, str_lit("")) && - !str_eq(e->token.string, str_lit("_"))) { + if (e->token.string != "" && + e->token.string != "_") { ir_fprintf(f, " "); ir_print_encoded_local(f, e->token.string); } else { @@ -1523,7 +1523,7 @@ void ir_print_proc(irFileBuffer *f, irModule *m, irProcedure *proc) { if (proc->entity != NULL) { if (proc->body != NULL) { - irDebugInfo **di_ = map_ir_debug_info_get(&proc->module->debug_info, hash_pointer(proc->entity)); + irDebugInfo **di_ = map_get(&proc->module->debug_info, hash_pointer(proc->entity)); if (di_ != NULL) { irDebugInfo *di = *di_; GB_ASSERT(di->kind == irDebugInfo_Proc); @@ -1538,14 +1538,14 @@ void ir_print_proc(irFileBuffer *f, irModule *m, irProcedure *proc) { ir_fprintf(f, "{\n"); for_array(i, proc->blocks) { - irBlock *block = proc->blocks.e[i]; + irBlock *block = proc->blocks[i]; if (i > 0) ir_fprintf(f, "\n"); ir_print_block_name(f, block); ir_fprintf(f, ":\n"); for_array(j, block->instrs) { - irValue *value = block->instrs.e[j]; + irValue *value = block->instrs[j]; ir_print_instr(f, m, value); } } @@ -1555,7 +1555,7 @@ void ir_print_proc(irFileBuffer *f, irModule *m, irProcedure *proc) { } for_array(i, proc->children) { - ir_print_proc(f, m, proc->children.e[i]); + ir_print_proc(f, m, proc->children[i]); } } @@ -1573,7 +1573,7 @@ void ir_print_type_name(irFileBuffer *f, irModule *m, irValue *v) { void print_llvm_ir(irGen *ir) { irModule *m = &ir->module; - irFileBuffer buf = {0}, *f = &buf; + irFileBuffer buf = {}, *f = &buf; ir_file_buffer_init(f, &ir->output_file); ir_print_encoded_local(f, str_lit("..string")); @@ -1606,7 +1606,7 @@ void print_llvm_ir(irGen *ir) { for_array(member_index, m->members.entries) { - MapIrValueEntry *entry = &m->members.entries.e[member_index]; + auto *entry = &m->members.entries[member_index]; irValue *v = entry->value; if (v->kind != irValue_TypeName) { continue; @@ -1619,7 +1619,7 @@ void print_llvm_ir(irGen *ir) { bool dll_main_found = false; for_array(member_index, m->members.entries) { - MapIrValueEntry *entry = &m->members.entries.e[member_index]; + auto *entry = &m->members.entries[member_index]; irValue *v = entry->value; if (v->kind != irValue_Proc) { continue; @@ -1631,7 +1631,7 @@ void print_llvm_ir(irGen *ir) { } for_array(member_index, m->members.entries) { - MapIrValueEntry *entry = &m->members.entries.e[member_index]; + auto *entry = &m->members.entries[member_index]; irValue *v = entry->value; if (v->kind != irValue_Proc) { continue; @@ -1643,7 +1643,7 @@ void print_llvm_ir(irGen *ir) { } for_array(member_index, m->members.entries) { - MapIrValueEntry *entry = &m->members.entries.e[member_index]; + auto *entry = &m->members.entries[member_index]; irValue *v = entry->value; if (v->kind != irValue_Global) { continue; @@ -1707,13 +1707,13 @@ void print_llvm_ir(irGen *ir) { ir_fprintf(f, "!%d = !{!\"clang version 3.9.0 (branches/release_39)\"}\n", diec+3); for_array(di_index, m->debug_info.entries) { - MapIrDebugInfoEntry *entry = &m->debug_info.entries.e[di_index]; + MapIrDebugInfoEntry *entry = &m->debug_info.entries[di_index]; irDebugInfo *di = entry->value; ir_fprintf(f, "!%d = ", di->id); switch (di->kind) { case irDebugInfo_CompileUnit: { - irDebugInfo *file = *map_ir_debug_info_get(&m->debug_info, hash_pointer(di->CompileUnit.file)); + irDebugInfo *file = *map_get(&m->debug_info, hash_pointer(di->CompileUnit.file)); ir_fprintf(f, "distinct !DICompileUnit(" "language: DW_LANG_Go, " // Is this good enough? @@ -1752,7 +1752,7 @@ void print_llvm_ir(irGen *ir) { case irDebugInfo_AllProcs: ir_fprintf(f, "!{"); for_array(proc_index, di->AllProcs.procs) { - irDebugInfo *p = di->AllProcs.procs.e[proc_index]; + irDebugInfo *p = di->AllProcs.procs[proc_index]; if (proc_index > 0) {ir_fprintf(f, ",");} ir_fprintf(f, "!%d", p->id); } diff --git a/src/main.c b/src/main.cpp similarity index 94% rename from src/main.c rename to src/main.cpp index eb5a5a220..e4c6e6606 100644 --- a/src/main.c +++ b/src/main.cpp @@ -1,20 +1,15 @@ -#if defined(__cplusplus) -extern "C" { -#endif - #define USE_CUSTOM_BACKEND false -#include "common.c" -#include "timings.c" -#include "build_settings.c" -#include "tokenizer.c" -#include "parser.c" -#include "checker.c" -#include "ssa.c" -#include "ir.c" -#include "ir_opt.c" -#include "ir_print.c" -// #include "vm.c" +#include "common.cpp" +#include "timings.cpp" +#include "build_settings.cpp" +#include "tokenizer.cpp" +#include "parser.cpp" +#include "checker.cpp" +#include "ssa.cpp" +#include "ir.cpp" +#include "ir_opt.cpp" +#include "ir_print.cpp" #if defined(GB_SYSTEM_WINDOWS) // NOTE(bill): `name` is used in debugging and profiling modes @@ -155,27 +150,27 @@ int main(int argc, char **argv) { char *init_filename = NULL; bool run_output = false; String arg1 = make_string_c(argv[1]); - if (str_eq(arg1, str_lit("run"))) { + if (arg1 == "run") { if (argc != 3) { usage(argv[0]); return 1; } init_filename = argv[2]; run_output = true; - } else if (str_eq(arg1, str_lit("build_dll"))) { + } else if (arg1 == "build_dll") { if (argc != 3) { usage(argv[0]); return 1; } init_filename = argv[2]; build_context.is_dll = true; - } else if (str_eq(arg1, str_lit("build"))) { + } else if (arg1 == "build") { if (argc != 3) { usage(argv[0]); return 1; } init_filename = argv[2]; - } else if (str_eq(arg1, str_lit("version"))) { + } else if (arg1 == "version") { gb_printf("%s version %.*s\n", argv[0], LIT(build_context.ODIN_VERSION)); return 0; } else { @@ -314,7 +309,7 @@ int main(int argc, char **argv) { // defer (gb_string_free(lib_str)); char lib_str_buf[1024] = {0}; for_array(i, ir_gen.module.foreign_library_paths) { - String lib = ir_gen.module.foreign_library_paths.e[i]; + String lib = ir_gen.module.foreign_library_paths[i]; // gb_printf_err("Linking lib: %.*s\n", LIT(lib)); isize len = gb_snprintf(lib_str_buf, gb_size_of(lib_str_buf), " \"%.*s\"", LIT(lib)); @@ -376,14 +371,14 @@ int main(int argc, char **argv) { // defer (gb_string_free(lib_str)); char lib_str_buf[1024] = {0}; for_array(i, ir_gen.module.foreign_library_paths) { - String lib = ir_gen.module.foreign_library_paths.e[i]; + String lib = ir_gen.module.foreign_library_paths[i]; // NOTE(zangent): Sometimes, you have to use -framework on MacOS. // This allows you to specify '-f' in a #foreign_system_library, // without having to implement any new syntax specifically for MacOS. #if defined(GB_SYSTEM_OSX) isize len; - if(lib.len > 2 && lib.text[0] == '-' && lib.text[1] == 'f') { + if(lib.len > 2 && lib[0] == '-' && lib[1] == 'f') { len = gb_snprintf(lib_str_buf, gb_size_of(lib_str_buf), " -framework %.*s ", (int)(lib.len) - 2, lib.text + 2); } else { @@ -461,7 +456,3 @@ int main(int argc, char **argv) { return 0; } - -#if defined(__cplusplus) -} -#endif diff --git a/src/map.c b/src/map.c deleted file mode 100644 index e0d091e93..000000000 --- a/src/map.c +++ /dev/null @@ -1,364 +0,0 @@ -/* - Example of usage: - - #define MAP_TYPE String - #define MAP_PROC map_string_ - #define MAP_NAME MapString - #include "map.c" -*/ -// A `Map` is an unordered hash table which can allow for a key to point to multiple values -// with the use of the `multi_*` procedures. -// TODO(bill): I should probably allow the `multi_*` stuff to be #ifdefed out - -#ifndef MAP_UTIL_STUFF -#define MAP_UTIL_STUFF -// NOTE(bill): This util stuff is the same for every `Map` -typedef struct MapFindResult { - isize hash_index; - isize entry_prev; - isize entry_index; -} MapFindResult; - -typedef enum HashKeyKind { - HashKey_Default, - HashKey_String, - HashKey_Pointer, -} HashKeyKind; - -typedef struct HashKey { - HashKeyKind kind; - u64 key; - union { - String string; // if String, s.len > 0 - void * ptr; - }; -} HashKey; - -gb_inline HashKey hashing_proc(void const *data, isize len) { - HashKey h = {HashKey_Default}; - h.kind = HashKey_Default; - // h.key = gb_murmur64(data, len); - h.key = gb_fnv64a(data, len); - // h.key = MurmurHash3_128(data, len, 0x3803cb8e); - - return h; -} - -gb_inline HashKey hash_string(String s) { - HashKey h = hashing_proc(s.text, s.len); - h.kind = HashKey_String; - h.string = s; - return h; -} - -gb_inline HashKey hash_pointer(void *ptr) { - HashKey h = {HashKey_Default}; - // h.key = u128_from_u64(cast(u64)cast(uintptr)ptr); - h.key = cast(u64)cast(uintptr)ptr; - h.ptr = ptr; - h.kind = HashKey_Default; - return h; -} - -bool hash_key_equal(HashKey a, HashKey b) { - if (a.key == b.key) { - // NOTE(bill): If two string's hashes collide, compare the strings themselves - if (a.kind == HashKey_String) { - if (b.kind == HashKey_String) { - return str_eq(a.string, b.string); - } - return false; - } - return true; - } - return false; -} -#endif - -#define _J2_IND(a, b) a##b -#define _J2(a, b) _J2_IND(a, b) - -/* -MAP_TYPE - Entry type -MAP_PROC - Function prefix (e.g. entity_map_) -MAP_NAME - Name of Map (e.g. EntityMap) -*/ -#define MAP_ENTRY _J2(MAP_NAME,Entry) - -typedef struct MAP_ENTRY { - HashKey key; - isize next; - MAP_TYPE value; -} MAP_ENTRY; - -typedef struct MAP_NAME { - Array(isize) hashes; - Array(MAP_ENTRY) entries; -} MAP_NAME; - -void _J2(MAP_PROC,init) (MAP_NAME *h, gbAllocator a); -void _J2(MAP_PROC,init_with_reserve)(MAP_NAME *h, gbAllocator a, isize capacity); -void _J2(MAP_PROC,destroy) (MAP_NAME *h); -MAP_TYPE *_J2(MAP_PROC,get) (MAP_NAME *h, HashKey key); -void _J2(MAP_PROC,set) (MAP_NAME *h, HashKey key, MAP_TYPE value); -void _J2(MAP_PROC,remove) (MAP_NAME *h, HashKey key); -void _J2(MAP_PROC,clear) (MAP_NAME *h); -void _J2(MAP_PROC,grow) (MAP_NAME *h); -void _J2(MAP_PROC,rehash) (MAP_NAME *h, isize new_count); - -// Mutlivalued map procedure -MAP_ENTRY *_J2(MAP_PROC,multi_find_first)(MAP_NAME *h, HashKey key); -MAP_ENTRY *_J2(MAP_PROC,multi_find_next) (MAP_NAME *h, MAP_ENTRY *e); - -isize _J2(MAP_PROC,multi_count) (MAP_NAME *h, HashKey key); -void _J2(MAP_PROC,multi_get_all) (MAP_NAME *h, HashKey key, MAP_TYPE *items); -void _J2(MAP_PROC,multi_insert) (MAP_NAME *h, HashKey key, MAP_TYPE value); -void _J2(MAP_PROC,multi_remove) (MAP_NAME *h, HashKey key, MAP_ENTRY *e); -void _J2(MAP_PROC,multi_remove_all)(MAP_NAME *h, HashKey key); - - - -gb_inline void _J2(MAP_PROC,init)(MAP_NAME *h, gbAllocator a) { - array_init(&h->hashes, a); - array_init(&h->entries, a); -} - -gb_inline void _J2(MAP_PROC,init_with_reserve)(MAP_NAME *h, gbAllocator a, isize capacity) { - array_init_reserve(&h->hashes, a, capacity); - array_init_reserve(&h->entries, a, capacity); -} - -gb_inline void _J2(MAP_PROC,destroy)(MAP_NAME *h) { - array_free(&h->entries); - array_free(&h->hashes); -} - -gb_internal isize _J2(MAP_PROC,_add_entry)(MAP_NAME *h, HashKey key) { - MAP_ENTRY e = {0}; - e.key = key; - e.next = -1; - array_add(&h->entries, e); - return h->entries.count-1; -} - -gb_internal MapFindResult _J2(MAP_PROC,_find)(MAP_NAME *h, HashKey key) { - MapFindResult fr = {-1, -1, -1}; - if (h->hashes.count > 0) { - fr.hash_index = key.key % h->hashes.count; - fr.entry_index = h->hashes.e[fr.hash_index]; - while (fr.entry_index >= 0) { - if (hash_key_equal(h->entries.e[fr.entry_index].key, key)) { - return fr; - } - fr.entry_prev = fr.entry_index; - fr.entry_index = h->entries.e[fr.entry_index].next; - } - } - return fr; -} - -gb_internal MapFindResult _J2(MAP_PROC,_find_from_entry)(MAP_NAME *h, MAP_ENTRY *e) { - MapFindResult fr = {-1, -1, -1}; - if (h->hashes.count > 0) { - fr.hash_index = e->key.key % h->hashes.count; - fr.entry_index = h->hashes.e[fr.hash_index]; - while (fr.entry_index >= 0) { - if (&h->entries.e[fr.entry_index] == e) { - return fr; - } - fr.entry_prev = fr.entry_index; - fr.entry_index = h->entries.e[fr.entry_index].next; - } - } - return fr; -} - - -gb_internal b32 _J2(MAP_PROC,_full)(MAP_NAME *h) { - return 0.75f * h->hashes.count <= h->entries.count; -} - -gb_inline void _J2(MAP_PROC,grow)(MAP_NAME *h) { - isize new_count = ARRAY_GROW_FORMULA(h->entries.count); - _J2(MAP_PROC,rehash)(h, new_count); -} - -void _J2(MAP_PROC,rehash)(MAP_NAME *h, isize new_count) { - isize i, j; - MAP_NAME nh = {0}; - _J2(MAP_PROC,init)(&nh, h->hashes.allocator); - array_resize(&nh.hashes, new_count); - array_reserve(&nh.entries, h->entries.count); - for (i = 0; i < new_count; i++) { - nh.hashes.e[i] = -1; - } - for (i = 0; i < h->entries.count; i++) { - MAP_ENTRY *e = &h->entries.e[i]; - MapFindResult fr; - if (nh.hashes.count == 0) { - _J2(MAP_PROC,grow)(&nh); - } - fr = _J2(MAP_PROC,_find)(&nh, e->key); - j = _J2(MAP_PROC,_add_entry)(&nh, e->key); - if (fr.entry_prev < 0) { - nh.hashes.e[fr.hash_index] = j; - } else { - nh.entries.e[fr.entry_prev].next = j; - } - nh.entries.e[j].next = fr.entry_index; - nh.entries.e[j].value = e->value; - if (_J2(MAP_PROC,_full)(&nh)) { - _J2(MAP_PROC,grow)(&nh); - } - } - _J2(MAP_PROC,destroy)(h); - *h = nh; -} - -gb_inline MAP_TYPE *_J2(MAP_PROC,get)(MAP_NAME *h, HashKey key) { - isize index = _J2(MAP_PROC,_find)(h, key).entry_index; - if (index >= 0) { - return &h->entries.e[index].value; - } - return NULL; -} - -void _J2(MAP_PROC,set)(MAP_NAME *h, HashKey key, MAP_TYPE value) { - isize index; - MapFindResult fr; - if (h->hashes.count == 0) - _J2(MAP_PROC,grow)(h); - fr = _J2(MAP_PROC,_find)(h, key); - if (fr.entry_index >= 0) { - index = fr.entry_index; - } else { - index = _J2(MAP_PROC,_add_entry)(h, key); - if (fr.entry_prev >= 0) { - h->entries.e[fr.entry_prev].next = index; - } else { - h->hashes.e[fr.hash_index] = index; - } - } - h->entries.e[index].value = value; - - if (_J2(MAP_PROC,_full)(h)) { - _J2(MAP_PROC,grow)(h); - } -} - - - -void _J2(MAP_PROC,_erase)(MAP_NAME *h, MapFindResult fr) { - MapFindResult last; - if (fr.entry_prev < 0) { - h->hashes.e[fr.hash_index] = h->entries.e[fr.entry_index].next; - } else { - h->entries.e[fr.entry_prev].next = h->entries.e[fr.entry_index].next; - } - if (fr.entry_index == h->entries.count-1) { - array_pop(&h->entries); - return; - } - h->entries.e[fr.entry_index] = h->entries.e[h->entries.count-1]; - last = _J2(MAP_PROC,_find)(h, h->entries.e[fr.entry_index].key); - if (last.entry_prev >= 0) { - h->entries.e[last.entry_prev].next = fr.entry_index; - } else { - h->hashes.e[last.hash_index] = fr.entry_index; - } -} - -void _J2(MAP_PROC,remove)(MAP_NAME *h, HashKey key) { - MapFindResult fr = _J2(MAP_PROC,_find)(h, key); - if (fr.entry_index >= 0) { - _J2(MAP_PROC,_erase)(h, fr); - } -} - -gb_inline void _J2(MAP_PROC,clear)(MAP_NAME *h) { - array_clear(&h->hashes); - array_clear(&h->entries); -} - - -#if 1 -MAP_ENTRY *_J2(MAP_PROC,multi_find_first)(MAP_NAME *h, HashKey key) { - isize i = _J2(MAP_PROC,_find)(h, key).entry_index; - if (i < 0) { - return NULL; - } - return &h->entries.e[i]; -} - -MAP_ENTRY *_J2(MAP_PROC,multi_find_next)(MAP_NAME *h, MAP_ENTRY *e) { - isize i = e->next; - while (i >= 0) { - if (hash_key_equal(h->entries.e[i].key, e->key)) { - return &h->entries.e[i]; - } - i = h->entries.e[i].next; - } - return NULL; -} - -isize _J2(MAP_PROC,multi_count)(MAP_NAME *h, HashKey key) { - isize count = 0; - MAP_ENTRY *e = _J2(MAP_PROC,multi_find_first)(h, key); - while (e != NULL) { - count++; - e = _J2(MAP_PROC,multi_find_next)(h, e); - } - return count; -} - -void _J2(MAP_PROC,multi_get_all)(MAP_NAME *h, HashKey key, MAP_TYPE *items) { - isize i = 0; - MAP_ENTRY *e = _J2(MAP_PROC,multi_find_first)(h, key); - while (e != NULL) { - items[i++] = e->value; - e = _J2(MAP_PROC,multi_find_next)(h, e); - } -} - -void _J2(MAP_PROC,multi_insert)(MAP_NAME *h, HashKey key, MAP_TYPE value) { - MapFindResult fr; - isize i; - if (h->hashes.count == 0) { - _J2(MAP_PROC,grow)(h); - } - // Make - fr = _J2(MAP_PROC,_find)(h, key); - i = _J2(MAP_PROC,_add_entry)(h, key); - if (fr.entry_prev < 0) { - h->hashes.e[fr.hash_index] = i; - } else { - h->entries.e[fr.entry_prev].next = i; - } - h->entries.e[i].next = fr.entry_index; - h->entries.e[i].value = value; - // Grow if needed - if (_J2(MAP_PROC,_full)(h)) { - _J2(MAP_PROC,grow)(h); - } -} - -void _J2(MAP_PROC,multi_remove)(MAP_NAME *h, HashKey key, MAP_ENTRY *e) { - MapFindResult fr = _J2(MAP_PROC,_find_from_entry)(h, e); - if (fr.entry_index >= 0) { - _J2(MAP_PROC,_erase)(h, fr); - } -} - -void _J2(MAP_PROC,multi_remove_all)(MAP_NAME *h, HashKey key) { - while (_J2(MAP_PROC,get)(h, key) != NULL) { - _J2(MAP_PROC,remove)(h, key); - } -} -#endif - - -#undef _J2 -#undef MAP_TYPE -#undef MAP_PROC -#undef MAP_NAME -#undef MAP_ENTRY diff --git a/src/map.cpp b/src/map.cpp new file mode 100644 index 000000000..57942365a --- /dev/null +++ b/src/map.cpp @@ -0,0 +1,364 @@ +// A `Map` is an unordered hash table which can allow for a key to point to multiple values +// with the use of the `multi_*` procedures. +// TODO(bill): I should probably allow the `multi_map_*` stuff to be #ifdefed out + +#ifndef MAP_UTIL_STUFF +#define MAP_UTIL_STUFF +// NOTE(bill): This util stuff is the same for every `Map` +struct MapFindResult { + isize hash_index; + isize entry_prev; + isize entry_index; +}; + +enum HashKeyKind { + HashKey_Default, + HashKey_String, + HashKey_Pointer, +}; + +struct HashKey { + HashKeyKind kind; + // u128 key; + u64 key; + union { + String string; // if String, s.len > 0 + void * ptr; + }; +}; + +gb_inline HashKey hashing_proc(void const *data, isize len) { + HashKey h = {HashKey_Default}; + h.kind = HashKey_Default; + // h.key = u128_from_u64(gb_fnv64a(data, len)); + h.key = gb_fnv64a(data, len); + + return h; +} + +gb_inline HashKey hash_string(String s) { + HashKey h = hashing_proc(s.text, s.len); + h.kind = HashKey_String; + h.string = s; + return h; +} + +gb_inline HashKey hash_pointer(void *ptr) { + HashKey h = {HashKey_Default}; + // h.key = u128_from_u64(cast(u64)cast(uintptr)ptr); + h.key = cast(u64)cast(uintptr)ptr; + h.ptr = ptr; + h.kind = HashKey_Default; + return h; +} + +bool hash_key_equal(HashKey a, HashKey b) { + if (a.key == b.key) { + // NOTE(bill): If two string's hashes collide, compare the strings themselves + if (a.kind == HashKey_String) { + if (b.kind == HashKey_String) { + return a.string == b.string; + } + return false; + } + return true; + } + return false; +} +bool operator==(HashKey a, HashKey b) { return hash_key_equal(a, b); } +bool operator!=(HashKey a, HashKey b) { return !hash_key_equal(a, b); } + +#endif + +template +struct MapEntry { + HashKey key; + isize next; + T value; +}; + +template +struct Map { + Array hashes; + Array > entries; +}; + + +template void map_init (Map *h, gbAllocator a); +template void map_init_with_reserve(Map *h, gbAllocator a, isize capacity); +template void map_destroy (Map *h); +template T * map_get (Map *h, HashKey key); +template void map_set (Map *h, HashKey key, T const &value); +template void map_remove (Map *h, HashKey key); +template void map_clear (Map *h); +template void map_grow (Map *h); +template void map_rehash (Map *h, isize new_count); + +// Mutlivalued map procedure +template MapEntry * multi_map_find_first(Map *h, HashKey key); +template MapEntry * multi_map_find_next (Map *h, MapEntry *e); + +template isize multi_map_count (Map *h, HashKey key); +template void multi_map_get_all (Map *h, HashKey key, T *items); +template void multi_map_insert (Map *h, HashKey key, T const &value); +template void multi_map_remove (Map *h, HashKey key, MapEntry *e); +template void multi_map_remove_all(Map *h, HashKey key); + + +template +gb_inline void map_init(Map *h, gbAllocator a) { + array_init(&h->hashes, a); + array_init(&h->entries, a); +} + +template +gb_inline void map_init_with_reserve(Map *h, gbAllocator a, isize capacity) { + array_init(&h->hashes, a, capacity); + array_init(&h->entries, a, capacity); +} + +template +gb_inline void map_destroy(Map *h) { + array_free(&h->entries); + array_free(&h->hashes); +} + +template +gb_internal isize map__add_entry(Map *h, HashKey key) { + MapEntry e = {}; + e.key = key; + e.next = -1; + array_add(&h->entries, e); + return h->entries.count-1; +} + +template +gb_internal MapFindResult map__find(Map *h, HashKey key) { + MapFindResult fr = {-1, -1, -1}; + if (h->hashes.count > 0) { + // fr.hash_index = u128_to_i64(key.key % u128_from_i64(h->hashes.count)); + fr.hash_index = key.key % h->hashes.count; + fr.entry_index = h->hashes[fr.hash_index]; + while (fr.entry_index >= 0) { + if (hash_key_equal(h->entries[fr.entry_index].key, key)) { + return fr; + } + fr.entry_prev = fr.entry_index; + fr.entry_index = h->entries[fr.entry_index].next; + } + } + return fr; +} + +template +gb_internal MapFindResult map__find_from_entry(Map *h, MapEntry *e) { + MapFindResult fr = {-1, -1, -1}; + if (h->hashes.count > 0) { + fr.hash_index = e->key.key % h->hashes.count; + fr.entry_index = h->hashes[fr.hash_index]; + while (fr.entry_index >= 0) { + if (&h->entries[fr.entry_index] == e) { + return fr; + } + fr.entry_prev = fr.entry_index; + fr.entry_index = h->entries[fr.entry_index].next; + } + } + return fr; +} + +template +gb_internal b32 map__full(Map *h) { + return 0.75f * h->hashes.count <= h->entries.count; +} + +template +gb_inline void map_grow(Map *h) { + isize new_count = ARRAY_GROW_FORMULA(h->entries.count); + map_rehash(h, new_count); +} + +template +void map_rehash(Map *h, isize new_count) { + isize i, j; + Map nh = {}; + map_init(&nh, h->hashes.allocator); + array_resize(&nh.hashes, new_count); + array_reserve(&nh.entries, h->entries.count); + for (i = 0; i < new_count; i++) { + nh.hashes[i] = -1; + } + for (i = 0; i < h->entries.count; i++) { + MapEntry *e = &h->entries[i]; + MapFindResult fr; + if (nh.hashes.count == 0) { + map_grow(&nh); + } + fr = map__find(&nh, e->key); + j = map__add_entry(&nh, e->key); + if (fr.entry_prev < 0) { + nh.hashes[fr.hash_index] = j; + } else { + nh.entries[fr.entry_prev].next = j; + } + nh.entries[j].next = fr.entry_index; + nh.entries[j].value = e->value; + if (map__full(&nh)) { + map_grow(&nh); + } + } + map_destroy(h); + *h = nh; +} + +template +gb_inline T *map_get(Map *h, HashKey key) { + isize index = map__find(h, key).entry_index; + if (index >= 0) { + return &h->entries[index].value; + } + return NULL; +} + +template +void map_set(Map *h, HashKey key, T const &value) { + isize index; + MapFindResult fr; + if (h->hashes.count == 0) + map_grow(h); + fr = map__find(h, key); + if (fr.entry_index >= 0) { + index = fr.entry_index; + } else { + index = map__add_entry(h, key); + if (fr.entry_prev >= 0) { + h->entries[fr.entry_prev].next = index; + } else { + h->hashes[fr.hash_index] = index; + } + } + h->entries[index].value = value; + + if (map__full(h)) { + map_grow(h); + } +} + + +template +void map__erase(Map *h, MapFindResult fr) { + MapFindResult last; + if (fr.entry_prev < 0) { + h->hashes[fr.hash_index] = h->entries[fr.entry_index].next; + } else { + h->entries[fr.entry_prev].next = h->entries[fr.entry_index].next; + } + if (fr.entry_index == h->entries.count-1) { + array_pop(&h->entries); + return; + } + h->entries[fr.entry_index] = h->entries[h->entries.count-1]; + last = map__find(h, h->entries[fr.entry_index].key); + if (last.entry_prev >= 0) { + h->entries[last.entry_prev].next = fr.entry_index; + } else { + h->hashes[last.hash_index] = fr.entry_index; + } +} + +template +void map_remove(Map *h, HashKey key) { + MapFindResult fr = map__find(h, key); + if (fr.entry_index >= 0) { + map__erase(h, fr); + } +} + +template +gb_inline void map_clear(Map *h) { + array_clear(&h->hashes); + array_clear(&h->entries); +} + + +#if 1 +template +MapEntry *multi_map_find_first(Map *h, HashKey key) { + isize i = map__find(h, key).entry_index; + if (i < 0) { + return NULL; + } + return &h->entries[i]; +} + +template +MapEntry *multi_map_find_next(Map *h, MapEntry *e) { + isize i = e->next; + while (i >= 0) { + if (hash_key_equal(h->entries[i].key, e->key)) { + return &h->entries[i]; + } + i = h->entries[i].next; + } + return NULL; +} + +template +isize multi_map_count(Map *h, HashKey key) { + isize count = 0; + MapEntry *e = multi_map_find_first(h, key); + while (e != NULL) { + count++; + e = multi_map_find_next(h, e); + } + return count; +} + +template +void multi_map_get_all(Map *h, HashKey key, T *items) { + isize i = 0; + MapEntry *e = multi_map_find_first(h, key); + while (e != NULL) { + items[i++] = e->value; + e = multi_map_find_next(h, e); + } +} + +template +void multi_map_insert(Map *h, HashKey key, T const &value) { + MapFindResult fr; + isize i; + if (h->hashes.count == 0) { + map_grow(h); + } + // Make + fr = map__find(h, key); + i = map__add_entry(h, key); + if (fr.entry_prev < 0) { + h->hashes[fr.hash_index] = i; + } else { + h->entries[fr.entry_prev].next = i; + } + h->entries[i].next = fr.entry_index; + h->entries[i].value = value; + // Grow if needed + if (map__full(h)) { + map_grow(h); + } +} + +template +void multi_map_remove(Map *h, HashKey key, MapEntry *e) { + MapFindResult fr = map__find_from_entry(h, e); + if (fr.entry_index >= 0) { + map__erase(h, fr); + } +} + +template +void multi_map_remove_all(Map *h, HashKey key) { + while (map_get(h, key) != NULL) { + map_remove(h, key); + } +} +#endif diff --git a/src/murmurhash3.c b/src/murmurhash3.cpp similarity index 83% rename from src/murmurhash3.c rename to src/murmurhash3.cpp index 23c9ac454..7eacdc060 100644 --- a/src/murmurhash3.c +++ b/src/murmurhash3.cpp @@ -41,15 +41,15 @@ gb_inline u64 fmix64(u64 k) { return k; } -gb_inline u32 mm3_getblock32(u32 *const p, isize i) { +gb_inline u32 mm3_getblock32(u32 const *p, isize i) { return p[i]; } -gb_inline u64 mm3_getblock64(u64 *const p, isize i) { +gb_inline u64 mm3_getblock64(u64 const *p, isize i) { return p[i]; } -u128 MurmurHash3_x64_128(void *const key, isize len, u32 seed) { - u8 *const data = cast(u8 *const)key; +void MurmurHash3_x64_128(void const *key, isize len, u32 seed, void *out) { + u8 const * data = cast(u8 const *)key; isize nblocks = len / 16; u64 h1 = seed; @@ -58,7 +58,7 @@ u128 MurmurHash3_x64_128(void *const key, isize len, u32 seed) { u64 const c1 = 0x87c37b91114253d5ULL; u64 const c2 = 0x4cf5ad432745937fULL; - u64 *const blocks = cast(u64 *const)data; + u64 const * blocks = cast(u64 const *)data; for (isize i = 0; i < nblocks; i++) { u64 k1 = mm3_getblock64(blocks, i*2 + 0); @@ -70,7 +70,7 @@ u128 MurmurHash3_x64_128(void *const key, isize len, u32 seed) { h2 = ROTL64(h2,31); h2 += h1; h2 = h2*5+0x38495ab5; } - u8 *const tail = cast(u8 *const)(data + nblocks*16); + u8 const * tail = cast(u8 const *)(data + nblocks*16); u64 k1 = 0; u64 k2 = 0; @@ -108,11 +108,12 @@ u128 MurmurHash3_x64_128(void *const key, isize len, u32 seed) { h1 += h2; h2 += h1; - return u128_lo_hi(h1, h2); + ((u64 *)out)[0] = h1; + ((u64 *)out)[1] = h2; } -u128 MurmurHash3_x86_128(void *const key, isize len, u32 seed) { - u8 *const data = cast(u8 * const)key; +void MurmurHash3_x86_128(void const *key, isize len, u32 seed, void *out) { + u8 const * data = cast(u8 * const)key; isize nblocks = len / 16; u32 h1 = seed; @@ -128,7 +129,7 @@ u128 MurmurHash3_x86_128(void *const key, isize len, u32 seed) { //---------- // body - u32 *const blocks = cast(u32 *const)(data + nblocks*16); + u32 const * blocks = cast(u32 const *)(data + nblocks*16); for (isize i = -nblocks; i != 0; i++) { u32 k1 = mm3_getblock32(blocks, i*4 + 0); @@ -156,7 +157,7 @@ u128 MurmurHash3_x86_128(void *const key, isize len, u32 seed) { //---------- // tail - u8 *const tail = cast(u8 *const)(data + nblocks*16); + u8 const * tail = cast(u8 const *)(data + nblocks*16); u32 k1 = 0; u32 k2 = 0; @@ -204,17 +205,21 @@ u128 MurmurHash3_x86_128(void *const key, isize len, u32 seed) { h1 += h2; h1 += h3; h1 += h4; h2 += h1; h3 += h1; h4 += h1; - u64 lo = (u64)h1 | ((u64)h2 << 32); - u64 hi = (u64)h3 | ((u64)h4 << 32); - return u128_lo_hi(lo, hi); + + ((u32 *)out)[0] = h1; + ((u32 *)out)[1] = h2; + ((u32 *)out)[2] = h3; + ((u32 *)out)[3] = h4; } -gb_inline u128 MurmurHash3_128(void *const key, isize len, u32 seed) { +gb_inline u128 MurmurHash3_128(void const *key, isize len, u32 seed) { + u128 res; #if defined(GB_ARCH_64_BIT) - return MurmurHash3_x64_128(key, len, seed); + MurmurHash3_x64_128(key, len, seed, &res); #else - return MurmurHash3_x86_128(key, len, seed); + MurmurHash3_x86_128(key, len, seed, &res); #endif + return res; } diff --git a/src/parser.c b/src/parser.cpp similarity index 91% rename from src/parser.c rename to src/parser.cpp index 18aa32a0f..2feaa1fc2 100644 --- a/src/parser.c +++ b/src/parser.cpp @@ -1,8 +1,8 @@ -typedef struct AstNode AstNode; -typedef struct Scope Scope; -typedef struct DeclInfo DeclInfo; +struct AstNode; +struct Scope; +struct DeclInfo; -typedef enum ParseFileError { +enum ParseFileError { ParseFile_None, ParseFile_WrongExtension, @@ -13,15 +13,14 @@ typedef enum ParseFileError { ParseFile_InvalidToken, ParseFile_Count, -} ParseFileError; +}; -typedef Array(AstNode *) AstNodeArray; -typedef struct AstFile { +struct AstFile { i32 id; gbArena arena; Tokenizer tokenizer; - Array(Token) tokens; + Array tokens; isize curr_token_index; Token curr_token; Token prev_token; // previous non-comment @@ -32,8 +31,8 @@ typedef struct AstFile { isize expr_level; bool allow_range; // NOTE(bill): Ranges are only allowed in certain cases - AstNodeArray decls; - bool is_global_scope; + Array decls; + bool is_global_scope; AstNode * curr_proc; isize scope_level; @@ -44,25 +43,25 @@ typedef struct AstFile { #define PARSER_MAX_FIX_COUNT 6 isize fix_count; TokenPos fix_prev_pos; -} AstFile; +}; -typedef struct ImportedFile { +struct ImportedFile { String path; String rel_path; TokenPos pos; // #import -} ImportedFile; +}; -typedef struct Parser { +struct Parser { String init_fullpath; - Array(AstFile) files; - Array(ImportedFile) imports; + Array files; + Array imports; gbAtomic32 import_index; isize total_token_count; isize total_line_count; gbMutex mutex; -} Parser; +}; -typedef enum ProcTag { +enum ProcTag { ProcTag_bounds_check = 1<<0, ProcTag_no_bounds_check = 1<<1, @@ -75,47 +74,47 @@ typedef enum ProcTag { ProcTag_no_inline = 1<<14, // ProcTag_dll_import = 1<<15, // ProcTag_dll_export = 1<<16, -} ProcTag; +}; -typedef enum ProcCallingConvention { +enum ProcCallingConvention { ProcCC_Odin = 0, ProcCC_C = 1, ProcCC_Std = 2, ProcCC_Fast = 3, ProcCC_Invalid, -} ProcCallingConvention; +}; -typedef enum VarDeclFlag { +enum VarDeclFlag { VarDeclFlag_using = 1<<0, VarDeclFlag_immutable = 1<<1, VarDeclFlag_thread_local = 1<<2, -} VarDeclFlag; +}; -typedef enum StmtStateFlag { +enum StmtStateFlag { StmtStateFlag_bounds_check = 1<<0, StmtStateFlag_no_bounds_check = 1<<1, -} StmtStateFlag; +}; -typedef enum FieldFlag { +enum FieldFlag { FieldFlag_ellipsis = 1<<0, FieldFlag_using = 1<<1, FieldFlag_no_alias = 1<<2, FieldFlag_immutable = 1<<3, FieldFlag_Signature = FieldFlag_ellipsis|FieldFlag_using|FieldFlag_no_alias|FieldFlag_immutable, -} FieldListTag; +}; -typedef enum StmtAllowFlag { +enum StmtAllowFlag { StmtAllowFlag_None = 0, StmtAllowFlag_In = 1<<0, StmtAllowFlag_Label = 1<<1, -} StmtAllowFlag; +}; -AstNodeArray make_ast_node_array(AstFile *f) { - AstNodeArray a; +Array make_ast_node_array(AstFile *f) { + Array a; // array_init(&a, gb_arena_allocator(&f->arena)); array_init(&a, heap_allocator()); return a; @@ -147,7 +146,7 @@ AstNodeArray make_ast_node_array(AstFile *f) { }) \ AST_NODE_KIND(CompoundLit, "compound literal", struct { \ AstNode *type; \ - AstNodeArray elems; \ + Array elems; \ Token open, close; \ }) \ AST_NODE_KIND(Alias, "alias", struct { \ @@ -174,7 +173,7 @@ AST_NODE_KIND(_ExprBegin, "", i32) \ }) \ AST_NODE_KIND(CallExpr, "call expression", struct { \ AstNode * proc; \ - AstNodeArray args; \ + Array args; \ Token open; \ Token close; \ Token ellipsis; \ @@ -182,7 +181,7 @@ AST_NODE_KIND(_ExprBegin, "", i32) \ AST_NODE_KIND(MacroCallExpr, "macro call expression", struct { \ AstNode * macro; \ Token bang; \ - AstNodeArray args; \ + Array args; \ Token open; \ Token close; \ }) \ @@ -201,7 +200,7 @@ AST_NODE_KIND(_StmtBegin, "", i32) \ }) \ AST_NODE_KIND(AssignStmt, "assign statement", struct { \ Token op; \ - AstNodeArray lhs, rhs; \ + Array lhs, rhs; \ }) \ AST_NODE_KIND(IncDecStmt, "increment decrement statement", struct { \ Token op; \ @@ -209,7 +208,7 @@ AST_NODE_KIND(_StmtBegin, "", i32) \ }) \ AST_NODE_KIND(_ComplexStmtBegin, "", i32) \ AST_NODE_KIND(BlockStmt, "block statement", struct { \ - AstNodeArray stmts; \ + Array stmts; \ Token open, close; \ }) \ AST_NODE_KIND(IfStmt, "if statement", struct { \ @@ -227,7 +226,7 @@ AST_NODE_KIND(_ComplexStmtBegin, "", i32) \ }) \ AST_NODE_KIND(ReturnStmt, "return statement", struct { \ Token token; \ - AstNodeArray results; \ + Array results; \ }) \ AST_NODE_KIND(ForStmt, "for statement", struct { \ Token token; \ @@ -248,8 +247,8 @@ AST_NODE_KIND(_ComplexStmtBegin, "", i32) \ }) \ AST_NODE_KIND(CaseClause, "case clause", struct { \ Token token; \ - AstNodeArray list; \ - AstNodeArray stmts; \ + Array list; \ + Array stmts; \ }) \ AST_NODE_KIND(MatchStmt, "match statement", struct { \ Token token; \ @@ -268,7 +267,7 @@ AST_NODE_KIND(_ComplexStmtBegin, "", i32) \ AST_NODE_KIND(BranchStmt, "branch statement", struct { Token token; AstNode *label; }) \ AST_NODE_KIND(UsingStmt, "using statement", struct { \ Token token; \ - AstNodeArray list; \ + Array list; \ }) \ AST_NODE_KIND(AsmOperand, "assembly operand", struct { \ Token string; \ @@ -300,9 +299,9 @@ AST_NODE_KIND(_DeclBegin, "", i32) \ AST_NODE_KIND(BadDecl, "bad declaration", struct { Token begin, end; }) \ AST_NODE_KIND(ValueDecl, "value declaration", struct { \ bool is_var; \ - AstNodeArray names; \ + Array names; \ AstNode * type; \ - AstNodeArray values; \ + Array values; \ u32 flags; \ }) \ AST_NODE_KIND(ImportDecl, "import declaration", struct { \ @@ -327,13 +326,14 @@ AST_NODE_KIND(_DeclBegin, "", i32) \ }) \ AST_NODE_KIND(_DeclEnd, "", i32) \ AST_NODE_KIND(Field, "field", struct { \ - AstNodeArray names; \ - AstNode * type; \ - u32 flags; \ + Array names; \ + AstNode * type; \ + AstNode * default_value; \ + u32 flags; \ }) \ AST_NODE_KIND(FieldList, "field list", struct { \ Token token; \ - AstNodeArray list; \ + Array list; \ }) \ AST_NODE_KIND(UnionField, "union field", struct { \ AstNode *name; \ @@ -375,7 +375,7 @@ AST_NODE_KIND(_TypeBegin, "", i32) \ }) \ AST_NODE_KIND(StructType, "struct type", struct { \ Token token; \ - AstNodeArray fields; \ + Array fields; \ isize field_count; \ bool is_packed; \ bool is_ordered; \ @@ -383,23 +383,23 @@ AST_NODE_KIND(_TypeBegin, "", i32) \ }) \ AST_NODE_KIND(UnionType, "union type", struct { \ Token token; \ - AstNodeArray fields; \ + Array fields; \ isize field_count; \ - AstNodeArray variants; \ + Array variants; \ }) \ AST_NODE_KIND(RawUnionType, "raw union type", struct { \ Token token; \ - AstNodeArray fields; \ + Array fields; \ isize field_count; \ }) \ AST_NODE_KIND(EnumType, "enum type", struct { \ Token token; \ AstNode *base_type; \ - AstNodeArray fields; /* FieldValue */ \ + Array fields; /* FieldValue */ \ }) \ AST_NODE_KIND(BitFieldType, "bit field type", struct { \ Token token; \ - AstNodeArray fields; /* FieldValue with : */ \ + Array fields; /* FieldValue with : */ \ AstNode *align; \ }) \ AST_NODE_KIND(MapType, "map type", struct { \ @@ -410,13 +410,13 @@ AST_NODE_KIND(_TypeBegin, "", i32) \ }) \ AST_NODE_KIND(_TypeEnd, "", i32) -typedef enum AstNodeKind { +enum AstNodeKind { AstNode_Invalid, #define AST_NODE_KIND(_kind_name_, ...) GB_JOIN2(AstNode_, _kind_name_), AST_NODE_KINDS #undef AST_NODE_KIND AstNode_Count, -} AstNodeKind; +}; String const ast_node_strings[] = { {cast(u8 *)"invalid node", gb_size_of("invalid node")}, @@ -429,7 +429,7 @@ String const ast_node_strings[] = { AST_NODE_KINDS #undef AST_NODE_KIND -typedef struct AstNode { +struct AstNode { AstNodeKind kind; u32 stmt_state_flags; union { @@ -437,7 +437,7 @@ typedef struct AstNode { AST_NODE_KINDS #undef AST_NODE_KIND }; -} AstNode; +}; #define ast_node(n_, Kind_, node_) GB_JOIN2(AstNode, Kind_) *n_ = &(node_)->Kind_; GB_ASSERT((node_)->kind == GB_JOIN2(AstNode_, Kind_)) @@ -525,7 +525,7 @@ Token ast_node_token(AstNode *node) { case AstNode_PushContext: return node->PushContext.token; case AstNode_BadDecl: return node->BadDecl.begin; - case AstNode_ValueDecl: return ast_node_token(node->ValueDecl.names.e[0]); + case AstNode_ValueDecl: return ast_node_token(node->ValueDecl.names[0]); case AstNode_ImportDecl: return node->ImportDecl.token; case AstNode_ForeignLibrary: return node->ForeignLibrary.token; case AstNode_Label: return node->Label.token; @@ -533,7 +533,7 @@ Token ast_node_token(AstNode *node) { case AstNode_Field: if (node->Field.names.count > 0) { - return ast_node_token(node->Field.names.e[0]); + return ast_node_token(node->Field.names[0]); } return ast_node_token(node->Field.type); case AstNode_FieldList: @@ -560,12 +560,12 @@ Token ast_node_token(AstNode *node) { } AstNode *clone_ast_node(gbAllocator a, AstNode *node); -AstNodeArray clone_ast_node_array(gbAllocator a, AstNodeArray array) { - AstNodeArray result = {0}; +Array clone_ast_node_array(gbAllocator a, Array array) { + Array result = {}; if (array.count > 0) { array_init_count(&result, a, array.count); for_array(i, array) { - result.e[i] = clone_ast_node(a, array.e[i]); + result[i] = clone_ast_node(a, array[i]); } } return result; @@ -933,7 +933,7 @@ AstNode *ast_paren_expr(AstFile *f, AstNode *expr, Token open, Token close) { return result; } -AstNode *ast_call_expr(AstFile *f, AstNode *proc, AstNodeArray args, Token open, Token close, Token ellipsis) { +AstNode *ast_call_expr(AstFile *f, AstNode *proc, Array args, Token open, Token close, Token ellipsis) { AstNode *result = make_ast_node(f, AstNode_CallExpr); result->CallExpr.proc = proc; result->CallExpr.args = args; @@ -943,7 +943,7 @@ AstNode *ast_call_expr(AstFile *f, AstNode *proc, AstNodeArray args, Token open, return result; } -AstNode *ast_macro_call_expr(AstFile *f, AstNode *macro, Token bang, AstNodeArray args, Token open, Token close) { +AstNode *ast_macro_call_expr(AstFile *f, AstNode *macro, Token bang, Array args, Token open, Token close) { AstNode *result = make_ast_node(f, AstNode_MacroCallExpr); result->MacroCallExpr.macro = macro; result->MacroCallExpr.bang = bang; @@ -1048,7 +1048,7 @@ AstNode *ast_field_value(AstFile *f, AstNode *field, AstNode *value, Token eq) { return result; } -AstNode *ast_compound_lit(AstFile *f, AstNode *type, AstNodeArray elems, Token open, Token close) { +AstNode *ast_compound_lit(AstFile *f, AstNode *type, Array elems, Token open, Token close) { AstNode *result = make_ast_node(f, AstNode_CompoundLit); result->CompoundLit.type = type; result->CompoundLit.elems = elems; @@ -1101,7 +1101,7 @@ AstNode *ast_expr_stmt(AstFile *f, AstNode *expr) { return result; } -AstNode *ast_assign_stmt(AstFile *f, Token op, AstNodeArray lhs, AstNodeArray rhs) { +AstNode *ast_assign_stmt(AstFile *f, Token op, Array lhs, Array rhs) { AstNode *result = make_ast_node(f, AstNode_AssignStmt); result->AssignStmt.op = op; result->AssignStmt.lhs = lhs; @@ -1119,7 +1119,7 @@ AstNode *ast_inc_dec_stmt(AstFile *f, Token op, AstNode *expr) { -AstNode *ast_block_stmt(AstFile *f, AstNodeArray stmts, Token open, Token close) { +AstNode *ast_block_stmt(AstFile *f, Array stmts, Token open, Token close) { AstNode *result = make_ast_node(f, AstNode_BlockStmt); result->BlockStmt.stmts = stmts; result->BlockStmt.open = open; @@ -1147,7 +1147,7 @@ AstNode *ast_when_stmt(AstFile *f, Token token, AstNode *cond, AstNode *body, As } -AstNode *ast_return_stmt(AstFile *f, Token token, AstNodeArray results) { +AstNode *ast_return_stmt(AstFile *f, Token token, Array results) { AstNode *result = make_ast_node(f, AstNode_ReturnStmt); result->ReturnStmt.token = token; result->ReturnStmt.results = results; @@ -1194,7 +1194,7 @@ AstNode *ast_type_match_stmt(AstFile *f, Token token, AstNode *tag, AstNode *bod return result; } -AstNode *ast_case_clause(AstFile *f, Token token, AstNodeArray list, AstNodeArray stmts) { +AstNode *ast_case_clause(AstFile *f, Token token, Array list, Array stmts) { AstNode *result = make_ast_node(f, AstNode_CaseClause); result->CaseClause.token = token; result->CaseClause.list = list; @@ -1217,7 +1217,7 @@ AstNode *ast_branch_stmt(AstFile *f, Token token, AstNode *label) { return result; } -AstNode *ast_using_stmt(AstFile *f, Token token, AstNodeArray list) { +AstNode *ast_using_stmt(AstFile *f, Token token, Array list) { AstNode *result = make_ast_node(f, AstNode_UsingStmt); result->UsingStmt.token = token; result->UsingStmt.list = list; @@ -1277,15 +1277,16 @@ AstNode *ast_bad_decl(AstFile *f, Token begin, Token end) { return result; } -AstNode *ast_field(AstFile *f, AstNodeArray names, AstNode *type, u32 flags) { +AstNode *ast_field(AstFile *f, Array names, AstNode *type, AstNode *default_value, u32 flags) { AstNode *result = make_ast_node(f, AstNode_Field); result->Field.names = names; result->Field.type = type; + result->Field.default_value = default_value; result->Field.flags = flags; return result; } -AstNode *ast_field_list(AstFile *f, Token token, AstNodeArray list) { +AstNode *ast_field_list(AstFile *f, Token token, Array list) { AstNode *result = make_ast_node(f, AstNode_FieldList); result->FieldList.token = token; result->FieldList.list = list; @@ -1354,7 +1355,7 @@ AstNode *ast_vector_type(AstFile *f, Token token, AstNode *count, AstNode *elem) return result; } -AstNode *ast_struct_type(AstFile *f, Token token, AstNodeArray fields, isize field_count, +AstNode *ast_struct_type(AstFile *f, Token token, Array fields, isize field_count, bool is_packed, bool is_ordered, AstNode *align) { AstNode *result = make_ast_node(f, AstNode_StructType); result->StructType.token = token; @@ -1367,7 +1368,7 @@ AstNode *ast_struct_type(AstFile *f, Token token, AstNodeArray fields, isize fie } -AstNode *ast_union_type(AstFile *f, Token token, AstNodeArray fields, isize field_count, AstNodeArray variants) { +AstNode *ast_union_type(AstFile *f, Token token, Array fields, isize field_count, Array variants) { AstNode *result = make_ast_node(f, AstNode_UnionType); result->UnionType.token = token; result->UnionType.fields = fields; @@ -1376,7 +1377,7 @@ AstNode *ast_union_type(AstFile *f, Token token, AstNodeArray fields, isize fiel return result; } -AstNode *ast_raw_union_type(AstFile *f, Token token, AstNodeArray fields, isize field_count) { +AstNode *ast_raw_union_type(AstFile *f, Token token, Array fields, isize field_count) { AstNode *result = make_ast_node(f, AstNode_RawUnionType); result->RawUnionType.token = token; result->RawUnionType.fields = fields; @@ -1385,7 +1386,7 @@ AstNode *ast_raw_union_type(AstFile *f, Token token, AstNodeArray fields, isize } -AstNode *ast_enum_type(AstFile *f, Token token, AstNode *base_type, AstNodeArray fields) { +AstNode *ast_enum_type(AstFile *f, Token token, AstNode *base_type, Array fields) { AstNode *result = make_ast_node(f, AstNode_EnumType); result->EnumType.token = token; result->EnumType.base_type = base_type; @@ -1393,7 +1394,7 @@ AstNode *ast_enum_type(AstFile *f, Token token, AstNode *base_type, AstNodeArray return result; } -AstNode *ast_bit_field_type(AstFile *f, Token token, AstNodeArray fields, AstNode *align) { +AstNode *ast_bit_field_type(AstFile *f, Token token, Array fields, AstNode *align) { AstNode *result = make_ast_node(f, AstNode_BitFieldType); result->BitFieldType.token = token; result->BitFieldType.fields = fields; @@ -1411,7 +1412,7 @@ AstNode *ast_map_type(AstFile *f, Token token, AstNode *count, AstNode *key, Ast } -AstNode *ast_value_decl(AstFile *f, bool is_var, AstNodeArray names, AstNode *type, AstNodeArray values) { +AstNode *ast_value_decl(AstFile *f, bool is_var, Array names, AstNode *type, Array values) { AstNode *result = make_ast_node(f, AstNode_ValueDecl); result->ValueDecl.is_var = is_var; result->ValueDecl.names = names; @@ -1457,7 +1458,7 @@ bool next_token(AstFile *f) { } f->curr_token_index++; - f->curr_token = f->tokens.e[f->curr_token_index]; + f->curr_token = f->tokens[f->curr_token_index]; if (f->curr_token.kind == Token_Comment) { return next_token(f); } @@ -1474,7 +1475,7 @@ TokenKind look_ahead_token_kind(AstFile *f, isize amount) { isize index = f->curr_token_index; while (amount > 0) { index++; - kind = f->tokens.e[index].kind; + kind = f->tokens[index].kind; if (kind != Token_Comment) { amount--; } @@ -1547,7 +1548,7 @@ bool allow_token(AstFile *f, TokenKind kind) { bool is_blank_ident(String str) { if (str.len == 1) { - return str.text[0] == '_'; + return str[0] == '_'; } return false; } @@ -1605,7 +1606,7 @@ void fix_advance_to_next_stmt(AstFile *f) { Token expect_closing(AstFile *f, TokenKind kind, String context) { if (f->curr_token.kind != kind && f->curr_token.kind == Token_Semicolon && - str_eq(f->curr_token.string, str_lit("\n"))) { + f->curr_token.string == "\n") { error(f->curr_token, "Missing `,` before newline in %.*s", LIT(context)); next_token(f); } @@ -1647,7 +1648,7 @@ bool is_semicolon_optional_for_node(AstFile *f, AstNode *s) { case AstNode_ValueDecl: if (!s->ValueDecl.is_var) { if (s->ValueDecl.values.count > 0) { - AstNode *last = s->ValueDecl.values.e[s->ValueDecl.values.count-1]; + AstNode *last = s->ValueDecl.values[s->ValueDecl.values.count-1]; return is_semicolon_optional_for_node(f, last); } } @@ -1693,7 +1694,7 @@ void expect_semicolon(AstFile *f, AstNode *s) { AstNode * parse_expr(AstFile *f, bool lhs); AstNode * parse_proc_type(AstFile *f, AstNode **foreign_library, String *foreign_name, String *link_name); -AstNodeArray parse_stmt_list(AstFile *f); +Array parse_stmt_list(AstFile *f); AstNode * parse_stmt(AstFile *f); AstNode * parse_body(AstFile *f); @@ -1731,8 +1732,8 @@ AstNode *unparen_expr(AstNode *node) { AstNode *parse_value(AstFile *f); -AstNodeArray parse_element_list(AstFile *f) { - AstNodeArray elems = make_ast_node_array(f); +Array parse_element_list(AstFile *f) { + Array elems = make_ast_node_array(f); while (f->curr_token.kind != Token_CloseBrace && f->curr_token.kind != Token_EOF) { @@ -1754,7 +1755,7 @@ AstNodeArray parse_element_list(AstFile *f) { } AstNode *parse_literal_value(AstFile *f, AstNode *type) { - AstNodeArray elems = {0}; + Array elems = {}; Token open = expect_token(f, Token_OpenBrace); f->expr_level++; if (f->curr_token.kind != Token_CloseBrace) { @@ -1847,11 +1848,11 @@ void parse_proc_tags(AstFile *f, u64 *tags, AstNode **foreign_library_token, Str String tag_name = te->name.string; #define ELSE_IF_ADD_TAG(name) \ - else if (str_eq(tag_name, str_lit(#name))) { \ + else if (tag_name == #name) { \ check_proc_add_tag(f, tag_expr, tags, ProcTag_##name, tag_name); \ } - if (str_eq(tag_name, str_lit("foreign"))) { + if (tag_name == "foreign") { check_proc_add_tag(f, tag_expr, tags, ProcTag_foreign, tag_name); *foreign_library_token = parse_ident(f); if (f->curr_token.kind == Token_String) { @@ -1863,7 +1864,7 @@ void parse_proc_tags(AstFile *f, u64 *tags, AstNode **foreign_library_token, Str next_token(f); } - } else if (str_eq(tag_name, str_lit("link_name"))) { + } else if (tag_name == "link_name") { check_proc_add_tag(f, tag_expr, tags, ProcTag_link_name, tag_name); if (f->curr_token.kind == Token_String) { *link_name = f->curr_token.string; @@ -1885,25 +1886,25 @@ void parse_proc_tags(AstFile *f, u64 *tags, AstNode **foreign_library_token, Str ELSE_IF_ADD_TAG(no_inline) // ELSE_IF_ADD_TAG(dll_import) // ELSE_IF_ADD_TAG(dll_export) - else if (str_eq(tag_name, str_lit("cc_odin"))) { + else if (tag_name == "cc_odin") { if (cc == ProcCC_Invalid) { cc = ProcCC_Odin; } else { syntax_error_node(tag_expr, "Multiple calling conventions for procedure type"); } - } else if (str_eq(tag_name, str_lit("cc_c"))) { + } else if (tag_name == "cc_c") { if (cc == ProcCC_Invalid) { cc = ProcCC_C; } else { syntax_error_node(tag_expr, "Multiple calling conventions for procedure type"); } - } else if (str_eq(tag_name, str_lit("cc_std"))) { + } else if (tag_name == "cc_std") { if (cc == ProcCC_Invalid) { cc = ProcCC_Std; } else { syntax_error_node(tag_expr, "Multiple calling conventions for procedure type"); } - } else if (str_eq(tag_name, str_lit("cc_fast"))) { + } else if (tag_name == "cc_fast") { if (cc == ProcCC_Invalid) { cc = ProcCC_Fast; } else { @@ -1946,8 +1947,8 @@ void parse_proc_tags(AstFile *f, u64 *tags, AstNode **foreign_library_token, Str } -AstNodeArray parse_lhs_expr_list(AstFile *f); -AstNodeArray parse_rhs_expr_list(AstFile *f); +Array parse_lhs_expr_list(AstFile *f); +Array parse_rhs_expr_list(AstFile *f); AstNode * parse_simple_stmt (AstFile *f, StmtAllowFlag flags); AstNode * parse_type (AstFile *f); @@ -1961,7 +1962,7 @@ AstNode *convert_stmt_to_expr(AstFile *f, AstNode *statement, String kind) { } syntax_error(f->curr_token, "Expected `%.*s`, found a simple statement.", LIT(kind)); - return ast_bad_expr(f, f->curr_token, f->tokens.e[f->curr_token_index+1]); + return ast_bad_expr(f, f->curr_token, f->tokens[f->curr_token_index+1]); } @@ -1990,20 +1991,20 @@ AstNode *parse_operand(AstFile *f, bool lhs) { // NOTE(bill): Allow neighbouring string literals to be merge together to // become one big string String s = f->curr_token.string; - Array(u8) data; - array_init_reserve(&data, heap_allocator(), token.string.len+s.len); - gb_memmove(data.e, token.string.text, token.string.len); + Array data; + array_init(&data, heap_allocator(), token.string.len+s.len); + gb_memmove(data.data, token.string.text, token.string.len); data.count += token.string.len; while (f->curr_token.kind == Token_String) { String s = f->curr_token.string; isize old_count = data.count; array_resize(&data, data.count + s.len); - gb_memmove(data.e+old_count, s.text, s.len); + gb_memmove(data.data+old_count, s.text, s.len); next_token(f); } - token.string = make_string(data.e, data.count); + token.string = make_string(data.data, data.count); array_add(&f->tokenizer.allocated_strings, token.string); } @@ -2025,7 +2026,7 @@ AstNode *parse_operand(AstFile *f, bool lhs) { case Token_Hash: { Token token = expect_token(f, Token_Hash); Token name = expect_token(f, Token_Ident); - if (str_eq(name.string, str_lit("run"))) { + if (name.string == "run") { AstNode *expr = parse_expr(f, false); operand = ast_run_expr(f, token, name, expr); if (unparen_expr(expr)->kind != AstNode_CallExpr) { @@ -2033,11 +2034,11 @@ AstNode *parse_operand(AstFile *f, bool lhs) { operand = ast_bad_expr(f, token, f->curr_token); } warning(token, "#run is not yet implemented"); - } else if (str_eq(name.string, str_lit("file"))) { return ast_basic_directive(f, token, name.string); - } else if (str_eq(name.string, str_lit("line"))) { return ast_basic_directive(f, token, name.string); - } else if (str_eq(name.string, str_lit("procedure"))) { return ast_basic_directive(f, token, name.string); - } else if (str_eq(name.string, str_lit("type"))) { return ast_helper_type(f, token, parse_type(f)); - } else if (!lhs && str_eq(name.string, str_lit("alias"))) { return ast_alias(f, token, parse_expr(f, false)); + } else if (name.string == "file") { return ast_basic_directive(f, token, name.string); + } else if (name.string == "line") { return ast_basic_directive(f, token, name.string); + } else if (name.string == "procedure") { return ast_basic_directive(f, token, name.string); + } else if (name.string == "type") { return ast_helper_type(f, token, parse_type(f)); + } else if (!lhs && name.string == "alias") { return ast_alias(f, token, parse_expr(f, false)); } else { operand = ast_tag_expr(f, token, name, parse_expr(f, false)); } @@ -2048,8 +2049,8 @@ AstNode *parse_operand(AstFile *f, bool lhs) { case Token_proc: { Token token = f->curr_token; AstNode *foreign_library = NULL; - String foreign_name = {0}; - String link_name = {0}; + String foreign_name = {}; + String link_name = {}; AstNode *type = parse_proc_type(f, &foreign_library, &foreign_name, &link_name); u64 tags = type->ProcType.tags; @@ -2109,9 +2110,9 @@ bool is_literal_type(AstNode *node) { } AstNode *parse_call_expr(AstFile *f, AstNode *operand) { - AstNodeArray args = make_ast_node_array(f); + Array args = make_ast_node_array(f); Token open_paren, close_paren; - Token ellipsis = {0}; + Token ellipsis = {}; f->expr_level++; open_paren = expect_token(f, Token_OpenParen); @@ -2129,6 +2130,11 @@ AstNode *parse_call_expr(AstFile *f, AstNode *operand) { } AstNode *arg = parse_expr(f, false); + if (f->curr_token.kind == Token_Eq) { + Token eq = expect_token(f, Token_Eq); + AstNode *value = parse_value(f); + arg = ast_field_value(f, arg, value, eq); + } array_add(&args, arg); if (!allow_token(f, Token_Comma)) { @@ -2144,7 +2150,7 @@ AstNode *parse_call_expr(AstFile *f, AstNode *operand) { AstNode *parse_macro_call_expr(AstFile *f, AstNode *operand) { - AstNodeArray args = make_ast_node_array(f); + Array args = make_ast_node_array(f); Token bang, open_paren, close_paren; bang = expect_token(f, Token_Not); @@ -2224,10 +2230,10 @@ AstNode *parse_atom_expr(AstFile *f, bool lhs) { bool prev_allow_range = f->allow_range; f->allow_range = false; - Token open = {0}, close = {0}, interval = {0}; - AstNode *indices[3] = {0}; + Token open = {}, close = {}, interval = {}; + AstNode *indices[3] = {}; isize ellipsis_count = 0; - Token ellipses[2] = {0}; + Token ellipses[2] = {}; f->expr_level++; open = expect_token(f, Token_OpenBracket); @@ -2411,8 +2417,8 @@ AstNode *parse_expr(AstFile *f, bool lhs) { } -AstNodeArray parse_expr_list(AstFile *f, bool lhs) { - AstNodeArray list = make_ast_node_array(f); +Array parse_expr_list(AstFile *f, bool lhs) { + Array list = make_ast_node_array(f); for (;;) { AstNode *e = parse_expr(f, lhs); array_add(&list, e); @@ -2426,16 +2432,16 @@ AstNodeArray parse_expr_list(AstFile *f, bool lhs) { return list; } -AstNodeArray parse_lhs_expr_list(AstFile *f) { +Array parse_lhs_expr_list(AstFile *f) { return parse_expr_list(f, true); } -AstNodeArray parse_rhs_expr_list(AstFile *f) { +Array parse_rhs_expr_list(AstFile *f) { return parse_expr_list(f, false); } -AstNodeArray parse_ident_list(AstFile *f) { - AstNodeArray list = make_ast_node_array(f); +Array parse_ident_list(AstFile *f) { + Array list = make_ast_node_array(f); do { array_add(&list, parse_ident(f)); @@ -2470,9 +2476,9 @@ AstNode *parse_type(AstFile *f) { } -AstNode *parse_value_decl(AstFile *f, AstNodeArray lhs) { +AstNode *parse_value_decl(AstFile *f, Array lhs) { AstNode *type = NULL; - AstNodeArray values = {0}; + Array values = {}; bool is_mutable = true; if (allow_token(f, Token_Colon)) { @@ -2512,19 +2518,19 @@ AstNode *parse_value_decl(AstFile *f, AstNodeArray lhs) { } } - if (values.e == NULL) { + if (values.data == NULL) { values = make_ast_node_array(f); } - AstNodeArray specs = {0}; - array_init_reserve(&specs, heap_allocator(), 1); + Array specs = {}; + array_init(&specs, heap_allocator(), 1); return ast_value_decl(f, is_mutable, lhs, type, values); } AstNode *parse_simple_stmt(AstFile *f, StmtAllowFlag flags) { - AstNodeArray lhs = parse_lhs_expr_list(f); + Array lhs = parse_lhs_expr_list(f); Token token = f->curr_token; switch (token.kind) { case Token_Eq: @@ -2548,7 +2554,7 @@ AstNode *parse_simple_stmt(AstFile *f, StmtAllowFlag flags) { return ast_bad_stmt(f, f->curr_token, f->curr_token); } next_token(f); - AstNodeArray rhs = parse_rhs_expr_list(f); + Array rhs = parse_rhs_expr_list(f); if (rhs.count == 0) { syntax_error(token, "No right-hand side in assignment statement."); return ast_bad_stmt(f, token, f->curr_token); @@ -2564,9 +2570,9 @@ AstNode *parse_simple_stmt(AstFile *f, StmtAllowFlag flags) { AstNode *expr = parse_expr(f, false); f->allow_range = prev_allow_range; - AstNodeArray rhs = {0}; + Array rhs = {}; array_init_count(&rhs, heap_allocator(), 1); - rhs.e[0] = expr; + rhs[0] = expr; return ast_assign_stmt(f, token, lhs, rhs); } @@ -2579,7 +2585,7 @@ AstNode *parse_simple_stmt(AstFile *f, StmtAllowFlag flags) { case Token_for: case Token_match: { next_token(f); - AstNode *name = lhs.e[0]; + AstNode *name = lhs[0]; AstNode *label = ast_label_decl(f, ast_node_token(name), name); AstNode *stmt = parse_stmt(f); #define _SET_LABEL(Kind_, label_) case GB_JOIN2(AstNode_, Kind_): (stmt->Kind_).label = label_; break @@ -2612,10 +2618,10 @@ AstNode *parse_simple_stmt(AstFile *f, StmtAllowFlag flags) { case Token_Inc: case Token_Dec: next_token(f); - return ast_inc_dec_stmt(f, token, lhs.e[0]); + return ast_inc_dec_stmt(f, token, lhs[0]); } - return ast_expr_stmt(f, lhs.e[0]); + return ast_expr_stmt(f, lhs[0]); } @@ -2638,10 +2644,10 @@ AstNode *parse_results(AstFile *f) { if (f->curr_token.kind != Token_OpenParen) { Token begin_token = f->curr_token; - AstNodeArray empty_names = {0}; - AstNodeArray list = make_ast_node_array(f); + Array empty_names = {}; + Array list = make_ast_node_array(f); AstNode *type = parse_type(f); - array_add(&list, ast_field(f, empty_names, type, 0)); + array_add(&list, ast_field(f, empty_names, type, NULL, 0)); return ast_field_list(f, begin_token, list); } @@ -2653,8 +2659,8 @@ AstNode *parse_results(AstFile *f) { } AstNode *parse_proc_type(AstFile *f, AstNode **foreign_library_, String *foreign_name_, String *link_name_) { - AstNode *params = {0}; - AstNode *results = {0}; + AstNode *params = {}; + AstNode *results = {}; Token proc_token = expect_token(f, Token_proc); expect_token(f, Token_OpenParen); @@ -2663,8 +2669,8 @@ AstNode *parse_proc_type(AstFile *f, AstNode **foreign_library_, String *foreign results = parse_results(f); u64 tags = 0; - String foreign_name = {0}; - String link_name = {0}; + String foreign_name = {}; + String link_name = {}; AstNode *foreign_library = NULL; ProcCallingConvention cc = ProcCC_Odin; @@ -2698,13 +2704,13 @@ AstNode *parse_var_type(AstFile *f, bool allow_ellipsis) { } -typedef enum FieldPrefixKind { +enum FieldPrefixKind { FieldPrefix_Invalid, FieldPrefix_Using, FieldPrefix_Immutable, FieldPrefix_NoAlias, -} FieldPrefixKind; +}; FieldPrefixKind is_token_field_prefix(AstFile *f) { switch (f->curr_token.kind) { @@ -2721,7 +2727,7 @@ FieldPrefixKind is_token_field_prefix(AstFile *f) { next_token(f); switch (f->curr_token.kind) { case Token_Ident: - if (str_eq(f->curr_token.string, str_lit("no_alias"))) { + if (f->curr_token.string == "no_alias") { return FieldPrefix_NoAlias; } break; @@ -2781,19 +2787,17 @@ u32 check_field_prefixes(AstFile *f, isize name_count, u32 allowed_flags, u32 se return set_flags; } -typedef struct AstNodeAndFlags { +struct AstNodeAndFlags { AstNode *node; u32 flags; -} AstNodeAndFlags; +}; -typedef Array(AstNodeAndFlags) AstNodeAndFlagsArray; - -AstNodeArray convert_to_ident_list(AstFile *f, AstNodeAndFlagsArray list, bool ignore_flags) { - AstNodeArray idents = {0}; - array_init_reserve(&idents, heap_allocator(), list.count); +Array convert_to_ident_list(AstFile *f, Array list, bool ignore_flags) { + Array idents = {}; + array_init(&idents, heap_allocator(), list.count); // Convert to ident list for_array(i, list) { - AstNode *ident = list.e[i].node; + AstNode *ident = list[i].node; if (!ignore_flags) { if (i != 0) { @@ -2833,10 +2837,11 @@ AstNode *parse_field_list(AstFile *f, isize *name_count_, u32 allowed_flags, Tok TokenKind separator = Token_Comma; Token start_token = f->curr_token; - AstNodeArray params = make_ast_node_array(f); - AstNodeAndFlagsArray list = {0}; array_init(&list, heap_allocator()); // LEAK(bill): + Array params = make_ast_node_array(f); + Array list = {}; array_init(&list, heap_allocator()); // LEAK(bill): isize total_name_count = 0; bool allow_ellipsis = allowed_flags&FieldFlag_ellipsis; + bool is_procedure = (allowed_flags&FieldFlag_Signature) != 0; while (f->curr_token.kind != follow && f->curr_token.kind != Token_Colon && @@ -2852,20 +2857,37 @@ AstNode *parse_field_list(AstFile *f, isize *name_count_, u32 allowed_flags, Tok } if (f->curr_token.kind == Token_Colon) { - AstNodeArray names = convert_to_ident_list(f, list, true); // Copy for semantic reasons + Array names = convert_to_ident_list(f, list, true); // Copy for semantic reasons if (names.count == 0) { syntax_error(f->curr_token, "Empty field declaration"); } u32 set_flags = 0; if (list.count > 0) { - set_flags = list.e[0].flags; + set_flags = list[0].flags; } set_flags = check_field_prefixes(f, names.count, allowed_flags, set_flags); total_name_count += names.count; expect_token_after(f, Token_Colon, "field list"); - AstNode *type = parse_var_type(f, allow_ellipsis); - AstNode *param = ast_field(f, names, type, set_flags); + AstNode *type = NULL; + AstNode *default_value = NULL; + + if (f->curr_token.kind != Token_Eq) { + type = parse_var_type(f, allow_ellipsis); + } + if (allow_token(f, Token_Eq)) { + // TODO(bill): Should this be true==lhs or false==rhs? + default_value = parse_expr(f, true); + if (!is_procedure) { + syntax_error(f->curr_token, "Default parameters are only allowed for procedures"); + } + } + + if (default_value != NULL && names.count > 1) { + syntax_error(f->curr_token, "Default parameters can only be applied to single values"); + } + + AstNode *param = ast_field(f, names, type, default_value, set_flags); array_add(¶ms, param); parse_expect_field_separator(f, type); @@ -2873,7 +2895,7 @@ AstNode *parse_field_list(AstFile *f, isize *name_count_, u32 allowed_flags, Tok while (f->curr_token.kind != follow && f->curr_token.kind != Token_EOF) { u32 set_flags = parse_field_prefixes(f); - AstNodeArray names = parse_ident_list(f); + Array names = parse_ident_list(f); if (names.count == 0) { syntax_error(f->curr_token, "Empty field declaration"); break; @@ -2882,8 +2904,24 @@ AstNode *parse_field_list(AstFile *f, isize *name_count_, u32 allowed_flags, Tok total_name_count += names.count; expect_token_after(f, Token_Colon, "field list"); - AstNode *type = parse_var_type(f, allow_ellipsis); - AstNode *param = ast_field(f, names, type, set_flags); + AstNode *type = NULL; + AstNode *default_value = NULL; + if (f->curr_token.kind != Token_Eq) { + type = parse_var_type(f, allow_ellipsis); + } + if (allow_token(f, Token_Eq)) { + // TODO(bill): Should this be true==lhs or false==rhs? + default_value = parse_expr(f, true); + if (!is_procedure) { + syntax_error(f->curr_token, "Default parameters are only allowed for procedures"); + } + } + + if (default_value != NULL && names.count > 1) { + syntax_error(f->curr_token, "Default parameters can only be applied to single values"); + } + + AstNode *param = ast_field(f, names, type, default_value, set_flags); array_add(¶ms, param); if (!parse_expect_field_separator(f, param)) { @@ -2896,16 +2934,16 @@ AstNode *parse_field_list(AstFile *f, isize *name_count_, u32 allowed_flags, Tok } for_array(i, list) { - AstNodeArray names = {0}; - AstNode *type = list.e[i].node; + Array names = {}; + AstNode *type = list[i].node; Token token = blank_token; array_init_count(&names, heap_allocator(), 1); token.pos = ast_node_token(type).pos; - names.e[0] = ast_ident(f, token); - u32 flags = check_field_prefixes(f, list.count, allowed_flags, list.e[i].flags); + names[0] = ast_ident(f, token); + u32 flags = check_field_prefixes(f, list.count, allowed_flags, list[i].flags); - AstNode *param = ast_field(f, names, list.e[i].node, flags); + AstNode *param = ast_field(f, names, list[i].node, NULL, flags); array_add(¶ms, param); } @@ -2941,7 +2979,7 @@ AstNode *parse_type_or_ident(AstFile *f) { Token hash_token = expect_token(f, Token_Hash); Token name = expect_token(f, Token_Ident); String tag = name.string; - if (str_eq(tag, str_lit("type"))) { + if (tag == "type") { AstNode *type = parse_type(f); return ast_helper_type(f, hash_token, type); } @@ -3023,17 +3061,17 @@ AstNode *parse_type_or_ident(AstFile *f) { while (allow_token(f, Token_Hash)) { Token tag = expect_token_after(f, Token_Ident, "#"); - if (str_eq(tag.string, str_lit("packed"))) { + if (tag.string == "packed") { if (is_packed) { syntax_error(tag, "Duplicate struct tag `#%.*s`", LIT(tag.string)); } is_packed = true; - } else if (str_eq(tag.string, str_lit("ordered"))) { + } else if (tag.string == "ordered") { if (is_ordered) { syntax_error(tag, "Duplicate struct tag `#%.*s`", LIT(tag.string)); } is_ordered = true; - } else if (str_eq(tag.string, str_lit("align"))) { + } else if (tag.string == "align") { if (align) { syntax_error(tag, "Duplicate struct tag `#%.*s`", LIT(tag.string)); } @@ -3054,7 +3092,7 @@ AstNode *parse_type_or_ident(AstFile *f) { AstNode *fields = parse_record_fields(f, &decl_count, FieldFlag_using, str_lit("struct")); Token close = expect_token(f, Token_CloseBrace); - AstNodeArray decls = {0}; + Array decls = {}; if (fields != NULL) { GB_ASSERT(fields->kind == AstNode_FieldList); decls = fields->FieldList.list; @@ -3066,15 +3104,15 @@ AstNode *parse_type_or_ident(AstFile *f) { case Token_union: { Token token = expect_token(f, Token_union); Token open = expect_token_after(f, Token_OpenBrace, "union"); - AstNodeArray decls = make_ast_node_array(f); - AstNodeArray variants = make_ast_node_array(f); + Array decls = make_ast_node_array(f); + Array variants = make_ast_node_array(f); isize total_decl_name_count = 0; while (f->curr_token.kind != Token_CloseBrace && f->curr_token.kind != Token_EOF) { u32 decl_flags = parse_field_prefixes(f); if (decl_flags != 0) { - AstNodeArray names = parse_ident_list(f); + Array names = parse_ident_list(f); if (names.count == 0) { syntax_error(f->curr_token, "Empty field declaration"); } @@ -3082,9 +3120,9 @@ AstNode *parse_type_or_ident(AstFile *f) { total_decl_name_count += names.count; expect_token_after(f, Token_Colon, "field list"); AstNode *type = parse_var_type(f, false); - array_add(&decls, ast_field(f, names, type, set_flags)); + array_add(&decls, ast_field(f, names, type, NULL, set_flags)); } else { - AstNodeArray names = parse_ident_list(f); + Array names = parse_ident_list(f); if (names.count == 0) { break; } @@ -3093,9 +3131,9 @@ AstNode *parse_type_or_ident(AstFile *f) { total_decl_name_count += names.count; expect_token_after(f, Token_Colon, "field list"); AstNode *type = parse_var_type(f, false); - array_add(&decls, ast_field(f, names, type, set_flags)); + array_add(&decls, ast_field(f, names, type, NULL, set_flags)); } else { - AstNode *name = names.e[0]; + AstNode *name = names[0]; Token open = expect_token(f, Token_OpenBrace); isize decl_count = 0; AstNode *list = parse_record_fields(f, &decl_count, FieldFlag_using, str_lit("union")); @@ -3123,7 +3161,7 @@ AstNode *parse_type_or_ident(AstFile *f) { AstNode *fields = parse_record_fields(f, &decl_count, FieldFlag_using, str_lit("raw_union")); Token close = expect_token(f, Token_CloseBrace); - AstNodeArray decls = {0}; + Array decls = {}; if (fields != NULL) { GB_ASSERT(fields->kind == AstNode_FieldList); decls = fields->FieldList.list; @@ -3140,7 +3178,7 @@ AstNode *parse_type_or_ident(AstFile *f) { } Token open = expect_token(f, Token_OpenBrace); - AstNodeArray values = parse_element_list(f); + Array values = parse_element_list(f); Token close = expect_token(f, Token_CloseBrace); return ast_enum_type(f, token, base_type, values); @@ -3148,7 +3186,7 @@ AstNode *parse_type_or_ident(AstFile *f) { case Token_bit_field: { Token token = expect_token(f, Token_bit_field); - AstNodeArray fields = make_ast_node_array(f); + Array fields = make_ast_node_array(f); AstNode *align = NULL; Token open, close; @@ -3157,7 +3195,7 @@ AstNode *parse_type_or_ident(AstFile *f) { while (allow_token(f, Token_Hash)) { Token tag = expect_token_after(f, Token_Ident, "#"); - if (str_eq(tag.string, str_lit("align"))) { + if (tag.string == "align") { if (align) { syntax_error(tag, "Duplicate bit_field tag `#%.*s`", LIT(tag.string)); } @@ -3214,7 +3252,7 @@ AstNode *parse_type_or_ident(AstFile *f) { AstNode *parse_body(AstFile *f) { - AstNodeArray stmts = {0}; + Array stmts = {}; Token open, close; isize prev_expr_level = f->expr_level; @@ -3273,7 +3311,7 @@ AstNode *parse_if_stmt(AstFile *f) { break; default: syntax_error(f->curr_token, "Expected if statement block statement"); - else_stmt = ast_bad_stmt(f, f->curr_token, f->tokens.e[f->curr_token_index+1]); + else_stmt = ast_bad_stmt(f, f->curr_token, f->tokens[f->curr_token_index+1]); break; } } @@ -3310,7 +3348,7 @@ AstNode *parse_when_stmt(AstFile *f) { break; default: syntax_error(f->curr_token, "Expected when statement block statement"); - else_stmt = ast_bad_stmt(f, f->curr_token, f->tokens.e[f->curr_token_index+1]); + else_stmt = ast_bad_stmt(f, f->curr_token, f->tokens[f->curr_token_index+1]); break; } } @@ -3330,14 +3368,18 @@ AstNode *parse_return_stmt(AstFile *f) { } Token token = expect_token(f, Token_return); - AstNodeArray results; + Array results; if (f->curr_token.kind != Token_Semicolon && f->curr_token.kind != Token_CloseBrace) { results = parse_rhs_expr_list(f); } else { results = make_ast_node_array(f); } - expect_semicolon(f, results.e[0]); + AstNode *end = NULL; + if (results.count > 0) { + end = results[results.count-1]; + } + expect_semicolon(f, end); return ast_return_stmt(f, token, results); } @@ -3353,7 +3395,7 @@ AstNode *parse_return_stmt(AstFile *f) { // } // Token token = expect_token(f, Token_give); -// AstNodeArray results; +// Array results; // if (f->curr_token.kind != Token_Semicolon && f->curr_token.kind != Token_CloseBrace) { // results = parse_rhs_expr_list(f); // } else { @@ -3413,11 +3455,11 @@ AstNode *parse_for_stmt(AstFile *f) { AstNode *index = NULL; switch (cond->AssignStmt.lhs.count) { case 1: - value = cond->AssignStmt.lhs.e[0]; + value = cond->AssignStmt.lhs[0]; break; case 2: - value = cond->AssignStmt.lhs.e[0]; - index = cond->AssignStmt.lhs.e[1]; + value = cond->AssignStmt.lhs[0]; + index = cond->AssignStmt.lhs[1]; break; default: error_node(cond, "Expected at 1 or 2 identifiers"); @@ -3426,7 +3468,7 @@ AstNode *parse_for_stmt(AstFile *f) { AstNode *rhs = NULL; if (cond->AssignStmt.rhs.count > 0) { - rhs = cond->AssignStmt.rhs.e[0]; + rhs = cond->AssignStmt.rhs[0]; } return ast_range_stmt(f, token, value, index, in_token, rhs, body); } @@ -3438,7 +3480,7 @@ AstNode *parse_for_stmt(AstFile *f) { AstNode *parse_case_clause(AstFile *f, bool is_type) { Token token = f->curr_token; - AstNodeArray list = make_ast_node_array(f); + Array list = make_ast_node_array(f); expect_token(f, Token_case); bool prev_allow_range = f->allow_range; f->allow_range = !is_type; @@ -3447,7 +3489,7 @@ AstNode *parse_case_clause(AstFile *f, bool is_type) { } f->allow_range = prev_allow_range; expect_token(f, Token_Colon); // TODO(bill): Is this the best syntax? - AstNodeArray stmts = parse_stmt_list(f); + Array stmts = parse_stmt_list(f); return ast_case_clause(f, token, list, stmts); } @@ -3465,7 +3507,7 @@ AstNode *parse_match_stmt(AstFile *f) { AstNode *body = NULL; Token open, close; bool is_type_match = false; - AstNodeArray list = make_ast_node_array(f); + Array list = make_ast_node_array(f); if (f->curr_token.kind != Token_OpenBrace) { isize prev_level = f->expr_level; @@ -3605,7 +3647,7 @@ AstNode *parse_stmt(AstFile *f) { case Token_using: { // TODO(bill): Make using statements better Token token = expect_token(f, Token_using); - AstNodeArray list = parse_lhs_expr_list(f); + Array list = parse_lhs_expr_list(f); if (list.count == 0) { syntax_error(token, "Illegal use of `using` statement"); expect_semicolon(f, NULL); @@ -3613,7 +3655,7 @@ AstNode *parse_stmt(AstFile *f) { } if (f->curr_token.kind != Token_Colon) { - expect_semicolon(f, list.e[list.count-1]); + expect_semicolon(f, list[list.count-1]); return ast_using_stmt(f, token, list); } @@ -3687,9 +3729,9 @@ AstNode *parse_stmt(AstFile *f) { Token name = expect_token(f, Token_Ident); String tag = name.string; - if (str_eq(tag, str_lit("import"))) { + if (tag == "import") { AstNode *cond = NULL; - Token import_name = {0}; + Token import_name = {}; switch (f->curr_token.kind) { case Token_Period: @@ -3706,7 +3748,7 @@ AstNode *parse_stmt(AstFile *f) { break; } - if (str_eq(import_name.string, str_lit("_"))) { + if (import_name.string == "_") { syntax_error(import_name, "Illegal #import name: `_`"); } @@ -3724,7 +3766,7 @@ AstNode *parse_stmt(AstFile *f) { } expect_semicolon(f, decl); return decl; - } else if (str_eq(tag, str_lit("load"))) { + } else if (tag == "load") { AstNode *cond = NULL; Token file_path = expect_token_after(f, Token_String, "#load"); Token import_name = file_path; @@ -3743,7 +3785,7 @@ AstNode *parse_stmt(AstFile *f) { } expect_semicolon(f, decl); return decl; - } else if (str_eq(tag, str_lit("shared_global_scope"))) { + } else if (tag == "shared_global_scope") { if (f->curr_proc == NULL) { f->is_global_scope = true; s = ast_empty_stmt(f, f->curr_token); @@ -3753,9 +3795,9 @@ AstNode *parse_stmt(AstFile *f) { } expect_semicolon(f, s); return s; - } else if (str_eq(tag, str_lit("foreign_system_library"))) { + } else if (tag == "foreign_system_library") { AstNode *cond = NULL; - Token lib_name = {0}; + Token lib_name = {}; switch (f->curr_token.kind) { case Token_Ident: @@ -3767,7 +3809,7 @@ AstNode *parse_stmt(AstFile *f) { break; } - if (str_eq(lib_name.string, str_lit("_"))) { + if (lib_name.string == "_") { syntax_error(lib_name, "Illegal #foreign_library name: `_`"); } Token file_path = expect_token(f, Token_String); @@ -3784,9 +3826,9 @@ AstNode *parse_stmt(AstFile *f) { } expect_semicolon(f, s); return s; - } else if (str_eq(tag, str_lit("foreign_library"))) { + } else if (tag == "foreign_library") { AstNode *cond = NULL; - Token lib_name = {0}; + Token lib_name = {}; switch (f->curr_token.kind) { case Token_Ident: @@ -3798,7 +3840,7 @@ AstNode *parse_stmt(AstFile *f) { break; } - if (str_eq(lib_name.string, str_lit("_"))) { + if (lib_name.string == "_") { syntax_error(lib_name, "Illegal #foreign_library name: `_`"); } Token file_path = expect_token(f, Token_String); @@ -3815,7 +3857,7 @@ AstNode *parse_stmt(AstFile *f) { } expect_semicolon(f, s); return s; - } else if (str_eq(tag, str_lit("thread_local"))) { + } else if (tag == "thread_local") { AstNode *s = parse_stmt(f); if (s->kind == AstNode_ValueDecl) { @@ -3831,14 +3873,14 @@ AstNode *parse_stmt(AstFile *f) { } syntax_error(token, "`thread_local` may only be applied to a variable declaration"); return ast_bad_stmt(f, token, f->curr_token); - } else if (str_eq(tag, str_lit("bounds_check"))) { + } else if (tag == "bounds_check") { s = parse_stmt(f); s->stmt_state_flags |= StmtStateFlag_bounds_check; if ((s->stmt_state_flags & StmtStateFlag_no_bounds_check) != 0) { syntax_error(token, "#bounds_check and #no_bounds_check cannot be applied together"); } return s; - } else if (str_eq(tag, str_lit("no_bounds_check"))) { + } else if (tag == "no_bounds_check") { s = parse_stmt(f); s->stmt_state_flags |= StmtStateFlag_no_bounds_check; if ((s->stmt_state_flags & StmtStateFlag_bounds_check) != 0) { @@ -3847,7 +3889,7 @@ AstNode *parse_stmt(AstFile *f) { return s; } - if (str_eq(tag, str_lit("include"))) { + if (tag == "include") { syntax_error(token, "#include is not a valid import declaration kind. Use #load instead"); s = ast_bad_stmt(f, token, f->curr_token); } else { @@ -3876,8 +3918,8 @@ AstNode *parse_stmt(AstFile *f) { return ast_bad_stmt(f, token, f->curr_token); } -AstNodeArray parse_stmt_list(AstFile *f) { - AstNodeArray list = make_ast_node_array(f); +Array parse_stmt_list(AstFile *f) { + Array list = make_ast_node_array(f); while (f->curr_token.kind != Token_case && f->curr_token.kind != Token_CloseBrace && @@ -3920,8 +3962,8 @@ ParseFileError init_ast_file(AstFile *f, String fullpath) { } f->curr_token_index = 0; - f->prev_token = f->tokens.e[f->curr_token_index]; - f->curr_token = f->tokens.e[f->curr_token_index]; + f->prev_token = f->tokens[f->curr_token_index]; + f->curr_token = f->tokens[f->curr_token_index]; // NOTE(bill): Is this big enough or too small? isize arena_size = gb_size_of(AstNode); @@ -3962,7 +4004,7 @@ bool init_parser(Parser *p) { void destroy_parser(Parser *p) { // TODO(bill): Fix memory leak for_array(i, p->files) { - destroy_ast_file(&p->files.e[i]); + destroy_ast_file(&p->files[i]); } #if 0 for_array(i, p->imports) { @@ -3982,8 +4024,8 @@ bool try_add_import_path(Parser *p, String path, String rel_path, TokenPos pos) rel_path = string_trim_whitespace(rel_path); for_array(i, p->imports) { - String import = p->imports.e[i].path; - if (str_eq(import, path)) { + String import = p->imports[i].path; + if (import == path) { return false; } } @@ -4040,9 +4082,9 @@ bool is_import_path_valid(String path) { return false; } -void parse_setup_file_decls(Parser *p, AstFile *f, String base_dir, AstNodeArray decls) { +void parse_setup_file_decls(Parser *p, AstFile *f, String base_dir, Array decls) { for_array(i, decls) { - AstNode *node = decls.e[i]; + AstNode *node = decls[i]; if (!is_ast_node_decl(node) && node->kind != AstNode_BadStmt && node->kind != AstNode_EmptyStmt) { @@ -4050,16 +4092,16 @@ void parse_setup_file_decls(Parser *p, AstFile *f, String base_dir, AstNodeArray syntax_error_node(node, "Only declarations are allowed at file scope %.*s", LIT(ast_node_strings[node->kind])); } else if (node->kind == AstNode_ImportDecl) { ast_node(id, ImportDecl, node); - String collection_name = {0}; + String collection_name = {}; String oirignal_string = id->relpath.string; String file_str = id->relpath.string; gbAllocator allocator = heap_allocator(); // TODO(bill): Change this allocator - String import_file = {0}; + String import_file = {}; #if 0 isize colon_pos = -1; for (isize j = 0; j < file_str.len; j++) { - if (file_str.text[j] == ':') { + if (file_str[j] == ':') { colon_pos = j; break; } @@ -4072,24 +4114,24 @@ void parse_setup_file_decls(Parser *p, AstFile *f, String base_dir, AstNodeArray if (collection_name.len == 0) { syntax_error_node(node, "Missing import collection for path: `%.*s`", LIT(oirignal_string)); - decls.e[i] = ast_bad_decl(f, id->relpath, id->relpath); + decls[i] = ast_bad_decl(f, id->relpath, id->relpath); continue; } - if (str_eq(collection_name, str_lit("core"))) { + if (collection_name == "core") { String abs_path = get_fullpath_core(allocator, file_str); if (gb_file_exists(cast(char *)abs_path.text)) { // NOTE(bill): This should be null terminated import_file = abs_path; } - } else if (str_eq(collection_name, str_lit("local"))) { + } else if (collection_name == "local") { String rel_path = get_fullpath_relative(allocator, base_dir, file_str); if (gb_file_exists(cast(char *)rel_path.text)) { // NOTE(bill): This should be null terminated import_file = rel_path; } } else { syntax_error_node(node, "Unknown import collection: `%.*s`", LIT(collection_name)); - decls.e[i] = ast_bad_decl(f, id->relpath, id->relpath); + decls[i] = ast_bad_decl(f, id->relpath, id->relpath); continue; } @@ -4100,7 +4142,7 @@ void parse_setup_file_decls(Parser *p, AstFile *f, String base_dir, AstNodeArray syntax_error_node(node, "Invalid include path: `%.*s`", LIT(file_str)); } // NOTE(bill): It's a naughty name - decls.e[i] = ast_bad_decl(f, id->relpath, id->relpath); + decls[i] = ast_bad_decl(f, id->relpath, id->relpath); continue; } @@ -4112,7 +4154,7 @@ void parse_setup_file_decls(Parser *p, AstFile *f, String base_dir, AstNodeArray syntax_error_node(node, "Invalid include path: `%.*s`", LIT(file_str)); } // NOTE(bill): It's a naughty name - decls.e[i] = ast_bad_decl(f, id->relpath, id->relpath); + decls[i] = ast_bad_decl(f, id->relpath, id->relpath); continue; } @@ -4140,7 +4182,7 @@ void parse_setup_file_decls(Parser *p, AstFile *f, String base_dir, AstNodeArray syntax_error_node(node, "Invalid `foreign_library` path"); } // NOTE(bill): It's a naughty name - f->decls.e[i] = ast_bad_decl(f, fl->token, fl->token); + f->decls[i] = ast_bad_decl(f, fl->token, fl->token); continue; } @@ -4153,8 +4195,8 @@ void parse_file(Parser *p, AstFile *f) { String filepath = f->tokenizer.fullpath; String base_dir = filepath; for (isize i = filepath.len-1; i >= 0; i--) { - if (base_dir.text[i] == '\\' || - base_dir.text[i] == '/') { + if (base_dir[i] == '\\' || + base_dir[i] == '/') { break; } base_dir.len--; @@ -4173,7 +4215,7 @@ void parse_file(Parser *p, AstFile *f) { ParseFileError parse_files(Parser *p, char *init_filename) { char *fullpath_str = gb_path_get_full_name(heap_allocator(), init_filename); String init_fullpath = make_string_c(fullpath_str); - TokenPos init_pos = {0}; + TokenPos init_pos = {}; ImportedFile init_imported_file = {init_fullpath, init_fullpath, init_pos}; @@ -4192,17 +4234,17 @@ ParseFileError parse_files(Parser *p, char *init_filename) { p->init_fullpath = init_fullpath; for_array(i, p->imports) { - ImportedFile imported_file = p->imports.e[i]; + ImportedFile imported_file = p->imports[i]; String import_path = imported_file.path; String import_rel_path = imported_file.rel_path; TokenPos pos = imported_file.pos; - AstFile file = {0}; + AstFile file = {}; ParseFileError err = init_ast_file(&file, import_path); if (err != ParseFile_None) { if (err == ParseFile_EmptyFile) { - if (str_eq(import_path, init_fullpath)) { + if (import_path == init_fullpath) { gb_printf_err("Initial file is empty - %.*s\n", LIT(init_fullpath)); gb_exit(1); } @@ -4245,7 +4287,7 @@ ParseFileError parse_files(Parser *p, char *init_filename) { } for_array(i, p->files) { - p->total_token_count += p->files.e[i].tokens.count; + p->total_token_count += p->files[i].tokens.count; } diff --git a/src/printer.c b/src/printer.cpp similarity index 100% rename from src/printer.c rename to src/printer.cpp diff --git a/src/ssa.c b/src/ssa.cpp similarity index 93% rename from src/ssa.c rename to src/ssa.cpp index b8e3f0b8d..f3c187222 100644 --- a/src/ssa.c +++ b/src/ssa.cpp @@ -1,27 +1,21 @@ -typedef struct ssaModule ssaModule; -typedef struct ssaValue ssaValue; -typedef struct ssaValueArgs ssaValueArgs; -typedef struct ssaDefer ssaDefer; -typedef struct ssaBlock ssaBlock; -typedef struct ssaProc ssaProc; -typedef struct ssaEdge ssaEdge; -typedef struct ssaRegister ssaRegister; -typedef struct ssaTargetList ssaTargetList; -typedef enum ssaBlockKind ssaBlockKind; -typedef enum ssaBranchPrediction ssaBranchPrediction; -typedef enum ssaDeferExitKind ssaDeferExitKind; +struct ssaModule; +struct ssaValue; +struct ssaValueArgs; +struct ssaDefer; +struct ssaBlock; +struct ssaProc; +struct ssaEdge; +struct ssaRegister; +struct ssaTargetList; +enum ssaBlockKind; +enum ssaBranchPrediction; +enum ssaDeferExitKind; String ssa_mangle_name(ssaModule *m, String path, Entity *e); -#define MAP_TYPE ssaValue * -#define MAP_PROC map_ssa_value_ -#define MAP_NAME MapSsaValue -#include "map.c" -typedef Array(ssaValue *) ssaValueArray; - -#include "ssa_op.c" +#include "ssa_op.cpp" #define SSA_DEFAULT_VALUE_ARG_CAPACITY 8 struct ssaValueArgs { @@ -30,6 +24,15 @@ struct ssaValueArgs { isize capacity; ssaValue * backing[SSA_DEFAULT_VALUE_ARG_CAPACITY]; gbAllocator allocator; + + ssaValue *&operator[](isize i) { + GB_ASSERT(0 <= i && i <= count); + return e[i]; + } + ssaValue * const &operator[](isize i) const { + GB_ASSERT(0 <= i && i <= count); + return e[i]; + } }; struct ssaValue { @@ -67,10 +70,10 @@ enum ssaBranchPrediction { ssaBranch_Unlikely = -1, }; -typedef enum ssaDeferKind { +enum ssaDeferKind { ssaDefer_Node, ssaDefer_Instr, -} ssaDeferKind; +}; struct ssaDefer { ssaDeferKind kind; @@ -97,8 +100,6 @@ struct ssaEdge { isize index; }; -typedef Array(ssaEdge) ssaEdgeArray; - struct ssaBlock { i32 id; // Unique identifier but the pointer could be used too ssaBlockKind kind; @@ -115,9 +116,9 @@ struct ssaBlock { // - BlockExit will be a memory control value ssaValue *control; - ssaValueArray values; - ssaEdgeArray preds; - ssaEdgeArray succs; + Array values; + Array preds; + Array succs; }; struct ssaTargetList { @@ -134,7 +135,7 @@ struct ssaProc { Entity * entity; DeclInfo * decl_info; - Array(ssaBlock *) blocks; + Array blocks; ssaBlock * entry; // Entry block ssaBlock * exit; // Exit block ssaBlock * curr_block; @@ -143,9 +144,9 @@ struct ssaProc { i32 block_id; i32 value_id; - MapSsaValue values; // Key: Entity * + Map values; // Key: Entity * - Array(ssaDefer) defer_stmts; + Array defer_stmts; i32 scope_level; }; @@ -161,10 +162,10 @@ struct ssaModule { gbAllocator tmp_allocator; gbArena tmp_arena; - MapEntity min_dep_map; // Key: Entity * - MapSsaValue values; // Key: Entity * + Map min_dep_map; // Key: Entity * + Map values; // Key: Entity * // List of registers for the specific architecture - Array(ssaRegister) registers; + Array registers; ssaProc *proc; // current procedure @@ -172,19 +173,19 @@ struct ssaModule { u32 stmt_state_flags; - Array(ssaProc *) procs; - ssaValueArray procs_to_generate; + Array procs; + Array procs_to_generate; }; -typedef enum ssaAddrKind { +enum ssaAddrKind { ssaAddr_Default, ssaAddr_Map, -} ssaAddrKind; +}; -typedef struct ssaAddr { +struct ssaAddr { ssaValue * addr; ssaAddrKind kind; -} ssaAddr; +}; @@ -287,7 +288,7 @@ void ssa_add_arg(ssaValueArgs *va, ssaValue *arg) { } else { isize old_cap_size = va->capacity * gb_size_of(ssaValue *); isize new_cap_size = capacity * gb_size_of(ssaValue *); - va->e = gb_resize(va->allocator, va->e, old_cap_size, new_cap_size); + *(cast(void **)&va->e) = gb_resize(va->allocator, va->e, old_cap_size, new_cap_size); } va->capacity = capacity; } @@ -378,9 +379,9 @@ ssaValue *ssa_const_i64 (ssaProc *p, Type *t, i64 c) { return ssa ssaValue *ssa_const_f32 (ssaProc *p, Type *t, f32 c) { return ssa_const_val(p, ssaOp_Const32F, t, exact_value_float(c)); } ssaValue *ssa_const_f64 (ssaProc *p, Type *t, f64 c) { return ssa_const_val(p, ssaOp_Const64F, t, exact_value_float(c)); } ssaValue *ssa_const_string (ssaProc *p, Type *t, String c) { return ssa_const_val(p, ssaOp_ConstString, t, exact_value_string(c)); } -ssaValue *ssa_const_empty_string(ssaProc *p, Type *t) { return ssa_const_val(p, ssaOp_ConstString, t, (ExactValue){0}); } +ssaValue *ssa_const_empty_string(ssaProc *p, Type *t) { return ssa_const_val(p, ssaOp_ConstString, t, empty_exact_value); } ssaValue *ssa_const_slice (ssaProc *p, Type *t, ExactValue v) { return ssa_const_val(p, ssaOp_ConstSlice, t, v); } -ssaValue *ssa_const_nil (ssaProc *p, Type *t) { return ssa_const_val(p, ssaOp_ConstNil, t, (ExactValue){0}); } +ssaValue *ssa_const_nil (ssaProc *p, Type *t) { return ssa_const_val(p, ssaOp_ConstNil, t, empty_exact_value); } ssaValue *ssa_const_int(ssaProc *p, Type *t, i64 c) { switch (8*type_size_of(p->allocator, t)) { @@ -399,21 +400,21 @@ ssaValue *ssa_const_int(ssaProc *p, Type *t, i64 c) { ssaAddr ssa_build_addr (ssaProc *p, AstNode *expr); ssaValue *ssa_build_expr (ssaProc *p, AstNode *expr); void ssa_build_stmt (ssaProc *p, AstNode *node); -void ssa_build_stmt_list(ssaProc *p, AstNodeArray nodes); +void ssa_build_stmt_list(ssaProc *p, Array nodes); ssaValue *ssa_emit_deep_field_ptr_index(ssaProc *p, ssaValue *e, Selection sel); void ssa_reset_value_args(ssaValue *v) { for_array(i, v->args) { - v->args.e[i]->uses--; + v->args[i]->uses--; } v->args.count = 0; } void ssa_reset(ssaValue *v, ssaOp op) { v->op = op; - v->exact_value = (ExactValue){0}; + v->exact_value = empty_exact_value; ssa_reset_value_args(v); } @@ -425,7 +426,7 @@ ssaValue *ssa_get_last_value(ssaBlock *b) { if (len <= 0) { return 0; } - ssaValue *v = b->values.e[len-1]; + ssaValue *v = b->values[len-1]; return v; } @@ -451,7 +452,7 @@ void ssa_build_defer_stmt(ssaProc *p, ssaDefer d) { void ssa_emit_defer_stmts(ssaProc *p, ssaDeferExitKind kind, ssaBlock *b) { isize count = p->defer_stmts.count; for (isize i = count-1; i >= 0; i--) { - ssaDefer d = p->defer_stmts.e[i]; + ssaDefer d = p->defer_stmts[i]; if (kind == ssaDeferExit_Default) { gb_printf_err("scope_level %d %d\n", p->scope_level, d.scope_level); if (p->scope_level == d.scope_level && @@ -579,7 +580,7 @@ ssaProc *ssa_new_proc(ssaModule *m, String name, Entity *entity, DeclInfo *decl_ array_init(&p->blocks, heap_allocator()); array_init(&p->defer_stmts, heap_allocator()); - map_ssa_value_init(&p->values, heap_allocator()); + map_init(&p->values, heap_allocator()); return p; } @@ -592,14 +593,14 @@ ssaAddr ssa_add_local(ssaProc *p, Entity *e, AstNode *expr) { ssaValue *local = ssa_new_value0(p, ssaOp_Local, t); p->curr_block = cb; - map_ssa_value_set(&p->values, hash_pointer(e), local); - map_ssa_value_set(&p->module->values, hash_pointer(e), local); + map_set(&p->values, hash_pointer(e), local); + map_set(&p->module->values, hash_pointer(e), local); local->comment_string = e->token.string; ssa_new_value1(p, ssaOp_Zero, t, local); return ssa_addr(local); } ssaAddr ssa_add_local_for_ident(ssaProc *p, AstNode *name) { - Entity **found = map_entity_get(&p->module->info->definitions, hash_pointer(name)); + Entity **found = map_get(&p->module->info->definitions, hash_pointer(name)); if (found) { Entity *e = *found; return ssa_add_local(p, e, name); @@ -705,7 +706,7 @@ ssaValue *ssa_get_using_variable(ssaProc *p, Entity *e) { Entity *parent = e->using_parent; Selection sel = lookup_field(p->allocator, parent->type, name, false); GB_ASSERT(sel.entity != NULL); - ssaValue **pv = map_ssa_value_get(&p->module->values, hash_pointer(parent)); + ssaValue **pv = map_get(&p->module->values, hash_pointer(parent)); ssaValue *v = NULL; if (pv != NULL) { v = *pv; @@ -721,7 +722,7 @@ ssaAddr ssa_build_addr_from_entity(ssaProc *p, Entity *e, AstNode *expr) { GB_ASSERT(e != NULL); ssaValue *v = NULL; - ssaValue **found = map_ssa_value_get(&p->module->values, hash_pointer(e)); + ssaValue **found = map_get(&p->module->values, hash_pointer(e)); if (found) { v = *found; } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) { @@ -782,7 +783,7 @@ ssaValue *ssa_emit_conv(ssaProc *p, ssaValue *v, Type *t) { // NOTE(bill): Returns NULL if not possible ssaValue *ssa_address_from_load_or_generate_local(ssaProc *p, ssaValue *v) { if (v->op == ssaOp_Load) { - return v->args.e[0]; + return v->args[0]; } ssaAddr addr = ssa_add_local_generated(p, v->type); ssa_new_value2(p, ssaOp_Store, addr.addr->type, addr.addr, v); @@ -863,7 +864,7 @@ ssaValue *ssa_emit_ptr_index(ssaProc *p, ssaValue *s, i64 index) { ssaValue *ssa_emit_value_index(ssaProc *p, ssaValue *s, i64 index) { if (s->op == ssaOp_Load) { if (!can_ssa_type(s->type)) { - ssaValue *e = ssa_emit_ptr_index(p, s->args.e[0], index); + ssaValue *e = ssa_emit_ptr_index(p, s->args[0], index); return ssa_emit_load(p, e); } } @@ -930,7 +931,7 @@ ssaValue *ssa_emit_deep_field_ptr_index(ssaProc *p, ssaValue *e, Selection sel) Type *type = type_deref(e->type); for_array(i, sel.index) { - i32 index = cast(i32)sel.index.e[i]; + i32 index = cast(i32)sel.index[i]; if (is_type_pointer(type)) { type = type_deref(type); e = ssa_emit_load(p, e); @@ -994,14 +995,14 @@ ssaValue *ssa_emit_deep_field_value_index(ssaProc *p, ssaValue *e, Selection sel Type *type = e->type; if (e->op == ssaOp_Load) { if (!can_ssa_type(e->type)) { - ssaValue *ptr = ssa_emit_deep_field_ptr_index(p, e->args.e[0], sel); + ssaValue *ptr = ssa_emit_deep_field_ptr_index(p, e->args[0], sel); return ssa_emit_load(p, ptr); } } GB_ASSERT(can_ssa_type(e->type)); for_array(i, sel.index) { - i32 index = cast(i32)sel.index.e[i]; + i32 index = cast(i32)sel.index[i]; if (is_type_pointer(type)) { e = ssa_emit_load(p, e); } @@ -1071,7 +1072,7 @@ ssaAddr ssa_build_addr(ssaProc *p, AstNode *expr) { // GB_ASSERT(e->kind == Entity_Variable); // GB_ASSERT(e->flags & EntityFlag_TypeField); // String name = e->token.string; - // if (str_eq(name, str_lit("names"))) { + // if (name == "names") { // ssaValue *ti_ptr = ir_type_info(p, type); // ssaValue *names_ptr = NULL; @@ -1685,7 +1686,7 @@ ssaValue *ssa_build_expr(ssaProc *p, AstNode *expr) { case_end; case_ast_node(i, Ident, expr); - Entity *e = *map_entity_get(&p->module->info->uses, hash_pointer(expr)); + Entity *e = *map_get(&p->module->info->uses, hash_pointer(expr)); if (e->kind == Entity_Builtin) { Token token = ast_node_token(expr); GB_PANIC("TODO(bill): ssa_build_expr Entity_Builtin `%.*s`\n" @@ -1697,7 +1698,7 @@ ssaValue *ssa_build_expr(ssaProc *p, AstNode *expr) { return NULL; } - ssaValue **found = map_ssa_value_get(&p->module->values, hash_pointer(e)); + ssaValue **found = map_get(&p->module->values, hash_pointer(e)); if (found) { ssaValue *v = *found; if (v->op == ssaOp_Proc) { @@ -1835,9 +1836,9 @@ ssaValue *ssa_build_expr(ssaProc *p, AstNode *expr) { case_ast_node(ce, CallExpr, expr); - if (map_tav_get(&p->module->info->types, hash_pointer(ce->proc))->mode == Addressing_Type) { + if (map_get(&p->module->info->types, hash_pointer(ce->proc))->mode == Addressing_Type) { GB_ASSERT(ce->args.count == 1); - ssaValue *x = ssa_build_expr(p, ce->args.e[0]); + ssaValue *x = ssa_build_expr(p, ce->args[0]); return ssa_emit_conv(p, x, tv.type); } @@ -1861,9 +1862,9 @@ ssaValue *ssa_build_expr(ssaProc *p, AstNode *expr) { -void ssa_build_stmt_list(ssaProc *p, AstNodeArray nodes) { +void ssa_build_stmt_list(ssaProc *p, Array nodes) { for_array(i, nodes) { - ssa_build_stmt(p, nodes.e[i]); + ssa_build_stmt(p, nodes[i]); } } @@ -1946,7 +1947,7 @@ void ssa_build_stmt_internal(ssaProc *p, AstNode *node) { case_ast_node(us, UsingStmt, node); for_array(i, us->list) { - AstNode *decl = unparen_expr(us->list.e[i]); + AstNode *decl = unparen_expr(us->list[i]); if (decl->kind == AstNode_ValueDecl) { ssa_build_stmt(p, decl); } @@ -1973,19 +1974,19 @@ void ssa_build_stmt_internal(ssaProc *p, AstNode *node) { gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&m->tmp_arena); if (vd->values.count == 0) { for_array(i, vd->names) { - AstNode *name = vd->names.e[i]; + AstNode *name = vd->names[i]; if (!ssa_is_blank_ident(name)) { ssa_add_local_for_ident(p, name); } } } else { - Array(ssaAddr) lvals = {0}; - ssaValueArray inits = {0}; - array_init_reserve(&lvals, m->tmp_allocator, vd->names.count); - array_init_reserve(&inits, m->tmp_allocator, vd->names.count); + Array lvals = {0}; + Array inits = {0}; + array_init(&lvals, m->tmp_allocator, vd->names.count); + array_init(&inits, m->tmp_allocator, vd->names.count); for_array(i, vd->names) { - AstNode *name = vd->names.e[i]; + AstNode *name = vd->names[i]; ssaAddr lval = ssa_addr(NULL); if (!ssa_is_blank_ident(name)) { lval = ssa_add_local_for_ident(p, name); @@ -1995,7 +1996,7 @@ void ssa_build_stmt_internal(ssaProc *p, AstNode *node) { } for_array(i, vd->values) { - ssaValue *init = ssa_build_expr(p, vd->values.e[i]); + ssaValue *init = ssa_build_expr(p, vd->values[i]); if (init == NULL) { // TODO(bill): remove this continue; } @@ -2012,7 +2013,7 @@ void ssa_build_stmt_internal(ssaProc *p, AstNode *node) { } for_array(i, inits) { - ssa_addr_store(p, lvals.e[i], inits.e[i]); + ssa_addr_store(p, lvals[i], inits[i]); } } @@ -2030,11 +2031,11 @@ void ssa_build_stmt_internal(ssaProc *p, AstNode *node) { switch (as->op.kind) { case Token_Eq: { - Array(ssaAddr) lvals = {0}; + Array lvals = {0}; array_init(&lvals, m->tmp_allocator); for_array(i, as->lhs) { - AstNode *lhs = as->lhs.e[i]; + AstNode *lhs = as->lhs[i]; ssaAddr lval = {0}; if (!ssa_is_blank_ident(lhs)) { lval = ssa_build_addr(p, lhs); @@ -2044,28 +2045,28 @@ void ssa_build_stmt_internal(ssaProc *p, AstNode *node) { if (as->lhs.count == as->rhs.count) { if (as->lhs.count == 1) { - AstNode *rhs = as->rhs.e[0]; + AstNode *rhs = as->rhs[0]; ssaValue *init = ssa_build_expr(p, rhs); - ssa_addr_store(p, lvals.e[0], init); + ssa_addr_store(p, lvals[0], init); } else { - ssaValueArray inits; - array_init_reserve(&inits, m->tmp_allocator, lvals.count); + Array inits; + array_init(&inits, m->tmp_allocator, lvals.count); for_array(i, as->rhs) { - ssaValue *init = ssa_build_expr(p, as->rhs.e[i]); + ssaValue *init = ssa_build_expr(p, as->rhs[i]); array_add(&inits, init); } for_array(i, inits) { - ssa_addr_store(p, lvals.e[i], inits.e[i]); + ssa_addr_store(p, lvals[i], inits[i]); } } } else { - ssaValueArray inits; - array_init_reserve(&inits, m->tmp_allocator, lvals.count); + Array inits; + array_init(&inits, m->tmp_allocator, lvals.count); for_array(i, as->rhs) { - ssaValue *init = ssa_build_expr(p, as->rhs.e[i]); + ssaValue *init = ssa_build_expr(p, as->rhs[i]); Type *t = base_type(init->type); // TODO(bill): refactor for code reuse as this is repeated a bit if (t->kind == Type_Tuple) { @@ -2080,7 +2081,7 @@ void ssa_build_stmt_internal(ssaProc *p, AstNode *node) { } for_array(i, inits) { - ssa_addr_store(p, lvals.e[i], inits.e[i]); + ssa_addr_store(p, lvals[i], inits[i]); } } } break; @@ -2091,8 +2092,8 @@ void ssa_build_stmt_internal(ssaProc *p, AstNode *node) { // +=, -=, etc i32 op = cast(i32)as->op.kind; op += Token_Add - Token_AddEq; // Convert += to + - ssaAddr lhs = ssa_build_addr(p, as->lhs.e[0]); - ssaValue *value = ssa_build_expr(p, as->rhs.e[0]); + ssaAddr lhs = ssa_build_addr(p, as->lhs[0]); + ssaValue *value = ssa_build_expr(p, as->rhs[0]); ssa_build_assign_op(p, lhs, value, cast(TokenKind)op); } break; } @@ -2316,7 +2317,7 @@ void ssa_print_reg_value(gbFile *f, ssaValue *v) { for_array(i, v->args) { gb_fprintf(f, " "); - ssa_print_value(f, v->args.e[i]); + ssa_print_value(f, v->args[i]); } if (v->comment_string.len > 0) { @@ -2335,12 +2336,12 @@ void ssa_print_proc(gbFile *f, ssaProc *p) { bool *printed = gb_alloc_array(heap_allocator(), bool, p->value_id+1); for_array(i, p->blocks) { - ssaBlock *b = p->blocks.e[i]; + ssaBlock *b = p->blocks[i]; gb_fprintf(f, " b%d:", b->id); if (b->preds.count > 0) { gb_fprintf(f, " <-"); for_array(j, b->preds) { - ssaBlock *pred = b->preds.e[j].block; + ssaBlock *pred = b->preds[j].block; gb_fprintf(f, " b%d", pred->id); } } @@ -2351,7 +2352,7 @@ void ssa_print_proc(gbFile *f, ssaProc *p) { isize n = 0; for_array(j, b->values) { - ssaValue *v = b->values.e[j]; + ssaValue *v = b->values[j]; if (v->op != ssaOp_Phi) { continue; } @@ -2363,13 +2364,13 @@ void ssa_print_proc(gbFile *f, ssaProc *p) { while (n < b->values.count) { isize m = 0; for_array(j, b->values) { - ssaValue *v = b->values.e[j]; + ssaValue *v = b->values[j]; if (printed[v->id]) { continue; } bool skip = false; for_array(k, v->args) { - ssaValue *w = v->args.e[k]; + ssaValue *w = v->args[k]; if (w != NULL && w->block == b && !printed[w->id]) { skip = true; break; @@ -2387,7 +2388,7 @@ void ssa_print_proc(gbFile *f, ssaProc *p) { if (m == n) { gb_fprintf(f, "!!!!DepCycle!!!!\n"); for_array(k, b->values) { - ssaValue *v = b->values.e[k]; + ssaValue *v = b->values[k]; if (printed[v->id]) { continue; } @@ -2401,14 +2402,14 @@ void ssa_print_proc(gbFile *f, ssaProc *p) { if (b->kind == ssaBlock_Plain) { GB_ASSERT(b->succs.count == 1); - ssaBlock *next = b->succs.e[0].block; + ssaBlock *next = b->succs[0].block; gb_fprintf(f, " "); gb_fprintf(f, "jump b%d", next->id); gb_fprintf(f, "\n"); } else if (b->kind == ssaBlock_If) { GB_ASSERT(b->succs.count == 2); - ssaBlock *yes = b->succs.e[0].block; - ssaBlock *no = b->succs.e[1].block; + ssaBlock *yes = b->succs[0].block; + ssaBlock *no = b->succs[1].block; gb_fprintf(f, " "); gb_fprintf(f, "branch v%d, b%d, b%d", b->control->id, yes->id, no->id); gb_fprintf(f, "\n"); @@ -2479,7 +2480,7 @@ bool ssa_generate(Parser *parser, CheckerInfo *info) { m.tmp_allocator = gb_arena_allocator(&m.tmp_arena); m.allocator = gb_arena_allocator(&m.arena); - map_ssa_value_init(&m.values, heap_allocator()); + map_init(&m.values, heap_allocator()); array_init(&m.registers, heap_allocator()); array_init(&m.procs, heap_allocator()); array_init(&m.procs_to_generate, heap_allocator()); @@ -2491,21 +2492,21 @@ bool ssa_generate(Parser *parser, CheckerInfo *info) { bool has_win_main = false; for_array(i, info->entities.entries) { - MapDeclInfoEntry *entry = &info->entities.entries.e[i]; - Entity *e = cast(Entity *)cast(uintptr)entry->key.key; + auto *entry = &info->entities.entries[i]; + Entity *e = cast(Entity *)entry->key.ptr; String name = e->token.string; if (e->kind == Entity_Variable) { global_variable_max_count++; } else if (e->kind == Entity_Procedure && !e->scope->is_global) { - if (e->scope->is_init && str_eq(name, str_lit("main"))) { + if (e->scope->is_init && name == "main") { entry_point = e; } if ((e->Procedure.tags & ProcTag_export) != 0 || (e->Procedure.link_name.len > 0) || (e->scope->is_file && e->Procedure.link_name.len > 0)) { - if (!has_dll_main && str_eq(name, str_lit("DllMain"))) { + if (!has_dll_main && name == "DllMain") { has_dll_main = true; - } else if (!has_win_main && str_eq(name, str_lit("WinMain"))) { + } else if (!has_win_main && name == "WinMain") { has_win_main = true; } } @@ -2517,7 +2518,7 @@ bool ssa_generate(Parser *parser, CheckerInfo *info) { m.min_dep_map = generate_minimum_dependency_map(info, entry_point); for_array(i, info->entities.entries) { - MapDeclInfoEntry *entry = &info->entities.entries.e[i]; + auto *entry = &info->entities.entries[i]; Entity *e = cast(Entity *)entry->key.ptr; String name = e->token.string; DeclInfo *decl = entry->value; @@ -2527,7 +2528,7 @@ bool ssa_generate(Parser *parser, CheckerInfo *info) { continue; } - if (map_entity_get(&m.min_dep_map, hash_pointer(e)) == NULL) { + if (map_get(&m.min_dep_map, hash_pointer(e)) == NULL) { // NOTE(bill): Nothing depends upon it so doesn't need to be built continue; } @@ -2536,7 +2537,7 @@ bool ssa_generate(Parser *parser, CheckerInfo *info) { if (e->kind == Entity_Procedure && (e->Procedure.tags & ProcTag_export) != 0) { } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) { // Handle later - } else if (scope->is_init && e->kind == Entity_Procedure && str_eq(name, str_lit("main"))) { + } else if (scope->is_init && e->kind == Entity_Procedure && name == "main") { } else { name = ssa_mangle_name(&m, e->token.pos.file, e); } @@ -2574,8 +2575,8 @@ bool ssa_generate(Parser *parser, CheckerInfo *info) { // ssa_module_add_value(m, e, p); // HashKey hash_name = hash_string(name); - // if (map_ssa_value_get(&m.members, hash_name) == NULL) { - // map_ssa_value_set(&m.members, hash_name, p); + // if (map_get(&m.members, hash_name) == NULL) { + // map_set(&m.members, hash_name, p); // } } break; } @@ -2595,7 +2596,7 @@ String ssa_mangle_name(ssaModule *m, String path, Entity *e) { String name = e->token.string; CheckerInfo *info = m->info; gbAllocator a = m->allocator; - AstFile *file = *map_ast_file_get(&info->files, hash_string(path)); + AstFile *file = *map_get(&info->files, hash_string(path)); char *str = gb_alloc_array(a, char, path.len+1); gb_memmove(str, path.text, path.len); diff --git a/src/ssa_op.c b/src/ssa_op.cpp similarity index 99% rename from src/ssa_op.c rename to src/ssa_op.cpp index 4c1921065..c62e7cf77 100644 --- a/src/ssa_op.c +++ b/src/ssa_op.cpp @@ -267,7 +267,6 @@ enum ssaOp { SSA_OPS #undef SSA_OP }; -typedef enum ssaOp ssaOp; String const ssa_op_strings[] = { #define SSA_OP(k) {cast(u8 *)#k, gb_size_of(#k)-1}, diff --git a/src/string.c b/src/string.cpp similarity index 79% rename from src/string.c rename to src/string.cpp index 139a46138..6b6302ede 100644 --- a/src/string.c +++ b/src/string.cpp @@ -1,5 +1,5 @@ -gb_global gbArena string_buffer_arena = {0}; -gb_global gbAllocator string_buffer_allocator = {0}; +gb_global gbArena string_buffer_arena = {}; +gb_global gbAllocator string_buffer_allocator = {}; void init_string_buffer_memory(void) { // NOTE(bill): This should be enough memory for file systems @@ -9,21 +9,38 @@ void init_string_buffer_memory(void) { // NOTE(bill): Used for UTF-8 strings -typedef struct String { +struct String { u8 * text; isize len; -} String; + + u8 &operator[](isize i) { + GB_ASSERT(0 <= i && i < len); + return text[i]; + } + u8 const &operator[](isize i) const { + GB_ASSERT(0 <= i && i < len); + return text[i]; + } +}; // NOTE(bill): used for printf style arguments #define LIT(x) ((int)(x).len), (x).text #define STR_LIT(c_str) {cast(u8 *)c_str, gb_size_of(c_str)-1} -#define str_lit(c_str) (String){cast(u8 *)c_str, gb_size_of(c_str)-1} +#define str_lit(c_str) String{cast(u8 *)c_str, gb_size_of(c_str)-1} // NOTE(bill): String16 is only used for Windows due to its file directories -typedef struct String16 { +struct String16 { wchar_t *text; isize len; -} String16; + wchar_t &operator[](isize i) { + GB_ASSERT(0 <= i && i < len); + return text[i]; + } + wchar_t const &operator[](isize i) const { + GB_ASSERT(0 <= i && i < len); + return text[i]; + } +}; gb_inline String make_string(u8 *text, isize len) { @@ -56,8 +73,8 @@ gb_inline bool str_eq_ignore_case(String a, String b) { if (a.len == b.len) { isize i; for (i = 0; i < a.len; i++) { - char x = cast(char)a.text[i]; - char y = cast(char)b.text[i]; + char x = cast(char)a[i]; + char y = cast(char)b[i]; if (gb_char_to_lower(x) != gb_char_to_lower(y)) return false; } @@ -88,16 +105,16 @@ int string_compare(String x, String y) { for (; curr_block < fast; curr_block++) { if (la[curr_block] ^ lb[curr_block]) { for (pos = curr_block*gb_size_of(isize); pos < n; pos++) { - if (x.text[pos] ^ y.text[pos]) { - return cast(int)x.text[pos] - cast(int)y.text[pos]; + if (x[pos] ^ y[pos]) { + return cast(int)x[pos] - cast(int)y[pos]; } } } } for (; offset < n; offset++) { - if (x.text[offset] ^ y.text[offset]) { - return cast(int)x.text[offset] - cast(int)y.text[offset]; + if (x[offset] ^ y[offset]) { + return cast(int)x[offset] - cast(int)y[offset]; } } } @@ -117,13 +134,29 @@ gb_inline bool str_gt(String a, String b) { return string_compare(a, b) > 0; gb_inline bool str_le(String a, String b) { return string_compare(a, b) <= 0; } gb_inline bool str_ge(String a, String b) { return string_compare(a, b) >= 0; } +bool operator == (String a, String b) { return str_eq(a, b); } +bool operator != (String a, String b) { return str_ne(a, b); } +bool operator < (String a, String b) { return str_lt(a, b); } +bool operator > (String a, String b) { return str_gt(a, b); } +bool operator <= (String a, String b) { return str_le(a, b); } +bool operator >= (String a, String b) { return str_ge(a, b); } + +template bool operator == (String a, char const (&b)[N]) { return str_eq(a, make_string(cast(u8 *)b, N-1)); } +template bool operator != (String a, char const (&b)[N]) { return str_ne(a, make_string(cast(u8 *)b, N-1)); } +template bool operator < (String a, char const (&b)[N]) { return str_lt(a, make_string(cast(u8 *)b, N-1)); } +template bool operator > (String a, char const (&b)[N]) { return str_gt(a, make_string(cast(u8 *)b, N-1)); } +template bool operator <= (String a, char const (&b)[N]) { return str_le(a, make_string(cast(u8 *)b, N-1)); } +template bool operator >= (String a, char const (&b)[N]) { return str_ge(a, make_string(cast(u8 *)b, N-1)); } + + + gb_inline bool str_has_prefix(String s, String prefix) { isize i; if (prefix.len < s.len) { return false; } for (i = 0; i < prefix.len; i++) { - if (s.text[i] != prefix.text[i]) { + if (s[i] != prefix[i]) { return false; } } @@ -135,9 +168,9 @@ gb_inline isize string_extension_position(String str) { isize i = str.len; bool seen_dot = false; while (i --> 0) { - if (str.text[i] == GB_PATH_SEPARATOR) + if (str[i] == GB_PATH_SEPARATOR) break; - if (str.text[i] == '.') { + if (str[i] == '.') { dot_pos = i; break; } @@ -147,11 +180,11 @@ gb_inline isize string_extension_position(String str) { } String string_trim_whitespace(String str) { - while (str.len > 0 && rune_is_whitespace(str.text[str.len-1])) { + while (str.len > 0 && rune_is_whitespace(str[str.len-1])) { str.len--; } - while (str.len > 0 && rune_is_whitespace(str.text[0])) { + while (str.len > 0 && rune_is_whitespace(str[0])) { str.text++; str.len--; } @@ -166,7 +199,7 @@ gb_inline bool string_has_extension(String str, String ext) { } isize len = str.len; for (isize i = len-1; i >= 0; i--) { - if (str.text[i] == '.') { + if (str[i] == '.') { break; } len--; @@ -182,7 +215,7 @@ gb_inline bool string_has_extension(String str, String ext) { bool string_contains_char(String s, u8 c) { isize i; for (i = 0; i < s.len; i++) { - if (s.text[i] == c) + if (s[i] == c) return true; } return false; @@ -194,8 +227,8 @@ String filename_from_path(String s) { isize j = 0; s.len = i; for (j = i-1; j >= 0; j--) { - if (s.text[j] == '/' || - s.text[j] == '\\') { + if (s[j] == '/' || + s[j] == '\\') { break; } } @@ -315,18 +348,18 @@ String string16_to_string(gbAllocator a, String16 s) { bool unquote_char(String s, u8 quote, Rune *rune, bool *multiple_bytes, String *tail_string) { u8 c; - if (s.text[0] == quote && + if (s[0] == quote && (quote == '\'' || quote == '"')) { return false; - } else if (s.text[0] >= 0x80) { + } else if (s[0] >= 0x80) { Rune r = -1; isize size = gb_utf8_decode(s.text, s.len, &r); *rune = r; *multiple_bytes = true; *tail_string = make_string(s.text+size, s.len-size); return true; - } else if (s.text[0] != '\\') { - *rune = s.text[0]; + } else if (s[0] != '\\') { + *rune = s[0]; *tail_string = make_string(s.text+1, s.len-1); return true; } @@ -334,7 +367,7 @@ bool unquote_char(String s, u8 quote, Rune *rune, bool *multiple_bytes, String * if (s.len <= 1) { return false; } - c = s.text[1]; + c = s[1]; s = make_string(s.text+2, s.len-2); switch (c) { @@ -372,7 +405,7 @@ bool unquote_char(String s, u8 quote, Rune *rune, bool *multiple_bytes, String * return false; } for (i = 0; i < 2; i++) { - i32 d = gb_digit_to_int(s.text[i]); + i32 d = gb_digit_to_int(s[i]); if (d < 0 || d > 7) { return false; } @@ -400,7 +433,7 @@ bool unquote_char(String s, u8 quote, Rune *rune, bool *multiple_bytes, String * return false; } for (i = 0; i < count; i++) { - i32 d = gb_hex_digit_to_int(s.text[i]); + i32 d = gb_hex_digit_to_int(s[i]); if (d < 0) { return false; } @@ -433,8 +466,8 @@ i32 unquote_string(gbAllocator a, String *s_) { if (n < 2) { return 0; } - quote = s.text[0]; - if (quote != s.text[n-1]) { + quote = s[0]; + if (quote != s[n-1]) { return 0; } s.text += 1; @@ -471,12 +504,12 @@ i32 unquote_string(gbAllocator a, String *s_) { { - u8 rune_temp[4] = {0}; + u8 rune_temp[4] = {}; isize buf_len = 3*s.len / 2; u8 *buf = gb_alloc_array(a, u8, buf_len); isize offset = 0; while (s.len > 0) { - String tail_string = {0}; + String tail_string = {}; Rune r = 0; bool multiple_bytes = false; bool success = unquote_char(s, quote, &r, &multiple_bytes, &tail_string); diff --git a/src/timings.c b/src/timings.cpp similarity index 90% rename from src/timings.c rename to src/timings.cpp index 046f476fe..27ee1f3a4 100644 --- a/src/timings.c +++ b/src/timings.cpp @@ -1,14 +1,14 @@ -typedef struct TimeStamp { +struct TimeStamp { u64 start; u64 finish; String label; -} TimeStamp; +}; -typedef struct Timings { +struct Timings { TimeStamp total; - Array(TimeStamp) sections; + Array sections; u64 freq; -} Timings; +}; #if defined(GB_SYSTEM_WINDOWS) @@ -83,7 +83,7 @@ TimeStamp make_time_stamp(String label) { } void timings_init(Timings *t, String label, isize buffer_size) { - array_init_reserve(&t->sections, heap_allocator(), buffer_size); + array_init(&t->sections, heap_allocator(), buffer_size); t->total = make_time_stamp(label); t->freq = time_stamp__freq(); } @@ -94,7 +94,7 @@ void timings_destroy(Timings *t) { void timings__stop_current_section(Timings *t) { if (t->sections.count > 0) { - t->sections.e[t->sections.count-1].finish = time_stamp_time_now(); + t->sections[t->sections.count-1].finish = time_stamp_time_now(); } } @@ -110,14 +110,14 @@ f64 time_stamp_as_ms(TimeStamp ts, u64 freq) { void timings_print_all(Timings *t) { char const SPACES[] = " "; - isize max_len, i; + isize max_len; timings__stop_current_section(t); t->total.finish = time_stamp_time_now(); max_len = t->total.label.len; for_array(i, t->sections) { - TimeStamp ts = t->sections.e[i]; + TimeStamp ts = t->sections[i]; max_len = gb_max(max_len, ts.label.len); } @@ -129,7 +129,7 @@ void timings_print_all(Timings *t) { time_stamp_as_ms(t->total, t->freq)); for_array(i, t->sections) { - TimeStamp ts = t->sections.e[i]; + TimeStamp ts = t->sections[i]; gb_printf("%.*s%.*s - %.3f ms\n", LIT(ts.label), cast(int)(max_len-ts.label.len), SPACES, diff --git a/src/tokenizer.c b/src/tokenizer.cpp similarity index 97% rename from src/tokenizer.c rename to src/tokenizer.cpp index 459fca163..38026deeb 100644 --- a/src/tokenizer.c +++ b/src/tokenizer.cpp @@ -117,11 +117,11 @@ TOKEN_KIND(Token__KeywordBegin, "_KeywordBegin"), \ TOKEN_KIND(Token__KeywordEnd, "_KeywordEnd"), \ TOKEN_KIND(Token_Count, "") -typedef enum TokenKind { +enum TokenKind { #define TOKEN_KIND(e, s) e TOKEN_KINDS #undef TOKEN_KIND -} TokenKind; +}; String const token_strings[] = { #define TOKEN_KIND(e, s) {cast(u8 *)s, gb_size_of(s)-1} @@ -130,11 +130,11 @@ String const token_strings[] = { }; -typedef struct TokenPos { +struct TokenPos { String file; isize line; isize column; -} TokenPos; +}; i32 token_pos_cmp(TokenPos a, TokenPos b) { if (a.line == b.line) { @@ -152,11 +152,11 @@ bool token_pos_eq(TokenPos a, TokenPos b) { return token_pos_cmp(a, b) == 0; } -typedef struct Token { +struct Token { TokenKind kind; String string; TokenPos pos; -} Token; +}; Token empty_token = {Token_Invalid}; Token blank_token = {Token_Ident, {cast(u8 *)"_", 1}}; @@ -167,12 +167,12 @@ Token make_token_ident(String s) { } -typedef struct ErrorCollector { +struct ErrorCollector { TokenPos prev; i64 count; i64 warning_count; gbMutex mutex; -} ErrorCollector; +}; gb_global ErrorCollector global_error_collector; @@ -306,7 +306,7 @@ gb_inline bool token_is_shift(TokenKind t) { gb_inline void print_token(Token t) { gb_printf("%.*s\n", LIT(t.string)); } -typedef enum TokenizerInitError { +enum TokenizerInitError { TokenizerInit_None, TokenizerInit_Invalid, @@ -315,18 +315,18 @@ typedef enum TokenizerInitError { TokenizerInit_Empty, TokenizerInit_Count, -} TokenizerInitError; +}; -typedef struct TokenizerState { +struct TokenizerState { Rune curr_rune; // current character u8 * curr; // character pos u8 * read_curr; // pos from start u8 * line; // current line pos isize line_count; -} TokenizerState; +}; -typedef struct Tokenizer { +struct Tokenizer { String fullpath; u8 *start; u8 *end; @@ -338,12 +338,12 @@ typedef struct Tokenizer { isize line_count; isize error_count; - Array(String) allocated_strings; -} Tokenizer; + Array allocated_strings; +}; TokenizerState save_tokenizer_state(Tokenizer *t) { - TokenizerState state = {0}; + TokenizerState state = {}; state.curr_rune = t->curr_rune; state.curr = t->curr; state.read_curr = t->read_curr; @@ -435,7 +435,7 @@ TokenizerInitError init_tokenizer(Tokenizer *t, String fullpath) { array_init(&t->allocated_strings, heap_allocator()); } else { - gbFile f = {0}; + gbFile f = {}; gbFileError file_err = gb_file_open(&f, c_str); switch (file_err) { @@ -460,7 +460,7 @@ gb_inline void destroy_tokenizer(Tokenizer *t) { gb_free(heap_allocator(), t->start); } for_array(i, t->allocated_strings) { - gb_free(heap_allocator(), t->allocated_strings.e[i].text); + gb_free(heap_allocator(), t->allocated_strings[i].text); } array_free(&t->allocated_strings); } @@ -492,7 +492,7 @@ gb_inline void scan_mantissa(Tokenizer *t, i32 base) { } Token scan_number_to_token(Tokenizer *t, bool seen_decimal_point) { - Token token = {0}; + Token token = {}; token.kind = Token_Integer; token.string = make_string(t->curr, 1); token.pos.file = t->fullpath; @@ -742,7 +742,7 @@ bool tokenizer_find_line_end(Tokenizer *t) { Token tokenizer_get_token(Tokenizer *t) { tokenizer_skip_whitespace(t); - Token token = {0}; + Token token = {}; token.string = make_string(t->curr, 1); token.pos.file = t->fullpath; token.pos.line = t->line_count; @@ -760,7 +760,7 @@ Token tokenizer_get_token(Tokenizer *t) { // NOTE(bill): All keywords are > 1 if (token.string.len > 1) { for (i32 k = Token__KeywordBegin+1; k < Token__KeywordEnd; k++) { - if (str_eq(token.string, token_strings[k])) { + if (token.string == token_strings[k]) { token.kind = cast(TokenKind)k; break; } @@ -963,7 +963,7 @@ Token tokenizer_get_token(Tokenizer *t) { default: if (curr_rune != GB_RUNE_BOM) { - u8 str[4] = {0}; + u8 str[4] = {}; int len = cast(int)gb_utf8_encode_rune(str, curr_rune); tokenizer_err(t, "Illegal character: %.*s (%d) ", len, str, curr_rune); } diff --git a/src/types.c b/src/types.cpp similarity index 97% rename from src/types.c rename to src/types.cpp index c98046a22..f8b6eba16 100644 --- a/src/types.c +++ b/src/types.cpp @@ -1,6 +1,6 @@ -typedef struct Scope Scope; +struct Scope; -typedef enum BasicKind { +enum BasicKind { Basic_Invalid, Basic_bool, Basic_i8, @@ -41,9 +41,9 @@ typedef enum BasicKind { Basic_COUNT, Basic_byte = Basic_u8, -} BasicKind; +}; -typedef enum BasicFlag { +enum BasicFlag { BasicFlag_Boolean = GB_BIT(0), BasicFlag_Integer = GB_BIT(1), BasicFlag_Unsigned = GB_BIT(2), @@ -57,16 +57,16 @@ typedef enum BasicFlag { BasicFlag_Numeric = BasicFlag_Integer | BasicFlag_Float | BasicFlag_Complex, BasicFlag_Ordered = BasicFlag_Integer | BasicFlag_Float | BasicFlag_String | BasicFlag_Pointer | BasicFlag_Rune, BasicFlag_ConstantType = BasicFlag_Boolean | BasicFlag_Numeric | BasicFlag_String | BasicFlag_Pointer | BasicFlag_Rune, -} BasicFlag; +}; -typedef struct BasicType { +struct BasicType { BasicKind kind; u32 flags; i64 size; // -1 if arch. dep. String name; -} BasicType; +}; -typedef enum TypeRecordKind { +enum TypeRecordKind { TypeRecord_Invalid, TypeRecord_Struct, @@ -75,9 +75,9 @@ typedef enum TypeRecordKind { TypeRecord_Enum, TypeRecord_Count, -} TypeRecordKind; +}; -typedef struct TypeRecord { +struct TypeRecord { TypeRecordKind kind; // All record types @@ -109,7 +109,7 @@ typedef struct TypeRecord { Entity * enum_count; Entity * enum_min_value; Entity * enum_max_value; -} TypeRecord; +}; #define TYPE_KINDS \ TYPE_KIND(Basic, BasicType) \ @@ -164,13 +164,13 @@ typedef struct TypeRecord { -typedef enum TypeKind { +enum TypeKind { Type_Invalid, #define TYPE_KIND(k, ...) GB_JOIN2(Type_, k), TYPE_KINDS #undef TYPE_KIND Type_Count, -} TypeKind; +}; String const type_strings[] = { {cast(u8 *)"Invalid", gb_size_of("Invalid")}, @@ -183,7 +183,7 @@ String const type_strings[] = { TYPE_KINDS #undef TYPE_KIND -typedef struct Type { +struct Type { TypeKind kind; union { #define TYPE_KIND(k, ...) GB_JOIN2(Type, k) k; @@ -191,19 +191,19 @@ typedef struct Type { #undef TYPE_KIND }; bool failure; -} Type; +}; // TODO(bill): Should I add extra information here specifying the kind of selection? // e.g. field, constant, vector field, type field, etc. -typedef struct Selection { - Entity * entity; - Array_i32 index; - bool indirect; // Set if there was a pointer deref anywhere down the line -} Selection; +struct Selection { + Entity * entity; + Array index; + bool indirect; // Set if there was a pointer deref anywhere down the line +}; Selection empty_selection = {0}; -Selection make_selection(Entity *entity, Array_i32 index, bool indirect) { +Selection make_selection(Entity *entity, Array index, bool indirect) { Selection s = {entity, index, indirect}; return s; } @@ -212,10 +212,10 @@ void selection_add_index(Selection *s, isize index) { // IMPORTANT NOTE(bill): this requires a stretchy buffer/dynamic array so it requires some form // of heap allocation // TODO(bill): Find a way to use a backing buffer for initial use as the general case is probably .count<3 - if (s->index.e == NULL) { + if (s->index.data == NULL) { array_init(&s->index, heap_allocator()); } - array_add(&s->index, index); + array_add(&s->index, cast(i32)index); } @@ -1025,7 +1025,7 @@ bool are_types_identical(Type *x, Type *y) { if (!are_types_identical(xf->type, yf->type)) { return false; } - if (str_ne(xf->token.string, yf->token.string)) { + if (xf->token.string != yf->token.string) { return false; } bool xf_is_using = (xf->flags&EntityFlag_Using) != 0; @@ -1039,7 +1039,7 @@ bool are_types_identical(Type *x, Type *y) { if (!are_types_identical(x->Record.variants[i]->type, y->Record.variants[i]->type)) { return false; } - if (str_ne(x->Record.variants[i]->token.string, y->Record.variants[i]->token.string)) { + if (x->Record.variants[i]->token.string != y->Record.variants[i]->token.string) { return false; } } @@ -1199,7 +1199,7 @@ bool is_type_cte_safe(Type *type) { return false; } -typedef enum ProcTypeOverloadKind { +enum ProcTypeOverloadKind { ProcOverload_Identical, // The types are identical ProcOverload_CallingConvention, @@ -1211,7 +1211,7 @@ typedef enum ProcTypeOverloadKind { ProcOverload_NotProcedure, -} ProcTypeOverloadKind; +}; ProcTypeOverloadKind are_proc_types_overload_safe(Type *x, Type *y) { if (x == NULL && y == NULL) return ProcOverload_NotProcedure; @@ -1297,9 +1297,9 @@ Selection lookup_field_from_index(gbAllocator a, Type *type, i64 index) { Entity *f = type->Record.fields[i]; if (f->kind == Entity_Variable) { if (f->Variable.field_src_index == index) { - Array_i32 sel_array = {0}; + Array sel_array = {0}; array_init_count(&sel_array, a, 1); - sel_array.e[0] = i; + sel_array[0] = i; return make_selection(f, sel_array, false); } } @@ -1309,18 +1309,18 @@ Selection lookup_field_from_index(gbAllocator a, Type *type, i64 index) { for (isize i = 0; i < max_count; i++) { Entity *f = type->Tuple.variables[i]; if (i == index) { - Array_i32 sel_array = {0}; + Array sel_array = {0}; array_init_count(&sel_array, a, 1); - sel_array.e[0] = i; + sel_array[0] = i; return make_selection(f, sel_array, false); } } break; case Type_BitField: { - Array_i32 sel_array = {0}; + Array sel_array = {0}; array_init_count(&sel_array, a, 1); - sel_array.e[0] = cast(i32)index; + sel_array[0] = cast(i32)index; return make_selection(type->BitField.fields[index], sel_array, false); } break; @@ -1337,7 +1337,7 @@ gb_global Entity *entity__any_type_info = NULL; Selection lookup_field_with_selection(gbAllocator a, Type *type_, String field_name, bool is_type, Selection sel) { GB_ASSERT(type_ != NULL); - if (str_eq(field_name, str_lit("_"))) { + if (field_name == "_") { return empty_selection; } @@ -1362,11 +1362,11 @@ Selection lookup_field_with_selection(gbAllocator a, Type *type_, String field_n entity__any_type_info = make_entity_field(a, NULL, make_token_ident(type_info_str), t_type_info_ptr, false, 1); } - if (str_eq(field_name, data_str)) { + if (field_name == data_str) { selection_add_index(&sel, 0); sel.entity = entity__any_data;; return sel; - } else if (str_eq(field_name, type_info_str)) { + } else if (field_name == type_info_str) { selection_add_index(&sel, 1); sel.entity = entity__any_type_info; return sel; @@ -1382,7 +1382,7 @@ Selection lookup_field_with_selection(gbAllocator a, Type *type_, String field_n switch (type->Vector.count) { #define _VECTOR_FIELD_CASE(_length, _name) \ case (_length): \ - if (str_eq(field_name, str_lit(_name))) { \ + if (field_name == _name) { \ selection_add_index(&sel, (_length)-1); \ sel.entity = make_entity_vector_elem(a, NULL, make_token_ident(str_lit(_name)), type->Vector.elem, (_length)-1); \ return sel; \ @@ -1403,7 +1403,7 @@ Selection lookup_field_with_selection(gbAllocator a, Type *type_, String field_n if (is_type) { if (type->kind == Type_Record) { if (type->Record.names != NULL && - str_eq(field_name, str_lit("names"))) { + field_name == "names") { sel.entity = type->Record.names; return sel; } @@ -1415,7 +1415,7 @@ Selection lookup_field_with_selection(gbAllocator a, Type *type_, String field_n GB_ASSERT(f->kind == Entity_TypeName); String str = f->token.string; - if (str_eq(str, field_name)) { + if (str == field_name) { sel.entity = f; // selection_add_index(&sel, i); return sel; @@ -1424,15 +1424,15 @@ Selection lookup_field_with_selection(gbAllocator a, Type *type_, String field_n } else if (is_type_enum(type)) { // NOTE(bill): These may not have been added yet, so check in case if (type->Record.enum_count != NULL) { - if (str_eq(field_name, str_lit("count"))) { + if (field_name == "count") { sel.entity = type->Record.enum_count; return sel; } - if (str_eq(field_name, str_lit("min_value"))) { + if (field_name == "min_value") { sel.entity = type->Record.enum_min_value; return sel; } - if (str_eq(field_name, str_lit("max_value"))) { + if (field_name == "max_value") { sel.entity = type->Record.enum_max_value; return sel; } @@ -1443,7 +1443,7 @@ Selection lookup_field_with_selection(gbAllocator a, Type *type_, String field_n GB_ASSERT(f->kind == Entity_Constant); String str = f->token.string; - if (str_eq(field_name, str)) { + if (field_name == str) { sel.entity = f; // selection_add_index(&sel, i); return sel; @@ -1457,7 +1457,7 @@ Selection lookup_field_with_selection(gbAllocator a, Type *type_, String field_n continue; } String str = f->token.string; - if (str_eq(field_name, str)) { + if (field_name == str) { selection_add_index(&sel, i); // HACK(bill): Leaky memory sel.entity = f; return sel; @@ -1479,7 +1479,7 @@ Selection lookup_field_with_selection(gbAllocator a, Type *type_, String field_n } } if (type->Record.kind == TypeRecord_Union) { - if (str_eq(field_name, str_lit("__tag"))) { + if (field_name == "__tag") { Entity *e = type->Record.union__tag; GB_ASSERT(e != NULL); selection_add_index(&sel, -1); // HACK(bill): Leaky memory @@ -1496,7 +1496,7 @@ Selection lookup_field_with_selection(gbAllocator a, Type *type_, String field_n } String str = f->token.string; - if (str_eq(field_name, str)) { + if (field_name == str) { selection_add_index(&sel, i); // HACK(bill): Leaky memory sel.entity = f; return sel; @@ -1508,10 +1508,10 @@ Selection lookup_field_with_selection(gbAllocator a, Type *type_, String field_n } -typedef struct TypePath { - Array(Type *) path; // Entity_TypeName; +struct TypePath { + Array path; // Entity_TypeName; bool failure; -} TypePath; +}; void type_path_init(TypePath *tp) { // TODO(bill): Use an allocator that uses a backing array if it can and then use alternative allocator when exhausted @@ -1526,7 +1526,7 @@ void type_path_print_illegal_cycle(TypePath *tp, isize start_index) { GB_ASSERT(tp != NULL); GB_ASSERT(start_index < tp->path.count); - Type *t = tp->path.e[start_index]; + Type *t = tp->path[start_index]; GB_ASSERT(t != NULL); GB_ASSERT_MSG(is_type_named(t), "%s", type_to_string(t)); @@ -1534,7 +1534,7 @@ void type_path_print_illegal_cycle(TypePath *tp, isize start_index) { error(e->token, "Illegal declaration cycle of `%.*s`", LIT(t->Named.name)); // NOTE(bill): Print cycle, if it's deep enough for (isize j = start_index; j < tp->path.count; j++) { - Type *t = tp->path.e[j]; + Type *t = tp->path[j]; GB_ASSERT_MSG(is_type_named(t), "%s", type_to_string(t)); Entity *e = t->Named.type_name; error(e->token, "\t%.*s refers to", LIT(t->Named.name)); @@ -1549,7 +1549,7 @@ TypePath *type_path_push(TypePath *tp, Type *t) { GB_ASSERT(tp != NULL); for (isize i = 0; i < tp->path.count; i++) { - if (tp->path.e[i] == t) { + if (tp->path[i] == t) { type_path_print_illegal_cycle(tp, i); } } @@ -1617,7 +1617,7 @@ i64 type_align_of_internal(gbAllocator allocator, Type *t, TypePath *path) { switch (t->kind) { case Type_Basic: { GB_ASSERT(is_type_typed(t)); - switch (t->kind) { + switch (t->Basic.kind) { case Basic_string: return build_context.word_size; case Basic_any: return build_context.word_size; @@ -2082,7 +2082,7 @@ i64 type_offset_of_from_selection(gbAllocator allocator, Type *type, Selection s Type *t = type; i64 offset = 0; for_array(i, sel.index) { - isize index = sel.index.e[i]; + isize index = sel.index[i]; t = base_type(t); offset += type_offset_of(allocator, t, index); if (t->kind == Type_Record && t->Record.kind == TypeRecord_Struct) { @@ -2291,7 +2291,7 @@ gbString write_type_to_string(gbString str, Type *type) { } if (var->flags&EntityFlag_Ellipsis) { Type *slice = base_type(var->type); - str = gb_string_appendc(str, "..."); + str = gb_string_appendc(str, ".."); GB_ASSERT(is_type_slice(var->type)); str = write_type_to_string(str, slice->Slice.elem); } else { diff --git a/src/unicode.c b/src/unicode.cpp similarity index 98% rename from src/unicode.c rename to src/unicode.cpp index c1277c4da..538e6adce 100644 --- a/src/unicode.c +++ b/src/unicode.cpp @@ -1,9 +1,10 @@ #pragma warning(push) #pragma warning(disable: 4245) +extern "C" { // #include "utf8proc/utf8proc.h" #include "utf8proc/utf8proc.c" - +} #pragma warning(pop) diff --git a/src/utf8proc/utf8proc.c b/src/utf8proc/utf8proc.c index c14bbe13f..f637390f7 100644 --- a/src/utf8proc/utf8proc.c +++ b/src/utf8proc/utf8proc.c @@ -383,7 +383,7 @@ UTF8PROC_DLLEXPORT int utf8proc_charwidth(utf8proc_int32_t c) { } UTF8PROC_DLLEXPORT utf8proc_category_t utf8proc_category(utf8proc_int32_t c) { - return utf8proc_get_property(c)->category; + return cast(utf8proc_category_t)utf8proc_get_property(c)->category; } UTF8PROC_DLLEXPORT const char *utf8proc_category_string(utf8proc_int32_t c) { @@ -393,15 +393,15 @@ UTF8PROC_DLLEXPORT const char *utf8proc_category_string(utf8proc_int32_t c) { #define utf8proc_decompose_lump(replacement_uc) \ return utf8proc_decompose_char((replacement_uc), dst, bufsize, \ - options & ~UTF8PROC_LUMP, last_boundclass) + (utf8proc_option_t)(options & ~UTF8PROC_LUMP), last_boundclass) UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_decompose_char(utf8proc_int32_t uc, utf8proc_int32_t *dst, utf8proc_ssize_t bufsize, utf8proc_option_t options, int *last_boundclass) { const utf8proc_property_t *property; - utf8proc_propval_t category; + utf8proc_category_t category; utf8proc_int32_t hangul_sindex; if (uc < 0 || uc >= 0x110000) return UTF8PROC_ERROR_NOTASSIGNED; property = unsafe_get_property(uc); - category = property->category; + category = cast(utf8proc_category_t)property->category; hangul_sindex = uc - UTF8PROC_HANGUL_SBASE; if (options & (UTF8PROC_COMPOSE|UTF8PROC_DECOMPOSE)) { if (hangul_sindex >= 0 && hangul_sindex < UTF8PROC_HANGUL_SCOUNT) { @@ -728,28 +728,24 @@ UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_map_custom( UTF8PROC_DLLEXPORT utf8proc_uint8_t *utf8proc_NFD(const utf8proc_uint8_t *str) { utf8proc_uint8_t *retval; - utf8proc_map(str, 0, &retval, UTF8PROC_NULLTERM | UTF8PROC_STABLE | - UTF8PROC_DECOMPOSE); + utf8proc_map(str, 0, &retval, cast(utf8proc_option_t)(UTF8PROC_NULLTERM|UTF8PROC_STABLE|UTF8PROC_DECOMPOSE)); return retval; } UTF8PROC_DLLEXPORT utf8proc_uint8_t *utf8proc_NFC(const utf8proc_uint8_t *str) { utf8proc_uint8_t *retval; - utf8proc_map(str, 0, &retval, UTF8PROC_NULLTERM | UTF8PROC_STABLE | - UTF8PROC_COMPOSE); + utf8proc_map(str, 0, &retval, cast(utf8proc_option_t)(UTF8PROC_NULLTERM|UTF8PROC_STABLE|UTF8PROC_COMPOSE)); return retval; } UTF8PROC_DLLEXPORT utf8proc_uint8_t *utf8proc_NFKD(const utf8proc_uint8_t *str) { utf8proc_uint8_t *retval; - utf8proc_map(str, 0, &retval, UTF8PROC_NULLTERM | UTF8PROC_STABLE | - UTF8PROC_DECOMPOSE | UTF8PROC_COMPAT); + utf8proc_map(str, 0, &retval, cast(utf8proc_option_t)(UTF8PROC_NULLTERM|UTF8PROC_STABLE|UTF8PROC_DECOMPOSE|UTF8PROC_COMPAT)); return retval; } UTF8PROC_DLLEXPORT utf8proc_uint8_t *utf8proc_NFKC(const utf8proc_uint8_t *str) { utf8proc_uint8_t *retval; - utf8proc_map(str, 0, &retval, UTF8PROC_NULLTERM | UTF8PROC_STABLE | - UTF8PROC_COMPOSE | UTF8PROC_COMPAT); + utf8proc_map(str, 0, &retval, cast(utf8proc_option_t)(UTF8PROC_NULLTERM|UTF8PROC_STABLE|UTF8PROC_COMPOSE|UTF8PROC_COMPAT)); return retval; }