From d9ce0b9da0cd1b6c76306734357e2452c30c7f4e Mon Sep 17 00:00:00 2001 From: Ginger Bill Date: Sat, 7 Jan 2017 12:01:52 +0000 Subject: File reorganization for checker system. --- src/check_decl.c | 594 ++++++ src/check_expr.c | 4759 +++++++++++++++++++++++++++++++++++++++++++++++++ src/check_stmt.c | 1301 ++++++++++++++ src/checker.c | 1580 ++++++++++++++++ src/checker/checker.c | 1580 ---------------- src/checker/decl.c | 594 ------ src/checker/entity.c | 190 -- src/checker/expr.c | 4759 ------------------------------------------------- src/checker/stmt.c | 1301 -------------- src/checker/types.c | 1703 ------------------ src/entity.c | 190 ++ src/main.c | 2 +- src/types.c | 1703 ++++++++++++++++++ 13 files changed, 10128 insertions(+), 10128 deletions(-) create mode 100644 src/check_decl.c create mode 100644 src/check_expr.c create mode 100644 src/check_stmt.c create mode 100644 src/checker.c delete mode 100644 src/checker/checker.c delete mode 100644 src/checker/decl.c delete mode 100644 src/checker/entity.c delete mode 100644 src/checker/expr.c delete mode 100644 src/checker/stmt.c delete mode 100644 src/checker/types.c create mode 100644 src/entity.c create mode 100644 src/types.c (limited to 'src') diff --git a/src/check_decl.c b/src/check_decl.c new file mode 100644 index 000000000..9f683cf29 --- /dev/null +++ b/src/check_decl.c @@ -0,0 +1,594 @@ +bool check_is_terminating(AstNode *node); +void check_stmt (Checker *c, AstNode *node, u32 flags); +void check_stmt_list (Checker *c, AstNodeArray stmts, u32 flags); + +// NOTE(bill): `content_name` is for debugging and error messages +Type *check_init_variable(Checker *c, Entity *e, Operand *operand, String context_name) { + if (operand->mode == Addressing_Invalid || + operand->type == t_invalid || + e->type == t_invalid) { + + if (operand->mode == Addressing_Builtin) { + gbString expr_str = expr_to_string(operand->expr); + + // TODO(bill): is this a good enough error message? + error_node(operand->expr, + "Cannot assign builtin procedure `%s` in %.*s", + expr_str, + LIT(context_name)); + + operand->mode = Addressing_Invalid; + + gb_string_free(expr_str); + } + + + if (e->type == NULL) { + e->type = t_invalid; + } + return NULL; + } + + if (e->type == NULL) { + // NOTE(bill): Use the type of the operand + Type *t = operand->type; + if (is_type_untyped(t)) { + if (t == t_invalid || is_type_untyped_nil(t)) { + error(e->token, "Use of untyped nil in %.*s", LIT(context_name)); + e->type = t_invalid; + return NULL; + } + t = default_type(t); + } + e->type = t; + } + + check_assignment(c, operand, e->type, context_name); + if (operand->mode == Addressing_Invalid) { + return NULL; + } + + return e->type; +} + +void check_init_variables(Checker *c, Entity **lhs, isize lhs_count, AstNodeArray inits, String context_name) { + if ((lhs == NULL || lhs_count == 0) && inits.count == 0) { + return; + } + + gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&c->tmp_arena); + + // NOTE(bill): If there is a bad syntax error, rhs > lhs which would mean there would need to be + // an extra allocation + Array(Operand) operands; + array_init_reserve(&operands, c->tmp_allocator, 2*lhs_count); + + for_array(i, inits) { + AstNode *rhs = inits.e[i]; + Operand o = {0}; + check_multi_expr(c, &o, rhs); + if (o.type->kind != Type_Tuple) { + array_add(&operands, o); + } else { + TypeTuple *tuple = &o.type->Tuple; + for (isize j = 0; j < tuple->variable_count; j++) { + o.type = tuple->variables[j]->type; + array_add(&operands, o); + } + } + } + + isize rhs_count = operands.count; + for_array(i, operands) { + if (operands.e[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); + } + + if (rhs_count > 0 && lhs_count != rhs_count) { + error(lhs[0]->token, "Assignment count mismatch `%td` = `%td`", lhs_count, rhs_count); + } + +#if 0 + if (lhs[0]->kind == Entity_Variable && + lhs[0]->Variable.is_let) { + if (lhs_count != rhs_count) { + error(lhs[0]->token, "`let` variables must be initialized, `%td` = `%td`", lhs_count, rhs_count); + } + } +#endif + + gb_temp_arena_memory_end(tmp); +} + +void check_var_decl_node(Checker *c, AstNodeValueDecl *vd) { + GB_ASSERT(vd->is_var == true); + isize entity_count = vd->names.count; + isize entity_index = 0; + Entity **entities = gb_alloc_array(c->allocator, Entity *, entity_count); + + for_array(i, vd->names) { + AstNode *name = vd->names.e[i]; + Entity *entity = NULL; + if (name->kind == AstNode_Ident) { + Token token = name->Ident; + String str = token.string; + Entity *found = NULL; + // NOTE(bill): Ignore assignments to `_` + if (str_ne(str, str_lit("_"))) { + found = current_scope_lookup_entity(c->context.scope, str); + } + if (found == NULL) { + entity = make_entity_variable(c->allocator, c->context.scope, token, NULL); + add_entity_definition(&c->info, name, entity); + } else { + TokenPos pos = found->token.pos; + error(token, + "Redeclaration of `%.*s` in this scope\n" + "\tat %.*s(%td:%td)", + LIT(str), LIT(pos.file), pos.line, pos.column); + entity = found; + } + } else { + error_node(name, "A variable declaration must be an identifier"); + } + if (entity == NULL) { + entity = make_entity_dummy_variable(c->allocator, c->global_scope, ast_node_token(name)); + } + entities[entity_index++] = entity; + } + + Type *init_type = NULL; + if (vd->type) { + init_type = check_type_extra(c, vd->type, NULL); + if (init_type == NULL) { + init_type = t_invalid; + } + } + + for (isize i = 0; i < entity_count; i++) { + Entity *e = entities[i]; + GB_ASSERT(e != NULL); + if (e->flags & EntityFlag_Visited) { + e->type = t_invalid; + continue; + } + e->flags |= EntityFlag_Visited; + + if (e->type == NULL) { + e->type = init_type; + } + } + + check_arity_match(c, vd); + check_init_variables(c, entities, entity_count, vd->values, str_lit("variable declaration")); + + for_array(i, vd->names) { + if (entities[i] != NULL) { + add_entity(c, c->context.scope, vd->names.e[i], entities[i]); + } + } + +} + + + +void check_init_constant(Checker *c, Entity *e, Operand *operand) { + if (operand->mode == Addressing_Invalid || + operand->type == t_invalid || + e->type == t_invalid) { + if (e->type == NULL) { + e->type = t_invalid; + } + return; + } + + if (operand->mode != Addressing_Constant) { + // TODO(bill): better error + gbString str = expr_to_string(operand->expr); + error_node(operand->expr, "`%s` is not a constant", str); + gb_string_free(str); + if (e->type == NULL) { + e->type = t_invalid; + } + return; + } + if (!is_type_constant_type(operand->type)) { + gbString type_str = type_to_string(operand->type); + error_node(operand->expr, "Invalid constant type: `%s`", type_str); + gb_string_free(type_str); + if (e->type == NULL) { + e->type = t_invalid; + } + return; + } + + if (e->type == NULL) { // NOTE(bill): type inference + e->type = operand->type; + } + + check_assignment(c, operand, e->type, str_lit("constant declaration")); + if (operand->mode == Addressing_Invalid) { + return; + } + + e->Constant.value = operand->value; +} + +void check_type_decl(Checker *c, Entity *e, AstNode *type_expr, Type *def) { + GB_ASSERT(e->type == NULL); + Type *named = make_type_named(c->allocator, e->token.string, NULL, e); + named->Named.type_name = e; + if (def != NULL && def->kind == Type_Named) { + def->Named.base = named; + } + e->type = named; + + // gb_printf_err("%.*s %p\n", LIT(e->token.string), e); + + Type *bt = check_type_extra(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)); + } +} + +void check_const_decl(Checker *c, Entity *e, AstNode *type_expr, AstNode *init, Type *named_type) { + GB_ASSERT(e->type == NULL); + GB_ASSERT(e->kind == Entity_Constant); + + if (e->flags & EntityFlag_Visited) { + e->type = t_invalid; + return; + } + e->flags |= EntityFlag_Visited; + + c->context.iota = e->Constant.value; + e->Constant.value = (ExactValue){0}; + + if (type_expr) { + Type *t = check_type(c, type_expr); + if (!is_type_constant_type(t)) { + gbString str = type_to_string(t); + error_node(type_expr, "Invalid constant type `%s`", str); + gb_string_free(str); + e->type = t_invalid; + c->context.iota = (ExactValue){0}; + return; + } + e->type = t; + } + + Operand operand = {0}; + if (init != NULL) { + check_expr_or_type(c, &operand, init); + } + if (operand.mode == Addressing_Type) { + c->context.iota = (ExactValue){0}; + + e->Constant.value = (ExactValue){0}; + e->kind = Entity_TypeName; + + DeclInfo *d = c->context.decl; + d->type_expr = d->init_expr; + check_type_decl(c, e, d->type_expr, named_type); + return; + } + + check_init_constant(c, e, &operand); + c->context.iota = (ExactValue){0}; + + if (operand.mode == Addressing_Invalid) { + error(e->token, "Illegal cyclic declaration"); + } +} + + + +bool are_signatures_similar_enough(Type *a_, Type *b_) { + GB_ASSERT(a_->kind == Type_Proc); + GB_ASSERT(b_->kind == Type_Proc); + TypeProc *a = &a_->Proc; + TypeProc *b = &b_->Proc; + + if (a->param_count != b->param_count) { + return false; + } + if (a->result_count != b->result_count) { + return false; + } + for (isize i = 0; i < a->param_count; i++) { + Type *x = base_type(a->params->Tuple.variables[i]->type); + Type *y = base_type(b->params->Tuple.variables[i]->type); + if (is_type_pointer(x) && is_type_pointer(y)) { + continue; + } + + if (!are_types_identical(x, y)) { + return false; + } + } + for (isize i = 0; i < a->result_count; i++) { + Type *x = base_type(a->results->Tuple.variables[i]->type); + Type *y = base_type(b->results->Tuple.variables[i]->type); + if (is_type_pointer(x) && is_type_pointer(y)) { + continue; + } + + if (!are_types_identical(x, y)) { + return false; + } + } + + return true; +} + +void check_proc_lit(Checker *c, Entity *e, DeclInfo *d) { + GB_ASSERT(e->type == NULL); + if (d->proc_lit->kind != AstNode_ProcLit) { + // TOOD(bill): Better error message + error_node(d->proc_lit, "Expected a procedure to check"); + return; + } + + Type *proc_type = make_type_proc(c->allocator, e->scope, NULL, 0, NULL, 0, false, ProcCC_Odin); + e->type = proc_type; + ast_node(pd, ProcLit, d->proc_lit); + + check_open_scope(c, pd->type); + check_procedure_type(c, proc_type, pd->type); + + bool is_foreign = (pd->tags & ProcTag_foreign) != 0; + bool is_link_name = (pd->tags & ProcTag_link_name) != 0; + bool is_export = (pd->tags & ProcTag_export) != 0; + bool is_inline = (pd->tags & ProcTag_inline) != 0; + bool is_no_inline = (pd->tags & ProcTag_no_inline) != 0; + + if ((d->scope->is_file || d->scope->is_global) && + str_eq(e->token.string, str_lit("main"))) { + if (proc_type != NULL) { + TypeProc *pt = &proc_type->Proc; + if (pt->param_count != 0 || + pt->result_count != 0) { + gbString str = type_to_string(proc_type); + error(e->token, "Procedure type of `main` was expected to be `proc()`, got %s", str); + gb_string_free(str); + } + } + } + + if (is_inline && is_no_inline) { + error_node(pd->type, "You cannot apply both `inline` and `no_inline` to a procedure"); + } + + if (is_foreign && is_link_name) { + error_node(pd->type, "You cannot apply both `foreign` and `link_name` to a procedure"); + } else if (is_foreign && is_export) { + error_node(pd->type, "You cannot apply both `foreign` and `export` to a procedure"); + } + + + if (pd->body != NULL) { + if (is_foreign) { + error_node(pd->body, "A procedure tagged as `#foreign` cannot have a body"); + } + + if (proc_type->Proc.calling_convention != ProcCC_Odin) { + error_node(d->proc_lit, "An internal procedure may only have the Odin calling convention"); + proc_type->Proc.calling_convention = ProcCC_Odin; + } + + d->scope = c->context.scope; + + GB_ASSERT(pd->body->kind == AstNode_BlockStmt); + check_procedure_later(c, c->curr_ast_file, e->token, d, proc_type, pd->body, pd->tags); + } + + if (is_foreign) { + MapEntity *fp = &c->info.foreign_procs; + String name = e->token.string; + if (pd->foreign_name.len > 0) { + name = pd->foreign_name; + } + + e->Procedure.is_foreign = true; + e->Procedure.foreign_name = name; + + HashKey key = hash_string(name); + Entity **found = map_entity_get(fp, key); + if (found) { + Entity *f = *found; + TokenPos pos = f->token.pos; + Type *this_type = base_type(e->type); + Type *other_type = base_type(f->type); + if (!are_signatures_similar_enough(this_type, other_type)) { + error_node(d->proc_lit, + "Redeclaration of #foreign procedure `%.*s` with different type signatures\n" + "\tat %.*s(%td:%td)", + LIT(name), LIT(pos.file), pos.line, pos.column); + } + } else { + map_entity_set(fp, key, e); + } + } else { + String name = e->token.string; + if (is_link_name) { + name = pd->link_name; + } + + if (is_link_name || is_export) { + MapEntity *fp = &c->info.foreign_procs; + + e->Procedure.link_name = name; + + HashKey key = hash_string(name); + Entity **found = map_entity_get(fp, key); + if (found) { + Entity *f = *found; + TokenPos pos = f->token.pos; + // TODO(bill): Better error message? + error_node(d->proc_lit, + "Non unique linking name for procedure `%.*s`\n" + "\tother at %.*s(%td:%td)", + LIT(name), LIT(pos.file), pos.line, pos.column); + } else { + map_entity_set(fp, key, e); + } + } + } + + check_close_scope(c); +} + +void check_var_decl(Checker *c, Entity *e, Entity **entities, isize entity_count, AstNode *type_expr, AstNode *init_expr) { + GB_ASSERT(e->type == NULL); + GB_ASSERT(e->kind == Entity_Variable); + + if (e->flags & EntityFlag_Visited) { + e->type = t_invalid; + return; + } + e->flags |= EntityFlag_Visited; + + if (type_expr != NULL) { + e->type = check_type_extra(c, type_expr, NULL); + } + + if (init_expr == NULL) { + if (type_expr == NULL) { + e->type = t_invalid; + } + return; + } + + if (entities == NULL || entity_count == 1) { + GB_ASSERT(entities == NULL || entities[0] == e); + Operand operand = {0}; + check_expr(c, &operand, init_expr); + check_init_variable(c, e, &operand, str_lit("variable declaration")); + } + + if (type_expr != NULL) { + for (isize i = 0; i < entity_count; i++) { + entities[i]->type = e->type; + } + } + + AstNodeArray inits; + array_init_reserve(&inits, c->allocator, 1); + array_add(&inits, init_expr); + check_init_variables(c, entities, entity_count, inits, str_lit("variable declaration")); +} + + +void check_entity_decl(Checker *c, Entity *e, DeclInfo *d, Type *named_type) { + if (e->type != NULL) { + return; + } + + if (d == NULL) { + DeclInfo **found = map_decl_info_get(&c->info.entities, hash_pointer(e)); + if (found) { + d = *found; + } else { + // TODO(bill): Err here? + e->type = t_invalid; + set_base_type(named_type, t_invalid); + return; + // GB_PANIC("`%.*s` should been declared!", LIT(e->token.string)); + } + } + + CheckerContext prev = c->context; + c->context.scope = d->scope; + c->context.decl = d; + + switch (e->kind) { + case Entity_Variable: + check_var_decl(c, e, d->entities, d->entity_count, d->type_expr, d->init_expr); + break; + case Entity_Constant: + check_const_decl(c, e, d->type_expr, d->init_expr, named_type); + break; + case Entity_TypeName: + check_type_decl(c, e, d->type_expr, named_type); + break; + case Entity_Procedure: + check_proc_lit(c, e, d); + break; + } + + c->context = prev; +} + + + +void check_proc_body(Checker *c, Token token, DeclInfo *decl, Type *type, AstNode *body) { + GB_ASSERT(body->kind == AstNode_BlockStmt); + + CheckerContext old_context = c->context; + c->context.scope = decl->scope; + c->context.decl = decl; + + GB_ASSERT(type->kind == Type_Proc); + if (type->Proc.param_count > 0) { + TypeTuple *params = &type->Proc.params->Tuple; + for (isize i = 0; i < params->variable_count; i++) { + Entity *e = params->variables[i]; + GB_ASSERT(e->kind == Entity_Variable); + if (!(e->flags & EntityFlag_Anonymous)) { + continue; + } + 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)); + GB_ASSERT(found != NULL); + for_array(i, (*found)->elements.entries) { + Entity *f = (*found)->elements.entries.e[i].value; + if (f->kind == Entity_Variable) { + Entity *uvar = make_entity_using_variable(c->allocator, e, f->token, f->type); + Entity *prev = scope_insert_entity(c->context.scope, uvar); + if (prev != NULL) { + error(e->token, "Namespace collision while `using` `%.*s` of: %.*s", LIT(name), LIT(prev->token.string)); + break; + } + } + } + } else { + error(e->token, "`using` can only be applied to variables of type struct or raw_union"); + break; + } + } + } + + push_procedure(c, type); + { + ast_node(bs, BlockStmt, body); + check_stmt_list(c, bs->stmts, 0); + if (type->Proc.result_count > 0) { + if (!check_is_terminating(body)) { + if (token.kind == Token_Ident) { + error(bs->close, "Missing return statement at the end of the procedure `%.*s`", LIT(token.string)); + } else { + error(bs->close, "Missing return statement at the end of the procedure"); + } + } + } + } + pop_procedure(c); + + + check_scope_usage(c, c->context.scope); + + c->context = old_context; +} + + + diff --git a/src/check_expr.c b/src/check_expr.c new file mode 100644 index 000000000..2c772d149 --- /dev/null +++ b/src/check_expr.c @@ -0,0 +1,4759 @@ +void check_expr (Checker *c, Operand *operand, AstNode *expression); +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); +void check_type_decl (Checker *c, Entity *e, AstNode *type_expr, Type *def); +Entity * check_selector (Checker *c, Operand *operand, AstNode *node); +void check_not_tuple (Checker *c, Operand *operand); +bool check_value_is_expressible(Checker *c, ExactValue in_value, Type *type, ExactValue *out_value); +void convert_to_typed (Checker *c, Operand *operand, Type *target_type, i32 level); +gbString expr_to_string (AstNode *expression); +void check_entity_decl (Checker *c, Entity *e, DeclInfo *decl, Type *named_type); +void check_const_decl (Checker *c, Entity *e, AstNode *type_expr, AstNode *init_expr, Type *named_type); +void check_proc_body (Checker *c, Token token, DeclInfo *decl, Type *type, AstNode *body); +void update_expr_type (Checker *c, AstNode *e, Type *type, bool final); +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_init_constant (Checker *c, Entity *e, Operand *operand); + + +gb_inline Type *check_type(Checker *c, AstNode *expression) { + return check_type_extra(c, expression, NULL); +} + + + + +typedef struct DelayedEntity { + AstNode * ident; + Entity * entity; + DeclInfo * decl; +} DelayedEntity; + +typedef struct DelayedOtherFields { + Entity **other_fields; + isize other_field_count; + isize other_field_index; + + MapEntity *entity_map; +} DelayedOtherFields; + +typedef Array(DelayedEntity) DelayedEntities; + +void check_local_collect_entities(Checker *c, AstNodeArray nodes, DelayedEntities *delayed_entities, DelayedOtherFields *dof); + +void check_local_collect_entities_from_when_stmt(Checker *c, AstNodeWhenStmt *ws, DelayedEntities *delayed_entities, DelayedOtherFields *dof) { + Operand operand = {Addressing_Invalid}; + check_expr(c, &operand, ws->cond); + if (operand.mode != Addressing_Invalid && !is_type_boolean(operand.type)) { + error_node(ws->cond, "Non-boolean condition in `when` statement"); + } + if (operand.mode != Addressing_Constant) { + error_node(ws->cond, "Non-constant condition in `when` statement"); + } + if (ws->body == NULL || ws->body->kind != AstNode_BlockStmt) { + error_node(ws->cond, "Invalid body for `when` statement"); + } else { + if (operand.value.kind == ExactValue_Bool && + operand.value.value_bool) { + check_local_collect_entities(c, ws->body->BlockStmt.stmts, delayed_entities, dof); + } else if (ws->else_stmt) { + switch (ws->else_stmt->kind) { + case AstNode_BlockStmt: + check_local_collect_entities(c, ws->else_stmt->BlockStmt.stmts, delayed_entities, dof); + break; + case AstNode_WhenStmt: + check_local_collect_entities_from_when_stmt(c, &ws->else_stmt->WhenStmt, delayed_entities, dof); + break; + default: + error_node(ws->else_stmt, "Invalid `else` statement in `when` statement"); + break; + } + } + } +} + +// NOTE(bill): The `dof` is for use within records +void check_local_collect_entities(Checker *c, AstNodeArray nodes, DelayedEntities *delayed_entities, DelayedOtherFields *dof) { + for_array(i, nodes) { + AstNode *node = nodes.e[i]; + switch (node->kind) { + case_ast_node(ws, WhenStmt, node); + // Will be handled later + case_end; + + case_ast_node(vd, ValueDecl, node); + if (vd->is_var) { + // NOTE(bill): Handled later + } else { + for_array(i, vd->names) { + AstNode *name = vd->names.e[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; + } + + AstNode *init = NULL; + if (i < vd->values.count) { + init = vd->values.e[i]; + } + + DeclInfo *d = make_declaration_info(c->allocator, c->context.scope); + Entity *e = NULL; + + AstNode *up_init = unparen_expr(init); + if (init != NULL && is_ast_node_type(up_init)) { + e = make_entity_type_name(c->allocator, d->scope, name->Ident, NULL); + d->type_expr = init; + d->init_expr = init; + } else if (init != NULL && up_init->kind == AstNode_ProcLit) { + e = make_entity_procedure(c->allocator, d->scope, name->Ident, NULL, up_init->ProcLit.tags); + d->proc_lit = init; + } else { + e = make_entity_constant(c->allocator, d->scope, name->Ident, NULL, (ExactValue){0}); + d->type_expr = vd->type; + d->init_expr = init; + } + GB_ASSERT(e != NULL); + e->identifier = name; + + add_entity_and_decl_info(c, name, e, d); + + DelayedEntity delay = {name, e, d}; + array_add(delayed_entities, delay); + } + + check_arity_match(c, vd); + } + case_end; +#if 0 + case_ast_node(pd, ProcDecl, node); + if (!ast_node_expect(pd->name, AstNode_Ident)) { + break; + } + + Entity *e = make_entity_procedure(c->allocator, c->context.scope, pd->name->Ident, NULL); + e->identifier = pd->name; + + DeclInfo *d = make_declaration_info(c->allocator, e->scope); + d->proc_lit = node; + + add_entity_and_decl_info(c, pd->name, e, d); + check_entity_decl(c, e, d, NULL, NULL); + case_end; +#endif + } + } + + // 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]; + switch (node->kind) { + case_ast_node(ws, WhenStmt, node); + check_local_collect_entities_from_when_stmt(c, ws, delayed_entities, dof); + case_end; + } + } +} + +void check_scope_decls(Checker *c, AstNodeArray nodes, isize reserve_size, DelayedOtherFields *dof) { + DelayedEntities delayed_entities; + array_init_reserve(&delayed_entities, heap_allocator(), reserve_size); + check_local_collect_entities(c, nodes, &delayed_entities, dof); + + for_array(i, delayed_entities) { + DelayedEntity delayed = delayed_entities.e[i]; + if (delayed.entity->kind == Entity_TypeName) { + check_entity_decl(c, delayed.entity, delayed.decl, NULL); + } + } + for_array(i, delayed_entities) { + DelayedEntity delayed = delayed_entities.e[i]; + if (delayed.entity->kind == Entity_Constant) { + add_entity_and_decl_info(c, delayed.ident, delayed.entity, delayed.decl); + check_entity_decl(c, delayed.entity, delayed.decl, NULL); + } + } + + array_free(&delayed_entities); +} + + +bool check_is_assignable_to_using_subtype(Type *dst, Type *src) { + bool src_is_ptr; + Type *prev_src = src; + src = type_deref(src); + src_is_ptr = src != prev_src; + src = base_type(src); + + if (is_type_struct(src)) { + for (isize i = 0; i < src->Record.field_count; i++) { + Entity *f = src->Record.fields[i]; + if (f->kind == Entity_Variable && (f->flags & EntityFlag_Anonymous)) { + if (are_types_identical(dst, f->type)) { + return true; + } + if (src_is_ptr && is_type_pointer(dst)) { + if (are_types_identical(type_deref(dst), f->type)) { + return true; + } + } + bool ok = check_is_assignable_to_using_subtype(dst, f->type); + if (ok) { + return true; + } + } + } + } + return false; +} + + +bool check_is_assignable_to(Checker *c, Operand *operand, Type *type) { + if (operand->mode == Addressing_Invalid || + type == t_invalid) { + return true; + } + + if (operand->mode == Addressing_Builtin) { + return false; + } + + Type *s = operand->type; + + if (are_types_identical(s, type)) { + return true; + } + + Type *src = base_type(s); + Type *dst = base_type(type); + + if (is_type_untyped(src)) { + switch (dst->kind) { + case Type_Basic: + if (operand->mode == Addressing_Constant) { + return check_value_is_expressible(c, operand->value, dst, NULL); + } + if (src->kind == Type_Basic && src->Basic.kind == Basic_UntypedBool) { + return is_type_boolean(dst); + } + break; + } + if (type_has_nil(dst)) { + return operand->mode == Addressing_Value && operand->type == t_untyped_nil; + } + } + + if (are_types_identical(dst, src) && (!is_type_named(dst) || !is_type_named(src))) { + return true; + } + + if (is_type_maybe(dst)) { + Type *elem = base_type(dst)->Maybe.elem; + return are_types_identical(elem, s); + } + + if (is_type_untyped_nil(src)) { + return type_has_nil(dst); + } + + // ^T <- rawptr + // TODO(bill): Should C-style (not C++) pointer cast be allowed? + // if (is_type_pointer(dst) && is_type_rawptr(src)) { + // return true; + // } + + // rawptr <- ^T + if (is_type_rawptr(dst) && is_type_pointer(src)) { + // TODO(bill): Handle this properly + if (dst != type) { + return false; + } + return true; + } + + + + if (dst->kind == Type_Array && src->kind == Type_Array) { + if (are_types_identical(dst->Array.elem, src->Array.elem)) { + return dst->Array.count == src->Array.count; + } + } + + if (dst->kind == Type_Slice && src->kind == Type_Slice) { + if (are_types_identical(dst->Slice.elem, src->Slice.elem)) { + return true; + } + } + + if (is_type_union(dst)) { + for (isize i = 0; i < dst->Record.field_count; i++) { + Entity *f = dst->Record.fields[i]; + if (are_types_identical(f->type, s)) { + return true; + } + } + } + + + if (is_type_any(dst)) { + // NOTE(bill): Anything can cast to `Any` + add_type_info_type(c, s); + return true; + } + + return false; +} + + +// NOTE(bill): `content_name` is for debugging and error messages +void check_assignment(Checker *c, Operand *operand, Type *type, String context_name) { + check_not_tuple(c, operand); + if (operand->mode == Addressing_Invalid) { + return; + } + + if (is_type_untyped(operand->type)) { + Type *target_type = type; + + if (type == NULL || is_type_any(type) || is_type_untyped_nil(type)) { + if (type == NULL && base_type(operand->type) == t_untyped_nil) { + error_node(operand->expr, "Use of untyped nil in %.*s", LIT(context_name)); + operand->mode = Addressing_Invalid; + return; + } + + add_type_info_type(c, type); + target_type = default_type(operand->type); + } + convert_to_typed(c, operand, target_type, 0); + if (operand->mode == Addressing_Invalid) { + return; + } + } + + if (type != NULL) { + if (!check_is_assignable_to(c, operand, type)) { + gbString type_str = type_to_string(type); + gbString op_type_str = type_to_string(operand->type); + gbString expr_str = expr_to_string(operand->expr); + + if (operand->mode == Addressing_Builtin) { + // TODO(bill): is this a good enough error message? + error_node(operand->expr, + "Cannot assign builtin procedure `%s` in %.*s", + expr_str, + LIT(context_name)); + } else { + // TODO(bill): is this a good enough error message? + error_node(operand->expr, + "Cannot assign value `%s` of type `%s` to `%s` in %.*s", + expr_str, + op_type_str, + type_str, + LIT(context_name)); + } + operand->mode = Addressing_Invalid; + + gb_string_free(expr_str); + gb_string_free(op_type_str); + gb_string_free(type_str); + return; + } + } +} + + +void populate_using_entity_map(Checker *c, AstNode *node, Type *t, MapEntity *entity_map) { + t = base_type(type_deref(t)); + gbString str = expr_to_string(node); + + if (t->kind == Type_Record) { + for (isize i = 0; i < t->Record.field_count; i++) { + Entity *f = t->Record.fields[i]; + GB_ASSERT(f->kind == Entity_Variable); + String name = f->token.string; + HashKey key = hash_string(name); + Entity **found = map_entity_get(entity_map, key); + if (found != NULL) { + Entity *e = *found; + // TODO(bill): Better type error + error(e->token, "`%.*s` is already declared in `%s`", LIT(name), str); + } else { + map_entity_set(entity_map, key, f); + add_entity(c, c->context.scope, NULL, f); + if (f->flags & EntityFlag_Anonymous) { + populate_using_entity_map(c, node, f->type, entity_map); + } + } + } + } + + gb_string_free(str); +} + + +void check_fields(Checker *c, AstNode *node, AstNodeArray 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); + + isize other_field_index = 0; + Entity *using_index_expr = NULL; + + if (node->kind == AstNode_UnionType) { + isize field_index = 0; + fields[field_index++] = make_entity_type_name(c->allocator, c->context.scope, empty_token, NULL); + for_array(decl_index, decls) { + AstNode *decl = decls.e[decl_index]; + if (decl->kind != AstNode_Field) { + continue; + } + + ast_node(f, Field, decl); + Type *base_type = check_type_extra(c, f->type, NULL); + + for_array(name_index, f->names) { + AstNode *name = f->names.e[name_index]; + if (!ast_node_expect(name, AstNode_Ident)) { + continue; + } + + Token name_token = name->Ident; + + Type *type = make_type_named(c->allocator, name_token.string, base_type, NULL); + Entity *e = make_entity_type_name(c->allocator, c->context.scope, name_token, type); + type->Named.type_name = e; + add_entity(c, c->context.scope, name, e); + + if (str_eq(name_token.string, str_lit("_"))) { + 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) { + // TODO(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); + fields[field_index++] = e; + } + add_entity_use(c, name, e); + } + } + } else { + isize field_index = 0; + for_array(decl_index, decls) { + AstNode *decl = decls.e[decl_index]; + if (decl->kind != AstNode_Field) { + continue; + } + ast_node(f, Field, decl); + + Type *type = check_type_extra(c, f->type, NULL); + + if (f->is_using) { + if (f->names.count > 1) { + error_node(f->names.e[0], "Cannot apply `using` to more than one of the same type"); + } + } + + for_array(name_index, f->names) { + AstNode *name = f->names.e[name_index]; + if (!ast_node_expect(name, AstNode_Ident)) { + continue; + } + + Token name_token = name->Ident; + + Entity *e = make_entity_field(c->allocator, c->context.scope, name_token, type, f->is_using, cast(i32)field_index); + e->identifier = name; + if (str_eq(name_token.string, str_lit("_"))) { + fields[field_index++] = e; + } else { + HashKey key = hash_string(name_token.string); + if (map_entity_get(&entity_map, key) != NULL) { + // TODO(bill): Scope checking already checks the declaration + error(name_token, "`%.*s` is already declared in this type", LIT(name_token.string)); + } else { + map_entity_set(&entity_map, key, e); + fields[field_index++] = e; + add_entity(c, c->context.scope, name, e); + } + add_entity_use(c, name, e); + } + } + + + if (f->is_using) { + Type *t = base_type(type_deref(type)); + if (!is_type_struct(t) && !is_type_raw_union(t) && + f->names.count >= 1 && + f->names.e[0]->kind == AstNode_Ident) { + Token name_token = f->names.e[0]->Ident; + if (is_type_indexable(t)) { + bool ok = true; + for_array(emi, entity_map.entries) { + Entity *e = entity_map.entries.e[emi].value; + if (e->kind == Entity_Variable && e->flags & EntityFlag_Anonymous) { + if (is_type_indexable(e->type)) { + if (e->identifier != f->names.e[0]) { + ok = false; + using_index_expr = e; + break; + } + } + } + } + if (ok) { + using_index_expr = fields[field_index-1]; + } else { + fields[field_index-1]->flags &= ~EntityFlag_Anonymous; + error(name_token, "Previous `using` for an index expression `%.*s`", LIT(name_token.string)); + } + } else { + error(name_token, "`using` on a field `%.*s` must be a `struct` or `raw_union`", LIT(name_token.string)); + continue; + } + } + + populate_using_entity_map(c, node, type, &entity_map); + } + } + } + + gb_temp_arena_memory_end(tmp); +} + + +// TODO(bill): Cleanup struct field reordering +// TODO(bill): Inline sorting procedure? +gb_global BaseTypeSizes __checker_sizes = {0}; +gb_global gbAllocator __checker_allocator = {0}; + +GB_COMPARE_PROC(cmp_struct_entity_size) { + // Rule: + // Biggest to smallest alignment + // if same alignment: biggest to smallest size + // if same size: order by source order + Entity *x = *(Entity **)a; + Entity *y = *(Entity **)b; + GB_ASSERT(x != NULL); + GB_ASSERT(y != NULL); + GB_ASSERT(x->kind == Entity_Variable); + GB_ASSERT(y->kind == Entity_Variable); + i64 xa = type_align_of(__checker_sizes, __checker_allocator, x->type); + i64 ya = type_align_of(__checker_sizes, __checker_allocator, y->type); + i64 xs = type_size_of(__checker_sizes, __checker_allocator, x->type); + i64 ys = type_size_of(__checker_sizes, __checker_allocator, y->type); + + if (xa == ya) { + if (xs == ys) { + i32 diff = x->Variable.field_index - y->Variable.field_index; + return diff < 0 ? -1 : diff > 0; + } + return xs > ys ? -1 : xs < ys; + } + return xa > ya ? -1 : xa < ya; +} + +void check_struct_type(Checker *c, Type *struct_type, AstNode *node) { + GB_ASSERT(is_type_struct(struct_type)); + ast_node(st, StructType, node); + + isize field_count = 0; + for_array(field_index, st->fields) { + AstNode *field = st->fields.e[field_index]; + switch (field->kind) { + case_ast_node(f, Field, field); + field_count += f->names.count; + case_end; + } + } + + Entity **fields = gb_alloc_array(c->allocator, Entity *, field_count); + + check_fields(c, node, st->fields, fields, field_count, str_lit("struct")); + + struct_type->Record.struct_is_packed = st->is_packed; + struct_type->Record.struct_is_ordered = st->is_ordered; + struct_type->Record.fields = fields; + struct_type->Record.fields_in_src_order = fields; + struct_type->Record.field_count = field_count; + + if (!st->is_packed && !st->is_ordered) { + // NOTE(bill): Reorder fields for reduced size/performance + + Entity **reordered_fields = gb_alloc_array(c->allocator, Entity *, field_count); + for (isize i = 0; i < field_count; i++) { + reordered_fields[i] = struct_type->Record.fields_in_src_order[i]; + } + + // NOTE(bill): Hacky thing + // TODO(bill): Probably make an inline sorting procedure rather than use global variables + __checker_sizes = c->sizes; + __checker_allocator = c->allocator; + // NOTE(bill): compound literal order must match source not layout + gb_sort_array(reordered_fields, field_count, cmp_struct_entity_size); + + for (isize i = 0; i < field_count; i++) { + reordered_fields[i]->Variable.field_index = i; + } + + struct_type->Record.fields = reordered_fields; + } + + type_set_offsets(c->sizes, c->allocator, struct_type); +} + +void check_union_type(Checker *c, Type *union_type, AstNode *node) { + GB_ASSERT(is_type_union(union_type)); + ast_node(ut, UnionType, node); + + isize field_count = 1; + for_array(field_index, ut->fields) { + AstNode *field = ut->fields.e[field_index]; + switch (field->kind) { + case_ast_node(f, Field, field); + field_count += f->names.count; + case_end; + } + } + + Entity **fields = gb_alloc_array(c->allocator, Entity *, field_count); + + check_fields(c, node, ut->fields, fields, field_count, str_lit("union")); + + union_type->Record.fields = fields; + union_type->Record.field_count = field_count; +} + +void check_raw_union_type(Checker *c, Type *union_type, AstNode *node) { + GB_ASSERT(node->kind == AstNode_RawUnionType); + GB_ASSERT(is_type_raw_union(union_type)); + ast_node(ut, RawUnionType, node); + + isize field_count = 0; + for_array(field_index, ut->fields) { + AstNode *field = ut->fields.e[field_index]; + switch (field->kind) { + case_ast_node(f, Field, field); + field_count += f->names.count; + case_end; + } + } + + Entity **fields = gb_alloc_array(c->allocator, Entity *, field_count); + + check_fields(c, node, ut->fields, fields, field_count, str_lit("raw_union")); + + union_type->Record.fields = fields; + union_type->Record.field_count = field_count; +} + +// GB_COMPARE_PROC(cmp_enum_order) { +// // Rule: +// // Biggest to smallest alignment +// // if same alignment: biggest to smallest size +// // if same size: order by source order +// Entity *x = *(Entity **)a; +// Entity *y = *(Entity **)b; +// GB_ASSERT(x != NULL); +// GB_ASSERT(y != NULL); +// GB_ASSERT(x->kind == Entity_Constant); +// GB_ASSERT(y->kind == Entity_Constant); +// GB_ASSERT(x->Constant.value.kind == ExactValue_Integer); +// GB_ASSERT(y->Constant.value.kind == ExactValue_Integer); +// i64 i = x->Constant.value.value_integer; +// i64 j = y->Constant.value.value_integer; + +// return i < j ? -1 : i > j; +// } + +void check_enum_type(Checker *c, Type *enum_type, Type *named_type, AstNode *node) { + ast_node(et, EnumType, node); + GB_ASSERT(is_type_enum(enum_type)); + + gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&c->tmp_arena); + + Type *base_type = t_int; + if (et->base_type != NULL) { + base_type = check_type(c, et->base_type); + } + + if (base_type == NULL || !(is_type_integer(base_type) || is_type_float(base_type))) { + error_node(node, "Base type for enumeration must be numeric"); + return; + } + + // 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)); + + Entity **fields = gb_alloc_array(c->allocator, Entity *, et->fields.count); + isize field_index = 0; + + Type *constant_type = enum_type; + if (named_type != NULL) { + constant_type = named_type; + } + + AstNode *prev_expr = NULL; + + i64 iota = 0; + + for_array(i, et->fields) { + AstNode *field = et->fields.e[i]; + AstNode *ident = NULL; + if (field->kind == AstNode_FieldValue) { + ast_node(fv, FieldValue, field); + if (fv->field == NULL || fv->field->kind != AstNode_Ident) { + error_node(field, "An enum field's name must be an identifier"); + continue; + } + ident = fv->field; + prev_expr = fv->value; + } else if (field->kind == AstNode_Ident) { + ident = field; + } else { + error_node(field, "An enum field's name must be an identifier"); + continue; + } + String name = ident->Ident.string; + + if (str_ne(name, str_lit("_"))) { + ExactValue v = make_exact_value_integer(iota); + Entity *e = make_entity_constant(c->allocator, c->context.scope, ident->Ident, constant_type, v); + e->identifier = ident; + e->flags |= EntityFlag_Visited; + + + AstNode *init = prev_expr; + if (init == NULL) { + error_node(field, "Missing initial expression for enumeration, e.g. iota"); + continue; + } + + ExactValue context_iota = c->context.iota; + c->context.iota = e->Constant.value; + e->Constant.value = (ExactValue){0}; + + Operand operand = {0}; + check_expr(c, &operand, init); + + check_init_constant(c, e, &operand); + c->context.iota = context_iota; + + if (operand.mode == Addressing_Constant) { + HashKey key = hash_string(name); + if (map_entity_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); + add_entity(c, c->context.scope, NULL, e); + fields[field_index++] = e; + add_entity_use(c, field, e); + } + } + } + iota++; + } + + GB_ASSERT(field_index <= et->fields.count); + + enum_type->Record.fields = fields; + enum_type->Record.field_count = field_index; + + gb_temp_arena_memory_end(tmp); +} + + +Type *check_get_params(Checker *c, Scope *scope, AstNodeArray params, bool *is_variadic_) { + if (params.count == 0) { + return NULL; + } + + isize variable_count = 0; + for_array(i, params) { + AstNode *field = params.e[i]; + if (ast_node_expect(field, AstNode_Field)) { + ast_node(f, Field, field); + variable_count += f->names.count; + } + } + + bool is_variadic = false; + 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) { + continue; + } + ast_node(p, Field, params.e[i]); + AstNode *type_expr = p->type; + if (type_expr) { + 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"); + } + } + + Type *type = check_type(c, type_expr); + 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->is_using); + add_entity(c, scope, name, param); + variables[variable_index++] = param; + } + } + } + } + + variable_count = variable_index; + + if (is_variadic) { + GB_ASSERT(params.count > 0); + // NOTE(bill): Change last variadic parameter to be a slice + // Custom Calling convention for variadic parameters + Entity *end = variables[variable_count-1]; + end->type = make_type_slice(c->allocator, end->type); + } + + Type *tuple = make_type_tuple(c->allocator); + tuple->Tuple.variables = variables; + tuple->Tuple.variable_count = variable_count; + + if (is_variadic_) *is_variadic_ = is_variadic; + + return tuple; +} + +Type *check_get_results(Checker *c, Scope *scope, AstNodeArray results) { + if (results.count == 0) { + return NULL; + } + Type *tuple = make_type_tuple(c->allocator); + + Entity **variables = gb_alloc_array(c->allocator, Entity *, results.count); + isize variable_index = 0; + for_array(i, results) { + AstNode *item = results.e[i]; + Type *type = check_type(c, item); + Token token = ast_node_token(item); + token.string = str_lit(""); // NOTE(bill): results are not named + // TODO(bill): Should I have named results? + Entity *param = make_entity_param(c->allocator, scope, token, type, false); + // NOTE(bill): No need to record + variables[variable_index++] = param; + } + tuple->Tuple.variables = variables; + tuple->Tuple.variable_count = results.count; + + return tuple; +} + + +void check_procedure_type(Checker *c, Type *type, AstNode *proc_type_node) { + ast_node(pt, ProcType, proc_type_node); + + bool variadic = false; + Type *params = check_get_params(c, c->context.scope, pt->params, &variadic); + Type *results = check_get_results(c, c->context.scope, pt->results); + + isize param_count = 0; + isize result_count = 0; + if (params) param_count = params ->Tuple.variable_count; + if (results) result_count = results->Tuple.variable_count; + + type->Proc.scope = c->context.scope; + type->Proc.params = params; + type->Proc.param_count = param_count; + type->Proc.results = results; + type->Proc.result_count = result_count; + type->Proc.variadic = variadic; + type->Proc.calling_convention = pt->calling_convention; +} + + +void check_identifier(Checker *c, Operand *o, AstNode *n, Type *named_type) { + GB_ASSERT(n->kind == AstNode_Ident); + o->mode = Addressing_Invalid; + o->expr = n; + Entity *e = scope_lookup_entity(c->context.scope, n->Ident.string); + if (e == NULL) { + if (str_eq(n->Ident.string, str_lit("_"))) { + error(n->Ident, "`_` cannot be used as a value type"); + } else { + error(n->Ident, "Undeclared name: %.*s", LIT(n->Ident.string)); + } + o->type = t_invalid; + o->mode = Addressing_Invalid; + if (named_type != NULL) { + set_base_type(named_type, t_invalid); + } + return; + } + add_entity_use(c, n, e); + + check_entity_decl(c, e, NULL, named_type); + + if (e->type == NULL) { + compiler_error("Compiler error: How did this happen? type: %s; identifier: %.*s\n", type_to_string(e->type), LIT(n->Ident.string)); + return; + } + + + Type *type = e->type; + + switch (e->kind) { + case Entity_Constant: + if (type == t_invalid) { + o->type = t_invalid; + return; + } + if (e == e_iota) { + if (c->context.iota.kind == ExactValue_Invalid) { + error(e->token, "Use of `iota` outside a enumeration is not allowed"); + return; + } + o->value = c->context.iota; + } else { + o->value = e->Constant.value; + } + if (o->value.kind == ExactValue_Invalid) { + return; + } + o->mode = Addressing_Constant; + break; + + case Entity_Variable: + e->flags |= EntityFlag_Used; + if (type == t_invalid) { + o->type = t_invalid; + return; + } + #if 0 + if (e->Variable.param) { + o->mode = Addressing_Value; + } else { + o->mode = Addressing_Variable; + } + #else + o->mode = Addressing_Variable; + if (e->Variable.is_immutable) { + o->mode = Addressing_Value; + } + #endif + break; + + case Entity_TypeName: { + o->mode = Addressing_Type; +#if 1 + // TODO(bill): Fix cyclical dependancy checker +#endif + } break; + + case Entity_Procedure: + o->mode = Addressing_Value; + break; + + case Entity_Builtin: + o->builtin_id = e->Builtin.id; + o->mode = Addressing_Builtin; + break; + + case Entity_ImportName: + error_node(n, "Use of import `%.*s` not in selector", LIT(e->ImportName.name)); + return; + + case Entity_Nil: + o->mode = Addressing_Value; + break; + + case Entity_ImplicitValue: + o->mode = Addressing_Value; + break; + + default: + compiler_error("Compiler error: Unknown EntityKind"); + break; + } + + o->type = type; +} + +i64 check_array_count(Checker *c, AstNode *e) { + if (e == NULL) { + return 0; + } + Operand o = {0}; + check_expr(c, &o, e); + if (o.mode != Addressing_Constant) { + if (o.mode != Addressing_Invalid) { + error_node(e, "Array count must be a constant"); + } + return 0; + } + Type *type = base_type(base_enum_type(o.type)); + if (is_type_untyped(type) || is_type_integer(type)) { + if (o.value.kind == ExactValue_Integer) { + i64 count = o.value.value_integer; + if (count >= 0) { + return count; + } + error_node(e, "Invalid array count"); + return 0; + } + } + + error_node(e, "Array count must be an integer"); + return 0; +} + +Type *check_type_extra(Checker *c, AstNode *e, Type *named_type) { + ExactValue null_value = {ExactValue_Invalid}; + Type *type = NULL; + gbString err_str = NULL; + + if (e == NULL) { + type = t_invalid; + goto end; + } + + switch (e->kind) { + case_ast_node(i, Ident, e); + Operand o = {0}; + check_identifier(c, &o, e, named_type); + + switch (o.mode) { + case Addressing_Invalid: + break; + case Addressing_Type: { + type = o.type; + goto end; + } break; + case Addressing_NoValue: + err_str = expr_to_string(e); + error_node(e, "`%s` used as a type", err_str); + break; + default: + err_str = expr_to_string(e); + error_node(e, "`%s` used as a type when not a type", err_str); + break; + } + case_end; + + case_ast_node(se, SelectorExpr, e); + Operand o = {0}; + check_selector(c, &o, e); + + switch (o.mode) { + case Addressing_Invalid: + break; + case Addressing_Type: + GB_ASSERT(o.type != NULL); + type = o.type; + goto end; + case Addressing_NoValue: + err_str = expr_to_string(e); + error_node(e, "`%s` used as a type", err_str); + break; + default: + err_str = expr_to_string(e); + error_node(e, "`%s` is not a type", err_str); + break; + } + case_end; + + case_ast_node(pe, ParenExpr, e); + type = check_type_extra(c, pe->expr, named_type); + goto end; + case_end; + + case_ast_node(ue, UnaryExpr, e); + if (ue->op.kind == Token_Pointer) { + type = make_type_pointer(c->allocator, check_type(c, ue->expr)); + goto end; + } else if (ue->op.kind == Token_Maybe) { + type = make_type_maybe(c->allocator, check_type(c, ue->expr)); + goto end; + } + case_end; + + case_ast_node(ht, HelperType, e); + type = check_type(c, ht->type); + goto end; + case_end; + + case_ast_node(pt, PointerType, e); + Type *elem = check_type(c, pt->type); + type = make_type_pointer(c->allocator, elem); + goto end; + case_end; + + case_ast_node(mt, MaybeType, e); + Type *elem = check_type(c, mt->type); + type = make_type_maybe(c->allocator, elem); + goto end; + case_end; + + case_ast_node(at, ArrayType, e); + if (at->count != NULL) { + Type *elem = check_type_extra(c, at->elem, NULL); + type = make_type_array(c->allocator, elem, check_array_count(c, at->count)); + } else { + Type *elem = check_type(c, at->elem); + type = make_type_slice(c->allocator, elem); + } + goto end; + case_end; + + + case_ast_node(vt, VectorType, e); + Type *elem = check_type(c, vt->elem); + Type *be = base_type(elem); + i64 count = check_array_count(c, vt->count); + if (!is_type_boolean(be) && !is_type_numeric(be)) { + err_str = type_to_string(elem); + error_node(vt->elem, "Vector element type must be numerical or a boolean, got `%s`", err_str); + } + type = make_type_vector(c->allocator, elem, count); + goto end; + case_end; + + case_ast_node(st, StructType, e); + type = make_type_struct(c->allocator); + set_base_type(named_type, type); + check_open_scope(c, e); + check_struct_type(c, type, e); + check_close_scope(c); + type->Record.node = e; + goto end; + case_end; + + case_ast_node(ut, UnionType, e); + type = make_type_union(c->allocator); + set_base_type(named_type, type); + check_open_scope(c, e); + check_union_type(c, type, e); + check_close_scope(c); + type->Record.node = e; + goto end; + case_end; + + case_ast_node(rut, RawUnionType, e); + type = make_type_raw_union(c->allocator); + set_base_type(named_type, type); + check_open_scope(c, e); + check_raw_union_type(c, type, e); + check_close_scope(c); + type->Record.node = e; + goto end; + case_end; + + case_ast_node(et, EnumType, e); + type = make_type_enum(c->allocator); + set_base_type(named_type, type); + check_open_scope(c, e); + check_enum_type(c, type, named_type, e); + check_close_scope(c); + type->Record.node = e; + goto end; + case_end; + + case_ast_node(pt, ProcType, e); + type = alloc_type(c->allocator, Type_Proc); + set_base_type(named_type, type); + check_open_scope(c, e); + check_procedure_type(c, type, e); + check_close_scope(c); + goto end; + case_end; + + + case_ast_node(ce, CallExpr, e); + Operand o = {0}; + check_expr_or_type(c, &o, e); + if (o.mode == Addressing_Type) { + type = o.type; + goto end; + } + case_end; + } + err_str = expr_to_string(e); + error_node(e, "`%s` is not a type", err_str); + + type = t_invalid; +end: + gb_string_free(err_str); + + if (type == NULL) { + type = t_invalid; + } + + if (is_type_named(type)) { + if (type->Named.base == NULL) { + gbString name = type_to_string(type); + error_node(e, "Invalid type definition of %s", name); + gb_string_free(name); + type->Named.base = t_invalid; + } + } + + if (is_type_typed(type)) { + add_type_and_value(&c->info, e, Addressing_Type, type, null_value); + } else { + gbString name = type_to_string(type); + error_node(e, "Invalid type definition of %s", name); + gb_string_free(name); + type = t_invalid; + } + set_base_type(named_type, type); + + + + return type; +} + + +bool check_unary_op(Checker *c, Operand *o, Token op) { + // TODO(bill): Handle errors correctly + Type *type = base_type(base_enum_type(base_vector_type(o->type))); + gbString str = NULL; + switch (op.kind) { + case Token_Add: + case Token_Sub: + if (!is_type_numeric(type)) { + str = expr_to_string(o->expr); + error(op, "Operator `%.*s` is not allowed with `%s`", LIT(op.string), str); + gb_string_free(str); + } + break; + + case Token_Xor: + if (!is_type_integer(type)) { + error(op, "Operator `%.*s` is only allowed with integers", LIT(op.string)); + } + break; + + case Token_Not: + if (!is_type_boolean(type)) { + str = expr_to_string(o->expr); + error(op, "Operator `%.*s` is only allowed on boolean expression", LIT(op.string)); + gb_string_free(str); + } + break; + + default: + error(op, "Unknown operator `%.*s`", LIT(op.string)); + return false; + } + + return true; +} + +bool check_binary_op(Checker *c, Operand *o, Token op) { + // TODO(bill): Handle errors correctly + Type *type = base_type(base_enum_type(base_vector_type(o->type))); + switch (op.kind) { + case Token_Sub: + case Token_SubEq: + if (!is_type_numeric(type) && !is_type_pointer(type)) { + error(op, "Operator `%.*s` is only allowed with numeric or pointer expressions", LIT(op.string)); + return false; + } + if (is_type_pointer(type)) { + o->type = t_int; + } + if (base_type(type) == t_rawptr) { + gbString str = type_to_string(type); + error_node(o->expr, "Invalid pointer type for pointer arithmetic: `%s`", str); + gb_string_free(str); + return false; + } + break; + + case Token_Add: + case Token_Mul: + case Token_Quo: + case Token_AddEq: + case Token_MulEq: + case Token_QuoEq: + if (!is_type_numeric(type)) { + error(op, "Operator `%.*s` is only allowed with numeric expressions", LIT(op.string)); + return false; + } + break; + + case Token_And: + case Token_Or: + case Token_AndEq: + case Token_OrEq: + if (!is_type_integer(type) && !is_type_boolean(type)) { + error(op, "Operator `%.*s` is only allowed with integers or booleans", LIT(op.string)); + return false; + } + break; + + case Token_Mod: + case Token_Xor: + case Token_AndNot: + case Token_ModEq: + case Token_XorEq: + case Token_AndNotEq: + if (!is_type_integer(type)) { + error(op, "Operator `%.*s` is only allowed with integers", LIT(op.string)); + return false; + } + break; + + case Token_CmpAnd: + case Token_CmpOr: + case Token_CmpAndEq: + case Token_CmpOrEq: + if (!is_type_boolean(type)) { + error(op, "Operator `%.*s` is only allowed with boolean expressions", LIT(op.string)); + return false; + } + break; + + default: + error(op, "Unknown operator `%.*s`", LIT(op.string)); + return false; + } + + return true; + +} +bool check_value_is_expressible(Checker *c, ExactValue in_value, Type *type, ExactValue *out_value) { + if (in_value.kind == ExactValue_Invalid) { + // NOTE(bill): There's already been an error + return true; + } + + type = base_type(base_enum_type(type)); + + if (is_type_boolean(type)) { + return in_value.kind == ExactValue_Bool; + } else if (is_type_string(type)) { + return in_value.kind == ExactValue_String; + } else if (is_type_integer(type)) { + ExactValue v = exact_value_to_integer(in_value); + if (v.kind != ExactValue_Integer) { + return false; + } + if (out_value) *out_value = v; + i64 i = v.value_integer; + u64 u = *cast(u64 *)&i; + i64 s = 8*type_size_of(c->sizes, c->allocator, type); + u64 umax = ~0ull; + if (s < 64) { + umax = (1ull << s) - 1ull; + } else { + // TODO(bill): I NEED A PROPER BIG NUMBER LIBRARY THAT CAN SUPPORT 128 bit integers and floats + s = 64; + } + i64 imax = (1ll << (s-1ll)); + + + switch (type->Basic.kind) { + case Basic_i8: + case Basic_i16: + case Basic_i32: + case Basic_i64: + // case Basic_i128: + case Basic_int: + return gb_is_between(i, -imax, imax-1); + + case Basic_u8: + case Basic_u16: + case Basic_u32: + case Basic_u64: + // case Basic_u128: + case Basic_uint: + return !(u < 0 || u > umax); + + case Basic_UntypedInteger: + return true; + + default: GB_PANIC("Compiler error: Unknown integer type!"); break; + } + } else if (is_type_float(type)) { + ExactValue v = exact_value_to_float(in_value); + if (v.kind != ExactValue_Float) { + return false; + } + + switch (type->Basic.kind) { + // case Basic_f16: + case Basic_f32: + case Basic_f64: + // case Basic_f128: + if (out_value) *out_value = v; + return true; + + case Basic_UntypedFloat: + return true; + } + } else if (is_type_pointer(type)) { + if (in_value.kind == ExactValue_Pointer) { + return true; + } + if (in_value.kind == ExactValue_Integer) { + return true; + } + if (out_value) *out_value = in_value; + } + + + return false; +} + +void check_is_expressible(Checker *c, Operand *o, Type *type) { + GB_ASSERT(is_type_constant_type(type)); + GB_ASSERT(o->mode == Addressing_Constant); + if (!check_value_is_expressible(c, o->value, type, &o->value)) { + gbString a = expr_to_string(o->expr); + gbString b = type_to_string(type); + if (is_type_numeric(o->type) && is_type_numeric(type)) { + if (!is_type_integer(o->type) && is_type_integer(type)) { + error_node(o->expr, "`%s` truncated to `%s`", a, b); + } else { + error_node(o->expr, "`%s = %lld` overflows `%s`", a, o->value.value_integer, b); + } + } else { + error_node(o->expr, "Cannot convert `%s` to `%s`", a, b); + } + + gb_string_free(b); + gb_string_free(a); + o->mode = Addressing_Invalid; + } +} + +bool check_is_expr_vector_index(Checker *c, AstNode *expr) { + // HACK(bill): Handle this correctly. Maybe with a custom AddressingMode + expr = unparen_expr(expr); + if (expr->kind == AstNode_IndexExpr) { + ast_node(ie, IndexExpr, expr); + Type *t = type_deref(type_of_expr(&c->info, ie->expr)); + if (t != NULL) { + return is_type_vector(t); + } + } + return false; +} + +bool check_is_vector_elem(Checker *c, AstNode *expr) { + // HACK(bill): Handle this correctly. Maybe with a custom AddressingMode + expr = unparen_expr(expr); + if (expr->kind == AstNode_SelectorExpr) { + ast_node(se, SelectorExpr, expr); + Type *t = type_deref(type_of_expr(&c->info, se->expr)); + if (t != NULL && is_type_vector(t)) { + return true; + } + } + return false; +} + +void check_unary_expr(Checker *c, Operand *o, Token op, AstNode *node) { + switch (op.kind) { + case Token_Pointer: { // Pointer address + if (o->mode == Addressing_Type) { + o->type = make_type_pointer(c->allocator, o->type); + return; + } + + if (o->mode != Addressing_Variable || + check_is_expr_vector_index(c, o->expr) || + check_is_vector_elem(c, o->expr)) { + if (ast_node_expect(node, AstNode_UnaryExpr)) { + ast_node(ue, UnaryExpr, node); + gbString str = expr_to_string(ue->expr); + error(op, "Cannot take the pointer address of `%s`", str); + gb_string_free(str); + } + o->mode = Addressing_Invalid; + return; + } + o->mode = Addressing_Value; + o->type = make_type_pointer(c->allocator, o->type); + return; + } + + case Token_Maybe: { // Make maybe + Type *t = default_type(o->type); + + if (o->mode == Addressing_Type) { + o->type = make_type_pointer(c->allocator, t); + return; + } + + bool is_value = + o->mode == Addressing_Variable || + o->mode == Addressing_Value || + o->mode == Addressing_Constant; + + if (!is_value || is_type_untyped(t)) { + if (ast_node_expect(node, AstNode_UnaryExpr)) { + ast_node(ue, UnaryExpr, node); + gbString str = expr_to_string(ue->expr); + error(op, "Cannot convert `%s` to a maybe", str); + gb_string_free(str); + } + o->mode = Addressing_Invalid; + return; + } + o->mode = Addressing_Value; + o->type = make_type_maybe(c->allocator, t); + return; + } + } + + if (!check_unary_op(c, o, op)) { + o->mode = Addressing_Invalid; + return; + } + + if (o->mode == Addressing_Constant) { + Type *type = base_type(o->type); + if (!is_type_constant_type(o->type)) { + gbString xt = type_to_string(o->type); + gbString err_str = expr_to_string(node); + error(op, "Invalid type, `%s`, for constant unary expression `%s`", xt, err_str); + gb_string_free(err_str); + gb_string_free(xt); + o->mode = Addressing_Invalid; + return; + } + + + i32 precision = 0; + if (is_type_unsigned(type)) { + precision = cast(i32)(8 * type_size_of(c->sizes, c->allocator, type)); + } + o->value = exact_unary_operator_value(op.kind, o->value, precision); + + if (is_type_typed(type)) { + if (node != NULL) { + o->expr = node; + } + check_is_expressible(c, o, type); + } + return; + } + + o->mode = Addressing_Value; +} + +void check_comparison(Checker *c, Operand *x, Operand *y, Token op) { + gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&c->tmp_arena); + + gbString err_str = NULL; + + if (check_is_assignable_to(c, x, y->type) || + check_is_assignable_to(c, y, x->type)) { + Type *err_type = x->type; + bool defined = false; + switch (op.kind) { + case Token_CmpEq: + case Token_NotEq: + defined = is_type_comparable(x->type); + break; + case Token_Lt: + case Token_Gt: + case Token_LtEq: + case Token_GtEq: { + defined = is_type_ordered(x->type); + } break; + } + + // CLEANUP(bill) NOTE(bill): there is an auto assignment to `any` which needs to be checked + if (is_type_any(x->type) && !is_type_any(y->type)) { + err_type = x->type; + defined = false; + } else if (is_type_any(y->type) && !is_type_any(x->type)) { + err_type = y->type; + defined = false; + } + + if (!defined) { + gbString type_string = type_to_string(err_type); + err_str = gb_string_make(c->tmp_allocator, + gb_bprintf("operator `%.*s` not defined for type `%s`", LIT(op.string), type_string)); + gb_string_free(type_string); + } + } else { + gbString xt = type_to_string(x->type); + gbString yt = type_to_string(y->type); + err_str = gb_string_make(c->tmp_allocator, + gb_bprintf("mismatched types `%s` and `%s`", xt, yt)); + gb_string_free(yt); + gb_string_free(xt); + } + + if (err_str != NULL) { + error_node(x->expr, "Cannot compare expression, %s", err_str); + x->type = t_untyped_bool; + } else { + if (x->mode == Addressing_Constant && + y->mode == Addressing_Constant) { + x->value = make_exact_value_bool(compare_exact_values(op.kind, x->value, y->value)); + } else { + x->mode = Addressing_Value; + + update_expr_type(c, x->expr, default_type(x->type), true); + update_expr_type(c, y->expr, default_type(y->type), true); + } + + if (is_type_vector(base_type(y->type))) { + x->type = make_type_vector(c->allocator, t_bool, base_type(y->type)->Vector.count); + } else { + x->type = t_untyped_bool; + } + } + + if (err_str != NULL) { + gb_string_free(err_str); + }; + + gb_temp_arena_memory_end(tmp); +} + +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}; + if (x->mode == Addressing_Constant) { + x_val = exact_value_to_integer(x->value); + } + + bool x_is_untyped = is_type_untyped(x->type); + if (!(is_type_integer(base_enum_type(x->type)) || (x_is_untyped && x_val.kind == ExactValue_Integer))) { + gbString err_str = expr_to_string(x->expr); + error_node(node, "Shifted operand `%s` must be an integer", err_str); + gb_string_free(err_str); + x->mode = Addressing_Invalid; + return; + } + + if (is_type_unsigned(base_enum_type(y->type))) { + + } else if (is_type_untyped(y->type)) { + convert_to_typed(c, y, t_untyped_integer, 0); + if (y->mode == Addressing_Invalid) { + x->mode = Addressing_Invalid; + return; + } + } else { + gbString err_str = expr_to_string(y->expr); + error_node(node, "Shift amount `%s` must be an unsigned integer", err_str); + gb_string_free(err_str); + x->mode = Addressing_Invalid; + return; + } + + + if (x->mode == Addressing_Constant) { + if (y->mode == Addressing_Constant) { + ExactValue y_val = exact_value_to_integer(y->value); + if (y_val.kind != ExactValue_Integer) { + gbString err_str = expr_to_string(y->expr); + error_node(node, "Shift amount `%s` must be an unsigned integer", err_str); + gb_string_free(err_str); + x->mode = Addressing_Invalid; + return; + } + + u64 amount = cast(u64)y_val.value_integer; + if (amount > 1074) { + gbString err_str = expr_to_string(y->expr); + error_node(node, "Shift amount too large: `%s`", err_str); + gb_string_free(err_str); + x->mode = Addressing_Invalid; + return; + } + + if (!is_type_integer(base_enum_type(x->type))) { + // NOTE(bill): It could be an untyped float but still representable + // as an integer + x->type = t_untyped_integer; + } + + x->value = exact_value_shift(be->op.kind, x_val, make_exact_value_integer(amount)); + + if (is_type_typed(x->type)) { + check_is_expressible(c, x, base_type(base_enum_type(x->type))); + } + return; + } + + if (x_is_untyped) { + ExprInfo *info = map_expr_info_get(&c->info.untyped, hash_pointer(x->expr)); + if (info != NULL) { + info->is_lhs = true; + } + x->mode = Addressing_Value; + return; + } + } + + if (y->mode == Addressing_Constant && y->value.value_integer < 0) { + gbString err_str = expr_to_string(y->expr); + error_node(node, "Shift amount cannot be negative: `%s`", err_str); + gb_string_free(err_str); + } + + x->mode = Addressing_Value; +} + +bool check_is_castable_to(Checker *c, Operand *operand, Type *y) { + if (check_is_assignable_to(c, operand, y)) { + return true; + } + + Type *x = operand->type; + Type *xb = base_type(base_enum_type(x)); + Type *yb = base_type(base_enum_type(y)); + if (are_types_identical(xb, yb)) { + return true; + } + + + // Cast between booleans and integers + if (is_type_boolean(xb) || is_type_integer(xb)) { + if (is_type_boolean(yb) || is_type_integer(yb)) { + return true; + } + } + + // Cast between numbers + if (is_type_integer(xb) || is_type_float(xb)) { + if (is_type_integer(yb) || is_type_float(yb)) { + return true; + } + } + + // Cast between pointers + if (is_type_pointer(xb) && is_type_pointer(yb)) { + return true; + } + + // (u)int <-> pointer + if (is_type_int_or_uint(xb) && is_type_rawptr(yb)) { + return true; + } + if (is_type_rawptr(xb) && is_type_int_or_uint(yb)) { + return true; + } + + // []byte/[]u8 <-> string + if (is_type_u8_slice(xb) && is_type_string(yb)) { + return true; + } + if (is_type_string(xb) && is_type_u8_slice(yb)) { + if (is_type_typed(xb)) { + return true; + } + } + + // proc <-> proc + if (is_type_proc(xb) && is_type_proc(yb)) { + return true; + } + + // proc -> rawptr + if (is_type_proc(xb) && is_type_rawptr(yb)) { + return true; + } + // rawptr -> proc + if (is_type_rawptr(xb) && is_type_proc(yb)) { + return true; + } + + return false; +} + +String check_down_cast_name(Type *dst_, Type *src_) { + String result = {0}; + Type *dst = type_deref(dst_); + Type *src = type_deref(src_); + Type *dst_s = base_type(dst); + GB_ASSERT(is_type_struct(dst_s) || is_type_raw_union(dst_s)); + for (isize i = 0; i < dst_s->Record.field_count; i++) { + Entity *f = dst_s->Record.fields[i]; + GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field); + if (f->flags & EntityFlag_Anonymous) { + if (are_types_identical(f->type, src_)) { + return f->token.string; + } + if (are_types_identical(type_deref(f->type), src_)) { + return f->token.string; + } + + if (!is_type_pointer(f->type)) { + result = check_down_cast_name(f->type, src_); + if (result.len > 0) { + return result; + } + } + } + } + + return result; +} + +Operand check_ptr_addition(Checker *c, TokenKind op, Operand *ptr, Operand *offset, AstNode *node) { + GB_ASSERT(node->kind == AstNode_BinaryExpr); + ast_node(be, BinaryExpr, node); + GB_ASSERT(is_type_pointer(ptr->type)); + GB_ASSERT(is_type_integer(offset->type)); + GB_ASSERT(op == Token_Add || op == Token_Sub); + + Operand operand = {0}; + operand.mode = Addressing_Value; + operand.type = ptr->type; + operand.expr = node; + + if (base_type(ptr->type) == t_rawptr) { + gbString str = type_to_string(ptr->type); + error_node(node, "Invalid pointer type for pointer arithmetic: `%s`", str); + gb_string_free(str); + operand.mode = Addressing_Invalid; + return operand; + } + + + if (ptr->mode == Addressing_Constant && offset->mode == Addressing_Constant) { + i64 elem_size = type_size_of(c->sizes, c->allocator, ptr->type); + i64 ptr_val = ptr->value.value_pointer; + i64 offset_val = exact_value_to_integer(offset->value).value_integer; + i64 new_ptr_val = ptr_val; + if (op == Token_Add) { + new_ptr_val += elem_size*offset_val; + } else { + new_ptr_val -= elem_size*offset_val; + } + operand.mode = Addressing_Constant; + operand.value = make_exact_value_pointer(new_ptr_val); + } + + return operand; +} + +void check_binary_expr(Checker *c, Operand *x, AstNode *node) { + GB_ASSERT(node->kind == AstNode_BinaryExpr); + Operand y_ = {0}, *y = &y_; + + ast_node(be, BinaryExpr, node); + + if (be->op.kind == Token_as) { + check_expr(c, x, be->left); + Type *type = check_type(c, be->right); + if (x->mode == Addressing_Invalid) { + return; + } + + bool is_const_expr = x->mode == Addressing_Constant; + bool can_convert = false; + + Type *bt = base_type(type); + if (is_const_expr && is_type_constant_type(bt)) { + if (bt->kind == Type_Basic) { + if (check_value_is_expressible(c, x->value, bt, &x->value)) { + can_convert = true; + } + } + } else if (check_is_castable_to(c, x, type)) { + if (x->mode != Addressing_Constant) { + x->mode = Addressing_Value; + } + can_convert = true; + } + + if (!can_convert) { + gbString expr_str = expr_to_string(x->expr); + gbString to_type = type_to_string(type); + gbString from_type = type_to_string(x->type); + error_node(x->expr, "Cannot cast `%s` as `%s` from `%s`", expr_str, to_type, from_type); + gb_string_free(from_type); + gb_string_free(to_type); + gb_string_free(expr_str); + + x->mode = Addressing_Invalid; + return; + } + + if (is_type_untyped(x->type)) { + Type *final_type = type; + if (is_const_expr && !is_type_constant_type(type)) { + final_type = default_type(x->type); + } + update_expr_type(c, x->expr, final_type, true); + } + + x->type = type; + return; + } else if (be->op.kind == Token_transmute) { + check_expr(c, x, be->left); + Type *type = check_type(c, be->right); + if (x->mode == Addressing_Invalid) { + return; + } + + if (x->mode == Addressing_Constant) { + gbString expr_str = expr_to_string(x->expr); + error_node(x->expr, "Cannot transmute constant expression: `%s`", expr_str); + gb_string_free(expr_str); + x->mode = Addressing_Invalid; + return; + } + + if (is_type_untyped(x->type)) { + gbString expr_str = expr_to_string(x->expr); + error_node(x->expr, "Cannot transmute untyped expression: `%s`", expr_str); + gb_string_free(expr_str); + x->mode = Addressing_Invalid; + return; + } + + i64 srcz = type_size_of(c->sizes, c->allocator, x->type); + i64 dstz = type_size_of(c->sizes, c->allocator, type); + if (srcz != dstz) { + gbString expr_str = expr_to_string(x->expr); + gbString type_str = type_to_string(type); + error_node(x->expr, "Cannot transmute `%s` to `%s`, %lld vs %lld bytes", expr_str, type_str, srcz, dstz); + gb_string_free(type_str); + gb_string_free(expr_str); + x->mode = Addressing_Invalid; + return; + } + + x->type = type; + + return; + } else if (be->op.kind == Token_down_cast) { + check_expr(c, x, be->left); + Type *type = check_type(c, be->right); + if (x->mode == Addressing_Invalid) { + return; + } + + if (x->mode == Addressing_Constant) { + gbString expr_str = expr_to_string(node); + error_node(node, "Cannot `down_cast` a constant expression: `%s`", expr_str); + gb_string_free(expr_str); + x->mode = Addressing_Invalid; + return; + } + + if (is_type_untyped(x->type)) { + gbString expr_str = expr_to_string(node); + error_node(node, "Cannot `down_cast` an untyped expression: `%s`", expr_str); + gb_string_free(expr_str); + x->mode = Addressing_Invalid; + return; + } + + if (!(is_type_pointer(x->type) && is_type_pointer(type))) { + gbString expr_str = expr_to_string(node); + error_node(node, "Can only `down_cast` pointers: `%s`", expr_str); + gb_string_free(expr_str); + x->mode = Addressing_Invalid; + return; + } + + Type *src = type_deref(x->type); + Type *dst = type_deref(type); + Type *bsrc = base_type(src); + Type *bdst = base_type(dst); + + if (!(is_type_struct(bsrc) || is_type_raw_union(bsrc))) { + gbString expr_str = expr_to_string(node); + error_node(node, "Can only `down_cast` pointer from structs or unions: `%s`", expr_str); + gb_string_free(expr_str); + x->mode = Addressing_Invalid; + return; + } + + if (!(is_type_struct(bdst) || is_type_raw_union(bdst))) { + gbString expr_str = expr_to_string(node); + error_node(node, "Can only `down_cast` pointer to structs or unions: `%s`", expr_str); + gb_string_free(expr_str); + x->mode = Addressing_Invalid; + return; + } + + String param_name = check_down_cast_name(dst, src); + if (param_name.len == 0) { + gbString expr_str = expr_to_string(node); + error_node(node, "Illegal `down_cast`: `%s`", expr_str); + gb_string_free(expr_str); + x->mode = Addressing_Invalid; + return; + } + + x->mode = Addressing_Value; + x->type = type; + return; + } else if (be->op.kind == Token_union_cast) { + check_expr(c, x, be->left); + Type *type = check_type(c, be->right); + if (x->mode == Addressing_Invalid) { + return; + } + + if (x->mode == Addressing_Constant) { + gbString expr_str = expr_to_string(node); + error_node(node, "Cannot `union_cast` a constant expression: `%s`", expr_str); + gb_string_free(expr_str); + x->mode = Addressing_Invalid; + return; + } + + if (is_type_untyped(x->type)) { + gbString expr_str = expr_to_string(node); + error_node(node, "Cannot `union_cast` an untyped expression: `%s`", expr_str); + gb_string_free(expr_str); + x->mode = Addressing_Invalid; + return; + } + + bool src_is_ptr = is_type_pointer(x->type); + bool dst_is_ptr = is_type_pointer(type); + Type *src = type_deref(x->type); + Type *dst = type_deref(type); + Type *bsrc = base_type(src); + Type *bdst = base_type(dst); + + if (src_is_ptr != dst_is_ptr) { + gbString src_type_str = type_to_string(x->type); + gbString dst_type_str = type_to_string(type); + error_node(node, "Invalid `union_cast` types: `%s` and `%s`", src_type_str, dst_type_str); + gb_string_free(dst_type_str); + gb_string_free(src_type_str); + x->mode = Addressing_Invalid; + return; + } + + if (!is_type_union(src)) { + error_node(node, "`union_cast` can only operate on unions"); + x->mode = Addressing_Invalid; + return; + } + + bool ok = false; + for (isize i = 1; i < bsrc->Record.field_count; i++) { + Entity *f = bsrc->Record.fields[i]; + if (are_types_identical(f->type, dst)) { + ok = true; + break; + } + } + + if (!ok) { + gbString expr_str = expr_to_string(node); + gbString dst_type_str = type_to_string(type); + error_node(node, "Cannot `union_cast` `%s` to `%s`", expr_str, dst_type_str); + gb_string_free(dst_type_str); + gb_string_free(expr_str); + x->mode = Addressing_Invalid; + return; + } + + Entity **variables = gb_alloc_array(c->allocator, Entity *, 2); + variables[0] = make_entity_param(c->allocator, NULL, empty_token, type, false); + variables[1] = make_entity_param(c->allocator, NULL, empty_token, t_bool, false); + + Type *tuple = make_type_tuple(c->allocator); + tuple->Tuple.variables = variables; + tuple->Tuple.variable_count = 2; + + x->type = tuple; + x->mode = Addressing_Value; + return; + } + + check_expr(c, x, be->left); + check_expr(c, y, be->right); + if (x->mode == Addressing_Invalid) { + return; + } + if (y->mode == Addressing_Invalid) { + x->mode = Addressing_Invalid; + x->expr = y->expr; + return; + } + + Token op = be->op; + + if (token_is_shift(op)) { + check_shift(c, x, y, node); + return; + } + + if (op.kind == Token_Add || op.kind == Token_Sub) { + if (is_type_pointer(x->type) && is_type_integer(base_enum_type(y->type))) { + *x = check_ptr_addition(c, op.kind, x, y, node); + return; + } else if (is_type_integer(base_enum_type(x->type)) && is_type_pointer(y->type)) { + if (op.kind == Token_Sub) { + gbString lhs = expr_to_string(x->expr); + gbString rhs = expr_to_string(y->expr); + error_node(node, "Invalid pointer arithmetic, did you mean `%s %.*s %s`?", rhs, LIT(op.string), lhs); + gb_string_free(rhs); + gb_string_free(lhs); + x->mode = Addressing_Invalid; + return; + } + *x = check_ptr_addition(c, op.kind, y, x, node); + return; + } + } + + + convert_to_typed(c, x, y->type, 0); + if (x->mode == Addressing_Invalid) { + return; + } + convert_to_typed(c, y, x->type, 0); + if (y->mode == Addressing_Invalid) { + x->mode = Addressing_Invalid; + return; + } + + if (token_is_comparison(op)) { + check_comparison(c, x, y, op); + return; + } + + if (!are_types_identical(x->type, y->type)) { + if (x->type != t_invalid && + y->type != t_invalid) { + gbString xt = type_to_string(x->type); + gbString yt = type_to_string(y->type); + gbString expr_str = expr_to_string(x->expr); + error(op, "Mismatched types in binary expression `%s` : `%s` vs `%s`", expr_str, xt, yt); + gb_string_free(expr_str); + gb_string_free(yt); + gb_string_free(xt); + } + x->mode = Addressing_Invalid; + return; + } + + if (!check_binary_op(c, x, op)) { + x->mode = Addressing_Invalid; + return; + } + + switch (op.kind) { + case Token_Quo: + case Token_Mod: + case Token_QuoEq: + case Token_ModEq: + if ((x->mode == Addressing_Constant || is_type_integer(x->type)) && + y->mode == Addressing_Constant) { + bool fail = false; + switch (y->value.kind) { + case ExactValue_Integer: + if (y->value.value_integer == 0) { + fail = true; + } + break; + case ExactValue_Float: + if (y->value.value_float == 0.0) { + fail = true; + } + break; + } + + if (fail) { + error_node(y->expr, "Division by zero not allowed"); + x->mode = Addressing_Invalid; + return; + } + } + } + + if (x->mode == Addressing_Constant && + y->mode == Addressing_Constant) { + ExactValue a = x->value; + ExactValue b = y->value; + + Type *type = base_type(x->type); + if (is_type_pointer(type)) { + GB_ASSERT(op.kind == Token_Sub); + i64 bytes = a.value_pointer - b.value_pointer; + i64 diff = bytes/type_size_of(c->sizes, c->allocator, type); + x->value = make_exact_value_pointer(diff); + return; + } + + if (!is_type_constant_type(type)) { + gbString xt = type_to_string(x->type); + gbString err_str = expr_to_string(node); + error(op, "Invalid type, `%s`, for constant binary expression `%s`", xt, err_str); + gb_string_free(err_str); + gb_string_free(xt); + x->mode = Addressing_Invalid; + return; + } + + if (op.kind == Token_Quo && is_type_integer(type)) { + op.kind = Token_QuoEq; // NOTE(bill): Hack to get division of integers + } + x->value = exact_binary_operator_value(op.kind, a, b); + if (is_type_typed(type)) { + if (node != NULL) { + x->expr = node; + } + check_is_expressible(c, x, type); + } + return; + } + + x->mode = Addressing_Value; +} + + +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); + if (found == NULL) { + return; + } + + switch (e->kind) { + case_ast_node(ue, UnaryExpr, e); + if (found->value.kind != ExactValue_Invalid) { + break; + } + update_expr_type(c, ue->expr, type, final); + case_end; + + case_ast_node(be, BinaryExpr, e); + if (found->value.kind != ExactValue_Invalid) { + break; + } + if (!token_is_comparison(be->op)) { + if (token_is_shift(be->op)) { + update_expr_type(c, be->left, type, final); + } else { + update_expr_type(c, be->left, type, final); + update_expr_type(c, be->right, type, final); + } + } + case_end; + } + + if (!final && is_type_untyped(type)) { + found->type = base_type(type); + map_expr_info_set(&c->info.untyped, key, *found); + } else { + ExprInfo old = *found; + map_expr_info_remove(&c->info.untyped, key); + + if (old.is_lhs && !is_type_integer(type)) { + gbString expr_str = expr_to_string(e); + gbString type_str = type_to_string(type); + error_node(e, "Shifted operand %s must be an integer, got %s", expr_str, type_str); + gb_string_free(type_str); + gb_string_free(expr_str); + return; + } + + add_type_and_value(&c->info, e, found->mode, type, found->value); + } +} + +void update_expr_value(Checker *c, AstNode *e, ExactValue value) { + ExprInfo *found = map_expr_info_get(&c->info.untyped, hash_pointer(e)); + if (found) { + found->value = value; + } +} + +void convert_untyped_error(Checker *c, Operand *operand, Type *target_type) { + gbString expr_str = expr_to_string(operand->expr); + gbString type_str = type_to_string(target_type); + char *extra_text = ""; + + if (operand->mode == Addressing_Constant) { + if (operand->value.value_integer == 0) { + if (str_ne(make_string_c(expr_str), str_lit("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`?"; + } + } + } + error_node(operand->expr, "Cannot convert `%s` to `%s`%s", expr_str, type_str, extra_text); + + gb_string_free(type_str); + gb_string_free(expr_str); + operand->mode = Addressing_Invalid; +} + +// NOTE(bill): Set initial level to 0 +void convert_to_typed(Checker *c, Operand *operand, Type *target_type, i32 level) { + GB_ASSERT_NOT_NULL(target_type); + if (operand->mode == Addressing_Invalid || + is_type_typed(operand->type) || + target_type == t_invalid) { + return; + } + + if (is_type_untyped(target_type)) { + GB_ASSERT(operand->type->kind == Type_Basic); + GB_ASSERT(target_type->kind == Type_Basic); + BasicKind x_kind = operand->type->Basic.kind; + BasicKind y_kind = target_type->Basic.kind; + if (is_type_numeric(operand->type) && is_type_numeric(target_type)) { + if (x_kind < y_kind) { + operand->type = target_type; + update_expr_type(c, operand->expr, target_type, false); + } + } else if (x_kind != y_kind) { + convert_untyped_error(c, operand, target_type); + } + return; + } + + Type *t = base_type(base_enum_type(target_type)); + switch (t->kind) { + case Type_Basic: + if (operand->mode == Addressing_Constant) { + check_is_expressible(c, operand, t); + if (operand->mode == Addressing_Invalid) { + return; + } + update_expr_value(c, operand->expr, operand->value); + } else { + switch (operand->type->Basic.kind) { + case Basic_UntypedBool: + if (!is_type_boolean(target_type)) { + convert_untyped_error(c, operand, target_type); + return; + } + break; + case Basic_UntypedInteger: + case Basic_UntypedFloat: + case Basic_UntypedRune: + if (!is_type_numeric(target_type)) { + convert_untyped_error(c, operand, target_type); + return; + } + break; + + case Basic_UntypedNil: + if (!type_has_nil(target_type)) { + convert_untyped_error(c, operand, target_type); + return; + } + break; + } + } + break; + + case Type_Maybe: + if (is_type_untyped_nil(operand->type)) { + // Okay + } else if (level == 0) { + convert_to_typed(c, operand, t->Maybe.elem, level+1); + return; + } + + default: + if (!is_type_untyped_nil(operand->type) || !type_has_nil(target_type)) { + convert_untyped_error(c, operand, target_type); + return; + } + break; + } + + + + operand->type = target_type; +} + +bool check_index_value(Checker *c, AstNode *index_value, i64 max_count, i64 *value) { + Operand operand = {Addressing_Invalid}; + check_expr(c, &operand, index_value); + if (operand.mode == Addressing_Invalid) { + if (value) *value = 0; + return false; + } + + convert_to_typed(c, &operand, t_int, 0); + if (operand.mode == Addressing_Invalid) { + if (value) *value = 0; + return false; + } + + if (!is_type_integer(base_enum_type(operand.type))) { + gbString expr_str = expr_to_string(operand.expr); + error_node(operand.expr, "Index `%s` must be an integer", expr_str); + gb_string_free(expr_str); + if (value) *value = 0; + return false; + } + + if (operand.mode == Addressing_Constant && + (c->context.stmt_state_flags & StmtStateFlag_bounds_check) != 0) { + i64 i = exact_value_to_integer(operand.value).value_integer; + if (i < 0) { + gbString expr_str = expr_to_string(operand.expr); + error_node(operand.expr, "Index `%s` cannot be a negative value", expr_str); + gb_string_free(expr_str); + if (value) *value = 0; + return false; + } + + if (max_count >= 0) { // NOTE(bill): Do array bound checking + if (value) *value = i; + if (i >= max_count) { + gbString expr_str = expr_to_string(operand.expr); + error_node(operand.expr, "Index `%s` is out of bounds range 0..<%lld", expr_str, max_count); + gb_string_free(expr_str); + return false; + } + + return true; + } + } + + // NOTE(bill): It's alright :D + if (value) *value = -1; + return true; +} + +Entity *check_selector(Checker *c, Operand *operand, AstNode *node) { + ast_node(se, SelectorExpr, node); + + 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 + + AstNode *op_expr = se->expr; + AstNode *selector = unparen_expr(se->selector); + if (selector == NULL) { + goto error; + } + + if (ast_node_expect(selector, AstNode_Ident)) { + + } + + if (op_expr->kind == AstNode_Ident) { + String name = op_expr->Ident.string; + Entity *e = scope_lookup_entity(c->context.scope, name); + add_entity_use(c, op_expr, e); + expr_entity = e; + if (e != NULL && e->kind == Entity_ImportName && + selector->kind == AstNode_Ident) { + String sel_name = selector->Ident.string; + check_op_expr = false; + entity = scope_lookup_entity(e->ImportName.scope, sel_name); + if (entity == NULL) { + error_node(op_expr, "`%.*s` is not declared by `%.*s`", LIT(sel_name), LIT(name)); + goto error; + } + if (entity->type == NULL) { // Not setup yet + check_entity_decl(c, entity, NULL, NULL); + } + GB_ASSERT(entity->type != NULL); + + b32 is_not_exported = true; + Entity **found = map_entity_get(&e->ImportName.scope->implicit, hash_string(sel_name)); + if (found == NULL) { + is_not_exported = false; + } else { + Entity *f = *found; + if (f->kind == Entity_ImportName) { + is_not_exported = true; + } + } + + if (is_not_exported) { + gbString sel_str = expr_to_string(selector); + error_node(op_expr, "`%s` is not exported by `%.*s`", sel_str, LIT(name)); + gb_string_free(sel_str); + // NOTE(bill): Not really an error so don't goto error + } + + add_entity_use(c, selector, entity); + } + } + if (check_op_expr) { + check_expr_base(c, operand, op_expr, NULL); + if (operand->mode == Addressing_Invalid) { + goto error; + } + } + + + if (entity == NULL && selector->kind == AstNode_Ident) { + sel = lookup_field(c->allocator, operand->type, selector->Ident.string, operand->mode == Addressing_Type); + entity = sel.entity; + } + if (entity == NULL) { + gbString op_str = expr_to_string(op_expr); + gbString type_str = type_to_string(operand->type); + gbString sel_str = expr_to_string(selector); + error_node(op_expr, "`%s` (`%s`) has no field `%s`", op_str, type_str, sel_str); + gb_string_free(sel_str); + gb_string_free(type_str); + gb_string_free(op_str); + goto error; + } + + if (expr_entity != NULL && expr_entity->kind == Entity_Constant && entity->kind != Entity_Constant) { + gbString op_str = expr_to_string(op_expr); + gbString type_str = type_to_string(operand->type); + gbString sel_str = expr_to_string(selector); + error_node(op_expr, "Cannot access non-constant field `%s` from `%s`", sel_str, op_str); + gb_string_free(sel_str); + gb_string_free(type_str); + gb_string_free(op_str); + goto error; + } + + + add_entity_use(c, selector, entity); + + switch (entity->kind) { + case Entity_Constant: + operand->mode = Addressing_Constant; + operand->value = entity->Constant.value; + break; + case Entity_Variable: + // TODO(bill): This is the rule I need? + if (sel.indirect || operand->mode != Addressing_Value) { + operand->mode = Addressing_Variable; + } + break; + case Entity_TypeName: + operand->mode = Addressing_Type; + break; + case Entity_Procedure: + operand->mode = Addressing_Value; + break; + case Entity_Builtin: + operand->mode = Addressing_Builtin; + operand->builtin_id = entity->Builtin.id; + break; + + // NOTE(bill): These cases should never be hit but are here for sanity reasons + case Entity_Nil: + operand->mode = Addressing_Value; + break; + case Entity_ImplicitValue: + operand->mode = Addressing_Value; + break; + } + + operand->type = entity->type; + operand->expr = node; + + return entity; + +error: + operand->mode = Addressing_Invalid; + operand->expr = node; + return NULL; +} + +bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id) { + GB_ASSERT(call->kind == AstNode_CallExpr); + ast_node(ce, CallExpr, call); + BuiltinProc *bp = &builtin_procs[id]; + { + char *err = NULL; + if (ce->args.count < bp->arg_count) { + err = "Too few"; + } else if (ce->args.count > bp->arg_count && !bp->variadic) { + err = "Too many"; + } + + if (err) { + ast_node(proc, Ident, ce->proc); + error(ce->close, "`%s` arguments for `%.*s`, expected %td, got %td", + err, LIT(proc->string), + bp->arg_count, ce->args.count); + return false; + } + } + + switch (id) { + case BuiltinProc_new: + case BuiltinProc_new_slice: + case BuiltinProc_size_of: + case BuiltinProc_align_of: + case BuiltinProc_offset_of: + case BuiltinProc_type_info: + // 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]); + } + + switch (id) { + default: + GB_PANIC("Implement builtin procedure: %.*s", LIT(builtin_procs[id].name)); + break; + + case BuiltinProc_new: { + // new :: proc(Type) -> ^Type + Operand op = {0}; + check_expr_or_type(c, &op, ce->args.e[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`"); + return false; + } + operand->mode = Addressing_Value; + operand->type = make_type_pointer(c->allocator, type); + } break; + case BuiltinProc_new_slice: { + // new_slice :: proc(Type, len: int) -> []Type + Operand op = {0}; + check_expr_or_type(c, &op, ce->args.e[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`"); + return false; + } + + check_expr(c, &op, ce->args.e[1]); + if (op.mode == Addressing_Invalid) { + return false; + } + if (!is_type_integer(base_enum_type(op.type))) { + gbString type_str = type_to_string(op.type); + error_node(call, "Length for `new_slice` must be an integer, got `%s`", type_str); + gb_string_free(type_str); + return false; + } + + operand->mode = Addressing_Value; + operand->type = make_type_slice(c->allocator, type); + } break; + + case BuiltinProc_size_of: { + // size_of :: proc(Type) -> untyped int + Type *type = check_type(c, ce->args.e[0]); + if (type == NULL || type == t_invalid) { + error_node(ce->args.e[0], "Expected a type for `size_of`"); + return false; + } + + operand->mode = Addressing_Constant; + operand->value = make_exact_value_integer(type_size_of(c->sizes, c->allocator, type)); + operand->type = t_untyped_integer; + + } break; + + case BuiltinProc_size_of_val: + // size_of_val :: proc(val: Type) -> untyped int + check_assignment(c, operand, NULL, str_lit("argument of `size_of_val`")); + if (operand->mode == Addressing_Invalid) { + return false; + } + + operand->mode = Addressing_Constant; + operand->value = make_exact_value_integer(type_size_of(c->sizes, c->allocator, operand->type)); + operand->type = t_untyped_integer; + break; + + case BuiltinProc_align_of: { + // align_of :: proc(Type) -> untyped int + Type *type = check_type(c, ce->args.e[0]); + if (type == NULL || type == t_invalid) { + error_node(ce->args.e[0], "Expected a type for `align_of`"); + return false; + } + operand->mode = Addressing_Constant; + operand->value = make_exact_value_integer(type_align_of(c->sizes, c->allocator, type)); + operand->type = t_untyped_integer; + } break; + + case BuiltinProc_align_of_val: + // align_of_val :: proc(val: Type) -> untyped int + check_assignment(c, operand, NULL, str_lit("argument of `align_of_val`")); + if (operand->mode == Addressing_Invalid) { + return false; + } + + operand->mode = Addressing_Constant; + operand->value = make_exact_value_integer(type_align_of(c->sizes, c->allocator, operand->type)); + operand->type = t_untyped_integer; + break; + + case BuiltinProc_offset_of: { + // offset_of :: proc(Type, field) -> untyped int + Operand op = {0}; + Type *bt = check_type(c, ce->args.e[0]); + Type *type = base_type(bt); + if (type == NULL || type == t_invalid) { + error_node(ce->args.e[0], "Expected a type for `offset_of`"); + return false; + } + + AstNode *field_arg = unparen_expr(ce->args.e[1]); + if (field_arg == NULL || + field_arg->kind != AstNode_Ident) { + error_node(field_arg, "Expected an identifier for field argument"); + return false; + } + if (is_type_array(type) || is_type_vector(type)) { + error_node(field_arg, "Invalid type for `offset_of`"); + return false; + } + + + ast_node(arg, Ident, field_arg); + 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], + "`%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], + "Field `%.*s` is embedded via a pointer in `%s`", LIT(arg->string), type_str); + gb_string_free(type_str); + return false; + } + + operand->mode = Addressing_Constant; + operand->value = make_exact_value_integer(type_offset_of_from_selection(c->sizes, c->allocator, type, sel)); + operand->type = t_untyped_integer; + } break; + + case BuiltinProc_offset_of_val: { + // offset_of_val :: proc(val: expression) -> untyped int + AstNode *arg = unparen_expr(ce->args.e[0]); + if (arg->kind != AstNode_SelectorExpr) { + gbString str = expr_to_string(arg); + error_node(arg, "`%s` is not a selector expression", str); + return false; + } + ast_node(s, SelectorExpr, arg); + + check_expr(c, operand, s->expr); + if (operand->mode == Addressing_Invalid) { + return false; + } + + Type *type = operand->type; + if (base_type(type)->kind == Type_Pointer) { + Type *p = base_type(type); + if (is_type_struct(p)) { + type = p->Pointer.elem; + } + } + if (is_type_array(type) || is_type_vector(type)) { + error_node(arg, "Invalid type for `offset_of_val`"); + return false; + } + + ast_node(i, Ident, s->selector); + Selection sel = lookup_field(c->allocator, type, i->string, operand->mode == Addressing_Type); + if (sel.entity == NULL) { + gbString type_str = type_to_string(type); + error_node(arg, + "`%s` has no field named `%.*s`", type_str, LIT(i->string)); + return false; + } + if (sel.indirect) { + gbString type_str = type_to_string(type); + error_node(ce->args.e[0], + "Field `%.*s` is embedded via a pointer in `%s`", LIT(i->string), type_str); + gb_string_free(type_str); + return false; + } + + operand->mode = Addressing_Constant; + // IMPORTANT TODO(bill): Fix for anonymous fields + operand->value = make_exact_value_integer(type_offset_of_from_selection(c->sizes, c->allocator, type, sel)); + operand->type = t_untyped_integer; + } break; + + case BuiltinProc_type_of_val: + // type_of_val :: proc(val: Type) -> type(Type) + check_assignment(c, operand, NULL, str_lit("argument of `type_of_val`")); + if (operand->mode == Addressing_Invalid || operand->mode == Addressing_Builtin) { + return false; + } + operand->mode = Addressing_Type; + break; + + + case BuiltinProc_type_info: { + // type_info :: proc(Type) -> ^Type_Info + if (c->context.scope->is_global) { + compiler_error("`type_info` Cannot be declared within a #shared_global_scope due to how the internals of the compiler works"); + } + + // NOTE(bill): The type information may not be setup yet + init_preload(c); + AstNode *expr = ce->args.e[0]; + Type *type = check_type(c, expr); + if (type == NULL || type == t_invalid) { + error_node(expr, "Invalid argument to `type_info`"); + return false; + } + + add_type_info_type(c, type); + + operand->mode = Addressing_Value; + operand->type = t_type_info_ptr; + } break; + + case BuiltinProc_type_info_of_val: { + // type_info_of_val :: proc(val: Type) -> ^Type_Info + if (c->context.scope->is_global) { + compiler_error("`type_info` Cannot be declared within a #shared_global_scope due to how the internals of the compiler works"); + } + + // NOTE(bill): The type information may not be setup yet + init_preload(c); + AstNode *expr = ce->args.e[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; + add_type_info_type(c, operand->type); + + operand->mode = Addressing_Value; + operand->type = t_type_info_ptr; + } break; + + + + case BuiltinProc_compile_assert: + // compile_assert :: proc(cond: bool) + + if (!is_type_boolean(operand->type) && operand->mode != Addressing_Constant) { + gbString str = expr_to_string(ce->args.e[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]); + error_node(call, "Compile time assertion: `%s`", str); + gb_string_free(str); + } + break; + + case BuiltinProc_assert: + // assert :: proc(cond: bool) + + if (!is_type_boolean(operand->type)) { + gbString str = expr_to_string(ce->args.e[0]); + error_node(call, "`%s` is not a boolean", str); + gb_string_free(str); + return false; + } + + operand->mode = Addressing_NoValue; + break; + + case BuiltinProc_panic: + // panic :: proc(msg: string) + + if (!is_type_string(operand->type)) { + gbString str = expr_to_string(ce->args.e[0]); + error_node(call, "`%s` is not a string", str); + gb_string_free(str); + return false; + } + + operand->mode = Addressing_NoValue; + break; + + case BuiltinProc_copy: { + // copy :: proc(x, y: []Type) -> int + Type *dest_type = NULL, *src_type = NULL; + + Type *d = base_type(operand->type); + if (d->kind == Type_Slice) { + dest_type = d->Slice.elem; + } + Operand op = {0}; + check_expr(c, &op, ce->args.e[1]); + if (op.mode == Addressing_Invalid) { + return false; + } + Type *s = base_type(op.type); + if (s->kind == Type_Slice) { + src_type = s->Slice.elem; + } + + if (dest_type == NULL || src_type == NULL) { + error_node(call, "`copy` only expects slices as arguments"); + return false; + } + + 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_str = type_to_string(dest_type); + gbString s_str = type_to_string(src_type); + error_node(call, + "Arguments to `copy`, %s, %s, have different elem types: %s vs %s", + d_arg, s_arg, d_str, s_str); + gb_string_free(s_str); + gb_string_free(d_str); + gb_string_free(s_arg); + gb_string_free(d_arg); + return false; + } + + operand->type = t_int; // Returns number of elems copied + operand->mode = Addressing_Value; + } break; + + #if 0 + case BuiltinProc_append: { + // append :: proc(x : ^[]Type, y : Type) -> bool + Type *x_type = NULL, *y_type = NULL; + x_type = base_type(operand->type); + + Operand op = {0}; + check_expr(c, &op, ce->args.e[1]); + if (op.mode == Addressing_Invalid) { + return false; + } + y_type = base_type(op.type); + + if (!(is_type_pointer(x_type) && is_type_slice(x_type->Pointer.elem))) { + error_node(call, "First argument to `append` must be a pointer to a slice"); + return false; + } + + Type *elem_type = x_type->Pointer.elem->Slice.elem; + if (!check_is_assignable_to(c, &op, elem_type)) { + gbString d_arg = expr_to_string(ce->args.e[0]); + gbString s_arg = expr_to_string(ce->args.e[1]); + gbString d_str = type_to_string(elem_type); + gbString s_str = type_to_string(y_type); + error_node(call, + "Arguments to `append`, %s, %s, have different element types: %s vs %s", + d_arg, s_arg, d_str, s_str); + gb_string_free(s_str); + gb_string_free(d_str); + gb_string_free(s_arg); + gb_string_free(d_arg); + return false; + } + + operand->type = t_bool; // Returns if it was successful + operand->mode = Addressing_Value; + } break; + #endif + + case BuiltinProc_swizzle: { + // swizzle :: proc(v: {N}T, T...) -> {M}T + Type *vector_type = base_type(operand->type); + if (!is_type_vector(vector_type)) { + gbString type_str = type_to_string(operand->type); + error_node(call, + "You can only `swizzle` a vector, got `%s`", + type_str); + gb_string_free(type_str); + return false; + } + + isize max_count = vector_type->Vector.count; + isize arg_count = 0; + for_array(i, ce->args) { + if (i == 0) { + continue; + } + AstNode *arg = ce->args.e[i]; + Operand op = {0}; + check_expr(c, &op, arg); + if (op.mode == Addressing_Invalid) { + return false; + } + Type *arg_type = base_type(op.type); + if (!is_type_integer(arg_type) || op.mode != Addressing_Constant) { + error_node(op.expr, "Indices to `swizzle` must be constant integers"); + return false; + } + + if (op.value.value_integer < 0) { + error_node(op.expr, "Negative `swizzle` index"); + return false; + } + + if (max_count <= op.value.value_integer) { + error_node(op.expr, "`swizzle` index exceeds vector length"); + return false; + } + + arg_count++; + } + + if (arg_count > max_count) { + error_node(call, "Too many `swizzle` indices, %td > %td", arg_count, max_count); + return false; + } + + Type *elem_type = vector_type->Vector.elem; + operand->type = make_type_vector(c->allocator, elem_type, arg_count); + operand->mode = Addressing_Value; + } break; + +#if 0 + case BuiltinProc_ptr_offset: { + // ptr_offset :: proc(ptr: ^T, offset: int) -> ^T + // ^T cannot be rawptr + Type *ptr_type = base_type(operand->type); + if (!is_type_pointer(ptr_type)) { + gbString type_str = type_to_string(operand->type); + defer (gb_string_free(type_str)); + error_node(call, + "Expected a pointer to `ptr_offset`, got `%s`", + type_str); + return false; + } + + if (ptr_type == t_rawptr) { + error_node(call, + "`rawptr` cannot have pointer arithmetic"); + return false; + } + + AstNode *offset = ce->args.e[1]; + Operand op = {0}; + check_expr(c, &op, offset); + if (op.mode == Addressing_Invalid) + return false; + Type *offset_type = base_type(op.type); + if (!is_type_integer(offset_type)) { + error_node(op.expr, "Pointer offsets for `ptr_offset` must be an integer"); + return false; + } + + if (operand->mode == Addressing_Constant && + op.mode == Addressing_Constant) { + i64 ptr = operand->value.value_pointer; + i64 elem_size = type_size_of(c->sizes, c->allocator, ptr_type->Pointer.elem); + ptr += elem_size * op.value.value_integer; + operand->value.value_pointer = ptr; + } else { + operand->mode = Addressing_Value; + } + + } break; + + case BuiltinProc_ptr_sub: { + // ptr_sub :: proc(a, b: ^T) -> int + // ^T cannot be rawptr + Type *ptr_type = base_type(operand->type); + if (!is_type_pointer(ptr_type)) { + gbString type_str = type_to_string(operand->type); + defer (gb_string_free(type_str)); + error_node(call, + "Expected a pointer to `ptr_add`, got `%s`", + type_str); + return false; + } + + if (ptr_type == t_rawptr) { + error_node(call, + "`rawptr` cannot have pointer arithmetic"); + return false; + } + AstNode *offset = ce->args[1]; + Operand op = {0}; + check_expr(c, &op, offset); + if (op.mode == Addressing_Invalid) + return false; + if (!is_type_pointer(op.type)) { + gbString type_str = type_to_string(operand->type); + defer (gb_string_free(type_str)); + error_node(call, + "Expected a pointer to `ptr_add`, got `%s`", + type_str); + return false; + } + + if (base_type(op.type) == t_rawptr) { + error_node(call, + "`rawptr` cannot have pointer arithmetic"); + return false; + } + + if (!are_types_identical(operand->type, op.type)) { + gbString a = type_to_string(operand->type); + gbString b = type_to_string(op.type); + defer (gb_string_free(a)); + defer (gb_string_free(b)); + error_node(op.expr, + "`ptr_sub` requires to pointer of the same type. Got `%s` and `%s`.", a, b); + return false; + } + + operand->type = t_int; + + if (operand->mode == Addressing_Constant && + op.mode == Addressing_Constant) { + u8 *ptr_a = cast(u8 *)operand->value.value_pointer; + u8 *ptr_b = cast(u8 *)op.value.value_pointer; + isize elem_size = type_size_of(c->sizes, c->allocator, ptr_type->Pointer.elem); + operand->value = make_exact_value_integer((ptr_a - ptr_b) / elem_size); + } else { + operand->mode = Addressing_Value; + } + } break; +#endif + + case BuiltinProc_slice_ptr: { + // slice_ptr :: proc(a: ^T, len: int) -> []T + // ^T cannot be rawptr + Type *ptr_type = base_type(operand->type); + if (!is_type_pointer(ptr_type)) { + gbString type_str = type_to_string(operand->type); + error_node(call, + "Expected a pointer to `slice_ptr`, got `%s`", + type_str); + gb_string_free(type_str); + return false; + } + + if (ptr_type == t_rawptr) { + error_node(call, + "`rawptr` cannot have pointer arithmetic"); + return false; + } + + AstNode *len = ce->args.e[1]; + + Operand op = {0}; + check_expr(c, &op, len); + if (op.mode == Addressing_Invalid) + return false; + if (!is_type_integer(op.type)) { + gbString type_str = type_to_string(operand->type); + error_node(call, + "Length for `slice_ptr` must be an integer, got `%s`", + type_str); + gb_string_free(type_str); + return false; + } + + operand->type = make_type_slice(c->allocator, ptr_type->Pointer.elem); + operand->mode = Addressing_Value; + } break; + + case BuiltinProc_min: { + // min :: proc(a, b: comparable) -> comparable + Type *type = base_type(operand->type); + if (!is_type_comparable(type) || !(is_type_numeric(type) || is_type_string(type))) { + gbString type_str = type_to_string(operand->type); + error_node(call, + "Expected a comparable numeric type to `min`, got `%s`", + type_str); + gb_string_free(type_str); + return false; + } + + AstNode *other_arg = ce->args.e[1]; + Operand a = *operand; + Operand b = {0}; + check_expr(c, &b, other_arg); + if (b.mode == Addressing_Invalid) { + return false; + } + if (!is_type_comparable(b.type) || !(is_type_numeric(b.type) || is_type_string(b.type))) { + gbString type_str = type_to_string(b.type); + error_node(call, + "Expected a comparable numeric type to `min`, got `%s`", + type_str); + gb_string_free(type_str); + return false; + } + + if (a.mode == Addressing_Constant && + b.mode == Addressing_Constant) { + ExactValue x = a.value; + ExactValue y = b.value; + + operand->mode = Addressing_Constant; + if (compare_exact_values(Token_Lt, x, y)) { + operand->value = x; + operand->type = a.type; + } else { + operand->value = y; + operand->type = b.type; + } + } else { + operand->mode = Addressing_Value; + operand->type = type; + + convert_to_typed(c, &a, b.type, 0); + if (a.mode == Addressing_Invalid) { + return false; + } + convert_to_typed(c, &b, a.type, 0); + if (b.mode == Addressing_Invalid) { + return false; + } + + if (!are_types_identical(operand->type, b.type)) { + gbString type_a = type_to_string(a.type); + gbString type_b = type_to_string(b.type); + error_node(call, + "Mismatched types to `min`, `%s` vs `%s`", + type_a, type_b); + gb_string_free(type_b); + gb_string_free(type_a); + return false; + } + } + + } break; + + case BuiltinProc_max: { + // min :: proc(a, b: comparable) -> comparable + Type *type = base_type(operand->type); + if (!is_type_comparable(type) || !(is_type_numeric(type) || is_type_string(type))) { + gbString type_str = type_to_string(operand->type); + error_node(call, + "Expected a comparable numeric or string type to `max`, got `%s`", + type_str); + gb_string_free(type_str); + return false; + } + + AstNode *other_arg = ce->args.e[1]; + Operand a = *operand; + Operand b = {0}; + check_expr(c, &b, other_arg); + if (b.mode == Addressing_Invalid) { + return false; + } + if (!is_type_comparable(b.type) || !(is_type_numeric(b.type) || is_type_string(b.type))) { + gbString type_str = type_to_string(b.type); + error_node(call, + "Expected a comparable numeric or string type to `max`, got `%s`", + type_str); + gb_string_free(type_str); + return false; + } + + if (a.mode == Addressing_Constant && + b.mode == Addressing_Constant) { + ExactValue x = a.value; + ExactValue y = b.value; + + operand->mode = Addressing_Constant; + if (compare_exact_values(Token_Gt, x, y)) { + operand->value = x; + operand->type = a.type; + } else { + operand->value = y; + operand->type = b.type; + } + } else { + operand->mode = Addressing_Value; + operand->type = type; + + convert_to_typed(c, &a, b.type, 0); + if (a.mode == Addressing_Invalid) { + return false; + } + convert_to_typed(c, &b, a.type, 0); + if (b.mode == Addressing_Invalid) { + return false; + } + + if (!are_types_identical(operand->type, b.type)) { + gbString type_a = type_to_string(a.type); + gbString type_b = type_to_string(b.type); + error_node(call, + "Mismatched types to `max`, `%s` vs `%s`", + type_a, type_b); + gb_string_free(type_b); + gb_string_free(type_a); + return false; + } + } + + } break; + + case BuiltinProc_abs: { + // abs :: proc(n: numeric) -> numeric + Type *type = base_type(operand->type); + if (!is_type_numeric(type)) { + gbString type_str = type_to_string(operand->type); + error_node(call, + "Expected a numeric type to `abs`, got `%s`", + type_str); + gb_string_free(type_str); + return false; + } + + if (operand->mode == Addressing_Constant) { + switch (operand->value.kind) { + case ExactValue_Integer: + operand->value.value_integer = gb_abs(operand->value.value_integer); + break; + case ExactValue_Float: + operand->value.value_float = gb_abs(operand->value.value_float); + break; + default: + GB_PANIC("Invalid numeric constant"); + break; + } + } else { + operand->mode = Addressing_Value; + } + + operand->type = type; + } break; + + case BuiltinProc_clamp: { + // clamp :: proc(a, min, max: comparable) -> comparable + Type *type = base_type(operand->type); + if (!is_type_comparable(type) || !(is_type_numeric(type) || is_type_string(type))) { + gbString type_str = type_to_string(operand->type); + error_node(call, + "Expected a comparable numeric or string type to `clamp`, got `%s`", + type_str); + gb_string_free(type_str); + return false; + } + + AstNode *min_arg = ce->args.e[1]; + AstNode *max_arg = ce->args.e[2]; + Operand x = *operand; + Operand y = {0}; + Operand z = {0}; + + check_expr(c, &y, min_arg); + if (y.mode == Addressing_Invalid) { + return false; + } + if (!is_type_comparable(y.type) || !(is_type_numeric(y.type) || is_type_string(y.type))) { + gbString type_str = type_to_string(y.type); + error_node(call, + "Expected a comparable numeric or string type to `clamp`, got `%s`", + type_str); + gb_string_free(type_str); + return false; + } + + check_expr(c, &z, max_arg); + if (z.mode == Addressing_Invalid) { + return false; + } + if (!is_type_comparable(z.type) || !(is_type_numeric(z.type) || is_type_string(z.type))) { + gbString type_str = type_to_string(z.type); + error_node(call, + "Expected a comparable numeric or string type to `clamp`, got `%s`", + type_str); + gb_string_free(type_str); + return false; + } + + if (x.mode == Addressing_Constant && + y.mode == Addressing_Constant && + z.mode == Addressing_Constant) { + ExactValue a = x.value; + ExactValue b = y.value; + ExactValue c = z.value; + + operand->mode = Addressing_Constant; + if (compare_exact_values(Token_Lt, a, b)) { + operand->value = b; + operand->type = y.type; + } else if (compare_exact_values(Token_Gt, a, c)) { + operand->value = c; + operand->type = z.type; + } else { + operand->value = a; + operand->type = x.type; + } + } else { + operand->mode = Addressing_Value; + operand->type = type; + + convert_to_typed(c, &x, y.type, 0); + if (x.mode == Addressing_Invalid) { return false; } + convert_to_typed(c, &y, x.type, 0); + if (y.mode == Addressing_Invalid) { return false; } + convert_to_typed(c, &x, z.type, 0); + if (x.mode == Addressing_Invalid) { return false; } + convert_to_typed(c, &z, x.type, 0); + if (z.mode == Addressing_Invalid) { return false; } + convert_to_typed(c, &y, z.type, 0); + if (y.mode == Addressing_Invalid) { return false; } + convert_to_typed(c, &z, y.type, 0); + if (z.mode == Addressing_Invalid) { return false; } + + if (!are_types_identical(x.type, y.type) || !are_types_identical(x.type, z.type)) { + gbString type_x = type_to_string(x.type); + gbString type_y = type_to_string(y.type); + gbString type_z = type_to_string(z.type); + error_node(call, + "Mismatched types to `clamp`, `%s`, `%s`, `%s`", + type_x, type_y, type_z); + gb_string_free(type_z); + gb_string_free(type_y); + gb_string_free(type_x); + return false; + } + } + } break; + } + + return true; +} + + +void check_call_arguments(Checker *c, Operand *operand, Type *proc_type, AstNode *call) { + GB_ASSERT(call->kind == AstNode_CallExpr); + GB_ASSERT(proc_type->kind == Type_Proc); + ast_node(ce, CallExpr, call); + + isize param_count = 0; + bool variadic = proc_type->Proc.variadic; + bool vari_expand = (ce->ellipsis.pos.line != 0); + + if (proc_type->Proc.params != NULL) { + param_count = proc_type->Proc.params->Tuple.variable_count; + if (variadic) { + param_count--; + } + } + + if (vari_expand && !variadic) { + error(ce->ellipsis, + "Cannot use `..` in call to a non-variadic procedure: `%.*s`", + LIT(ce->proc->Ident.string)); + return; + } + + if (ce->args.count == 0 && param_count == 0) { + return; + } + + gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&c->tmp_arena); + + Array(Operand) operands; + array_init_reserve(&operands, c->tmp_allocator, 2*param_count); + + for_array(i, ce->args) { + Operand o = {0}; + check_multi_expr(c, &o, ce->args.e[i]); + if (o.type->kind != Type_Tuple) { + array_add(&operands, o); + } else { + TypeTuple *tuple = &o.type->Tuple; + if (variadic && i >= param_count) { + error_node(ce->args.e[i], "`..` in a variadic procedure cannot be applied to a %td-valued expression", tuple->variable_count); + operand->mode = Addressing_Invalid; + goto end; + } + for (isize j = 0; j < tuple->variable_count; j++) { + o.type = tuple->variables[j]->type; + array_add(&operands, o); + } + } + } + + i32 error_code = 0; + if (operands.count < param_count) { + error_code = -1; + } else if (!variadic && operands.count > param_count) { + error_code = +1; + } + if (error_code != 0) { + char *err_fmt = "Too many arguments for `%s`, expected %td arguments"; + if (error_code < 0) { + err_fmt = "Too few arguments for `%s`, expected %td arguments"; + } + + gbString proc_str = expr_to_string(ce->proc); + error_node(call, err_fmt, proc_str, param_count); + gb_string_free(proc_str); + operand->mode = Addressing_Invalid; + goto end; + } + + 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 *arg_type = sig_params[operand_index]->type; + Operand o = operands.e[operand_index]; + if (variadic) { + o = operands.e[operand_index]; + } + check_assignment(c, &o, arg_type, str_lit("argument")); + } + + 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.e[operand_index]; + if (vari_expand) { + variadic_expand = true; + t = slice; + if (operand_index != param_count) { + error_node(o.expr, "`..` in a variadic procedure can only have one variadic argument at the end"); + break; + } + } + check_assignment(c, &o, t, str_lit("argument")); + } + } +end: + gb_temp_arena_memory_end(tmp); +} + + +Entity *find_using_index_expr(Type *t) { + t = base_type(t); + if (t->kind != Type_Record) { + return NULL; + } + + for (isize i = 0; i < t->Record.field_count; i++) { + Entity *f = t->Record.fields[i]; + if (f->kind == Entity_Variable && + f->flags & (EntityFlag_Anonymous|EntityFlag_Field)) { + if (is_type_indexable(f->type)) { + return f; + } + Entity *res = find_using_index_expr(f->type); + if (res != NULL) { + return res; + } + } + } + return NULL; +} + +ExprKind check_call_expr(Checker *c, Operand *operand, AstNode *call) { + GB_ASSERT(call->kind == AstNode_CallExpr); + ast_node(ce, CallExpr, call); + check_expr_or_type(c, operand, ce->proc); + + if (operand->mode == Addressing_Invalid) { + for_array(i, ce->args) { + check_expr_base(c, operand, ce->args.e[i], NULL); + } + operand->mode = Addressing_Invalid; + operand->expr = call; + return Expr_Stmt; + } + + + if (operand->mode == Addressing_Builtin) { + i32 id = operand->builtin_id; + if (!check_builtin_procedure(c, operand, call, id)) { + operand->mode = Addressing_Invalid; + } + operand->expr = call; + return builtin_procs[id].kind; + } + + Type *proc_type = base_type(operand->type); + if (proc_type == NULL || proc_type->kind != Type_Proc || + !(operand->mode == Addressing_Value || operand->mode == Addressing_Variable)) { + AstNode *e = operand->expr; + gbString str = expr_to_string(e); + error_node(e, "Cannot call a non-procedure: `%s`", str); + gb_string_free(str); + + operand->mode = Addressing_Invalid; + operand->expr = call; + + return Expr_Stmt; + } + + check_call_arguments(c, operand, proc_type, call); + + switch (proc_type->Proc.result_count) { + case 0: + operand->mode = Addressing_NoValue; + break; + case 1: + operand->mode = Addressing_Value; + operand->type = proc_type->Proc.results->Tuple.variables[0]->type; + break; + default: + operand->mode = Addressing_Value; + operand->type = proc_type->Proc.results; + break; + } + + operand->expr = call; + return Expr_Stmt; +} + +void check_expr_with_type_hint(Checker *c, Operand *o, AstNode *e, Type *t) { + check_expr_base(c, o, e, t); + check_not_tuple(c, o); + char *err_str = NULL; + switch (o->mode) { + case Addressing_NoValue: + err_str = "used as a value"; + break; + case Addressing_Type: + err_str = "is not an expression"; + break; + case Addressing_Builtin: + err_str = "must be called"; + break; + } + if (err_str != NULL) { + gbString str = expr_to_string(e); + error_node(e, "`%s` %s", str, err_str); + gb_string_free(str); + o->mode = Addressing_Invalid; + } +} + +bool check_set_index_data(Operand *o, Type *t, i64 *max_count) { + t = base_type(type_deref(t)); + + switch (t->kind) { + case Type_Basic: + if (is_type_string(t)) { + if (o->mode == Addressing_Constant) { + *max_count = o->value.value_string.len; + } + if (o->mode != Addressing_Variable) { + o->mode = Addressing_Value; + } + o->type = t_u8; + return true; + } + break; + + case Type_Array: + *max_count = t->Array.count; + if (o->mode != Addressing_Variable) { + o->mode = Addressing_Value; + } + o->type = t->Array.elem; + return true; + + case Type_Vector: + *max_count = t->Vector.count; + if (o->mode != Addressing_Variable) { + o->mode = Addressing_Value; + } + o->type = t->Vector.elem; + return true; + + + case Type_Slice: + o->type = t->Slice.elem; + o->mode = Addressing_Variable; + return true; + } + + return false; +} + + +bool check_is_giving(AstNode *node, AstNode **give_expr) { + switch (node->kind) { + case_ast_node(es, ExprStmt, node); + if (es->expr->kind == AstNode_GiveExpr) { + if (give_expr) *give_expr = es->expr; + return true; + } + case_end; + + case_ast_node(ge, GiveExpr, node); + if (give_expr) *give_expr = node; + return true; + case_end; + + case_ast_node(be, BlockExpr, node); + // Iterate backwards + for (isize n = be->stmts.count-1; n >= 0; n--) { + AstNode *stmt = be->stmts.e[n]; + if (stmt->kind == AstNode_EmptyStmt) { + continue; + } + if (stmt->kind == AstNode_ExprStmt && stmt->ExprStmt.expr->kind == AstNode_GiveExpr) { + if (give_expr) *give_expr = stmt->ExprStmt.expr; + return true; + } + } + case_end; + } + + if (give_expr) *give_expr = NULL; + return false; +} + +ExprKind check__expr_base(Checker *c, Operand *o, AstNode *node, Type *type_hint) { + ExprKind kind = Expr_Stmt; + + o->mode = Addressing_Invalid; + o->type = t_invalid; + + switch (node->kind) { + default: + goto error; + break; + + case_ast_node(be, BadExpr, node) + goto error; + case_end; + + case_ast_node(i, IntervalExpr, node); + error_node(node, "Invalid use of an interval expression"); + goto error; + case_end; + + case_ast_node(i, Ident, node); + check_identifier(c, o, node, type_hint); + case_end; + + case_ast_node(bl, BasicLit, node); + Type *t = t_invalid; + switch (bl->kind) { + case Token_Integer: t = t_untyped_integer; break; + case Token_Float: t = t_untyped_float; break; + case Token_String: t = t_untyped_string; break; + case Token_Rune: t = t_untyped_rune; break; + default: GB_PANIC("Unknown literal"); break; + } + o->mode = Addressing_Constant; + o->type = t; + o->value = make_exact_value_from_basic_literal(*bl); + case_end; + + case_ast_node(pl, ProcLit, node); + Type *type = check_type(c, pl->type); + if (type == NULL || !is_type_proc(type)) { + gbString str = expr_to_string(node); + error_node(node, "Invalid procedure literal `%s`", str); + gb_string_free(str); + check_close_scope(c); + goto error; + } + if (pl->tags != 0) { + error_node(node, "A procedure literal cannot have tags"); + pl->tags = 0; // TODO(bill): Should I zero this?! + } + + check_open_scope(c, pl->type); + check_procedure_later(c, c->curr_ast_file, empty_token, c->context.decl, type, pl->body, pl->tags); + // check_proc_body(c, empty_token, c->context.decl, type, pl->body); + check_close_scope(c); + + o->mode = Addressing_Value; + o->type = type; + case_end; + + case_ast_node(ge, GiveExpr, node); + if (c->proc_stack.count == 0) { + error_node(node, "A give expression is only allowed within a procedure"); + goto error; + } + + if (ge->results.count == 0) { + error_node(node, "`give` has no results"); + goto error; + } + + gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&c->tmp_arena); + + Array(Operand) operands; + array_init_reserve(&operands, c->tmp_allocator, 2*ge->results.count); + + for_array(i, ge->results) { + AstNode *rhs = ge->results.e[i]; + Operand o = {0}; + check_multi_expr(c, &o, rhs); + if (!is_operand_value(o)) { + error_node(rhs, "Expected a value for a `give`"); + continue; + } + if (o.type->kind != Type_Tuple) { + array_add(&operands, o); + } else { + TypeTuple *tuple = &o.type->Tuple; + for (isize j = 0; j < tuple->variable_count; j++) { + o.type = tuple->variables[j]->type; + array_add(&operands, o); + } + } + } + + if (operands.count == 0) { + error_node(node, "`give` has no value"); + gb_temp_arena_memory_end(tmp); + goto error; + } else if (operands.count == 1) { + Operand operand = operands.e[0]; + if (type_hint != NULL) { + convert_to_typed(c, &operand, type_hint, 0); + } + o->type = default_type(operand.type); + o->mode = Addressing_Value; + } else { + Type *tuple = make_type_tuple(c->allocator); + + Entity **variables = gb_alloc_array(c->allocator, Entity *, operands.count); + isize variable_index = 0; + for_array(i, operands) { + Operand operand = operands.e[i]; + // Type *type = default_type(operand.type); + Type *type = operand.type; + switch (operand.mode) { + case Addressing_Constant: + variables[variable_index++] = make_entity_constant(c->allocator, NULL, empty_token, type, operand.value); + break; + default: + variables[variable_index++] = make_entity_param(c->allocator, NULL, empty_token, type, false); + break; + } + } + tuple->Tuple.variables = variables; + tuple->Tuple.variable_count = operands.count; + + o->type = tuple; + o->mode = Addressing_Value; + } + gb_temp_arena_memory_end(tmp); + case_end; + + case_ast_node(be, BlockExpr, node); + if (c->proc_stack.count == 0) { + error_node(node, "A block expression is only allowed within a procedure"); + goto error; + } + + for (isize i = be->stmts.count-1; i >= 0; i--) { + if (be->stmts.e[i]->kind != AstNode_EmptyStmt) { + break; + } + be->stmts.count--; + } + + if (be->stmts.count == 0) { + error_node(node, "Empty block expression"); + goto error; + } + + check_open_scope(c, node); + check_stmt_list(c, be->stmts, Stmt_GiveAllowed); + check_close_scope(c); + + AstNode *give_node = NULL; + if (!check_is_giving(node, &give_node) || give_node == NULL) { + error_node(node, "Missing give statement at end of block expression"); + goto error; + } + + GB_ASSERT(give_node != NULL && give_node->kind == AstNode_GiveExpr); + be->give_node = give_node; + + Type *type = type_of_expr(&c->info, give_node); + if (type == NULL) { + goto error; + } else if (type == t_invalid) { + o->type = t_invalid; + o->mode = Addressing_Invalid; + } else { + o->type = type; + o->mode = Addressing_Value; + } + case_end; + + case_ast_node(ie, IfExpr, node); + if (c->proc_stack.count == 0) { + error_node(node, "An if expression is only allowed within a procedure"); + goto error; + } + + check_open_scope(c, node); + + if (ie->init != NULL) { + check_stmt(c, ie->init, 0); + } + + Operand operand = {Addressing_Invalid}; + check_expr(c, &operand, ie->cond); + if (operand.mode != Addressing_Invalid && !is_type_boolean(operand.type)) { + error_node(ie->cond, "Non-boolean condition in if expression"); + } + + + Operand x = {Addressing_Invalid}; + Operand y = {Addressing_Invalid}; + Type *if_type = NULL; + Type *else_type = NULL; + check_expr(c, &x, ie->body); + if_type = x.type; + + if (ie->else_expr != NULL) { + switch (ie->else_expr->kind) { + case AstNode_IfExpr: + case AstNode_BlockExpr: + check_expr(c, &y, ie->else_expr); + else_type = y.type; + break; + default: + error_node(ie->else_expr, "Invalid else expression in if expression"); + break; + } + } else { + error_node(ie->else_expr, "An if expression must have an else expression"); + check_close_scope(c); + goto error; + } + + check_close_scope(c); + + if (if_type == NULL || if_type == t_invalid || + else_type == NULL || else_type == t_invalid) { + goto error; + } + + convert_to_typed(c, &x, y.type, 0); + if (x.mode == Addressing_Invalid) { + goto error; + } + convert_to_typed(c, &y, x.type, 0); + if (y.mode == Addressing_Invalid) { + x.mode = Addressing_Invalid; + goto error; + } + + + if (!are_types_identical(if_type, else_type)) { + gbString its = type_to_string(if_type); + gbString ets = type_to_string(else_type); + error_node(node, "Mismatched types in if expression, %s vs %s", its, ets); + gb_string_free(ets); + gb_string_free(its); + goto error; + } + + o->type = if_type; + o->mode = Addressing_Value; + case_end; + + case_ast_node(cl, CompoundLit, node); + Type *type = type_hint; + bool ellipsis_array = false; + bool is_constant = true; + if (cl->type != NULL) { + type = NULL; + + // [..]Type + if (cl->type->kind == AstNode_ArrayType && cl->type->ArrayType.count != NULL) { + if (cl->type->ArrayType.count->kind == AstNode_Ellipsis) { + type = make_type_array(c->allocator, check_type(c, cl->type->ArrayType.elem), -1); + ellipsis_array = true; + } + } + + if (type == NULL) { + type = check_type(c, cl->type); + } + } + + if (type == NULL) { + error_node(node, "Missing type in compound literal"); + goto error; + } + + Type *t = base_type(type); + switch (t->kind) { + case Type_Record: { + if (!is_type_struct(t)) { + if (cl->elems.count != 0) { + error_node(node, "Illegal compound literal"); + } + break; + } + if (cl->elems.count == 0) { + break; // NOTE(bill): No need to init + } + { // Checker values + isize field_count = t->Record.field_count; + if (cl->elems.e[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]; + if (elem->kind != AstNode_FieldValue) { + error_node(elem, "Mixture of `field = value` and value elements in a structure literal is not allowed"); + continue; + } + ast_node(fv, FieldValue, elem); + if (fv->field->kind != AstNode_Ident) { + gbString expr_str = expr_to_string(fv->field); + error_node(elem, "Invalid field name `%s` in structure literal", expr_str); + gb_string_free(expr_str); + continue; + } + String name = fv->field->Ident.string; + + Selection sel = lookup_field(c->allocator, type, name, o->mode == Addressing_Type); + if (sel.entity == NULL) { + error_node(elem, "Unknown field `%.*s` in structure literal", LIT(name)); + continue; + } + + if (sel.index.count > 1) { + error_node(elem, "Cannot assign to an anonymous field `%.*s` in a structure literal (at the moment)", LIT(name)); + continue; + } + + Entity *field = t->Record.fields[sel.index.e[0]]; + add_entity_use(c, fv->field, field); + + if (fields_visited[sel.index.e[0]]) { + error_node(elem, "Duplicate field `%.*s` in structure literal", LIT(name)); + continue; + } + + fields_visited[sel.index.e[0]] = true; + check_expr(c, o, fv->value); + + if (base_type(field->type) == t_any) { + is_constant = false; + } + if (is_constant) { + is_constant = o->mode == Addressing_Constant; + } + + + check_assignment(c, o, field->type, str_lit("structure literal")); + } + } else { + for_array(index, cl->elems) { + AstNode *elem = cl->elems.e[index]; + if (elem->kind == AstNode_FieldValue) { + error_node(elem, "Mixture of `field = value` and value elements in a structure literal is not allowed"); + continue; + } + Entity *field = t->Record.fields_in_src_order[index]; + + check_expr(c, o, elem); + if (index >= field_count) { + error_node(o->expr, "Too many values in structure literal, expected %td", field_count); + break; + } + + if (base_type(field->type) == t_any) { + is_constant = false; + } + if (is_constant) { + is_constant = o->mode == Addressing_Constant; + } + + check_assignment(c, o, field->type, str_lit("structure literal")); + } + if (cl->elems.count < field_count) { + error(cl->close, "Too few values in structure literal, expected %td, got %td", field_count, cl->elems.count); + } + } + } + + } break; + + case Type_Slice: + case Type_Array: + case Type_Vector: + { + Type *elem_type = NULL; + String context_name = {0}; + if (t->kind == Type_Slice) { + elem_type = t->Slice.elem; + context_name = str_lit("slice literal"); + } else if (t->kind == Type_Vector) { + elem_type = t->Vector.elem; + context_name = str_lit("vector literal"); + } else { + elem_type = t->Array.elem; + context_name = str_lit("array literal"); + } + + + i64 max = 0; + isize index = 0; + isize elem_count = cl->elems.count; + + if (base_type(elem_type) == t_any) { + is_constant = false; + } + + for (; index < elem_count; index++) { + AstNode *e = cl->elems.e[index]; + if (e->kind == AstNode_FieldValue) { + error_node(e, + "`field = value` is only allowed in struct literals"); + continue; + } + + if (t->kind == Type_Array && + t->Array.count >= 0 && + index >= t->Array.count) { + error_node(e, "Index %lld is out of bounds (>= %lld) for array literal", index, t->Array.count); + } + if (t->kind == Type_Vector && + t->Vector.count >= 0 && + index >= t->Vector.count) { + error_node(e, "Index %lld is out of bounds (>= %lld) for vector literal", index, t->Vector.count); + } + + Operand operand = {0}; + check_expr_with_type_hint(c, &operand, e, elem_type); + check_assignment(c, &operand, elem_type, context_name); + + if (is_constant) { + is_constant = operand.mode == Addressing_Constant; + } + } + if (max < index) { + max = index; + } + + 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); + } + } + + if (t->kind == Type_Array && ellipsis_array) { + t->Array.count = max; + } + } break; + + default: { + gbString str = type_to_string(type); + error_node(node, "Invalid compound literal type `%s`", str); + gb_string_free(str); + goto error; + } break; + } + + if (is_constant) { + o->mode = Addressing_Constant; + o->value = make_exact_value_compound(node); + } else { + o->mode = Addressing_Value; + } + o->type = type; + case_end; + + case_ast_node(pe, ParenExpr, node); + kind = check_expr_base(c, o, pe->expr, type_hint); + o->expr = node; + case_end; + + + case_ast_node(te, TagExpr, node); + // TODO(bill): Tag expressions + error_node(node, "Tag expressions are not supported yet"); + kind = check_expr_base(c, o, te->expr, type_hint); + o->expr = node; + case_end; + + case_ast_node(re, RunExpr, node); + // TODO(bill): Tag expressions + kind = check_expr_base(c, o, re->expr, type_hint); + o->expr = node; + case_end; + + + case_ast_node(ue, UnaryExpr, node); + check_expr(c, o, ue->expr); + if (o->mode == Addressing_Invalid) { + goto error; + } + check_unary_expr(c, o, ue->op, node); + if (o->mode == Addressing_Invalid) { + goto error; + } + case_end; + + + case_ast_node(be, BinaryExpr, node); + check_binary_expr(c, o, node); + if (o->mode == Addressing_Invalid) { + goto error; + } + case_end; + + + + case_ast_node(se, SelectorExpr, node); + check_selector(c, o, node); + case_end; + + + case_ast_node(ie, IndexExpr, node); + check_expr(c, o, ie->expr); + if (o->mode == Addressing_Invalid) { + goto error; + } + + Type *t = base_type(type_deref(o->type)); + bool is_const = o->mode == Addressing_Constant; + + i64 max_count = -1; + bool valid = check_set_index_data(o, t, &max_count); + + if (is_const) { + valid = false; + } + + if (!valid && (is_type_struct(t) || is_type_raw_union(t))) { + Entity *found = find_using_index_expr(t); + if (found != NULL) { + valid = check_set_index_data(o, found->type, &max_count); + } + } + + if (!valid) { + gbString str = expr_to_string(o->expr); + if (is_const) { + error_node(o->expr, "Cannot index a constant `%s`", str); + } else { + error_node(o->expr, "Cannot index `%s`", str); + } + gb_string_free(str); + goto error; + } + + if (ie->index == NULL) { + gbString str = expr_to_string(o->expr); + error_node(o->expr, "Missing index for `%s`", str); + gb_string_free(str); + goto error; + } + + i64 index = 0; + bool ok = check_index_value(c, ie->index, max_count, &index); + + case_end; + + + + case_ast_node(se, SliceExpr, node); + check_expr(c, o, se->expr); + if (o->mode == Addressing_Invalid) { + goto error; + } + + bool valid = false; + i64 max_count = -1; + Type *t = base_type(type_deref(o->type)); + switch (t->kind) { + case Type_Basic: + if (is_type_string(t)) { + valid = true; + if (o->mode == Addressing_Constant) { + max_count = o->value.value_string.len; + } + o->type = t_string; + } + break; + + case Type_Array: + valid = true; + max_count = t->Array.count; + if (o->mode != Addressing_Variable) { + gbString str = expr_to_string(node); + error_node(node, "Cannot slice array `%s`, value is not addressable", str); + gb_string_free(str); + goto error; + } + o->type = make_type_slice(c->allocator, t->Array.elem); + break; + + case Type_Slice: + valid = true; + break; + } + + if (!valid) { + gbString str = expr_to_string(o->expr); + error_node(o->expr, "Cannot slice `%s`", str); + gb_string_free(str); + goto error; + } + + o->mode = Addressing_Value; + + i64 indices[2] = {0}; + AstNode *nodes[2] = {se->low, se->high}; + for (isize i = 0; i < gb_count_of(nodes); i++) { + i64 index = max_count; + if (nodes[i] != NULL) { + i64 capacity = -1; + if (max_count >= 0) + capacity = max_count; + i64 j = 0; + if (check_index_value(c, nodes[i], capacity, &j)) { + index = j; + } + } else if (i == 0) { + index = 0; + } + indices[i] = index; + } + + for (isize i = 0; i < gb_count_of(indices); i++) { + i64 a = indices[i]; + for (isize j = i+1; j < gb_count_of(indices); j++) { + i64 b = indices[j]; + if (a > b && b >= 0) { + error(se->close, "Invalid slice indices: [%td > %td]", a, b); + } + } + } + + case_end; + + + case_ast_node(ce, CallExpr, node); + return check_call_expr(c, o, node); + case_end; + + case_ast_node(de, DerefExpr, node); + check_expr_or_type(c, o, de->expr); + if (o->mode == Addressing_Invalid) { + goto error; + } else { + Type *t = base_type(o->type); + if (t->kind == Type_Pointer) { + o->mode = Addressing_Variable; + o->type = t->Pointer.elem; + } else { + gbString str = expr_to_string(o->expr); + error_node(o->expr, "Cannot dereference `%s`", str); + gb_string_free(str); + goto error; + } + } + case_end; + + case_ast_node(de, DemaybeExpr, node); + check_expr_or_type(c, o, de->expr); + if (o->mode == Addressing_Invalid) { + goto error; + } else { + Type *t = base_type(o->type); + if (t->kind == Type_Maybe) { + Entity **variables = gb_alloc_array(c->allocator, Entity *, 2); + Type *elem = t->Maybe.elem; + Token tok = make_token_ident(str_lit("")); + variables[0] = make_entity_param(c->allocator, NULL, tok, elem, false); + variables[1] = make_entity_param(c->allocator, NULL, tok, t_bool, false); + + Type *tuple = make_type_tuple(c->allocator); + tuple->Tuple.variables = variables; + tuple->Tuple.variable_count = 2; + + o->type = tuple; + o->mode = Addressing_Variable; + } else { + gbString str = expr_to_string(o->expr); + error_node(o->expr, "Cannot demaybe `%s`", str); + gb_string_free(str); + goto error; + } + } + case_end; + + case AstNode_ProcType: + case AstNode_PointerType: + case AstNode_MaybeType: + case AstNode_ArrayType: + case AstNode_VectorType: + case AstNode_StructType: + case AstNode_UnionType: + case AstNode_RawUnionType: + case AstNode_EnumType: + o->mode = Addressing_Type; + o->type = check_type(c, node); + break; + } + + kind = Expr_Expr; + o->expr = node; + return kind; + +error: + o->mode = Addressing_Invalid; + o->expr = node; + return kind; +} + +ExprKind check_expr_base(Checker *c, Operand *o, AstNode *node, Type *type_hint) { + ExprKind kind = check__expr_base(c, o, node, type_hint); + Type *type = NULL; + ExactValue value = {ExactValue_Invalid}; + switch (o->mode) { + case Addressing_Invalid: + type = t_invalid; + break; + case Addressing_NoValue: + type = NULL; + break; + case Addressing_Constant: + type = o->type; + value = o->value; + break; + default: + type = o->type; + break; + } + + if (type != NULL && is_type_untyped(type)) { + add_untyped(&c->info, node, false, o->mode, type, value); + } else { + add_type_and_value(&c->info, node, o->mode, type, value); + } + return kind; +} + + +void check_multi_expr(Checker *c, Operand *o, AstNode *e) { + gbString err_str = NULL; + check_expr_base(c, o, e, NULL); + switch (o->mode) { + default: + return; // NOTE(bill): Valid + + case Addressing_NoValue: + err_str = expr_to_string(e); + error_node(e, "`%s` used as value", err_str); + break; + case Addressing_Type: + err_str = expr_to_string(e); + error_node(e, "`%s` is not an expression", err_str); + break; + } + gb_string_free(err_str); + o->mode = Addressing_Invalid; +} + +void check_not_tuple(Checker *c, Operand *o) { + if (o->mode == Addressing_Value) { + // NOTE(bill): Tuples are not first class thus never named + if (o->type->kind == Type_Tuple) { + isize count = o->type->Tuple.variable_count; + GB_ASSERT(count != 1); + error_node(o->expr, + "%td-valued tuple found where single value expected", count); + o->mode = Addressing_Invalid; + } + } +} + +void check_expr(Checker *c, Operand *o, AstNode *e) { + check_multi_expr(c, o, e); + check_not_tuple(c, o); +} + + +void check_expr_or_type(Checker *c, Operand *o, AstNode *e) { + check_expr_base(c, o, e, NULL); + check_not_tuple(c, o); + if (o->mode == Addressing_NoValue) { + gbString str = expr_to_string(o->expr); + error_node(o->expr, "`%s` used as value or type", str); + gb_string_free(str); + o->mode = Addressing_Invalid; + } +} + + +gbString write_expr_to_string(gbString str, AstNode *node); + +gbString write_params_to_string(gbString str, AstNodeArray params, char *sep) { + for_array(i, params) { + ast_node(p, Field, params.e[i]); + if (i > 0) { + str = gb_string_appendc(str, sep); + } + + str = write_expr_to_string(str, params.e[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 str; +} + + +gbString write_expr_to_string(gbString str, AstNode *node) { + if (node == NULL) + return str; + + if (is_ast_node_stmt(node)) { + GB_ASSERT("stmt passed to write_expr_to_string"); + } + + switch (node->kind) { + default: + str = gb_string_appendc(str, "(BadExpr)"); + break; + + case_ast_node(i, Ident, node); + str = string_append_token(str, *i); + case_end; + + case_ast_node(bl, BasicLit, node); + str = string_append_token(str, *bl); + case_end; + + case_ast_node(pl, ProcLit, node); + str = write_expr_to_string(str, pl->type); + case_end; + + case_ast_node(cl, CompoundLit, node); + str = write_expr_to_string(str, cl->type); + str = gb_string_appendc(str, "{"); + for_array(i, cl->elems) { + if (i > 0) { + str = gb_string_appendc(str, ", "); + } + str = write_expr_to_string(str, cl->elems.e[i]); + } + str = gb_string_appendc(str, "}"); + case_end; + + case_ast_node(be, BlockExpr, node); + str = gb_string_appendc(str, "block expression"); + case_end; + case_ast_node(ie, IfExpr, node); + str = gb_string_appendc(str, "if expression"); + case_end; + + case_ast_node(te, TagExpr, node); + str = gb_string_appendc(str, "#"); + str = string_append_token(str, te->name); + str = write_expr_to_string(str, te->expr); + case_end; + + case_ast_node(ue, UnaryExpr, node); + str = string_append_token(str, ue->op); + str = write_expr_to_string(str, ue->expr); + case_end; + + case_ast_node(de, DerefExpr, node); + str = write_expr_to_string(str, de->expr); + str = gb_string_appendc(str, "^"); + case_end; + + case_ast_node(de, DemaybeExpr, node); + str = write_expr_to_string(str, de->expr); + str = gb_string_appendc(str, "?"); + case_end; + + case_ast_node(be, BinaryExpr, node); + str = write_expr_to_string(str, be->left); + str = gb_string_appendc(str, " "); + str = string_append_token(str, be->op); + str = gb_string_appendc(str, " "); + str = write_expr_to_string(str, be->right); + case_end; + + case_ast_node(pe, ParenExpr, node); + str = gb_string_appendc(str, "("); + str = write_expr_to_string(str, pe->expr); + str = gb_string_appendc(str, ")"); + case_end; + + case_ast_node(se, SelectorExpr, node); + str = write_expr_to_string(str, se->expr); + str = gb_string_appendc(str, "."); + str = write_expr_to_string(str, se->selector); + case_end; + + case_ast_node(ie, IndexExpr, node); + str = write_expr_to_string(str, ie->expr); + str = gb_string_appendc(str, "["); + str = write_expr_to_string(str, ie->index); + str = gb_string_appendc(str, "]"); + case_end; + + case_ast_node(se, SliceExpr, node); + str = write_expr_to_string(str, se->expr); + str = gb_string_appendc(str, "["); + str = write_expr_to_string(str, se->low); + str = gb_string_appendc(str, ":"); + str = write_expr_to_string(str, se->high); + str = gb_string_appendc(str, "]"); + case_end; + + case_ast_node(e, Ellipsis, node); + str = gb_string_appendc(str, ".."); + case_end; + + case_ast_node(fv, FieldValue, node); + str = write_expr_to_string(str, fv->field); + str = gb_string_appendc(str, " = "); + str = write_expr_to_string(str, fv->value); + case_end; + + case_ast_node(pt, PointerType, node); + str = gb_string_appendc(str, "^"); + str = write_expr_to_string(str, pt->type); + case_end; + + case_ast_node(mt, MaybeType, node); + str = gb_string_appendc(str, "?"); + str = write_expr_to_string(str, mt->type); + case_end; + + case_ast_node(at, ArrayType, node); + str = gb_string_appendc(str, "["); + str = write_expr_to_string(str, at->count); + str = gb_string_appendc(str, "]"); + str = write_expr_to_string(str, at->elem); + case_end; + + case_ast_node(vt, VectorType, node); + str = gb_string_appendc(str, "[vector "); + str = write_expr_to_string(str, vt->count); + str = gb_string_appendc(str, "]"); + str = write_expr_to_string(str, vt->elem); + case_end; + + case_ast_node(p, Field, node); + if (p->is_using) { + str = gb_string_appendc(str, "using "); + } + for_array(i, p->names) { + AstNode *name = p->names.e[i]; + if (i > 0) { + str = gb_string_appendc(str, ", "); + } + str = write_expr_to_string(str, name); + } + + str = gb_string_appendc(str, ": "); + str = write_expr_to_string(str, p->type); + case_end; + + case_ast_node(ce, CallExpr, node); + str = write_expr_to_string(str, ce->proc); + str = gb_string_appendc(str, "("); + + for_array(i, ce->args) { + AstNode *arg = ce->args.e[i]; + if (i > 0) { + str = gb_string_appendc(str, ", "); + } + str = write_expr_to_string(str, arg); + } + str = gb_string_appendc(str, ")"); + case_end; + + case_ast_node(pt, ProcType, node); + str = gb_string_appendc(str, "proc("); + str = write_params_to_string(str, pt->params, ", "); + str = gb_string_appendc(str, ")"); + case_end; + + case_ast_node(st, StructType, node); + str = gb_string_appendc(str, "struct "); + if (st->is_packed) str = gb_string_appendc(str, "#packed "); + if (st->is_ordered) str = gb_string_appendc(str, "#ordered "); + for_array(i, st->fields) { + if (i > 0) { + str = gb_string_appendc(str, "; "); + } + str = write_expr_to_string(str, st->fields.e[i]); + } + // str = write_params_to_string(str, st->decl_list, ", "); + str = gb_string_appendc(str, "}"); + case_end; + + case_ast_node(st, RawUnionType, node); + str = gb_string_appendc(str, "raw_union {"); + for_array(i, st->fields) { + if (i > 0) { + str = gb_string_appendc(str, "; "); + } + str = write_expr_to_string(str, st->fields.e[i]); + } + // str = write_params_to_string(str, st->decl_list, ", "); + str = gb_string_appendc(str, "}"); + case_end; + + case_ast_node(st, UnionType, node); + str = gb_string_appendc(str, "union {"); + for_array(i, st->fields) { + if (i > 0) { + str = gb_string_appendc(str, "; "); + } + str = write_expr_to_string(str, st->fields.e[i]); + } + // str = write_params_to_string(str, st->decl_list, ", "); + str = gb_string_appendc(str, "}"); + case_end; + + case_ast_node(et, EnumType, node); + str = gb_string_appendc(str, "enum "); + if (et->base_type != NULL) { + str = write_expr_to_string(str, et->base_type); + str = gb_string_appendc(str, " "); + } + str = gb_string_appendc(str, "{"); + str = gb_string_appendc(str, "}"); + case_end; + + case_ast_node(ht, HelperType, node); + str = gb_string_appendc(str, "type "); + str = write_expr_to_string(str, ht->type); + case_end; + } + + return str; +} + +gbString expr_to_string(AstNode *expression) { + return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression); +} diff --git a/src/check_stmt.c b/src/check_stmt.c new file mode 100644 index 000000000..068f6a2b3 --- /dev/null +++ b/src/check_stmt.c @@ -0,0 +1,1301 @@ +void check_stmt_list(Checker *c, AstNodeArray stmts, u32 flags) { + if (stmts.count == 0) { + return; + } + + check_scope_decls(c, stmts, 1.2*stmts.count, NULL); + + bool ft_ok = (flags & Stmt_FallthroughAllowed) != 0; + flags &= ~Stmt_FallthroughAllowed; + + isize max = stmts.count; + for (isize i = stmts.count-1; i >= 0; i--) { + if (stmts.e[i]->kind != AstNode_EmptyStmt) { + break; + } + max--; + } + for (isize i = 0; i < max; i++) { + AstNode *n = stmts.e[i]; + if (n->kind == AstNode_EmptyStmt) { + continue; + } + u32 new_flags = flags; + if (ft_ok && i+1 == max) { + new_flags |= Stmt_FallthroughAllowed; + } + + if (i+1 < max) { + switch (n->kind) { + case AstNode_ReturnStmt: + error_node(n, "Statements after this `return` are never executed"); + break; + case AstNode_ExprStmt: + if (n->ExprStmt.expr->kind == AstNode_GiveExpr) { + error_node(n, "A `give` must be the last statement in a block"); + } + break; + } + } + + check_stmt(c, n, new_flags); + } + +} + +bool check_is_terminating_list(AstNodeArray stmts) { + // Iterate backwards + for (isize n = stmts.count-1; n >= 0; n--) { + AstNode *stmt = stmts.e[n]; + if (stmt->kind != AstNode_EmptyStmt) { + return check_is_terminating(stmt); + } + } + + return false; +} + +bool check_has_break_list(AstNodeArray stmts, bool implicit) { + for_array(i, stmts) { + AstNode *stmt = stmts.e[i]; + if (check_has_break(stmt, implicit)) { + return true; + } + } + return false; +} + + +bool check_has_break(AstNode *stmt, bool implicit) { + switch (stmt->kind) { + case AstNode_BranchStmt: + if (stmt->BranchStmt.token.kind == Token_break) { + return implicit; + } + break; + case AstNode_BlockStmt: + return check_has_break_list(stmt->BlockStmt.stmts, implicit); + + case AstNode_IfStmt: + if (check_has_break(stmt->IfStmt.body, implicit) || + (stmt->IfStmt.else_stmt != NULL && check_has_break(stmt->IfStmt.else_stmt, implicit))) { + return true; + } + break; + + case AstNode_CaseClause: + return check_has_break_list(stmt->CaseClause.stmts, implicit); + } + + return false; +} + + + +// NOTE(bill): The last expression has to be a `return` statement +// TODO(bill): This is a mild hack and should be probably handled properly +// TODO(bill): Warn/err against code after `return` that it won't be executed +bool check_is_terminating(AstNode *node) { + switch (node->kind) { + case_ast_node(rs, ReturnStmt, node); + return true; + case_end; + + case_ast_node(bs, BlockStmt, node); + return check_is_terminating_list(bs->stmts); + case_end; + + case_ast_node(es, ExprStmt, node); + return check_is_terminating(es->expr); + case_end; + + case_ast_node(is, IfStmt, node); + if (is->else_stmt != NULL) { + if (check_is_terminating(is->body) && + check_is_terminating(is->else_stmt)) { + return true; + } + } + case_end; + + case_ast_node(ws, WhenStmt, node); + if (ws->else_stmt != NULL) { + if (check_is_terminating(ws->body) && + check_is_terminating(ws->else_stmt)) { + return true; + } + } + case_end; + + case_ast_node(ws, WhileStmt, node); + if (ws->cond != NULL && !check_has_break(ws->body, true)) { + return check_is_terminating(ws->body); + } + case_end; + + case_ast_node(rs, ForStmt, node); + if (!check_has_break(rs->body, true)) { + return check_is_terminating(rs->body); + } + case_end; + + 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]; + ast_node(cc, CaseClause, clause); + if (cc->list.count == 0) { + has_default = true; + } + if (!check_is_terminating_list(cc->stmts) || + check_has_break_list(cc->stmts, true)) { + return false; + } + } + return has_default; + case_end; + + 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]; + ast_node(cc, CaseClause, clause); + if (cc->list.count == 0) { + has_default = true; + } + if (!check_is_terminating_list(cc->stmts) || + check_has_break_list(cc->stmts, true)) { + return false; + } + } + return has_default; + case_end; + + case_ast_node(pa, PushAllocator, node); + return check_is_terminating(pa->body); + case_end; + case_ast_node(pc, PushContext, node); + return check_is_terminating(pc->body); + case_end; + } + + return false; +} + +Type *check_assignment_variable(Checker *c, Operand *op_a, AstNode *lhs) { + if (op_a->mode == Addressing_Invalid || + op_a->type == t_invalid) { + return NULL; + } + + AstNode *node = unparen_expr(lhs); + + // NOTE(bill): Ignore assignments to `_` + if (node->kind == AstNode_Ident && + str_eq(node->Ident.string, str_lit("_"))) { + add_entity_definition(&c->info, node, NULL); + check_assignment(c, op_a, NULL, str_lit("assignment to `_` identifier")); + if (op_a->mode == Addressing_Invalid) + return NULL; + return op_a->type; + } + + Entity *e = NULL; + bool used = false; + if (node->kind == AstNode_Ident) { + ast_node(i, Ident, node); + e = scope_lookup_entity(c->context.scope, i->string); + if (e != NULL && e->kind == Entity_Variable) { + used = (e->flags & EntityFlag_Used) != 0; // TODO(bill): Make backup just in case + } + } + + + Operand op_b = {Addressing_Invalid}; + check_expr(c, &op_b, lhs); + if (e) { + e->flags |= EntityFlag_Used*used; + } + + if (op_b.mode == Addressing_Invalid || + op_b.type == t_invalid) { + return NULL; + } + + switch (op_b.mode) { + case Addressing_Invalid: + return NULL; + case Addressing_Variable: + break; + default: { + if (op_b.expr->kind == AstNode_SelectorExpr) { + // NOTE(bill): Extra error checks + Operand op_c = {Addressing_Invalid}; + ast_node(se, SelectorExpr, op_b.expr); + check_expr(c, &op_c, se->expr); + } + + gbString str = expr_to_string(op_b.expr); + switch (op_b.mode) { + case Addressing_Value: + error_node(op_b.expr, "Cannot assign to `%s`", str); + break; + default: + error_node(op_b.expr, "Cannot assign to `%s`", str); + break; + } + gb_string_free(str); + } break; + } + + check_assignment(c, op_a, op_b.type, str_lit("assignment")); + if (op_a->mode == Addressing_Invalid) { + return NULL; + } + + return op_a->type; +} + +bool check_valid_type_match_type(Type *type, bool *is_union_ptr, bool *is_any) { + if (is_type_pointer(type)) { + *is_union_ptr = is_type_union(type_deref(type)); + return *is_union_ptr; + } + if (is_type_any(type)) { + *is_any = true; + return *is_any; + } + return false; +} + +void check_stmt_internal(Checker *c, AstNode *node, u32 flags); +void check_stmt(Checker *c, AstNode *node, u32 flags) { + u32 prev_stmt_state_flags = c->context.stmt_state_flags; + + if (node->stmt_state_flags != 0) { + u32 in = node->stmt_state_flags; + u32 out = c->context.stmt_state_flags; + + if (in & StmtStateFlag_bounds_check) { + out |= StmtStateFlag_bounds_check; + out &= ~StmtStateFlag_no_bounds_check; + } else if (in & StmtStateFlag_no_bounds_check) { + out |= StmtStateFlag_no_bounds_check; + out &= ~StmtStateFlag_bounds_check; + } + + c->context.stmt_state_flags = out; + } + + check_stmt_internal(c, node, flags); + + c->context.stmt_state_flags = prev_stmt_state_flags; +} + + + +typedef 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) { + Operand operand = {Addressing_Invalid}; + check_expr(c, &operand, ws->cond); + if (operand.mode != Addressing_Constant || !is_type_boolean(operand.type)) { + error_node(ws->cond, "Non-constant boolean `when` condition"); + return; + } + if (ws->body == NULL || ws->body->kind != AstNode_BlockStmt) { + error_node(ws->cond, "Invalid body for `when` statement"); + return; + } + if (operand.value.kind == ExactValue_Bool && + operand.value.value_bool) { + check_stmt_list(c, ws->body->BlockStmt.stmts, flags); + } else if (ws->else_stmt) { + switch (ws->else_stmt->kind) { + case AstNode_BlockStmt: + check_stmt_list(c, ws->else_stmt->BlockStmt.stmts, flags); + break; + case AstNode_WhenStmt: + check_when_stmt(c, &ws->else_stmt->WhenStmt, flags); + break; + default: + error_node(ws->else_stmt, "Invalid `else` statement in `when` statement"); + break; + } + } +} + +void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { + u32 mod_flags = flags & (~Stmt_FallthroughAllowed); + switch (node->kind) { + case_ast_node(_, EmptyStmt, node); case_end; + case_ast_node(_, BadStmt, node); case_end; + case_ast_node(_, BadDecl, node); case_end; + + case_ast_node(es, ExprStmt, node) + Operand operand = {Addressing_Invalid}; + ExprKind kind = check_expr_base(c, &operand, es->expr, NULL); + switch (operand.mode) { + case Addressing_Type: + error_node(node, "Is not an expression"); + break; + case Addressing_NoValue: + return; + default: { + if (kind == Expr_Stmt) { + return; + } + if (operand.expr->kind == AstNode_CallExpr) { + return; + } + if (operand.expr->kind == AstNode_GiveExpr) { + if ((flags&Stmt_GiveAllowed) != 0) { + return; + } + error_node(node, "Illegal use of `give`"); + } + gbString expr_str = expr_to_string(operand.expr); + error_node(node, "Expression is not used: `%s`", expr_str); + gb_string_free(expr_str); + } break; + } + case_end; + + case_ast_node(ts, TagStmt, node); + // TODO(bill): Tag Statements + error_node(node, "Tag statements are not supported yet"); + check_stmt(c, ts->stmt, flags); + case_end; + + case_ast_node(as, AssignStmt, node); + switch (as->op.kind) { + case Token_Eq: { + // a, b, c = 1, 2, 3; // Multisided + if (as->lhs.count == 0) { + error(as->op, "Missing lhs in assignment statement"); + return; + } + + gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&c->tmp_arena); + + // NOTE(bill): If there is a bad syntax error, rhs > lhs which would mean there would need to be + // an extra allocation + Array(Operand) operands; + array_init_reserve(&operands, c->tmp_allocator, 2 * as->lhs.count); + + for_array(i, as->rhs) { + AstNode *rhs = as->rhs.e[i]; + Operand o = {0}; + check_multi_expr(c, &o, rhs); + if (o.type->kind != Type_Tuple) { + array_add(&operands, o); + } else { + TypeTuple *tuple = &o.type->Tuple; + for (isize j = 0; j < tuple->variable_count; j++) { + o.type = tuple->variables[j]->type; + array_add(&operands, o); + } + } + } + + isize lhs_count = as->lhs.count; + isize rhs_count = operands.count; + + isize operand_count = gb_min(as->lhs.count, operands.count); + for (isize i = 0; i < operand_count; i++) { + AstNode *lhs = as->lhs.e[i]; + check_assignment_variable(c, &operands.e[i], lhs); + } + if (lhs_count != rhs_count) { + error_node(as->lhs.e[0], "Assignment count mismatch `%td` = `%td`", lhs_count, rhs_count); + } + + gb_temp_arena_memory_end(tmp); + } break; + + default: { + // a += 1; // Single-sided + Token op = as->op; + if (as->lhs.count != 1 || as->rhs.count != 1) { + error(op, "Assignment operation `%.*s` requires single-valued expressions", LIT(op.string)); + return; + } + if (!gb_is_between(op.kind, Token__AssignOpBegin+1, Token__AssignOpEnd-1)) { + error(op, "Unknown Assignment operation `%.*s`", LIT(op.string)); + return; + } + // TODO(bill): Check if valid assignment operator + Operand operand = {Addressing_Invalid}; + AstNode binary_expr = {AstNode_BinaryExpr}; + ast_node(be, BinaryExpr, &binary_expr); + 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]; + + 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]); + } break; + } + case_end; + + case_ast_node(bs, BlockStmt, node); + check_open_scope(c, node); + check_stmt_list(c, bs->stmts, mod_flags); + check_close_scope(c); + case_end; + + case_ast_node(is, IfStmt, node); + check_open_scope(c, node); + + if (is->init != NULL) { + check_stmt(c, is->init, 0); + } + + Operand operand = {Addressing_Invalid}; + check_expr(c, &operand, is->cond); + if (operand.mode != Addressing_Invalid && !is_type_boolean(operand.type)) { + error_node(is->cond, "Non-boolean condition in `if` statement"); + } + + check_stmt(c, is->body, mod_flags); + + if (is->else_stmt != NULL) { + switch (is->else_stmt->kind) { + case AstNode_IfStmt: + case AstNode_BlockStmt: + check_stmt(c, is->else_stmt, mod_flags); + break; + default: + error_node(is->else_stmt, "Invalid `else` statement in `if` statement"); + break; + } + } + + check_close_scope(c); + case_end; + + case_ast_node(ws, WhenStmt, node); + check_when_stmt(c, ws, flags); + case_end; + + case_ast_node(rs, ReturnStmt, node); + GB_ASSERT(c->proc_stack.count > 0); + + if (c->in_defer) { + error(rs->token, "You cannot `return` within a defer statement"); + // TODO(bill): Should I break here? + break; + } + + + Type *proc_type = c->proc_stack.e[c->proc_stack.count-1]; + isize result_count = 0; + if (proc_type->Proc.results) { + result_count = proc_type->Proc.results->Tuple.variable_count; + } + + if (result_count > 0) { + Entity **variables = NULL; + if (proc_type->Proc.results != NULL) { + TypeTuple *tuple = &proc_type->Proc.results->Tuple; + variables = tuple->variables; + } + if (rs->results.count == 0) { + error_node(node, "Expected %td return values, got 0", result_count); + } else { + check_init_variables(c, variables, result_count, + rs->results, str_lit("return statement")); + } + } else if (rs->results.count > 0) { + error_node(rs->results.e[0], "No return values expected"); + } + case_end; + + case_ast_node(ws, WhileStmt, node); + u32 new_flags = mod_flags | Stmt_BreakAllowed | Stmt_ContinueAllowed; + check_open_scope(c, node); + + if (ws->init != NULL) { + check_stmt(c, ws->init, 0); + } + if (ws->cond) { + Operand operand = {Addressing_Invalid}; + check_expr(c, &operand, ws->cond); + if (operand.mode != Addressing_Invalid && + !is_type_boolean(operand.type)) { + error_node(ws->cond, "Non-boolean condition in `while` statement"); + } + } + check_stmt(c, ws->body, new_flags); + + check_close_scope(c); + case_end; + + case_ast_node(rs, ForStmt, node); + u32 new_flags = mod_flags | Stmt_BreakAllowed | Stmt_ContinueAllowed; + check_open_scope(c, node); + + Type *val = NULL; + Type *idx = NULL; + Entity *entities[2] = {0}; + isize entity_count = 0; + + + if (rs->expr != NULL && rs->expr->kind == AstNode_IntervalExpr) { + ast_node(ie, IntervalExpr, rs->expr); + Operand x = {Addressing_Invalid}; + Operand y = {Addressing_Invalid}; + + check_expr(c, &x, ie->left); + if (x.mode == Addressing_Invalid) { + goto skip_expr; + } + check_expr(c, &y, ie->right); + if (y.mode == Addressing_Invalid) { + goto skip_expr; + } + + convert_to_typed(c, &x, y.type, 0); + if (x.mode == Addressing_Invalid) { + goto skip_expr; + } + convert_to_typed(c, &y, x.type, 0); + if (y.mode == Addressing_Invalid) { + goto skip_expr; + } + + convert_to_typed(c, &x, default_type(y.type), 0); + if (x.mode == Addressing_Invalid) { + goto skip_expr; + } + convert_to_typed(c, &y, default_type(x.type), 0); + if (y.mode == Addressing_Invalid) { + goto skip_expr; + } + + if (!are_types_identical(x.type, y.type)) { + if (x.type != t_invalid && + y.type != t_invalid) { + gbString xt = type_to_string(x.type); + gbString yt = type_to_string(y.type); + gbString expr_str = expr_to_string(x.expr); + error(ie->op, "Mismatched types in interval expression `%s` : `%s` vs `%s`", expr_str, xt, yt); + gb_string_free(expr_str); + gb_string_free(yt); + gb_string_free(xt); + } + goto skip_expr; + } + + Type *type = x.type; + Type *bt = base_type(base_enum_type(type)); + + if (!is_type_integer(bt) && !is_type_float(bt) && !is_type_pointer(bt)) { + error(ie->op, "Only numerical and pointer types are allowed within interval expressions"); + goto skip_expr; + } + + if (x.mode == Addressing_Constant && + y.mode == Addressing_Constant) { + ExactValue a = x.value; + ExactValue b = y.value; + + GB_ASSERT(are_types_identical(x.type, y.type)); + + bool ok = compare_exact_values(Token_Lt, a, b); + if (!ok) { + // TODO(bill): Better error message + error(ie->op, "Invalid interval range"); + goto skip_expr; + } + } + + add_type_and_value(&c->info, ie->left, x.mode, x.type, x.value); + add_type_and_value(&c->info, ie->right, y.mode, y.type, y.value); + val = type; + idx = t_int; + } else { + Operand operand = {Addressing_Invalid}; + check_expr(c, &operand, rs->expr); + + if (operand.mode != Addressing_Invalid) { + Type *t = base_type(type_deref(operand.type)); + switch (t->kind) { + case Type_Basic: + if (is_type_string(t)) { + val = t_rune; + idx = t_int; + } + break; + case Type_Array: + val = t->Array.elem; + idx = t_int; + break; + case Type_Slice: + val = t->Array.elem; + idx = t_int; + break; + } + } + + if (val == NULL) { + gbString s = expr_to_string(operand.expr); + gbString t = type_to_string(operand.type); + error_node(operand.expr, "Cannot iterate over `%s` of type `%s`", s, t); + gb_string_free(t); + gb_string_free(s); + } + } + + skip_expr: + AstNode *lhs[2] = {rs->value, rs->index}; + Type * rhs[2] = {val, idx}; + + for (isize i = 0; i < 2; i++) { + if (lhs[i] == NULL) { + continue; + } + AstNode *name = lhs[i]; + Type * type = rhs[i]; + + Entity *entity = NULL; + if (name->kind == AstNode_Ident) { + Token token = name->Ident; + String str = token.string; + Entity *found = NULL; + + if (str_ne(str, str_lit("_"))) { + found = current_scope_lookup_entity(c->context.scope, str); + } + if (found == NULL) { + entity = make_entity_variable(c->allocator, c->context.scope, token, type); + entity->Variable.is_immutable = true; + add_entity_definition(&c->info, name, entity); + } else { + TokenPos pos = found->token.pos; + error(token, + "Redeclaration of `%.*s` in this scope\n" + "\tat %.*s(%td:%td)", + LIT(str), LIT(pos.file), pos.line, pos.column); + entity = found; + } + } else { + error_node(name, "A variable declaration must be an identifier"); + } + + if (entity == NULL) { + entity = make_entity_dummy_variable(c->allocator, c->global_scope, ast_node_token(name)); + } + + entities[entity_count++] = entity; + + if (type == NULL) { + entity->type = t_invalid; + entity->flags |= EntityFlag_Used; + } + } + + for (isize i = 0; i < entity_count; i++) { + add_entity(c, c->context.scope, entities[i]->identifier, entities[i]); + } + + check_stmt(c, rs->body, new_flags); + + check_close_scope(c); + case_end; + + case_ast_node(ms, MatchStmt, node); + Operand x = {0}; + + mod_flags |= Stmt_BreakAllowed; + check_open_scope(c, node); + + if (ms->init != NULL) { + check_stmt(c, ms->init, 0); + } + if (ms->tag != NULL) { + check_expr(c, &x, ms->tag); + check_assignment(c, &x, NULL, str_lit("match expression")); + } else { + x.mode = Addressing_Constant; + x.type = t_bool; + x.value = make_exact_value_bool(true); + + Token token = {0}; + token.pos = ast_node_token(ms->body).pos; + token.string = str_lit("true"); + x.expr = make_ident(c->curr_ast_file, token); + } + + // NOTE(bill): Check for multiple defaults + AstNode *first_default = NULL; + ast_node(bs, BlockStmt, ms->body); + for_array(i, bs->stmts) { + AstNode *stmt = bs->stmts.e[i]; + AstNode *default_stmt = NULL; + if (stmt->kind == AstNode_CaseClause) { + ast_node(cc, CaseClause, stmt); + if (cc->list.count == 0) { + default_stmt = stmt; + } + } else { + error_node(stmt, "Invalid AST - expected case clause"); + } + + if (default_stmt != NULL) { + if (first_default != NULL) { + TokenPos pos = ast_node_token(first_default).pos; + error_node(stmt, + "multiple `default` clauses\n" + "\tfirst at %.*s(%td:%td)", + LIT(pos.file), pos.line, pos.column); + } else { + first_default = default_stmt; + } + } + } + + MapTypeAndToken seen = {0}; // NOTE(bill): Multimap + map_type_and_token_init(&seen, heap_allocator()); + + for_array(i, bs->stmts) { + AstNode *stmt = bs->stmts.e[i]; + if (stmt->kind != AstNode_CaseClause) { + // NOTE(bill): error handled by above multiple default checker + continue; + } + ast_node(cc, CaseClause, stmt); + + + for_array(j, cc->list) { + AstNode *expr = cc->list.e[j]; + Operand y = {0}; + Operand z = {0}; + Token eq = {Token_CmpEq}; + + check_expr(c, &y, expr); + if (x.mode == Addressing_Invalid || + y.mode == Addressing_Invalid) { + continue; + } + convert_to_typed(c, &y, x.type, 0); + if (y.mode == Addressing_Invalid) { + continue; + } + + z = y; + check_comparison(c, &z, &x, eq); + if (z.mode == Addressing_Invalid) { + continue; + } + if (y.mode != Addressing_Constant) { + continue; + } + + if (y.value.kind != ExactValue_Invalid) { + HashKey key = hash_exact_value(y.value); + TypeAndToken *found = map_type_and_token_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); + TypeAndToken *taps = gb_alloc_array(c->tmp_allocator, TypeAndToken, count); + + map_type_and_token_multi_get_all(&seen, key, taps); + bool continue_outer = false; + + for (isize i = 0; i < count; i++) { + TypeAndToken tap = taps[i]; + if (are_types_identical(y.type, tap.type)) { + TokenPos pos = tap.token.pos; + gbString expr_str = expr_to_string(y.expr); + error_node(y.expr, + "Duplicate case `%s`\n" + "\tprevious case at %.*s(%td:%td)", + expr_str, + LIT(pos.file), pos.line, pos.column); + gb_string_free(expr_str); + continue_outer = true; + break; + } + } + + gb_temp_arena_memory_end(tmp); + + if (continue_outer) { + continue; + } + } + TypeAndToken tap = {y.type, ast_node_token(y.expr)}; + map_type_and_token_multi_insert(&seen, key, tap); + } + } + + check_open_scope(c, stmt); + u32 ft_flags = mod_flags; + if (i+1 < bs->stmts.count) { + ft_flags |= Stmt_FallthroughAllowed; + } + check_stmt_list(c, cc->stmts, ft_flags); + check_close_scope(c); + } + + map_type_and_token_destroy(&seen); + + check_close_scope(c); + case_end; + + case_ast_node(ms, TypeMatchStmt, node); + Operand x = {0}; + + mod_flags |= Stmt_BreakAllowed; + check_open_scope(c, node); + + bool is_union_ptr = false; + bool is_any = false; + + check_expr(c, &x, ms->tag); + check_assignment(c, &x, NULL, str_lit("type match expression")); + if (!check_valid_type_match_type(x.type, &is_union_ptr, &is_any)) { + gbString str = type_to_string(x.type); + error_node(x.expr, + "Invalid type for this type match expression, got `%s`", str); + gb_string_free(str); + break; + } + + + // NOTE(bill): Check for multiple defaults + AstNode *first_default = NULL; + ast_node(bs, BlockStmt, ms->body); + for_array(i, bs->stmts) { + AstNode *stmt = bs->stmts.e[i]; + AstNode *default_stmt = NULL; + if (stmt->kind == AstNode_CaseClause) { + ast_node(cc, CaseClause, stmt); + if (cc->list.count == 0) { + default_stmt = stmt; + } + } else { + error_node(stmt, "Invalid AST - expected case clause"); + } + + if (default_stmt != NULL) { + if (first_default != NULL) { + TokenPos pos = ast_node_token(first_default).pos; + error_node(stmt, + "Multiple `default` clauses\n" + "\tfirst at %.*s(%td:%td)", LIT(pos.file), pos.line, pos.column); + } else { + first_default = default_stmt; + } + } + } + + if (ms->var->kind != AstNode_Ident) { + break; + } + + + MapBool seen = {0}; + map_bool_init(&seen, heap_allocator()); + + for_array(i, bs->stmts) { + AstNode *stmt = bs->stmts.e[i]; + if (stmt->kind != AstNode_CaseClause) { + // NOTE(bill): error handled by above multiple default checker + continue; + } + ast_node(cc, CaseClause, stmt); + + // TODO(bill): Make robust + Type *bt = base_type(type_deref(x.type)); + + + AstNode *type_expr = cc->list.count > 0 ? cc->list.e[0] : NULL; + Type *case_type = NULL; + if (type_expr != NULL) { // Otherwise it's a default expression + Operand y = {0}; + check_expr_or_type(c, &y, type_expr); + + if (is_union_ptr) { + GB_ASSERT(is_type_union(bt)); + bool tag_type_found = false; + for (isize i = 0; i < bt->Record.field_count; i++) { + Entity *f = bt->Record.fields[i]; + if (are_types_identical(f->type, y.type)) { + tag_type_found = true; + break; + } + } + if (!tag_type_found) { + gbString type_str = type_to_string(y.type); + error_node(y.expr, + "Unknown tag type, got `%s`", type_str); + gb_string_free(type_str); + continue; + } + case_type = y.type; + } else if (is_any) { + case_type = y.type; + } else { + GB_PANIC("Unknown type to type match statement"); + } + + HashKey key = hash_pointer(y.type); + bool *found = map_bool_get(&seen, key); + if (found) { + TokenPos pos = cc->token.pos; + gbString expr_str = expr_to_string(y.expr); + error_node(y.expr, + "Duplicate type case `%s`\n" + "\tprevious type case at %.*s(%td:%td)", + expr_str, + LIT(pos.file), pos.line, pos.column); + gb_string_free(expr_str); + break; + } + map_bool_set(&seen, key, cast(bool)true); + } + + check_open_scope(c, stmt); + if (case_type != NULL) { + add_type_info_type(c, case_type); + + // NOTE(bill): Dummy type + Type *tt = case_type; + if (is_union_ptr) { + tt = make_type_pointer(c->allocator, case_type); + add_type_info_type(c, tt); + } + Entity *tag_var = make_entity_variable(c->allocator, c->context.scope, ms->var->Ident, tt); + tag_var->flags |= EntityFlag_Used; + tag_var->Variable.is_immutable = true; + add_entity(c, c->context.scope, ms->var, tag_var); + add_entity_use(c, ms->var, tag_var); + } + check_stmt_list(c, cc->stmts, mod_flags); + check_close_scope(c); + } + map_bool_destroy(&seen); + + check_close_scope(c); + case_end; + + + case_ast_node(ds, DeferStmt, node); + if (is_ast_node_decl(ds->stmt)) { + error(ds->token, "You cannot defer a declaration"); + } else { + bool out_in_defer = c->in_defer; + c->in_defer = true; + check_stmt(c, ds->stmt, 0); + c->in_defer = out_in_defer; + } + case_end; + + case_ast_node(bs, BranchStmt, node); + Token token = bs->token; + switch (token.kind) { + case Token_break: + if ((flags & Stmt_BreakAllowed) == 0) { + error(token, "`break` only allowed in loops or `match` statements"); + } + break; + case Token_continue: + if ((flags & Stmt_ContinueAllowed) == 0) { + error(token, "`continue` only allowed in loops"); + } + break; + case Token_fallthrough: + if ((flags & Stmt_FallthroughAllowed) == 0) { + error(token, "`fallthrough` statement in illegal position"); + } + break; + default: + error(token, "Invalid AST: Branch Statement `%.*s`", LIT(token.string)); + break; + } + case_end; + + case_ast_node(us, UsingStmt, node); + switch (us->node->kind) { + case_ast_node(es, ExprStmt, us->node); + // TODO(bill): Allow for just a LHS expression list rather than this silly code + Entity *e = NULL; + + bool is_selector = false; + AstNode *expr = unparen_expr(es->expr); + if (expr->kind == AstNode_Ident) { + String name = expr->Ident.string; + e = scope_lookup_entity(c->context.scope, name); + } else if (expr->kind == AstNode_SelectorExpr) { + Operand o = {0}; + e = check_selector(c, &o, expr); + is_selector = true; + } + + if (e == NULL) { + error(us->token, "`using` applied to an unknown entity"); + return; + } + + switch (e->kind) { + case Entity_TypeName: { + Type *t = base_type(e->type); + if (is_type_union(t)) { + for (isize i = 0; i < t->Record.field_count; i++) { + Entity *f = t->Record.fields[i]; + Entity *found = scope_insert_entity(c->context.scope, f); + if (found != NULL) { + gbString expr_str = expr_to_string(expr); + error(us->token, "Namespace collision while `using` `%s` of: %.*s", expr_str, LIT(found->token.string)); + gb_string_free(expr_str); + return; + } + f->using_parent = e; + } + } else if (is_type_enum(t)) { + for (isize i = 0; i < t->Record.field_count; i++) { + Entity *f = t->Record.fields[i]; + Entity *found = scope_insert_entity(c->context.scope, f); + if (found != NULL) { + gbString expr_str = expr_to_string(expr); + error(us->token, "Namespace collision while `using` `%s` of: %.*s", expr_str, LIT(found->token.string)); + gb_string_free(expr_str); + return; + } + f->using_parent = e; + } + + } else { + error(us->token, "`using` can be only applied to `union` or `enum` type entities"); + } + } break; + + case Entity_ImportName: { + Scope *scope = e->ImportName.scope; + for_array(i, scope->elements.entries) { + Entity *decl = scope->elements.entries.e[i].value; + Entity *found = scope_insert_entity(c->context.scope, decl); + if (found != NULL) { + gbString expr_str = expr_to_string(expr); + error(us->token, + "Namespace collision while `using` `%s` of: %.*s\n" + "\tat %.*s(%td:%td)\n" + "\tat %.*s(%td:%td)", + expr_str, LIT(found->token.string), + LIT(found->token.pos.file), found->token.pos.line, found->token.pos.column, + LIT(decl->token.pos.file), decl->token.pos.line, decl->token.pos.column + ); + gb_string_free(expr_str); + return; + } + } + } break; + + case Entity_Variable: { + 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)); + GB_ASSERT(found != NULL); + for_array(i, (*found)->elements.entries) { + Entity *f = (*found)->elements.entries.e[i].value; + if (f->kind == Entity_Variable) { + Entity *uvar = make_entity_using_variable(c->allocator, e, f->token, f->type); + if (is_selector) { + uvar->using_expr = expr; + } + Entity *prev = scope_insert_entity(c->context.scope, uvar); + if (prev != NULL) { + gbString expr_str = expr_to_string(expr); + error(us->token, "Namespace collision while `using` `%s` of: %.*s", expr_str, LIT(prev->token.string)); + gb_string_free(expr_str); + return; + } + } + } + } else { + error(us->token, "`using` can only be applied to variables of type struct or raw_union"); + return; + } + } break; + + case Entity_Constant: + error(us->token, "`using` cannot be applied to a constant"); + break; + + case Entity_Procedure: + case Entity_Builtin: + error(us->token, "`using` cannot be applied to a procedure"); + break; + + case Entity_ImplicitValue: + error(us->token, "`using` cannot be applied to an implicit value"); + break; + + case Entity_Nil: + error(us->token, "`using` cannot be applied to `nil`"); + break; + + case Entity_Invalid: + error(us->token, "`using` cannot be applied to an invalid entity"); + break; + + default: + GB_PANIC("TODO(bill): `using` other expressions?"); + } + case_end; + + case_ast_node(vd, ValueDecl, us->node); + if (!vd->is_var) { + error_node(us->node, "`using` can only be applied to a variable declaration"); + return; + } + + if (vd->names.count > 1 && vd->type != NULL) { + error(us->token, "`using` can only be applied to one variable of the same type"); + } + + check_var_decl_node(c, vd); + + for_array(name_index, vd->names) { + AstNode *item = vd->names.e[name_index]; + if (item->kind != AstNode_Ident) { + // TODO(bill): Handle error here??? + continue; + } + ast_node(i, Ident, item); + String name = i->string; + Entity *e = scope_lookup_entity(c->context.scope, name); + 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)); + GB_ASSERT(found != NULL); + for_array(i, (*found)->elements.entries) { + Entity *f = (*found)->elements.entries.e[i].value; + if (f->kind == Entity_Variable) { + Entity *uvar = make_entity_using_variable(c->allocator, e, f->token, f->type); + Entity *prev = scope_insert_entity(c->context.scope, uvar); + if (prev != NULL) { + error(us->token, "Namespace collision while `using` `%.*s` of: %.*s", LIT(name), LIT(prev->token.string)); + return; + } + } + } + } else { + error(us->token, "`using` can only be applied to variables of type struct or raw_union"); + return; + } + } + case_end; + + default: + error(us->token, "Invalid AST: Using Statement"); + break; + } + case_end; + + + + case_ast_node(pa, PushAllocator, node); + Operand op = {0}; + 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); + case_end; + + + case_ast_node(pa, PushContext, node); + Operand op = {0}; + 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); + case_end; + + + case_ast_node(vd, ValueDecl, node); + if (vd->is_var) { + isize entity_count = vd->names.count; + isize entity_index = 0; + Entity **entities = gb_alloc_array(c->allocator, Entity *, entity_count); + + for_array(i, vd->names) { + AstNode *name = vd->names.e[i]; + Entity *entity = NULL; + if (name->kind == AstNode_Ident) { + Token token = name->Ident; + String str = token.string; + Entity *found = NULL; + // NOTE(bill): Ignore assignments to `_` + if (str_ne(str, str_lit("_"))) { + found = current_scope_lookup_entity(c->context.scope, str); + } + if (found == NULL) { + entity = make_entity_variable(c->allocator, c->context.scope, token, NULL); + add_entity_definition(&c->info, name, entity); + } else { + TokenPos pos = found->token.pos; + error(token, + "Redeclaration of `%.*s` in this scope\n" + "\tat %.*s(%td:%td)", + LIT(str), LIT(pos.file), pos.line, pos.column); + entity = found; + } + } else { + error_node(name, "A variable declaration must be an identifier"); + } + if (entity == NULL) { + entity = make_entity_dummy_variable(c->allocator, c->global_scope, ast_node_token(name)); + } + entities[entity_index++] = entity; + } + + Type *init_type = NULL; + if (vd->type) { + init_type = check_type_extra(c, vd->type, NULL); + if (init_type == NULL) { + init_type = t_invalid; + } + } + + for (isize i = 0; i < entity_count; i++) { + Entity *e = entities[i]; + GB_ASSERT(e != NULL); + if (e->flags & EntityFlag_Visited) { + e->type = t_invalid; + continue; + } + e->flags |= EntityFlag_Visited; + + if (e->type == NULL) + e->type = init_type; + } + check_arity_match(c, vd); + + check_init_variables(c, entities, entity_count, vd->values, str_lit("variable declaration")); + + for_array(i, vd->names) { + if (entities[i] != NULL) { + add_entity(c, c->context.scope, vd->names.e[i], entities[i]); + } + } + } else { + // NOTE(bill): Handled elsewhere + } + case_end; + } +} diff --git a/src/checker.c b/src/checker.c new file mode 100644 index 000000000..6685d56ab --- /dev/null +++ b/src/checker.c @@ -0,0 +1,1580 @@ +#include "exact_value.c" +#include "entity.c" +#include "types.c" + +#define MAP_TYPE Entity * +#define MAP_PROC map_entity_ +#define MAP_NAME MapEntity +#include "map.c" + +typedef enum AddressingMode { + Addressing_Invalid, + Addressing_NoValue, + Addressing_Value, + Addressing_Variable, + Addressing_Constant, + Addressing_Type, + Addressing_Builtin, + Addressing_Count, +} AddressingMode; + +typedef struct Operand { + AddressingMode mode; + Type * type; + ExactValue value; + AstNode * expr; + BuiltinProcId builtin_id; +} Operand; + +typedef struct TypeAndValue { + AddressingMode mode; + Type * type; + ExactValue value; +} TypeAndValue; + +bool is_operand_value(Operand o) { + switch (o.mode) { + case Addressing_Value: + case Addressing_Variable: + case Addressing_Constant: + return true; + } + return false; +} + + + +typedef struct DeclInfo { + Scope *scope; + + Entity **entities; + isize entity_count; + + AstNode *type_expr; + AstNode *init_expr; + AstNode *proc_lit; // AstNode_ProcLit + u32 var_decl_tags; + + MapBool deps; // Key: Entity * +} DeclInfo; + +typedef 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}; + return ei; +} + +typedef struct ProcedureInfo { + AstFile * file; + Token token; + DeclInfo *decl; + Type * type; // Type_Procedure + AstNode * body; // AstNode_BlockStmt + u32 tags; +} ProcedureInfo; + +typedef struct Scope { + Scope * parent; + Scope * prev, *next; + Scope * first_child; + Scope * last_child; + MapEntity elements; // Key: String + MapEntity implicit; // Key: String + + Array(Scope *) shared; + Array(Scope *) imported; + bool is_proc; + bool is_global; + bool is_file; + bool is_init; + AstFile * file; +} Scope; +gb_global Scope *universal_scope = NULL; + +typedef enum ExprKind { + Expr_Expr, + Expr_Stmt, +} ExprKind; + +// Statements and Declarations +typedef enum StmtFlag { + Stmt_BreakAllowed = 1<<0, + Stmt_ContinueAllowed = 1<<1, + Stmt_FallthroughAllowed = 1<<2, + Stmt_GiveAllowed = 1<<3, +} StmtFlag; + +typedef enum BuiltinProcId { + BuiltinProc_Invalid, + + BuiltinProc_new, + BuiltinProc_new_slice, + + BuiltinProc_size_of, + BuiltinProc_size_of_val, + BuiltinProc_align_of, + BuiltinProc_align_of_val, + BuiltinProc_offset_of, + BuiltinProc_offset_of_val, + BuiltinProc_type_of_val, + + BuiltinProc_type_info, + BuiltinProc_type_info_of_val, + + BuiltinProc_compile_assert, + BuiltinProc_assert, + BuiltinProc_panic, + + BuiltinProc_copy, + // BuiltinProc_append, + + BuiltinProc_swizzle, + + // BuiltinProc_ptr_offset, + // BuiltinProc_ptr_sub, + BuiltinProc_slice_ptr, + + BuiltinProc_min, + BuiltinProc_max, + BuiltinProc_abs, + BuiltinProc_clamp, + + BuiltinProc_Count, +} BuiltinProcId; +typedef struct BuiltinProc { + String name; + isize arg_count; + bool variadic; + ExprKind kind; +} BuiltinProc; +gb_global BuiltinProc builtin_procs[BuiltinProc_Count] = { + {STR_LIT(""), 0, false, Expr_Stmt}, + + {STR_LIT("new"), 1, false, Expr_Expr}, + {STR_LIT("new_slice"), 2, false, Expr_Expr}, + + {STR_LIT("size_of"), 1, false, Expr_Expr}, + {STR_LIT("size_of_val"), 1, false, Expr_Expr}, + {STR_LIT("align_of"), 1, false, Expr_Expr}, + {STR_LIT("align_of_val"), 1, false, Expr_Expr}, + {STR_LIT("offset_of"), 2, false, Expr_Expr}, + {STR_LIT("offset_of_val"), 1, false, Expr_Expr}, + {STR_LIT("type_of_val"), 1, false, Expr_Expr}, + + {STR_LIT("type_info"), 1, false, Expr_Expr}, + {STR_LIT("type_info_of_val"), 1, false, Expr_Expr}, + + {STR_LIT("compile_assert"), 1, false, Expr_Stmt}, + {STR_LIT("assert"), 1, false, Expr_Stmt}, + {STR_LIT("panic"), 1, false, Expr_Stmt}, + + {STR_LIT("copy"), 2, false, Expr_Expr}, + // {STR_LIT("append"), 2, false, Expr_Expr}, + + {STR_LIT("swizzle"), 1, true, Expr_Expr}, + + // {STR_LIT("ptr_offset"), 2, false, Expr_Expr}, + // {STR_LIT("ptr_sub"), 2, false, Expr_Expr}, + {STR_LIT("slice_ptr"), 2, false, Expr_Expr}, + + {STR_LIT("min"), 2, false, Expr_Expr}, + {STR_LIT("max"), 2, false, Expr_Expr}, + {STR_LIT("abs"), 1, false, Expr_Expr}, + {STR_LIT("clamp"), 3, false, Expr_Expr}, +}; + +typedef enum ImplicitValueId { + ImplicitValue_Invalid, + + ImplicitValue_context, + + ImplicitValue_Count, +} ImplicitValueId; +typedef struct ImplicitValueInfo { + String name; + String backing_name; + Type * type; +} ImplicitValueInfo; +// NOTE(bill): This is initialized later +gb_global ImplicitValueInfo implicit_value_infos[ImplicitValue_Count] = {0}; + + + +typedef struct CheckerContext { + Scope * scope; + DeclInfo * decl; + u32 stmt_state_flags; + ExactValue iota; // Value of `iota` in a constant declaration; Invalid otherwise +} CheckerContext; + +#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 { + Scope * parent; + AstNode *decl; +} DelayedDecl; + + +// NOTE(bill): Symbol tables +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 + MapDeclInfo entities; // Key: Entity * + MapEntity foreign_procs; // Key: String + MapAstFile files; // Key: String (full path) + MapIsize type_info_map; // Key: Type * + isize type_info_count; + Entity * implicit_values[ImplicitValue_Count]; + Array(String) foreign_libraries; // For the linker +} CheckerInfo; + +typedef struct Checker { + Parser * parser; + CheckerInfo info; + + AstFile * curr_ast_file; + BaseTypeSizes sizes; + Scope * global_scope; + Array(ProcedureInfo) procs; // NOTE(bill): Procedures to check + Array(DelayedDecl) delayed_imports; + Array(DelayedDecl) delayed_foreign_libraries; + + + gbArena arena; + gbArena tmp_arena; + gbAllocator allocator; + gbAllocator tmp_allocator; + + CheckerContext context; + + Array(Type *) proc_stack; + bool in_defer; // TODO(bill): Actually handle correctly + bool done_preload; +} Checker; + + + + +void init_declaration_info(DeclInfo *d, Scope *scope) { + d->scope = scope; + map_bool_init(&d->deps, heap_allocator()); +} + +DeclInfo *make_declaration_info(gbAllocator a, Scope *scope) { + DeclInfo *d = gb_alloc_item(a, DeclInfo); + init_declaration_info(d, scope); + return d; +} + +void destroy_declaration_info(DeclInfo *d) { + map_bool_destroy(&d->deps); +} + +bool decl_info_has_init(DeclInfo *d) { + if (d->init_expr != NULL) { + return true; + } + if (d->proc_lit != NULL) { + switch (d->proc_lit->kind) { + case_ast_node(pd, ProcLit, d->proc_lit); + if (pd->body != NULL) { + return true; + } + case_end; + } + } + + return false; +} + + + + + +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_entity_init(&s->implicit, heap_allocator()); + array_init(&s->shared, heap_allocator()); + array_init(&s->imported, heap_allocator()); + + if (parent != NULL && parent != universal_scope) { + DLIST_APPEND(parent->first_child, parent->last_child, s); + } + return s; +} + +void destroy_scope(Scope *scope) { + for_array(i, scope->elements.entries) { + Entity *e =scope->elements.entries.e[i].value; + if (e->kind == Entity_Variable) { + if (!(e->flags & EntityFlag_Used)) { +#if 0 + warning(e->token, "Unused variable `%.*s`", LIT(e->token.string)); +#endif + } + } + } + + for (Scope *child = scope->first_child; child != NULL; child = child->next) { + destroy_scope(child); + } + + map_entity_destroy(&scope->elements); + map_entity_destroy(&scope->implicit); + array_free(&scope->shared); + array_free(&scope->imported); + + // NOTE(bill): No need to free scope as it "should" be allocated in an arena (except for the global 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); +} + + +void check_open_scope(Checker *c, AstNode *node) { + GB_ASSERT(node != NULL); + node = unparen_expr(node); + GB_ASSERT(node->kind == AstNode_Invalid || + is_ast_node_stmt(node) || + is_ast_node_type(node) || + node->kind == AstNode_BlockExpr || + node->kind == AstNode_IfExpr ); + Scope *scope = make_scope(c->context.scope, c->allocator); + add_scope(c, node, scope); + if (node->kind == AstNode_ProcType) { + scope->is_proc = true; + } + c->context.scope = scope; + c->context.stmt_state_flags |= StmtStateFlag_bounds_check; +} + +void check_close_scope(Checker *c) { + c->context.scope = c->context.scope->parent; +} + +void scope_lookup_parent_entity(Scope *scope, String name, Scope **scope_, Entity **entity_) { + bool gone_thru_proc = false; + 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); + if (found) { + Entity *e = *found; + if (gone_thru_proc) { + if (e->kind == Entity_Variable && + !e->scope->is_file && + !e->scope->is_global) { + continue; + } + } + + if (entity_) *entity_ = e; + if (scope_) *scope_ = s; + return; + } + + if (s->is_proc) { + gone_thru_proc = true; + } 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); + if (found) { + Entity *e = *found; + if (e->kind == Entity_Variable && + !e->scope->is_file && + !e->scope->is_global) { + continue; + } + + if (e->scope != shared) { + // Do not return imported entities even #include ones + continue; + } + + if (e->kind == Entity_ImportName && gone_thru_file) { + continue; + } + + if (entity_) *entity_ = e; + if (scope_) *scope_ = shared; + return; + } + } + } + + if (s->is_file) { + gone_thru_file = true; + } + } + + + if (entity_) *entity_ = NULL; + if (scope_) *scope_ = NULL; +} + +Entity *scope_lookup_entity(Scope *s, String name) { + Entity *entity = NULL; + scope_lookup_parent_entity(s, name, NULL, &entity); + return entity; +} + +Entity *current_scope_lookup_entity(Scope *s, String name) { + HashKey key = hash_string(name); + Entity **found = map_entity_get(&s->elements, key); + if (found) { + return *found; + } + for_array(i, s->shared) { + Entity **found = map_entity_get(&s->shared.e[i]->elements, key); + if (found) { + return *found; + } + } + return NULL; +} + + + +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); + if (found) { + return *found; + } + map_entity_set(&s->elements, key, entity); + if (entity->scope == NULL) { + entity->scope = s; + } + return NULL; +} + +void check_scope_usage(Checker *c, Scope *scope) { + // TODO(bill): Use this? +} + + +void add_dependency(DeclInfo *d, Entity *e) { + map_bool_set(&d->deps, hash_pointer(e), cast(bool)true); +} + +void add_declaration_dependency(Checker *c, Entity *e) { + if (e == NULL) { + return; + } + if (c->context.decl != NULL) { + DeclInfo **found = map_decl_info_get(&c->info.entities, hash_pointer(e)); + if (found) { + add_dependency(c->context.decl, e); + } + } +} + + +void add_global_entity(Entity *entity) { + String name = entity->token.string; + if (gb_memchr(name.text, ' ', name.len)) { + return; // NOTE(bill): `untyped thing` + } + if (scope_insert_entity(universal_scope, entity)) { + compiler_error("double declaration"); + } +} + +void add_global_constant(gbAllocator a, String name, Type *type, ExactValue value) { + Entity *entity = alloc_entity(a, Entity_Constant, NULL, make_token_ident(name), type); + entity->Constant.value = value; + add_global_entity(entity); +} + + +void add_global_string_constant(gbAllocator a, String name, String value) { + add_global_constant(a, name, t_untyped_string, make_exact_value_string(value)); + +} + + +void init_universal_scope(BuildContext *bc) { + // NOTE(bill): No need to free these + gbAllocator a = heap_allocator(); + universal_scope = make_scope(NULL, a); + +// Types + for (isize i = 0; i < gb_count_of(basic_types); i++) { + add_global_entity(make_entity_type_name(a, NULL, make_token_ident(basic_types[i].Basic.name), &basic_types[i])); + } + for (isize i = 0; i < gb_count_of(basic_type_aliases); i++) { + add_global_entity(make_entity_type_name(a, NULL, make_token_ident(basic_type_aliases[i].Basic.name), &basic_type_aliases[i])); + } + +// Constants + add_global_constant(a, str_lit("true"), t_untyped_bool, make_exact_value_bool(true)); + add_global_constant(a, str_lit("false"), t_untyped_bool, make_exact_value_bool(false)); + add_global_constant(a, str_lit("iota"), t_untyped_integer, make_exact_value_integer(0)); + + add_global_entity(make_entity_nil(a, str_lit("nil"), t_untyped_nil)); + + // TODO(bill): Set through flags in the compiler + add_global_string_constant(a, str_lit("ODIN_OS"), bc->ODIN_OS); + add_global_string_constant(a, str_lit("ODIN_ARCH"), bc->ODIN_ARCH); + add_global_string_constant(a, str_lit("ODIN_VENDOR"), bc->ODIN_VENDOR); + add_global_string_constant(a, str_lit("ODIN_VERSION"), bc->ODIN_VERSION); + add_global_string_constant(a, str_lit("ODIN_ROOT"), bc->ODIN_ROOT); + + +// Builtin Procedures + for (isize i = 0; i < gb_count_of(builtin_procs); i++) { + BuiltinProcId id = cast(BuiltinProcId)i; + Entity *entity = alloc_entity(a, Entity_Builtin, NULL, make_token_ident(builtin_procs[i].name), t_invalid); + entity->Builtin.id = id; + add_global_entity(entity); + } + + + t_u8_ptr = make_type_pointer(a, t_u8); + t_int_ptr = make_type_pointer(a, t_int); + e_iota = scope_lookup_entity(universal_scope, str_lit("iota")); +} + + + + +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->foreign_procs, a); + map_isize_init(&i->type_info_map, a); + map_ast_file_init(&i->files, a); + array_init(&i->foreign_libraries, 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->foreign_procs); + map_isize_destroy(&i->type_info_map); + map_ast_file_destroy(&i->files); + array_free(&i->foreign_libraries); +} + + +void init_checker(Checker *c, Parser *parser, BuildContext *bc) { + gbAllocator a = heap_allocator(); + + c->parser = parser; + init_checker_info(&c->info); + c->sizes.word_size = bc->word_size; + c->sizes.max_align = bc->max_align; + + array_init(&c->proc_stack, a); + array_init(&c->procs, a); + array_init(&c->delayed_imports, a); + array_init(&c->delayed_foreign_libraries, a); + + // NOTE(bill): Is this big enough or too small? + 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]; + total_token_count += f->tokens.count; + } + isize arena_size = 2 * item_size * total_token_count; + gb_arena_init_from_allocator(&c->arena, a, arena_size); + gb_arena_init_from_allocator(&c->tmp_arena, a, arena_size); + + + c->allocator = gb_arena_allocator(&c->arena); + c->tmp_allocator = gb_arena_allocator(&c->tmp_arena); + + c->global_scope = make_scope(universal_scope, c->allocator); + c->context.scope = c->global_scope; +} + +void destroy_checker(Checker *c) { + destroy_checker_info(&c->info); + destroy_scope(c->global_scope); + array_free(&c->proc_stack); + array_free(&c->procs); + array_free(&c->delayed_imports); + array_free(&c->delayed_foreign_libraries); + + gb_arena_free(&c->arena); +} + + +TypeAndValue *type_and_value_of_expression(CheckerInfo *i, AstNode *expression) { + TypeAndValue *found = map_tav_get(&i->types, hash_pointer(expression)); + return found; +} + + +Entity *entity_of_ident(CheckerInfo *i, AstNode *identifier) { + if (identifier->kind == AstNode_Ident) { + Entity **found = map_entity_get(&i->definitions, hash_pointer(identifier)); + if (found) { + return *found; + } + found = map_entity_get(&i->uses, hash_pointer(identifier)); + if (found) { + return *found; + } + } + return NULL; +} + +Type *type_of_expr(CheckerInfo *i, AstNode *expression) { + TypeAndValue *found = type_and_value_of_expression(i, expression); + if (found) { + return found->type; + } + if (expression->kind == AstNode_Ident) { + Entity *entity = entity_of_ident(i, expression); + if (entity) { + return entity->type; + } + } + + return NULL; +} + + +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)); +} + +void add_type_and_value(CheckerInfo *i, AstNode *expression, AddressingMode mode, Type *type, ExactValue value) { + if (expression == NULL) { + return; + } + if (mode == Addressing_Invalid) { + return; + } + + if (mode == Addressing_Constant) { + if (is_type_constant_type(type)) { + // if (value.kind == ExactValue_Invalid) { + // TODO(bill): Is this correct? + // return; + // } + if (!(type != t_invalid || is_type_constant_type(type))) { + compiler_error("add_type_and_value - invalid type: %s", type_to_string(type)); + } + } + } + + TypeAndValue tv = {0}; + tv.type = type; + tv.value = value; + tv.mode = mode; + map_tav_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("_"))) { + return; + } + HashKey key = hash_pointer(identifier); + map_entity_set(&i->definitions, key, entity); + } else { + // NOTE(bill): Error should handled elsewhere + } +} + +bool add_entity(Checker *c, Scope *scope, AstNode *identifier, Entity *entity) { + if (str_ne(entity->token.string, str_lit("_"))) { + Entity *insert_entity = scope_insert_entity(scope, entity); + if (insert_entity) { + Entity *up = insert_entity->using_parent; + if (up != NULL) { + error(entity->token, + "Redeclararation of `%.*s` in this scope through `using`\n" + "\tat %.*s(%td:%td)", + LIT(entity->token.string), + LIT(up->token.pos.file), up->token.pos.line, up->token.pos.column); + return false; + } else { + TokenPos pos = insert_entity->token.pos; + if (token_pos_eq(pos, entity->token.pos)) { + // NOTE(bill): Error should have been handled already + return false; + } + error(entity->token, + "Redeclararation of `%.*s` in this scope\n" + "\tat %.*s(%td:%td)", + LIT(entity->token.string), + LIT(pos.file), pos.line, pos.column); + return false; + } + } + } + if (identifier != NULL) { + add_entity_definition(&c->info, identifier, entity); + } + return true; +} + +void add_entity_use(Checker *c, AstNode *identifier, Entity *entity) { + GB_ASSERT(identifier != NULL); + if (identifier->kind != AstNode_Ident) { + return; + } + map_entity_set(&c->info.uses, hash_pointer(identifier), entity); + add_declaration_dependency(c, entity); // TODO(bill): Should this be here? +} + + +void add_entity_and_decl_info(Checker *c, AstNode *identifier, Entity *e, DeclInfo *d) { + GB_ASSERT(identifier->kind == AstNode_Ident); + GB_ASSERT(str_eq(identifier->Ident.string, e->token.string)); + add_entity(c, e->scope, identifier, e); + map_decl_info_set(&c->info.entities, hash_pointer(e), d); +} + +// NOTE(bill): Returns true if it's added +bool try_add_foreign_library_path(Checker *c, String import_file) { + for_array(i, c->info.foreign_libraries) { + String import = c->info.foreign_libraries.e[i]; + if (str_eq(import, import_file)) { + return false; + } + } + array_add(&c->info.foreign_libraries, import_file); + return true; +} + + +void add_type_info_type(Checker *c, Type *t) { + if (t == NULL) { + return; + } + t = default_type(t); + if (is_type_untyped(t)) { + return; // Could be nil + } + + if (map_isize_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]; + Type *prev_type = cast(Type *)e->key.ptr; + if (are_types_identical(t, prev_type)) { + // Duplicate entry + ti_index = e->value; + break; + } + } + if (ti_index < 0) { + // Unique entry + // NOTE(bill): map entries grow linearly and in order + 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); + + + + + // Add nested types + + if (t->kind == Type_Named) { + // NOTE(bill): Just in case + add_type_info_type(c, t->Named.base); + return; + } + + Type *bt = base_type(t); + add_type_info_type(c, bt); + + switch (bt->kind) { + case Type_Basic: { + switch (bt->Basic.kind) { + case Basic_string: + add_type_info_type(c, t_u8_ptr); + add_type_info_type(c, t_int); + break; + case Basic_any: + add_type_info_type(c, t_type_info_ptr); + add_type_info_type(c, t_rawptr); + break; + } + } break; + + case Type_Maybe: + add_type_info_type(c, bt->Maybe.elem); + add_type_info_type(c, t_bool); + break; + + case Type_Pointer: + add_type_info_type(c, bt->Pointer.elem); + break; + + case Type_Array: + add_type_info_type(c, bt->Array.elem); + add_type_info_type(c, make_type_pointer(c->allocator, bt->Array.elem)); + add_type_info_type(c, t_int); + break; + case Type_Slice: + add_type_info_type(c, bt->Slice.elem); + add_type_info_type(c, make_type_pointer(c->allocator, bt->Slice.elem)); + add_type_info_type(c, t_int); + break; + case Type_Vector: + add_type_info_type(c, bt->Vector.elem); + add_type_info_type(c, t_int); + break; + + case Type_Record: { + switch (bt->Record.kind) { + case TypeRecord_Enum: + add_type_info_type(c, bt->Record.enum_base_type); + break; + case TypeRecord_Union: + add_type_info_type(c, t_int); + /* fallthrough */ + default: + for (isize i = 0; i < bt->Record.field_count; i++) { + Entity *f = bt->Record.fields[i]; + add_type_info_type(c, f->type); + } + break; + } + } break; + + case Type_Tuple: + for (isize i = 0; i < bt->Tuple.variable_count; i++) { + Entity *var = bt->Tuple.variables[i]; + add_type_info_type(c, var->type); + } + break; + + case Type_Proc: + add_type_info_type(c, bt->Proc.params); + add_type_info_type(c, bt->Proc.results); + break; + } +} + + +void check_procedure_later(Checker *c, AstFile *file, Token token, DeclInfo *decl, Type *type, AstNode *body, u32 tags) { + ProcedureInfo info = {0}; + info.file = file; + info.token = token; + info.decl = decl; + info.type = type; + info.body = body; + info.tags = tags; + array_add(&c->procs, info); +} + +void push_procedure(Checker *c, Type *type) { + array_add(&c->proc_stack, type); +} + +void pop_procedure(Checker *c) { + array_pop(&c->proc_stack); +} + +Type *const curr_procedure(Checker *c) { + isize count = c->proc_stack.count; + if (count > 0) { + return c->proc_stack.e[count-1]; + } + return NULL; +} + +void add_curr_ast_file(Checker *c, AstFile *file) { + if (file != NULL) { + TokenPos zero_pos = {0}; + global_error_collector.prev = zero_pos; + c->curr_ast_file = file; + c->context.decl = file->decl_info; + } +} + + + + +void add_dependency_to_map(MapEntity *map, CheckerInfo *info, Entity *node) { + if (node == NULL) { + return; + } + if (map_entity_get(map, hash_pointer(node)) != NULL) { + return; + } + map_entity_set(map, hash_pointer(node), node); + + + DeclInfo **found = map_decl_info_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; + 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()); + + for_array(i, info->definitions.entries) { + Entity *e = info->definitions.entries.e[i].value; + if (e->scope->is_global) { + // NOTE(bill): Require runtime stuff + add_dependency_to_map(&map, info, e); + } else if (e->kind == Entity_Procedure) { + if ((e->Procedure.tags & ProcTag_export) != 0) { + add_dependency_to_map(&map, info, e); + } + } + } + + add_dependency_to_map(&map, info, start); + + return map; +} + + +void add_implicit_value(Checker *c, ImplicitValueId id, String name, String backing_name, Type *type) { + ImplicitValueInfo info = {name, backing_name, type}; + Entity *value = make_entity_implicit_value(c->allocator, info.name, info.type, id); + Entity *prev = scope_insert_entity(c->global_scope, value); + GB_ASSERT(prev == NULL); + implicit_value_infos[id] = info; + c->info.implicit_values[id] = value; +} + + +void init_preload(Checker *c) { + if (c->done_preload) { + return; + } + + if (t_type_info == NULL) { + Entity *type_info_entity = current_scope_lookup_entity(c->global_scope, str_lit("Type_Info")); + if (type_info_entity == NULL) { + compiler_error("Could not find type declaration for `Type_Info`\n" + "Is `runtime.odin` missing from the `core` directory relative to odin.exe?"); + } + Entity *type_info_member_entity = current_scope_lookup_entity(c->global_scope, str_lit("Type_Info_Member")); + if (type_info_entity == NULL) { + compiler_error("Could not find type declaration for `Type_Info_Member`\n" + "Is `runtime.odin` missing from the `core` directory relative to odin.exe?"); + } + t_type_info = type_info_entity->type; + t_type_info_ptr = make_type_pointer(c->allocator, t_type_info); + GB_ASSERT(is_type_union(type_info_entity->type)); + TypeRecord *record = &base_type(type_info_entity->type)->Record; + + t_type_info_member = type_info_member_entity->type; + t_type_info_member_ptr = make_type_pointer(c->allocator, t_type_info_member); + + if (record->field_count != 18) { + compiler_error("Invalid `Type_Info` layout"); + } + t_type_info_named = record->fields[ 1]->type; + t_type_info_integer = record->fields[ 2]->type; + t_type_info_float = record->fields[ 3]->type; + t_type_info_any = record->fields[ 4]->type; + t_type_info_string = record->fields[ 5]->type; + t_type_info_boolean = record->fields[ 6]->type; + t_type_info_pointer = record->fields[ 7]->type; + t_type_info_maybe = record->fields[ 8]->type; + t_type_info_procedure = record->fields[ 9]->type; + t_type_info_array = record->fields[10]->type; + t_type_info_slice = record->fields[11]->type; + t_type_info_vector = record->fields[12]->type; + t_type_info_tuple = record->fields[13]->type; + t_type_info_struct = record->fields[14]->type; + t_type_info_union = record->fields[15]->type; + t_type_info_raw_union = record->fields[16]->type; + t_type_info_enum = record->fields[17]->type; + + t_type_info_named_ptr = make_type_pointer(heap_allocator(), t_type_info_named); + t_type_info_integer_ptr = make_type_pointer(heap_allocator(), t_type_info_integer); + t_type_info_float_ptr = make_type_pointer(heap_allocator(), t_type_info_float); + t_type_info_any_ptr = make_type_pointer(heap_allocator(), t_type_info_any); + t_type_info_string_ptr = make_type_pointer(heap_allocator(), t_type_info_string); + t_type_info_boolean_ptr = make_type_pointer(heap_allocator(), t_type_info_boolean); + t_type_info_pointer_ptr = make_type_pointer(heap_allocator(), t_type_info_pointer); + t_type_info_maybe_ptr = make_type_pointer(heap_allocator(), t_type_info_maybe); + t_type_info_procedure_ptr = make_type_pointer(heap_allocator(), t_type_info_procedure); + t_type_info_array_ptr = make_type_pointer(heap_allocator(), t_type_info_array); + t_type_info_slice_ptr = make_type_pointer(heap_allocator(), t_type_info_slice); + t_type_info_vector_ptr = make_type_pointer(heap_allocator(), t_type_info_vector); + t_type_info_tuple_ptr = make_type_pointer(heap_allocator(), t_type_info_tuple); + t_type_info_struct_ptr = make_type_pointer(heap_allocator(), t_type_info_struct); + t_type_info_union_ptr = make_type_pointer(heap_allocator(), t_type_info_union); + t_type_info_raw_union_ptr = make_type_pointer(heap_allocator(), t_type_info_raw_union); + t_type_info_enum_ptr = make_type_pointer(heap_allocator(), t_type_info_enum); + } + + if (t_allocator == NULL) { + Entity *e = current_scope_lookup_entity(c->global_scope, str_lit("Allocator")); + if (e == NULL) { + compiler_error("Could not find type declaration for `Allocator`\n" + "Is `runtime.odin` missing from the `core` directory relative to odin.exe?"); + } + t_allocator = e->type; + t_allocator_ptr = make_type_pointer(c->allocator, t_allocator); + } + + if (t_context == NULL) { + Entity *e = current_scope_lookup_entity(c->global_scope, str_lit("Context")); + if (e == NULL) { + compiler_error("Could not find type declaration for `Context`\n" + "Is `runtime.odin` missing from the `core` directory relative to odin.exe?"); + } + t_context = e->type; + t_context_ptr = make_type_pointer(c->allocator, t_context); + } + + c->done_preload = true; +} + +bool check_arity_match(Checker *c, AstNodeValueDecl *d); + +#include "check_expr.c" +#include "check_decl.c" +#include "check_stmt.c" + +bool check_arity_match(Checker *c, AstNodeValueDecl *d) { + isize lhs = d->names.count; + isize rhs = d->values.count; + + if (rhs == 0) { + if (d->type == NULL) { + error_node(d->names.e[0], "Missing type or initial expression"); + return false; + } + } else if (lhs < rhs) { + if (lhs < d->values.count) { + AstNode *n = d->values.e[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"); + } + return false; + } else if (lhs > rhs && rhs != 1) { + AstNode *n = d->names.e[rhs]; + gbString str = expr_to_string(n); + error_node(n, "Missing expression for `%s`", str); + gb_string_free(str); + return false; + } + + return true; +} + + + +void check_all_global_entities(Checker *c) { + Scope *prev_file = {0}; + + for_array(i, c->info.entities.entries) { + MapDeclInfoEntry *entry = &c->info.entities.entries.e[i]; + Entity *e = cast(Entity *)cast(uintptr)entry->key.key; + DeclInfo *d = entry->value; + + if (d->scope != e->scope) { + continue; + } + add_curr_ast_file(c, d->scope->file); + + if (e->kind != Entity_Procedure && str_eq(e->token.string, str_lit("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"))) { + error(e->token, "`main` is reserved as the entry point procedure in the initial scope"); + continue; + } + + Scope *prev_scope = c->context.scope; + c->context.scope = d->scope; + check_entity_decl(c, e, d, NULL); + + + if (d->scope->is_init && !c->done_preload) { + init_preload(c); + } + } +} + +void check_global_collect_entities_from_file(Checker *c, Scope *parent_scope, AstNodeArray nodes, MapScope *file_scopes) { + for_array(decl_index, nodes) { + AstNode *decl = nodes.e[decl_index]; + if (!is_ast_node_decl(decl) && !is_ast_node_when_stmt(decl)) { + continue; + } + + switch (decl->kind) { + case_ast_node(bd, BadDecl, decl); + case_end; + + case_ast_node(vd, ValueDecl, decl); + if (vd->is_var) { + // NOTE(bill): You need to store the entity information here unline a constant declaration + isize entity_count = vd->names.count; + isize entity_index = 0; + Entity **entities = gb_alloc_array(c->allocator, Entity *, entity_count); + DeclInfo *di = NULL; + if (vd->values.count > 0) { + di = make_declaration_info(heap_allocator(), parent_scope); + di->entities = entities; + di->entity_count = entity_count; + di->type_expr = vd->type; + di->init_expr = vd->values.e[0]; + } + + for_array(i, vd->names) { + AstNode *name = vd->names.e[i]; + AstNode *value = NULL; + if (i < vd->values.count) { + value = vd->values.e[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, parent_scope, name->Ident, NULL); + e->identifier = name; + entities[entity_index++] = e; + + DeclInfo *d = di; + if (d == NULL) { + AstNode *init_expr = value; + d = make_declaration_info(heap_allocator(), e->scope); + d->type_expr = vd->type; + d->init_expr = init_expr; + d->var_decl_tags = vd->tags; + } + + add_entity_and_decl_info(c, name, e, d); + } + + check_arity_match(c, vd); + } else { + for_array(i, vd->names) { + AstNode *name = vd->names.e[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; + } + + + AstNode *init = NULL; + if (i < vd->values.count) { + init = vd->values.e[i]; + } + + DeclInfo *d = make_declaration_info(c->allocator, parent_scope); + Entity *e = NULL; + + AstNode *up_init = unparen_expr(init); + if (init != NULL && is_ast_node_type(up_init)) { + e = make_entity_type_name(c->allocator, d->scope, name->Ident, NULL); + d->type_expr = init; + d->init_expr = init; + } else if (init != NULL && up_init->kind == AstNode_ProcLit) { + e = make_entity_procedure(c->allocator, d->scope, name->Ident, NULL, up_init->ProcLit.tags); + d->proc_lit = init; + } else { + e = make_entity_constant(c->allocator, d->scope, name->Ident, NULL, (ExactValue){0}); + d->type_expr = vd->type; + d->init_expr = init; + } + GB_ASSERT(e != NULL); + e->identifier = name; + + add_entity_and_decl_info(c, name, e, d); + } + + check_arity_match(c, vd); + } + case_end; + + case_ast_node(id, ImportDecl, decl); + if (!parent_scope->is_file) { + // NOTE(bill): _Should_ be caught by the parser + // TODO(bill): Better error handling if it isn't + continue; + } + DelayedDecl di = {parent_scope, decl}; + array_add(&c->delayed_imports, di); + case_end; + case_ast_node(fl, ForeignLibrary, decl); + if (!parent_scope->is_file) { + // NOTE(bill): _Should_ be caught by the parser + // TODO(bill): Better error handling if it isn't + continue; + } + + DelayedDecl di = {parent_scope, decl}; + array_add(&c->delayed_foreign_libraries, di); + case_end; + default: + if (parent_scope->is_file) { + error_node(decl, "Only declarations are allowed at file scope"); + } + break; + } + } +} + +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; + ast_node(id, ImportDecl, decl); + Token token = id->relpath; + + HashKey key = hash_string(id->fullpath); + Scope **found = map_scope_get(file_scopes, key); + if (found == NULL) { + for_array(scope_index, file_scopes->entries) { + Scope *scope = file_scopes->entries.e[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); + GB_PANIC("Unable to find scope for file: %.*s", LIT(id->fullpath)); + } + Scope *scope = *found; + + if (scope->is_global) { + error(token, "Importing a #shared_global_scope is disallowed and unnecessary"); + continue; + } + + if (id->cond != NULL) { + Operand operand = {Addressing_Invalid}; + check_expr(c, &operand, id->cond); + if (operand.mode != Addressing_Constant || !is_type_boolean(operand.type)) { + error_node(id->cond, "Non-constant boolean `when` condition"); + continue; + } + if (operand.value.kind == ExactValue_Bool && + !operand.value.value_bool) { + continue; + } + } + + bool previously_added = false; + for_array(import_index, parent_scope->imported) { + Scope *prev = parent_scope->imported.e[import_index]; + if (prev == scope) { + previously_added = true; + break; + } + } + + + if (!previously_added) { + array_add(&parent_scope->imported, scope); + } else { + warning(token, "Multiple #import of the same file within this scope"); + } + + if (str_eq(id->import_name.string, str_lit("."))) { + // 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; + if (e->scope == parent_scope) { + continue; + } + // NOTE(bill): Do not add other imported entities + add_entity(c, parent_scope, NULL, e); + if (id->is_import) { // `#import`ed entities don't get exported + HashKey key = hash_string(e->token.string); + map_entity_set(&parent_scope->implicit, key, e); + } + } + } else { + String import_name = id->import_name.string; + if (import_name.len == 0) { + // NOTE(bill): use file name (without extension) as the identifier + // If it is a valid identifier + String filename = id->fullpath; + isize slash = 0; + isize dot = 0; + for (isize i = filename.len-1; i >= 0; i--) { + u8 c = filename.text[i]; + if (c == '/' || c == '\\') { + break; + } + slash = i; + } + + filename.text += slash; + filename.len -= slash; + + dot = filename.len; + while (dot --> 0) { + u8 c = filename.text[dot]; + if (c == '.') { + break; + } + } + + filename.len = dot; + + if (is_string_an_identifier(filename)) { + import_name = filename; + } else { + error(token, "File name, %.*s, cannot be as an import name as it is not a valid identifier", LIT(filename)); + } + } + + if (import_name.len > 0) { + GB_ASSERT(id->import_name.pos.line != 0); + id->import_name.string = import_name; + Entity *e = make_entity_import_name(c->allocator, parent_scope, id->import_name, t_invalid, + id->fullpath, id->import_name.string, + scope); + add_entity(c, parent_scope, NULL, e); + } + } + } + + 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; + ast_node(fl, ForeignLibrary, decl); + + String file_str = fl->filepath.string; + String base_dir = fl->base_dir; + + if (!fl->is_system) { + gbAllocator a = heap_allocator(); // TODO(bill): Change this allocator + + String rel_path = get_fullpath_relative(a, base_dir, file_str); + String import_file = rel_path; + if (!gb_file_exists(cast(char *)rel_path.text)) { // NOTE(bill): This should be null terminated + String abs_path = get_fullpath_core(a, file_str); + if (gb_file_exists(cast(char *)abs_path.text)) { + import_file = abs_path; + } + } + file_str = import_file; + } + + try_add_foreign_library_path(c, file_str); + } +} + + +void check_parsed_files(Checker *c) { + MapScope file_scopes; // Key: String (fullpath) + map_scope_init(&file_scopes, heap_allocator()); + + // Map full filepaths to Scopes + for_array(i, c->parser->files) { + AstFile *f = &c->parser->files.e[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)) { + scope->is_init = true; + } + + if (scope->is_global) { + array_add(&c->global_scope->shared, scope); + } + + f->scope = scope; + f->decl_info = make_declaration_info(c->allocator, f->scope); + HashKey key = hash_string(f->tokenizer.fullpath); + map_scope_set(&file_scopes, key, scope); + map_ast_file_set(&c->info.files, key, f); + } + + // Collect Entities + for_array(i, c->parser->files) { + AstFile *f = &c->parser->files.e[i]; + add_curr_ast_file(c, f); + check_global_collect_entities_from_file(c, f->scope, f->decls, &file_scopes); + } + + check_import_entities(c, &file_scopes); + + + check_all_global_entities(c); + init_preload(c); // NOTE(bill): This could be setup previously through the use of `type_info(_of_val)` + // NOTE(bill): Nothing is the global scope _should_ depend on this implicit value as implicit + // values are only useful within procedures + add_implicit_value(c, ImplicitValue_context, str_lit("context"), str_lit("__context"), t_context); + + // Initialize implicit values with backing variables + // TODO(bill): Are implicit values "too implicit"? + for (isize i = 1; i < ImplicitValue_Count; i++) { + // NOTE(bill): 0th is invalid + Entity *e = c->info.implicit_values[i]; + GB_ASSERT(e->kind == Entity_ImplicitValue); + + ImplicitValueInfo *ivi = &implicit_value_infos[i]; + Entity *backing = scope_lookup_entity(e->scope, ivi->backing_name); + // GB_ASSERT(backing != NULL); + if (backing == NULL) { + gb_exit(1); + } + e->ImplicitValue.backing = backing; + } + + + // 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]; + add_curr_ast_file(c, pi->file); + + bool bounds_check = (pi->tags & ProcTag_bounds_check) != 0; + bool no_bounds_check = (pi->tags & ProcTag_no_bounds_check) != 0; + + CheckerContext prev_context = c->context; + + if (bounds_check) { + c->context.stmt_state_flags |= StmtStateFlag_bounds_check; + c->context.stmt_state_flags &= ~StmtStateFlag_no_bounds_check; + } else if (no_bounds_check) { + c->context.stmt_state_flags |= StmtStateFlag_no_bounds_check; + c->context.stmt_state_flags &= ~StmtStateFlag_bounds_check; + } + + check_proc_body(c, pi->token, pi->decl, pi->type, pi->body); + + c->context = prev_context; + } + + // Add untyped expression values + for_array(i, c->info.untyped.entries) { + MapExprInfoEntry *entry = &c->info.untyped.entries.e[i]; + HashKey key = entry->key; + AstNode *expr = cast(AstNode *)cast(uintptr)key.key; + ExprInfo *info = &entry->value; + if (info != NULL && expr != NULL) { + if (is_type_typed(info->type)) { + compiler_error("%s (type %s) is typed!", expr_to_string(expr), type_to_string(info->type)); + } + add_type_and_value(&c->info, expr, info->mode, info->type, info->value); + } + } + + // TODO(bill): Check for unused imports (and remove) or even warn/err + // TODO(bill): Any other checks? + + + // Add "Basic" type information + for (isize i = 0; i < gb_count_of(basic_types)-1; i++) { + Type *t = &basic_types[i]; + if (t->Basic.size > 0) { + add_type_info_type(c, t); + } + } + + for (isize i = 0; i < gb_count_of(basic_type_aliases)-1; i++) { + Type *t = &basic_type_aliases[i]; + if (t->Basic.size > 0) { + add_type_info_type(c, t); + } + } + + // NOTE(bill): Check for illegal cyclic type declarations + for_array(i, c->info.definitions.entries) { + Entity *e = c->info.definitions.entries.e[i].value; + if (e->kind == Entity_TypeName) { + // i64 size = type_size_of(c->sizes, c->allocator, e->type); + i64 align = type_align_of(c->sizes, c->allocator, e->type); + } + } + + for_array(i, file_scopes.entries) { + Scope *s = file_scopes.entries.e[i].value; + if (s->is_init) { + Entity *e = current_scope_lookup_entity(s, str_lit("main")); + if (e == NULL) { + Token token = {0}; + if (s->file->tokens.count > 0) { + token = s->file->tokens.e[0]; + } else { + token.pos.file = s->file->tokenizer.fullpath; + token.pos.line = 1; + token.pos.column = 1; + } + + error(token, "Undefined entry point procedure `main`"); + } + + break; + } + } + + map_scope_destroy(&file_scopes); + +} + + + diff --git a/src/checker/checker.c b/src/checker/checker.c deleted file mode 100644 index 436a89391..000000000 --- a/src/checker/checker.c +++ /dev/null @@ -1,1580 +0,0 @@ -#include "../exact_value.c" -#include "entity.c" -#include "types.c" - -#define MAP_TYPE Entity * -#define MAP_PROC map_entity_ -#define MAP_NAME MapEntity -#include "../map.c" - -typedef enum AddressingMode { - Addressing_Invalid, - Addressing_NoValue, - Addressing_Value, - Addressing_Variable, - Addressing_Constant, - Addressing_Type, - Addressing_Builtin, - Addressing_Count, -} AddressingMode; - -typedef struct Operand { - AddressingMode mode; - Type * type; - ExactValue value; - AstNode * expr; - BuiltinProcId builtin_id; -} Operand; - -typedef struct TypeAndValue { - AddressingMode mode; - Type * type; - ExactValue value; -} TypeAndValue; - -bool is_operand_value(Operand o) { - switch (o.mode) { - case Addressing_Value: - case Addressing_Variable: - case Addressing_Constant: - return true; - } - return false; -} - - - -typedef struct DeclInfo { - Scope *scope; - - Entity **entities; - isize entity_count; - - AstNode *type_expr; - AstNode *init_expr; - AstNode *proc_lit; // AstNode_ProcLit - u32 var_decl_tags; - - MapBool deps; // Key: Entity * -} DeclInfo; - -typedef 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}; - return ei; -} - -typedef struct ProcedureInfo { - AstFile * file; - Token token; - DeclInfo *decl; - Type * type; // Type_Procedure - AstNode * body; // AstNode_BlockStmt - u32 tags; -} ProcedureInfo; - -typedef struct Scope { - Scope * parent; - Scope * prev, *next; - Scope * first_child; - Scope * last_child; - MapEntity elements; // Key: String - MapEntity implicit; // Key: String - - Array(Scope *) shared; - Array(Scope *) imported; - bool is_proc; - bool is_global; - bool is_file; - bool is_init; - AstFile * file; -} Scope; -gb_global Scope *universal_scope = NULL; - -typedef enum ExprKind { - Expr_Expr, - Expr_Stmt, -} ExprKind; - -// Statements and Declarations -typedef enum StmtFlag { - Stmt_BreakAllowed = 1<<0, - Stmt_ContinueAllowed = 1<<1, - Stmt_FallthroughAllowed = 1<<2, - Stmt_GiveAllowed = 1<<3, -} StmtFlag; - -typedef enum BuiltinProcId { - BuiltinProc_Invalid, - - BuiltinProc_new, - BuiltinProc_new_slice, - - BuiltinProc_size_of, - BuiltinProc_size_of_val, - BuiltinProc_align_of, - BuiltinProc_align_of_val, - BuiltinProc_offset_of, - BuiltinProc_offset_of_val, - BuiltinProc_type_of_val, - - BuiltinProc_type_info, - BuiltinProc_type_info_of_val, - - BuiltinProc_compile_assert, - BuiltinProc_assert, - BuiltinProc_panic, - - BuiltinProc_copy, - // BuiltinProc_append, - - BuiltinProc_swizzle, - - // BuiltinProc_ptr_offset, - // BuiltinProc_ptr_sub, - BuiltinProc_slice_ptr, - - BuiltinProc_min, - BuiltinProc_max, - BuiltinProc_abs, - BuiltinProc_clamp, - - BuiltinProc_Count, -} BuiltinProcId; -typedef struct BuiltinProc { - String name; - isize arg_count; - bool variadic; - ExprKind kind; -} BuiltinProc; -gb_global BuiltinProc builtin_procs[BuiltinProc_Count] = { - {STR_LIT(""), 0, false, Expr_Stmt}, - - {STR_LIT("new"), 1, false, Expr_Expr}, - {STR_LIT("new_slice"), 2, false, Expr_Expr}, - - {STR_LIT("size_of"), 1, false, Expr_Expr}, - {STR_LIT("size_of_val"), 1, false, Expr_Expr}, - {STR_LIT("align_of"), 1, false, Expr_Expr}, - {STR_LIT("align_of_val"), 1, false, Expr_Expr}, - {STR_LIT("offset_of"), 2, false, Expr_Expr}, - {STR_LIT("offset_of_val"), 1, false, Expr_Expr}, - {STR_LIT("type_of_val"), 1, false, Expr_Expr}, - - {STR_LIT("type_info"), 1, false, Expr_Expr}, - {STR_LIT("type_info_of_val"), 1, false, Expr_Expr}, - - {STR_LIT("compile_assert"), 1, false, Expr_Stmt}, - {STR_LIT("assert"), 1, false, Expr_Stmt}, - {STR_LIT("panic"), 1, false, Expr_Stmt}, - - {STR_LIT("copy"), 2, false, Expr_Expr}, - // {STR_LIT("append"), 2, false, Expr_Expr}, - - {STR_LIT("swizzle"), 1, true, Expr_Expr}, - - // {STR_LIT("ptr_offset"), 2, false, Expr_Expr}, - // {STR_LIT("ptr_sub"), 2, false, Expr_Expr}, - {STR_LIT("slice_ptr"), 2, false, Expr_Expr}, - - {STR_LIT("min"), 2, false, Expr_Expr}, - {STR_LIT("max"), 2, false, Expr_Expr}, - {STR_LIT("abs"), 1, false, Expr_Expr}, - {STR_LIT("clamp"), 3, false, Expr_Expr}, -}; - -typedef enum ImplicitValueId { - ImplicitValue_Invalid, - - ImplicitValue_context, - - ImplicitValue_Count, -} ImplicitValueId; -typedef struct ImplicitValueInfo { - String name; - String backing_name; - Type * type; -} ImplicitValueInfo; -// NOTE(bill): This is initialized later -gb_global ImplicitValueInfo implicit_value_infos[ImplicitValue_Count] = {0}; - - - -typedef struct CheckerContext { - Scope * scope; - DeclInfo * decl; - u32 stmt_state_flags; - ExactValue iota; // Value of `iota` in a constant declaration; Invalid otherwise -} CheckerContext; - -#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 { - Scope * parent; - AstNode *decl; -} DelayedDecl; - - -// NOTE(bill): Symbol tables -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 - MapDeclInfo entities; // Key: Entity * - MapEntity foreign_procs; // Key: String - MapAstFile files; // Key: String (full path) - MapIsize type_info_map; // Key: Type * - isize type_info_count; - Entity * implicit_values[ImplicitValue_Count]; - Array(String) foreign_libraries; // For the linker -} CheckerInfo; - -typedef struct Checker { - Parser * parser; - CheckerInfo info; - - AstFile * curr_ast_file; - BaseTypeSizes sizes; - Scope * global_scope; - Array(ProcedureInfo) procs; // NOTE(bill): Procedures to check - Array(DelayedDecl) delayed_imports; - Array(DelayedDecl) delayed_foreign_libraries; - - - gbArena arena; - gbArena tmp_arena; - gbAllocator allocator; - gbAllocator tmp_allocator; - - CheckerContext context; - - Array(Type *) proc_stack; - bool in_defer; // TODO(bill): Actually handle correctly - bool done_preload; -} Checker; - - - - -void init_declaration_info(DeclInfo *d, Scope *scope) { - d->scope = scope; - map_bool_init(&d->deps, heap_allocator()); -} - -DeclInfo *make_declaration_info(gbAllocator a, Scope *scope) { - DeclInfo *d = gb_alloc_item(a, DeclInfo); - init_declaration_info(d, scope); - return d; -} - -void destroy_declaration_info(DeclInfo *d) { - map_bool_destroy(&d->deps); -} - -bool decl_info_has_init(DeclInfo *d) { - if (d->init_expr != NULL) { - return true; - } - if (d->proc_lit != NULL) { - switch (d->proc_lit->kind) { - case_ast_node(pd, ProcLit, d->proc_lit); - if (pd->body != NULL) { - return true; - } - case_end; - } - } - - return false; -} - - - - - -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_entity_init(&s->implicit, heap_allocator()); - array_init(&s->shared, heap_allocator()); - array_init(&s->imported, heap_allocator()); - - if (parent != NULL && parent != universal_scope) { - DLIST_APPEND(parent->first_child, parent->last_child, s); - } - return s; -} - -void destroy_scope(Scope *scope) { - for_array(i, scope->elements.entries) { - Entity *e =scope->elements.entries.e[i].value; - if (e->kind == Entity_Variable) { - if (!(e->flags & EntityFlag_Used)) { -#if 0 - warning(e->token, "Unused variable `%.*s`", LIT(e->token.string)); -#endif - } - } - } - - for (Scope *child = scope->first_child; child != NULL; child = child->next) { - destroy_scope(child); - } - - map_entity_destroy(&scope->elements); - map_entity_destroy(&scope->implicit); - array_free(&scope->shared); - array_free(&scope->imported); - - // NOTE(bill): No need to free scope as it "should" be allocated in an arena (except for the global 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); -} - - -void check_open_scope(Checker *c, AstNode *node) { - GB_ASSERT(node != NULL); - node = unparen_expr(node); - GB_ASSERT(node->kind == AstNode_Invalid || - is_ast_node_stmt(node) || - is_ast_node_type(node) || - node->kind == AstNode_BlockExpr || - node->kind == AstNode_IfExpr ); - Scope *scope = make_scope(c->context.scope, c->allocator); - add_scope(c, node, scope); - if (node->kind == AstNode_ProcType) { - scope->is_proc = true; - } - c->context.scope = scope; - c->context.stmt_state_flags |= StmtStateFlag_bounds_check; -} - -void check_close_scope(Checker *c) { - c->context.scope = c->context.scope->parent; -} - -void scope_lookup_parent_entity(Scope *scope, String name, Scope **scope_, Entity **entity_) { - bool gone_thru_proc = false; - 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); - if (found) { - Entity *e = *found; - if (gone_thru_proc) { - if (e->kind == Entity_Variable && - !e->scope->is_file && - !e->scope->is_global) { - continue; - } - } - - if (entity_) *entity_ = e; - if (scope_) *scope_ = s; - return; - } - - if (s->is_proc) { - gone_thru_proc = true; - } 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); - if (found) { - Entity *e = *found; - if (e->kind == Entity_Variable && - !e->scope->is_file && - !e->scope->is_global) { - continue; - } - - if (e->scope != shared) { - // Do not return imported entities even #include ones - continue; - } - - if (e->kind == Entity_ImportName && gone_thru_file) { - continue; - } - - if (entity_) *entity_ = e; - if (scope_) *scope_ = shared; - return; - } - } - } - - if (s->is_file) { - gone_thru_file = true; - } - } - - - if (entity_) *entity_ = NULL; - if (scope_) *scope_ = NULL; -} - -Entity *scope_lookup_entity(Scope *s, String name) { - Entity *entity = NULL; - scope_lookup_parent_entity(s, name, NULL, &entity); - return entity; -} - -Entity *current_scope_lookup_entity(Scope *s, String name) { - HashKey key = hash_string(name); - Entity **found = map_entity_get(&s->elements, key); - if (found) { - return *found; - } - for_array(i, s->shared) { - Entity **found = map_entity_get(&s->shared.e[i]->elements, key); - if (found) { - return *found; - } - } - return NULL; -} - - - -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); - if (found) { - return *found; - } - map_entity_set(&s->elements, key, entity); - if (entity->scope == NULL) { - entity->scope = s; - } - return NULL; -} - -void check_scope_usage(Checker *c, Scope *scope) { - // TODO(bill): Use this? -} - - -void add_dependency(DeclInfo *d, Entity *e) { - map_bool_set(&d->deps, hash_pointer(e), cast(bool)true); -} - -void add_declaration_dependency(Checker *c, Entity *e) { - if (e == NULL) { - return; - } - if (c->context.decl != NULL) { - DeclInfo **found = map_decl_info_get(&c->info.entities, hash_pointer(e)); - if (found) { - add_dependency(c->context.decl, e); - } - } -} - - -void add_global_entity(Entity *entity) { - String name = entity->token.string; - if (gb_memchr(name.text, ' ', name.len)) { - return; // NOTE(bill): `untyped thing` - } - if (scope_insert_entity(universal_scope, entity)) { - compiler_error("double declaration"); - } -} - -void add_global_constant(gbAllocator a, String name, Type *type, ExactValue value) { - Entity *entity = alloc_entity(a, Entity_Constant, NULL, make_token_ident(name), type); - entity->Constant.value = value; - add_global_entity(entity); -} - - -void add_global_string_constant(gbAllocator a, String name, String value) { - add_global_constant(a, name, t_untyped_string, make_exact_value_string(value)); - -} - - -void init_universal_scope(BuildContext *bc) { - // NOTE(bill): No need to free these - gbAllocator a = heap_allocator(); - universal_scope = make_scope(NULL, a); - -// Types - for (isize i = 0; i < gb_count_of(basic_types); i++) { - add_global_entity(make_entity_type_name(a, NULL, make_token_ident(basic_types[i].Basic.name), &basic_types[i])); - } - for (isize i = 0; i < gb_count_of(basic_type_aliases); i++) { - add_global_entity(make_entity_type_name(a, NULL, make_token_ident(basic_type_aliases[i].Basic.name), &basic_type_aliases[i])); - } - -// Constants - add_global_constant(a, str_lit("true"), t_untyped_bool, make_exact_value_bool(true)); - add_global_constant(a, str_lit("false"), t_untyped_bool, make_exact_value_bool(false)); - add_global_constant(a, str_lit("iota"), t_untyped_integer, make_exact_value_integer(0)); - - add_global_entity(make_entity_nil(a, str_lit("nil"), t_untyped_nil)); - - // TODO(bill): Set through flags in the compiler - add_global_string_constant(a, str_lit("ODIN_OS"), bc->ODIN_OS); - add_global_string_constant(a, str_lit("ODIN_ARCH"), bc->ODIN_ARCH); - add_global_string_constant(a, str_lit("ODIN_VENDOR"), bc->ODIN_VENDOR); - add_global_string_constant(a, str_lit("ODIN_VERSION"), bc->ODIN_VERSION); - add_global_string_constant(a, str_lit("ODIN_ROOT"), bc->ODIN_ROOT); - - -// Builtin Procedures - for (isize i = 0; i < gb_count_of(builtin_procs); i++) { - BuiltinProcId id = cast(BuiltinProcId)i; - Entity *entity = alloc_entity(a, Entity_Builtin, NULL, make_token_ident(builtin_procs[i].name), t_invalid); - entity->Builtin.id = id; - add_global_entity(entity); - } - - - t_u8_ptr = make_type_pointer(a, t_u8); - t_int_ptr = make_type_pointer(a, t_int); - e_iota = scope_lookup_entity(universal_scope, str_lit("iota")); -} - - - - -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->foreign_procs, a); - map_isize_init(&i->type_info_map, a); - map_ast_file_init(&i->files, a); - array_init(&i->foreign_libraries, 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->foreign_procs); - map_isize_destroy(&i->type_info_map); - map_ast_file_destroy(&i->files); - array_free(&i->foreign_libraries); -} - - -void init_checker(Checker *c, Parser *parser, BuildContext *bc) { - gbAllocator a = heap_allocator(); - - c->parser = parser; - init_checker_info(&c->info); - c->sizes.word_size = bc->word_size; - c->sizes.max_align = bc->max_align; - - array_init(&c->proc_stack, a); - array_init(&c->procs, a); - array_init(&c->delayed_imports, a); - array_init(&c->delayed_foreign_libraries, a); - - // NOTE(bill): Is this big enough or too small? - 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]; - total_token_count += f->tokens.count; - } - isize arena_size = 2 * item_size * total_token_count; - gb_arena_init_from_allocator(&c->arena, a, arena_size); - gb_arena_init_from_allocator(&c->tmp_arena, a, arena_size); - - - c->allocator = gb_arena_allocator(&c->arena); - c->tmp_allocator = gb_arena_allocator(&c->tmp_arena); - - c->global_scope = make_scope(universal_scope, c->allocator); - c->context.scope = c->global_scope; -} - -void destroy_checker(Checker *c) { - destroy_checker_info(&c->info); - destroy_scope(c->global_scope); - array_free(&c->proc_stack); - array_free(&c->procs); - array_free(&c->delayed_imports); - array_free(&c->delayed_foreign_libraries); - - gb_arena_free(&c->arena); -} - - -TypeAndValue *type_and_value_of_expression(CheckerInfo *i, AstNode *expression) { - TypeAndValue *found = map_tav_get(&i->types, hash_pointer(expression)); - return found; -} - - -Entity *entity_of_ident(CheckerInfo *i, AstNode *identifier) { - if (identifier->kind == AstNode_Ident) { - Entity **found = map_entity_get(&i->definitions, hash_pointer(identifier)); - if (found) { - return *found; - } - found = map_entity_get(&i->uses, hash_pointer(identifier)); - if (found) { - return *found; - } - } - return NULL; -} - -Type *type_of_expr(CheckerInfo *i, AstNode *expression) { - TypeAndValue *found = type_and_value_of_expression(i, expression); - if (found) { - return found->type; - } - if (expression->kind == AstNode_Ident) { - Entity *entity = entity_of_ident(i, expression); - if (entity) { - return entity->type; - } - } - - return NULL; -} - - -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)); -} - -void add_type_and_value(CheckerInfo *i, AstNode *expression, AddressingMode mode, Type *type, ExactValue value) { - if (expression == NULL) { - return; - } - if (mode == Addressing_Invalid) { - return; - } - - if (mode == Addressing_Constant) { - if (is_type_constant_type(type)) { - // if (value.kind == ExactValue_Invalid) { - // TODO(bill): Is this correct? - // return; - // } - if (!(type != t_invalid || is_type_constant_type(type))) { - compiler_error("add_type_and_value - invalid type: %s", type_to_string(type)); - } - } - } - - TypeAndValue tv = {0}; - tv.type = type; - tv.value = value; - tv.mode = mode; - map_tav_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("_"))) { - return; - } - HashKey key = hash_pointer(identifier); - map_entity_set(&i->definitions, key, entity); - } else { - // NOTE(bill): Error should handled elsewhere - } -} - -bool add_entity(Checker *c, Scope *scope, AstNode *identifier, Entity *entity) { - if (str_ne(entity->token.string, str_lit("_"))) { - Entity *insert_entity = scope_insert_entity(scope, entity); - if (insert_entity) { - Entity *up = insert_entity->using_parent; - if (up != NULL) { - error(entity->token, - "Redeclararation of `%.*s` in this scope through `using`\n" - "\tat %.*s(%td:%td)", - LIT(entity->token.string), - LIT(up->token.pos.file), up->token.pos.line, up->token.pos.column); - return false; - } else { - TokenPos pos = insert_entity->token.pos; - if (token_pos_eq(pos, entity->token.pos)) { - // NOTE(bill): Error should have been handled already - return false; - } - error(entity->token, - "Redeclararation of `%.*s` in this scope\n" - "\tat %.*s(%td:%td)", - LIT(entity->token.string), - LIT(pos.file), pos.line, pos.column); - return false; - } - } - } - if (identifier != NULL) { - add_entity_definition(&c->info, identifier, entity); - } - return true; -} - -void add_entity_use(Checker *c, AstNode *identifier, Entity *entity) { - GB_ASSERT(identifier != NULL); - if (identifier->kind != AstNode_Ident) { - return; - } - map_entity_set(&c->info.uses, hash_pointer(identifier), entity); - add_declaration_dependency(c, entity); // TODO(bill): Should this be here? -} - - -void add_entity_and_decl_info(Checker *c, AstNode *identifier, Entity *e, DeclInfo *d) { - GB_ASSERT(identifier->kind == AstNode_Ident); - GB_ASSERT(str_eq(identifier->Ident.string, e->token.string)); - add_entity(c, e->scope, identifier, e); - map_decl_info_set(&c->info.entities, hash_pointer(e), d); -} - -// NOTE(bill): Returns true if it's added -bool try_add_foreign_library_path(Checker *c, String import_file) { - for_array(i, c->info.foreign_libraries) { - String import = c->info.foreign_libraries.e[i]; - if (str_eq(import, import_file)) { - return false; - } - } - array_add(&c->info.foreign_libraries, import_file); - return true; -} - - -void add_type_info_type(Checker *c, Type *t) { - if (t == NULL) { - return; - } - t = default_type(t); - if (is_type_untyped(t)) { - return; // Could be nil - } - - if (map_isize_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]; - Type *prev_type = cast(Type *)e->key.ptr; - if (are_types_identical(t, prev_type)) { - // Duplicate entry - ti_index = e->value; - break; - } - } - if (ti_index < 0) { - // Unique entry - // NOTE(bill): map entries grow linearly and in order - 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); - - - - - // Add nested types - - if (t->kind == Type_Named) { - // NOTE(bill): Just in case - add_type_info_type(c, t->Named.base); - return; - } - - Type *bt = base_type(t); - add_type_info_type(c, bt); - - switch (bt->kind) { - case Type_Basic: { - switch (bt->Basic.kind) { - case Basic_string: - add_type_info_type(c, t_u8_ptr); - add_type_info_type(c, t_int); - break; - case Basic_any: - add_type_info_type(c, t_type_info_ptr); - add_type_info_type(c, t_rawptr); - break; - } - } break; - - case Type_Maybe: - add_type_info_type(c, bt->Maybe.elem); - add_type_info_type(c, t_bool); - break; - - case Type_Pointer: - add_type_info_type(c, bt->Pointer.elem); - break; - - case Type_Array: - add_type_info_type(c, bt->Array.elem); - add_type_info_type(c, make_type_pointer(c->allocator, bt->Array.elem)); - add_type_info_type(c, t_int); - break; - case Type_Slice: - add_type_info_type(c, bt->Slice.elem); - add_type_info_type(c, make_type_pointer(c->allocator, bt->Slice.elem)); - add_type_info_type(c, t_int); - break; - case Type_Vector: - add_type_info_type(c, bt->Vector.elem); - add_type_info_type(c, t_int); - break; - - case Type_Record: { - switch (bt->Record.kind) { - case TypeRecord_Enum: - add_type_info_type(c, bt->Record.enum_base_type); - break; - case TypeRecord_Union: - add_type_info_type(c, t_int); - /* fallthrough */ - default: - for (isize i = 0; i < bt->Record.field_count; i++) { - Entity *f = bt->Record.fields[i]; - add_type_info_type(c, f->type); - } - break; - } - } break; - - case Type_Tuple: - for (isize i = 0; i < bt->Tuple.variable_count; i++) { - Entity *var = bt->Tuple.variables[i]; - add_type_info_type(c, var->type); - } - break; - - case Type_Proc: - add_type_info_type(c, bt->Proc.params); - add_type_info_type(c, bt->Proc.results); - break; - } -} - - -void check_procedure_later(Checker *c, AstFile *file, Token token, DeclInfo *decl, Type *type, AstNode *body, u32 tags) { - ProcedureInfo info = {0}; - info.file = file; - info.token = token; - info.decl = decl; - info.type = type; - info.body = body; - info.tags = tags; - array_add(&c->procs, info); -} - -void push_procedure(Checker *c, Type *type) { - array_add(&c->proc_stack, type); -} - -void pop_procedure(Checker *c) { - array_pop(&c->proc_stack); -} - -Type *const curr_procedure(Checker *c) { - isize count = c->proc_stack.count; - if (count > 0) { - return c->proc_stack.e[count-1]; - } - return NULL; -} - -void add_curr_ast_file(Checker *c, AstFile *file) { - if (file != NULL) { - TokenPos zero_pos = {0}; - global_error_collector.prev = zero_pos; - c->curr_ast_file = file; - c->context.decl = file->decl_info; - } -} - - - - -void add_dependency_to_map(MapEntity *map, CheckerInfo *info, Entity *node) { - if (node == NULL) { - return; - } - if (map_entity_get(map, hash_pointer(node)) != NULL) { - return; - } - map_entity_set(map, hash_pointer(node), node); - - - DeclInfo **found = map_decl_info_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; - 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()); - - for_array(i, info->definitions.entries) { - Entity *e = info->definitions.entries.e[i].value; - if (e->scope->is_global) { - // NOTE(bill): Require runtime stuff - add_dependency_to_map(&map, info, e); - } else if (e->kind == Entity_Procedure) { - if ((e->Procedure.tags & ProcTag_export) != 0) { - add_dependency_to_map(&map, info, e); - } - } - } - - add_dependency_to_map(&map, info, start); - - return map; -} - - -void add_implicit_value(Checker *c, ImplicitValueId id, String name, String backing_name, Type *type) { - ImplicitValueInfo info = {name, backing_name, type}; - Entity *value = make_entity_implicit_value(c->allocator, info.name, info.type, id); - Entity *prev = scope_insert_entity(c->global_scope, value); - GB_ASSERT(prev == NULL); - implicit_value_infos[id] = info; - c->info.implicit_values[id] = value; -} - - -void init_preload(Checker *c) { - if (c->done_preload) { - return; - } - - if (t_type_info == NULL) { - Entity *type_info_entity = current_scope_lookup_entity(c->global_scope, str_lit("Type_Info")); - if (type_info_entity == NULL) { - compiler_error("Could not find type declaration for `Type_Info`\n" - "Is `runtime.odin` missing from the `core` directory relative to odin.exe?"); - } - Entity *type_info_member_entity = current_scope_lookup_entity(c->global_scope, str_lit("Type_Info_Member")); - if (type_info_entity == NULL) { - compiler_error("Could not find type declaration for `Type_Info_Member`\n" - "Is `runtime.odin` missing from the `core` directory relative to odin.exe?"); - } - t_type_info = type_info_entity->type; - t_type_info_ptr = make_type_pointer(c->allocator, t_type_info); - GB_ASSERT(is_type_union(type_info_entity->type)); - TypeRecord *record = &base_type(type_info_entity->type)->Record; - - t_type_info_member = type_info_member_entity->type; - t_type_info_member_ptr = make_type_pointer(c->allocator, t_type_info_member); - - if (record->field_count != 18) { - compiler_error("Invalid `Type_Info` layout"); - } - t_type_info_named = record->fields[ 1]->type; - t_type_info_integer = record->fields[ 2]->type; - t_type_info_float = record->fields[ 3]->type; - t_type_info_any = record->fields[ 4]->type; - t_type_info_string = record->fields[ 5]->type; - t_type_info_boolean = record->fields[ 6]->type; - t_type_info_pointer = record->fields[ 7]->type; - t_type_info_maybe = record->fields[ 8]->type; - t_type_info_procedure = record->fields[ 9]->type; - t_type_info_array = record->fields[10]->type; - t_type_info_slice = record->fields[11]->type; - t_type_info_vector = record->fields[12]->type; - t_type_info_tuple = record->fields[13]->type; - t_type_info_struct = record->fields[14]->type; - t_type_info_union = record->fields[15]->type; - t_type_info_raw_union = record->fields[16]->type; - t_type_info_enum = record->fields[17]->type; - - t_type_info_named_ptr = make_type_pointer(heap_allocator(), t_type_info_named); - t_type_info_integer_ptr = make_type_pointer(heap_allocator(), t_type_info_integer); - t_type_info_float_ptr = make_type_pointer(heap_allocator(), t_type_info_float); - t_type_info_any_ptr = make_type_pointer(heap_allocator(), t_type_info_any); - t_type_info_string_ptr = make_type_pointer(heap_allocator(), t_type_info_string); - t_type_info_boolean_ptr = make_type_pointer(heap_allocator(), t_type_info_boolean); - t_type_info_pointer_ptr = make_type_pointer(heap_allocator(), t_type_info_pointer); - t_type_info_maybe_ptr = make_type_pointer(heap_allocator(), t_type_info_maybe); - t_type_info_procedure_ptr = make_type_pointer(heap_allocator(), t_type_info_procedure); - t_type_info_array_ptr = make_type_pointer(heap_allocator(), t_type_info_array); - t_type_info_slice_ptr = make_type_pointer(heap_allocator(), t_type_info_slice); - t_type_info_vector_ptr = make_type_pointer(heap_allocator(), t_type_info_vector); - t_type_info_tuple_ptr = make_type_pointer(heap_allocator(), t_type_info_tuple); - t_type_info_struct_ptr = make_type_pointer(heap_allocator(), t_type_info_struct); - t_type_info_union_ptr = make_type_pointer(heap_allocator(), t_type_info_union); - t_type_info_raw_union_ptr = make_type_pointer(heap_allocator(), t_type_info_raw_union); - t_type_info_enum_ptr = make_type_pointer(heap_allocator(), t_type_info_enum); - } - - if (t_allocator == NULL) { - Entity *e = current_scope_lookup_entity(c->global_scope, str_lit("Allocator")); - if (e == NULL) { - compiler_error("Could not find type declaration for `Allocator`\n" - "Is `runtime.odin` missing from the `core` directory relative to odin.exe?"); - } - t_allocator = e->type; - t_allocator_ptr = make_type_pointer(c->allocator, t_allocator); - } - - if (t_context == NULL) { - Entity *e = current_scope_lookup_entity(c->global_scope, str_lit("Context")); - if (e == NULL) { - compiler_error("Could not find type declaration for `Context`\n" - "Is `runtime.odin` missing from the `core` directory relative to odin.exe?"); - } - t_context = e->type; - t_context_ptr = make_type_pointer(c->allocator, t_context); - } - - c->done_preload = true; -} - -bool check_arity_match(Checker *c, AstNodeValueDecl *d); - -#include "expr.c" -#include "decl.c" -#include "stmt.c" - -bool check_arity_match(Checker *c, AstNodeValueDecl *d) { - isize lhs = d->names.count; - isize rhs = d->values.count; - - if (rhs == 0) { - if (d->type == NULL) { - error_node(d->names.e[0], "Missing type or initial expression"); - return false; - } - } else if (lhs < rhs) { - if (lhs < d->values.count) { - AstNode *n = d->values.e[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"); - } - return false; - } else if (lhs > rhs && rhs != 1) { - AstNode *n = d->names.e[rhs]; - gbString str = expr_to_string(n); - error_node(n, "Missing expression for `%s`", str); - gb_string_free(str); - return false; - } - - return true; -} - - - -void check_all_global_entities(Checker *c) { - Scope *prev_file = {0}; - - for_array(i, c->info.entities.entries) { - MapDeclInfoEntry *entry = &c->info.entities.entries.e[i]; - Entity *e = cast(Entity *)cast(uintptr)entry->key.key; - DeclInfo *d = entry->value; - - if (d->scope != e->scope) { - continue; - } - add_curr_ast_file(c, d->scope->file); - - if (e->kind != Entity_Procedure && str_eq(e->token.string, str_lit("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"))) { - error(e->token, "`main` is reserved as the entry point procedure in the initial scope"); - continue; - } - - Scope *prev_scope = c->context.scope; - c->context.scope = d->scope; - check_entity_decl(c, e, d, NULL); - - - if (d->scope->is_init && !c->done_preload) { - init_preload(c); - } - } -} - -void check_global_collect_entities_from_file(Checker *c, Scope *parent_scope, AstNodeArray nodes, MapScope *file_scopes) { - for_array(decl_index, nodes) { - AstNode *decl = nodes.e[decl_index]; - if (!is_ast_node_decl(decl) && !is_ast_node_when_stmt(decl)) { - continue; - } - - switch (decl->kind) { - case_ast_node(bd, BadDecl, decl); - case_end; - - case_ast_node(vd, ValueDecl, decl); - if (vd->is_var) { - // NOTE(bill): You need to store the entity information here unline a constant declaration - isize entity_count = vd->names.count; - isize entity_index = 0; - Entity **entities = gb_alloc_array(c->allocator, Entity *, entity_count); - DeclInfo *di = NULL; - if (vd->values.count > 0) { - di = make_declaration_info(heap_allocator(), parent_scope); - di->entities = entities; - di->entity_count = entity_count; - di->type_expr = vd->type; - di->init_expr = vd->values.e[0]; - } - - for_array(i, vd->names) { - AstNode *name = vd->names.e[i]; - AstNode *value = NULL; - if (i < vd->values.count) { - value = vd->values.e[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, parent_scope, name->Ident, NULL); - e->identifier = name; - entities[entity_index++] = e; - - DeclInfo *d = di; - if (d == NULL) { - AstNode *init_expr = value; - d = make_declaration_info(heap_allocator(), e->scope); - d->type_expr = vd->type; - d->init_expr = init_expr; - d->var_decl_tags = vd->tags; - } - - add_entity_and_decl_info(c, name, e, d); - } - - check_arity_match(c, vd); - } else { - for_array(i, vd->names) { - AstNode *name = vd->names.e[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; - } - - - AstNode *init = NULL; - if (i < vd->values.count) { - init = vd->values.e[i]; - } - - DeclInfo *d = make_declaration_info(c->allocator, parent_scope); - Entity *e = NULL; - - AstNode *up_init = unparen_expr(init); - if (init != NULL && is_ast_node_type(up_init)) { - e = make_entity_type_name(c->allocator, d->scope, name->Ident, NULL); - d->type_expr = init; - d->init_expr = init; - } else if (init != NULL && up_init->kind == AstNode_ProcLit) { - e = make_entity_procedure(c->allocator, d->scope, name->Ident, NULL, up_init->ProcLit.tags); - d->proc_lit = init; - } else { - e = make_entity_constant(c->allocator, d->scope, name->Ident, NULL, (ExactValue){0}); - d->type_expr = vd->type; - d->init_expr = init; - } - GB_ASSERT(e != NULL); - e->identifier = name; - - add_entity_and_decl_info(c, name, e, d); - } - - check_arity_match(c, vd); - } - case_end; - - case_ast_node(id, ImportDecl, decl); - if (!parent_scope->is_file) { - // NOTE(bill): _Should_ be caught by the parser - // TODO(bill): Better error handling if it isn't - continue; - } - DelayedDecl di = {parent_scope, decl}; - array_add(&c->delayed_imports, di); - case_end; - case_ast_node(fl, ForeignLibrary, decl); - if (!parent_scope->is_file) { - // NOTE(bill): _Should_ be caught by the parser - // TODO(bill): Better error handling if it isn't - continue; - } - - DelayedDecl di = {parent_scope, decl}; - array_add(&c->delayed_foreign_libraries, di); - case_end; - default: - if (parent_scope->is_file) { - error_node(decl, "Only declarations are allowed at file scope"); - } - break; - } - } -} - -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; - ast_node(id, ImportDecl, decl); - Token token = id->relpath; - - HashKey key = hash_string(id->fullpath); - Scope **found = map_scope_get(file_scopes, key); - if (found == NULL) { - for_array(scope_index, file_scopes->entries) { - Scope *scope = file_scopes->entries.e[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); - GB_PANIC("Unable to find scope for file: %.*s", LIT(id->fullpath)); - } - Scope *scope = *found; - - if (scope->is_global) { - error(token, "Importing a #shared_global_scope is disallowed and unnecessary"); - continue; - } - - if (id->cond != NULL) { - Operand operand = {Addressing_Invalid}; - check_expr(c, &operand, id->cond); - if (operand.mode != Addressing_Constant || !is_type_boolean(operand.type)) { - error_node(id->cond, "Non-constant boolean `when` condition"); - continue; - } - if (operand.value.kind == ExactValue_Bool && - !operand.value.value_bool) { - continue; - } - } - - bool previously_added = false; - for_array(import_index, parent_scope->imported) { - Scope *prev = parent_scope->imported.e[import_index]; - if (prev == scope) { - previously_added = true; - break; - } - } - - - if (!previously_added) { - array_add(&parent_scope->imported, scope); - } else { - warning(token, "Multiple #import of the same file within this scope"); - } - - if (str_eq(id->import_name.string, str_lit("."))) { - // 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; - if (e->scope == parent_scope) { - continue; - } - // NOTE(bill): Do not add other imported entities - add_entity(c, parent_scope, NULL, e); - if (id->is_import) { // `#import`ed entities don't get exported - HashKey key = hash_string(e->token.string); - map_entity_set(&parent_scope->implicit, key, e); - } - } - } else { - String import_name = id->import_name.string; - if (import_name.len == 0) { - // NOTE(bill): use file name (without extension) as the identifier - // If it is a valid identifier - String filename = id->fullpath; - isize slash = 0; - isize dot = 0; - for (isize i = filename.len-1; i >= 0; i--) { - u8 c = filename.text[i]; - if (c == '/' || c == '\\') { - break; - } - slash = i; - } - - filename.text += slash; - filename.len -= slash; - - dot = filename.len; - while (dot --> 0) { - u8 c = filename.text[dot]; - if (c == '.') { - break; - } - } - - filename.len = dot; - - if (is_string_an_identifier(filename)) { - import_name = filename; - } else { - error(token, "File name, %.*s, cannot be as an import name as it is not a valid identifier", LIT(filename)); - } - } - - if (import_name.len > 0) { - GB_ASSERT(id->import_name.pos.line != 0); - id->import_name.string = import_name; - Entity *e = make_entity_import_name(c->allocator, parent_scope, id->import_name, t_invalid, - id->fullpath, id->import_name.string, - scope); - add_entity(c, parent_scope, NULL, e); - } - } - } - - 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; - ast_node(fl, ForeignLibrary, decl); - - String file_str = fl->filepath.string; - String base_dir = fl->base_dir; - - if (!fl->is_system) { - gbAllocator a = heap_allocator(); // TODO(bill): Change this allocator - - String rel_path = get_fullpath_relative(a, base_dir, file_str); - String import_file = rel_path; - if (!gb_file_exists(cast(char *)rel_path.text)) { // NOTE(bill): This should be null terminated - String abs_path = get_fullpath_core(a, file_str); - if (gb_file_exists(cast(char *)abs_path.text)) { - import_file = abs_path; - } - } - file_str = import_file; - } - - try_add_foreign_library_path(c, file_str); - } -} - - -void check_parsed_files(Checker *c) { - MapScope file_scopes; // Key: String (fullpath) - map_scope_init(&file_scopes, heap_allocator()); - - // Map full filepaths to Scopes - for_array(i, c->parser->files) { - AstFile *f = &c->parser->files.e[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)) { - scope->is_init = true; - } - - if (scope->is_global) { - array_add(&c->global_scope->shared, scope); - } - - f->scope = scope; - f->decl_info = make_declaration_info(c->allocator, f->scope); - HashKey key = hash_string(f->tokenizer.fullpath); - map_scope_set(&file_scopes, key, scope); - map_ast_file_set(&c->info.files, key, f); - } - - // Collect Entities - for_array(i, c->parser->files) { - AstFile *f = &c->parser->files.e[i]; - add_curr_ast_file(c, f); - check_global_collect_entities_from_file(c, f->scope, f->decls, &file_scopes); - } - - check_import_entities(c, &file_scopes); - - - check_all_global_entities(c); - init_preload(c); // NOTE(bill): This could be setup previously through the use of `type_info(_of_val)` - // NOTE(bill): Nothing is the global scope _should_ depend on this implicit value as implicit - // values are only useful within procedures - add_implicit_value(c, ImplicitValue_context, str_lit("context"), str_lit("__context"), t_context); - - // Initialize implicit values with backing variables - // TODO(bill): Are implicit values "too implicit"? - for (isize i = 1; i < ImplicitValue_Count; i++) { - // NOTE(bill): 0th is invalid - Entity *e = c->info.implicit_values[i]; - GB_ASSERT(e->kind == Entity_ImplicitValue); - - ImplicitValueInfo *ivi = &implicit_value_infos[i]; - Entity *backing = scope_lookup_entity(e->scope, ivi->backing_name); - // GB_ASSERT(backing != NULL); - if (backing == NULL) { - gb_exit(1); - } - e->ImplicitValue.backing = backing; - } - - - // 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]; - add_curr_ast_file(c, pi->file); - - bool bounds_check = (pi->tags & ProcTag_bounds_check) != 0; - bool no_bounds_check = (pi->tags & ProcTag_no_bounds_check) != 0; - - CheckerContext prev_context = c->context; - - if (bounds_check) { - c->context.stmt_state_flags |= StmtStateFlag_bounds_check; - c->context.stmt_state_flags &= ~StmtStateFlag_no_bounds_check; - } else if (no_bounds_check) { - c->context.stmt_state_flags |= StmtStateFlag_no_bounds_check; - c->context.stmt_state_flags &= ~StmtStateFlag_bounds_check; - } - - check_proc_body(c, pi->token, pi->decl, pi->type, pi->body); - - c->context = prev_context; - } - - // Add untyped expression values - for_array(i, c->info.untyped.entries) { - MapExprInfoEntry *entry = &c->info.untyped.entries.e[i]; - HashKey key = entry->key; - AstNode *expr = cast(AstNode *)cast(uintptr)key.key; - ExprInfo *info = &entry->value; - if (info != NULL && expr != NULL) { - if (is_type_typed(info->type)) { - compiler_error("%s (type %s) is typed!", expr_to_string(expr), type_to_string(info->type)); - } - add_type_and_value(&c->info, expr, info->mode, info->type, info->value); - } - } - - // TODO(bill): Check for unused imports (and remove) or even warn/err - // TODO(bill): Any other checks? - - - // Add "Basic" type information - for (isize i = 0; i < gb_count_of(basic_types)-1; i++) { - Type *t = &basic_types[i]; - if (t->Basic.size > 0) { - add_type_info_type(c, t); - } - } - - for (isize i = 0; i < gb_count_of(basic_type_aliases)-1; i++) { - Type *t = &basic_type_aliases[i]; - if (t->Basic.size > 0) { - add_type_info_type(c, t); - } - } - - // NOTE(bill): Check for illegal cyclic type declarations - for_array(i, c->info.definitions.entries) { - Entity *e = c->info.definitions.entries.e[i].value; - if (e->kind == Entity_TypeName) { - // i64 size = type_size_of(c->sizes, c->allocator, e->type); - i64 align = type_align_of(c->sizes, c->allocator, e->type); - } - } - - for_array(i, file_scopes.entries) { - Scope *s = file_scopes.entries.e[i].value; - if (s->is_init) { - Entity *e = current_scope_lookup_entity(s, str_lit("main")); - if (e == NULL) { - Token token = {0}; - if (s->file->tokens.count > 0) { - token = s->file->tokens.e[0]; - } else { - token.pos.file = s->file->tokenizer.fullpath; - token.pos.line = 1; - token.pos.column = 1; - } - - error(token, "Undefined entry point procedure `main`"); - } - - break; - } - } - - map_scope_destroy(&file_scopes); - -} - - - diff --git a/src/checker/decl.c b/src/checker/decl.c deleted file mode 100644 index 9f683cf29..000000000 --- a/src/checker/decl.c +++ /dev/null @@ -1,594 +0,0 @@ -bool check_is_terminating(AstNode *node); -void check_stmt (Checker *c, AstNode *node, u32 flags); -void check_stmt_list (Checker *c, AstNodeArray stmts, u32 flags); - -// NOTE(bill): `content_name` is for debugging and error messages -Type *check_init_variable(Checker *c, Entity *e, Operand *operand, String context_name) { - if (operand->mode == Addressing_Invalid || - operand->type == t_invalid || - e->type == t_invalid) { - - if (operand->mode == Addressing_Builtin) { - gbString expr_str = expr_to_string(operand->expr); - - // TODO(bill): is this a good enough error message? - error_node(operand->expr, - "Cannot assign builtin procedure `%s` in %.*s", - expr_str, - LIT(context_name)); - - operand->mode = Addressing_Invalid; - - gb_string_free(expr_str); - } - - - if (e->type == NULL) { - e->type = t_invalid; - } - return NULL; - } - - if (e->type == NULL) { - // NOTE(bill): Use the type of the operand - Type *t = operand->type; - if (is_type_untyped(t)) { - if (t == t_invalid || is_type_untyped_nil(t)) { - error(e->token, "Use of untyped nil in %.*s", LIT(context_name)); - e->type = t_invalid; - return NULL; - } - t = default_type(t); - } - e->type = t; - } - - check_assignment(c, operand, e->type, context_name); - if (operand->mode == Addressing_Invalid) { - return NULL; - } - - return e->type; -} - -void check_init_variables(Checker *c, Entity **lhs, isize lhs_count, AstNodeArray inits, String context_name) { - if ((lhs == NULL || lhs_count == 0) && inits.count == 0) { - return; - } - - gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&c->tmp_arena); - - // NOTE(bill): If there is a bad syntax error, rhs > lhs which would mean there would need to be - // an extra allocation - Array(Operand) operands; - array_init_reserve(&operands, c->tmp_allocator, 2*lhs_count); - - for_array(i, inits) { - AstNode *rhs = inits.e[i]; - Operand o = {0}; - check_multi_expr(c, &o, rhs); - if (o.type->kind != Type_Tuple) { - array_add(&operands, o); - } else { - TypeTuple *tuple = &o.type->Tuple; - for (isize j = 0; j < tuple->variable_count; j++) { - o.type = tuple->variables[j]->type; - array_add(&operands, o); - } - } - } - - isize rhs_count = operands.count; - for_array(i, operands) { - if (operands.e[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); - } - - if (rhs_count > 0 && lhs_count != rhs_count) { - error(lhs[0]->token, "Assignment count mismatch `%td` = `%td`", lhs_count, rhs_count); - } - -#if 0 - if (lhs[0]->kind == Entity_Variable && - lhs[0]->Variable.is_let) { - if (lhs_count != rhs_count) { - error(lhs[0]->token, "`let` variables must be initialized, `%td` = `%td`", lhs_count, rhs_count); - } - } -#endif - - gb_temp_arena_memory_end(tmp); -} - -void check_var_decl_node(Checker *c, AstNodeValueDecl *vd) { - GB_ASSERT(vd->is_var == true); - isize entity_count = vd->names.count; - isize entity_index = 0; - Entity **entities = gb_alloc_array(c->allocator, Entity *, entity_count); - - for_array(i, vd->names) { - AstNode *name = vd->names.e[i]; - Entity *entity = NULL; - if (name->kind == AstNode_Ident) { - Token token = name->Ident; - String str = token.string; - Entity *found = NULL; - // NOTE(bill): Ignore assignments to `_` - if (str_ne(str, str_lit("_"))) { - found = current_scope_lookup_entity(c->context.scope, str); - } - if (found == NULL) { - entity = make_entity_variable(c->allocator, c->context.scope, token, NULL); - add_entity_definition(&c->info, name, entity); - } else { - TokenPos pos = found->token.pos; - error(token, - "Redeclaration of `%.*s` in this scope\n" - "\tat %.*s(%td:%td)", - LIT(str), LIT(pos.file), pos.line, pos.column); - entity = found; - } - } else { - error_node(name, "A variable declaration must be an identifier"); - } - if (entity == NULL) { - entity = make_entity_dummy_variable(c->allocator, c->global_scope, ast_node_token(name)); - } - entities[entity_index++] = entity; - } - - Type *init_type = NULL; - if (vd->type) { - init_type = check_type_extra(c, vd->type, NULL); - if (init_type == NULL) { - init_type = t_invalid; - } - } - - for (isize i = 0; i < entity_count; i++) { - Entity *e = entities[i]; - GB_ASSERT(e != NULL); - if (e->flags & EntityFlag_Visited) { - e->type = t_invalid; - continue; - } - e->flags |= EntityFlag_Visited; - - if (e->type == NULL) { - e->type = init_type; - } - } - - check_arity_match(c, vd); - check_init_variables(c, entities, entity_count, vd->values, str_lit("variable declaration")); - - for_array(i, vd->names) { - if (entities[i] != NULL) { - add_entity(c, c->context.scope, vd->names.e[i], entities[i]); - } - } - -} - - - -void check_init_constant(Checker *c, Entity *e, Operand *operand) { - if (operand->mode == Addressing_Invalid || - operand->type == t_invalid || - e->type == t_invalid) { - if (e->type == NULL) { - e->type = t_invalid; - } - return; - } - - if (operand->mode != Addressing_Constant) { - // TODO(bill): better error - gbString str = expr_to_string(operand->expr); - error_node(operand->expr, "`%s` is not a constant", str); - gb_string_free(str); - if (e->type == NULL) { - e->type = t_invalid; - } - return; - } - if (!is_type_constant_type(operand->type)) { - gbString type_str = type_to_string(operand->type); - error_node(operand->expr, "Invalid constant type: `%s`", type_str); - gb_string_free(type_str); - if (e->type == NULL) { - e->type = t_invalid; - } - return; - } - - if (e->type == NULL) { // NOTE(bill): type inference - e->type = operand->type; - } - - check_assignment(c, operand, e->type, str_lit("constant declaration")); - if (operand->mode == Addressing_Invalid) { - return; - } - - e->Constant.value = operand->value; -} - -void check_type_decl(Checker *c, Entity *e, AstNode *type_expr, Type *def) { - GB_ASSERT(e->type == NULL); - Type *named = make_type_named(c->allocator, e->token.string, NULL, e); - named->Named.type_name = e; - if (def != NULL && def->kind == Type_Named) { - def->Named.base = named; - } - e->type = named; - - // gb_printf_err("%.*s %p\n", LIT(e->token.string), e); - - Type *bt = check_type_extra(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)); - } -} - -void check_const_decl(Checker *c, Entity *e, AstNode *type_expr, AstNode *init, Type *named_type) { - GB_ASSERT(e->type == NULL); - GB_ASSERT(e->kind == Entity_Constant); - - if (e->flags & EntityFlag_Visited) { - e->type = t_invalid; - return; - } - e->flags |= EntityFlag_Visited; - - c->context.iota = e->Constant.value; - e->Constant.value = (ExactValue){0}; - - if (type_expr) { - Type *t = check_type(c, type_expr); - if (!is_type_constant_type(t)) { - gbString str = type_to_string(t); - error_node(type_expr, "Invalid constant type `%s`", str); - gb_string_free(str); - e->type = t_invalid; - c->context.iota = (ExactValue){0}; - return; - } - e->type = t; - } - - Operand operand = {0}; - if (init != NULL) { - check_expr_or_type(c, &operand, init); - } - if (operand.mode == Addressing_Type) { - c->context.iota = (ExactValue){0}; - - e->Constant.value = (ExactValue){0}; - e->kind = Entity_TypeName; - - DeclInfo *d = c->context.decl; - d->type_expr = d->init_expr; - check_type_decl(c, e, d->type_expr, named_type); - return; - } - - check_init_constant(c, e, &operand); - c->context.iota = (ExactValue){0}; - - if (operand.mode == Addressing_Invalid) { - error(e->token, "Illegal cyclic declaration"); - } -} - - - -bool are_signatures_similar_enough(Type *a_, Type *b_) { - GB_ASSERT(a_->kind == Type_Proc); - GB_ASSERT(b_->kind == Type_Proc); - TypeProc *a = &a_->Proc; - TypeProc *b = &b_->Proc; - - if (a->param_count != b->param_count) { - return false; - } - if (a->result_count != b->result_count) { - return false; - } - for (isize i = 0; i < a->param_count; i++) { - Type *x = base_type(a->params->Tuple.variables[i]->type); - Type *y = base_type(b->params->Tuple.variables[i]->type); - if (is_type_pointer(x) && is_type_pointer(y)) { - continue; - } - - if (!are_types_identical(x, y)) { - return false; - } - } - for (isize i = 0; i < a->result_count; i++) { - Type *x = base_type(a->results->Tuple.variables[i]->type); - Type *y = base_type(b->results->Tuple.variables[i]->type); - if (is_type_pointer(x) && is_type_pointer(y)) { - continue; - } - - if (!are_types_identical(x, y)) { - return false; - } - } - - return true; -} - -void check_proc_lit(Checker *c, Entity *e, DeclInfo *d) { - GB_ASSERT(e->type == NULL); - if (d->proc_lit->kind != AstNode_ProcLit) { - // TOOD(bill): Better error message - error_node(d->proc_lit, "Expected a procedure to check"); - return; - } - - Type *proc_type = make_type_proc(c->allocator, e->scope, NULL, 0, NULL, 0, false, ProcCC_Odin); - e->type = proc_type; - ast_node(pd, ProcLit, d->proc_lit); - - check_open_scope(c, pd->type); - check_procedure_type(c, proc_type, pd->type); - - bool is_foreign = (pd->tags & ProcTag_foreign) != 0; - bool is_link_name = (pd->tags & ProcTag_link_name) != 0; - bool is_export = (pd->tags & ProcTag_export) != 0; - bool is_inline = (pd->tags & ProcTag_inline) != 0; - bool is_no_inline = (pd->tags & ProcTag_no_inline) != 0; - - if ((d->scope->is_file || d->scope->is_global) && - str_eq(e->token.string, str_lit("main"))) { - if (proc_type != NULL) { - TypeProc *pt = &proc_type->Proc; - if (pt->param_count != 0 || - pt->result_count != 0) { - gbString str = type_to_string(proc_type); - error(e->token, "Procedure type of `main` was expected to be `proc()`, got %s", str); - gb_string_free(str); - } - } - } - - if (is_inline && is_no_inline) { - error_node(pd->type, "You cannot apply both `inline` and `no_inline` to a procedure"); - } - - if (is_foreign && is_link_name) { - error_node(pd->type, "You cannot apply both `foreign` and `link_name` to a procedure"); - } else if (is_foreign && is_export) { - error_node(pd->type, "You cannot apply both `foreign` and `export` to a procedure"); - } - - - if (pd->body != NULL) { - if (is_foreign) { - error_node(pd->body, "A procedure tagged as `#foreign` cannot have a body"); - } - - if (proc_type->Proc.calling_convention != ProcCC_Odin) { - error_node(d->proc_lit, "An internal procedure may only have the Odin calling convention"); - proc_type->Proc.calling_convention = ProcCC_Odin; - } - - d->scope = c->context.scope; - - GB_ASSERT(pd->body->kind == AstNode_BlockStmt); - check_procedure_later(c, c->curr_ast_file, e->token, d, proc_type, pd->body, pd->tags); - } - - if (is_foreign) { - MapEntity *fp = &c->info.foreign_procs; - String name = e->token.string; - if (pd->foreign_name.len > 0) { - name = pd->foreign_name; - } - - e->Procedure.is_foreign = true; - e->Procedure.foreign_name = name; - - HashKey key = hash_string(name); - Entity **found = map_entity_get(fp, key); - if (found) { - Entity *f = *found; - TokenPos pos = f->token.pos; - Type *this_type = base_type(e->type); - Type *other_type = base_type(f->type); - if (!are_signatures_similar_enough(this_type, other_type)) { - error_node(d->proc_lit, - "Redeclaration of #foreign procedure `%.*s` with different type signatures\n" - "\tat %.*s(%td:%td)", - LIT(name), LIT(pos.file), pos.line, pos.column); - } - } else { - map_entity_set(fp, key, e); - } - } else { - String name = e->token.string; - if (is_link_name) { - name = pd->link_name; - } - - if (is_link_name || is_export) { - MapEntity *fp = &c->info.foreign_procs; - - e->Procedure.link_name = name; - - HashKey key = hash_string(name); - Entity **found = map_entity_get(fp, key); - if (found) { - Entity *f = *found; - TokenPos pos = f->token.pos; - // TODO(bill): Better error message? - error_node(d->proc_lit, - "Non unique linking name for procedure `%.*s`\n" - "\tother at %.*s(%td:%td)", - LIT(name), LIT(pos.file), pos.line, pos.column); - } else { - map_entity_set(fp, key, e); - } - } - } - - check_close_scope(c); -} - -void check_var_decl(Checker *c, Entity *e, Entity **entities, isize entity_count, AstNode *type_expr, AstNode *init_expr) { - GB_ASSERT(e->type == NULL); - GB_ASSERT(e->kind == Entity_Variable); - - if (e->flags & EntityFlag_Visited) { - e->type = t_invalid; - return; - } - e->flags |= EntityFlag_Visited; - - if (type_expr != NULL) { - e->type = check_type_extra(c, type_expr, NULL); - } - - if (init_expr == NULL) { - if (type_expr == NULL) { - e->type = t_invalid; - } - return; - } - - if (entities == NULL || entity_count == 1) { - GB_ASSERT(entities == NULL || entities[0] == e); - Operand operand = {0}; - check_expr(c, &operand, init_expr); - check_init_variable(c, e, &operand, str_lit("variable declaration")); - } - - if (type_expr != NULL) { - for (isize i = 0; i < entity_count; i++) { - entities[i]->type = e->type; - } - } - - AstNodeArray inits; - array_init_reserve(&inits, c->allocator, 1); - array_add(&inits, init_expr); - check_init_variables(c, entities, entity_count, inits, str_lit("variable declaration")); -} - - -void check_entity_decl(Checker *c, Entity *e, DeclInfo *d, Type *named_type) { - if (e->type != NULL) { - return; - } - - if (d == NULL) { - DeclInfo **found = map_decl_info_get(&c->info.entities, hash_pointer(e)); - if (found) { - d = *found; - } else { - // TODO(bill): Err here? - e->type = t_invalid; - set_base_type(named_type, t_invalid); - return; - // GB_PANIC("`%.*s` should been declared!", LIT(e->token.string)); - } - } - - CheckerContext prev = c->context; - c->context.scope = d->scope; - c->context.decl = d; - - switch (e->kind) { - case Entity_Variable: - check_var_decl(c, e, d->entities, d->entity_count, d->type_expr, d->init_expr); - break; - case Entity_Constant: - check_const_decl(c, e, d->type_expr, d->init_expr, named_type); - break; - case Entity_TypeName: - check_type_decl(c, e, d->type_expr, named_type); - break; - case Entity_Procedure: - check_proc_lit(c, e, d); - break; - } - - c->context = prev; -} - - - -void check_proc_body(Checker *c, Token token, DeclInfo *decl, Type *type, AstNode *body) { - GB_ASSERT(body->kind == AstNode_BlockStmt); - - CheckerContext old_context = c->context; - c->context.scope = decl->scope; - c->context.decl = decl; - - GB_ASSERT(type->kind == Type_Proc); - if (type->Proc.param_count > 0) { - TypeTuple *params = &type->Proc.params->Tuple; - for (isize i = 0; i < params->variable_count; i++) { - Entity *e = params->variables[i]; - GB_ASSERT(e->kind == Entity_Variable); - if (!(e->flags & EntityFlag_Anonymous)) { - continue; - } - 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)); - GB_ASSERT(found != NULL); - for_array(i, (*found)->elements.entries) { - Entity *f = (*found)->elements.entries.e[i].value; - if (f->kind == Entity_Variable) { - Entity *uvar = make_entity_using_variable(c->allocator, e, f->token, f->type); - Entity *prev = scope_insert_entity(c->context.scope, uvar); - if (prev != NULL) { - error(e->token, "Namespace collision while `using` `%.*s` of: %.*s", LIT(name), LIT(prev->token.string)); - break; - } - } - } - } else { - error(e->token, "`using` can only be applied to variables of type struct or raw_union"); - break; - } - } - } - - push_procedure(c, type); - { - ast_node(bs, BlockStmt, body); - check_stmt_list(c, bs->stmts, 0); - if (type->Proc.result_count > 0) { - if (!check_is_terminating(body)) { - if (token.kind == Token_Ident) { - error(bs->close, "Missing return statement at the end of the procedure `%.*s`", LIT(token.string)); - } else { - error(bs->close, "Missing return statement at the end of the procedure"); - } - } - } - } - pop_procedure(c); - - - check_scope_usage(c, c->context.scope); - - c->context = old_context; -} - - - diff --git a/src/checker/entity.c b/src/checker/entity.c deleted file mode 100644 index 17fb70e06..000000000 --- a/src/checker/entity.c +++ /dev/null @@ -1,190 +0,0 @@ -typedef struct Scope Scope; -typedef struct Checker Checker; -typedef struct Type Type; -typedef enum BuiltinProcId BuiltinProcId; -typedef enum ImplicitValueId ImplicitValueId; - -#define ENTITY_KINDS \ - ENTITY_KIND(Invalid) \ - ENTITY_KIND(Constant) \ - ENTITY_KIND(Variable) \ - ENTITY_KIND(TypeName) \ - ENTITY_KIND(Procedure) \ - ENTITY_KIND(Builtin) \ - ENTITY_KIND(ImportName) \ - ENTITY_KIND(Nil) \ - ENTITY_KIND(ImplicitValue) \ - ENTITY_KIND(Count) - -typedef enum EntityKind { -#define ENTITY_KIND(k) GB_JOIN2(Entity_, k), - ENTITY_KINDS -#undef ENTITY_KIND -} EntityKind; - -String const entity_strings[] = { -#define ENTITY_KIND(k) {cast(u8 *)#k, gb_size_of(#k)-1}, - ENTITY_KINDS -#undef ENTITY_KIND -}; - -typedef enum EntityFlag { - EntityFlag_Visited = 1<<0, - EntityFlag_Used = 1<<1, - EntityFlag_Anonymous = 1<<2, - EntityFlag_Field = 1<<3, - EntityFlag_Param = 1<<4, - EntityFlag_VectorElem = 1<<5, -} EntityFlag; - -typedef struct Entity Entity; -struct Entity { - EntityKind kind; - u32 flags; - Token token; - Scope * scope; - Type * type; - AstNode * identifier; // Can be NULL - - // TODO(bill): Cleanup how `using` works for entities - Entity * using_parent; - AstNode * using_expr; - - union { - struct { - ExactValue value; - } Constant; - struct { - i32 field_index; - i32 field_src_index; - bool is_immutable; - } Variable; - i32 TypeName; - struct { - bool is_foreign; - String foreign_name; - String link_name; - u64 tags; - } Procedure; - struct { - BuiltinProcId id; - } Builtin; - struct { - String path; - String name; - Scope *scope; - bool used; - } ImportName; - i32 Nil; - struct { - // TODO(bill): Should this be a user-level construct rather than compiler-level? - ImplicitValueId id; - Entity * backing; - } ImplicitValue; - }; -}; - - -Entity *e_iota = NULL; - - -Entity *alloc_entity(gbAllocator a, EntityKind kind, Scope *scope, Token token, Type *type) { - Entity *entity = gb_alloc_item(a, Entity); - entity->kind = kind; - entity->scope = scope; - entity->token = token; - entity->type = type; - return entity; -} - -Entity *make_entity_variable(gbAllocator a, Scope *scope, Token token, Type *type) { - Entity *entity = alloc_entity(a, Entity_Variable, scope, token, type); - return entity; -} - -Entity *make_entity_using_variable(gbAllocator a, Entity *parent, Token token, Type *type) { - GB_ASSERT(parent != NULL); - Entity *entity = alloc_entity(a, Entity_Variable, parent->scope, token, type); - entity->using_parent = parent; - entity->flags |= EntityFlag_Anonymous; - return entity; -} - - -Entity *make_entity_constant(gbAllocator a, Scope *scope, Token token, Type *type, ExactValue value) { - Entity *entity = alloc_entity(a, Entity_Constant, scope, token, type); - entity->Constant.value = value; - return entity; -} - -Entity *make_entity_type_name(gbAllocator a, Scope *scope, Token token, Type *type) { - Entity *entity = alloc_entity(a, Entity_TypeName, scope, token, type); - return entity; -} - -Entity *make_entity_param(gbAllocator a, Scope *scope, Token token, Type *type, bool anonymous) { - Entity *entity = make_entity_variable(a, scope, token, type); - entity->flags |= EntityFlag_Used; - entity->flags |= EntityFlag_Anonymous*(anonymous != 0); - entity->flags |= EntityFlag_Param; - return entity; -} - -Entity *make_entity_field(gbAllocator a, Scope *scope, Token token, Type *type, bool anonymous, i32 field_src_index) { - Entity *entity = make_entity_variable(a, scope, token, type); - entity->Variable.field_src_index = field_src_index; - entity->Variable.field_index = field_src_index; - entity->flags |= EntityFlag_Field; - entity->flags |= EntityFlag_Anonymous*(anonymous != 0); - return entity; -} - -Entity *make_entity_vector_elem(gbAllocator a, Scope *scope, Token token, Type *type, i32 field_src_index) { - Entity *entity = make_entity_variable(a, scope, token, type); - entity->Variable.field_src_index = field_src_index; - entity->Variable.field_index = field_src_index; - entity->flags |= EntityFlag_Field; - entity->flags |= EntityFlag_VectorElem; - return entity; -} - -Entity *make_entity_procedure(gbAllocator a, Scope *scope, Token token, Type *signature_type, u64 tags) { - Entity *entity = alloc_entity(a, Entity_Procedure, scope, token, signature_type); - entity->Procedure.tags = tags; - return entity; -} - -Entity *make_entity_builtin(gbAllocator a, Scope *scope, Token token, Type *type, BuiltinProcId id) { - Entity *entity = alloc_entity(a, Entity_Builtin, scope, token, type); - entity->Builtin.id = id; - return entity; -} - -Entity *make_entity_import_name(gbAllocator a, Scope *scope, Token token, Type *type, - String path, String name, Scope *import_scope) { - Entity *entity = alloc_entity(a, Entity_ImportName, scope, token, type); - entity->ImportName.path = path; - entity->ImportName.name = name; - entity->ImportName.scope = import_scope; - return entity; -} - -Entity *make_entity_nil(gbAllocator a, String name, Type *type) { - Token token = make_token_ident(name); - Entity *entity = alloc_entity(a, Entity_Nil, NULL, token, type); - return entity; -} - -Entity *make_entity_implicit_value(gbAllocator a, String name, Type *type, ImplicitValueId id) { - Token token = make_token_ident(name); - Entity *entity = alloc_entity(a, Entity_ImplicitValue, NULL, token, type); - entity->ImplicitValue.id = id; - return entity; -} - - -Entity *make_entity_dummy_variable(gbAllocator a, Scope *scope, Token token) { - token.string = str_lit("_"); - return make_entity_variable(a, scope, token, NULL); -} - diff --git a/src/checker/expr.c b/src/checker/expr.c deleted file mode 100644 index 2c772d149..000000000 --- a/src/checker/expr.c +++ /dev/null @@ -1,4759 +0,0 @@ -void check_expr (Checker *c, Operand *operand, AstNode *expression); -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); -void check_type_decl (Checker *c, Entity *e, AstNode *type_expr, Type *def); -Entity * check_selector (Checker *c, Operand *operand, AstNode *node); -void check_not_tuple (Checker *c, Operand *operand); -bool check_value_is_expressible(Checker *c, ExactValue in_value, Type *type, ExactValue *out_value); -void convert_to_typed (Checker *c, Operand *operand, Type *target_type, i32 level); -gbString expr_to_string (AstNode *expression); -void check_entity_decl (Checker *c, Entity *e, DeclInfo *decl, Type *named_type); -void check_const_decl (Checker *c, Entity *e, AstNode *type_expr, AstNode *init_expr, Type *named_type); -void check_proc_body (Checker *c, Token token, DeclInfo *decl, Type *type, AstNode *body); -void update_expr_type (Checker *c, AstNode *e, Type *type, bool final); -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_init_constant (Checker *c, Entity *e, Operand *operand); - - -gb_inline Type *check_type(Checker *c, AstNode *expression) { - return check_type_extra(c, expression, NULL); -} - - - - -typedef struct DelayedEntity { - AstNode * ident; - Entity * entity; - DeclInfo * decl; -} DelayedEntity; - -typedef struct DelayedOtherFields { - Entity **other_fields; - isize other_field_count; - isize other_field_index; - - MapEntity *entity_map; -} DelayedOtherFields; - -typedef Array(DelayedEntity) DelayedEntities; - -void check_local_collect_entities(Checker *c, AstNodeArray nodes, DelayedEntities *delayed_entities, DelayedOtherFields *dof); - -void check_local_collect_entities_from_when_stmt(Checker *c, AstNodeWhenStmt *ws, DelayedEntities *delayed_entities, DelayedOtherFields *dof) { - Operand operand = {Addressing_Invalid}; - check_expr(c, &operand, ws->cond); - if (operand.mode != Addressing_Invalid && !is_type_boolean(operand.type)) { - error_node(ws->cond, "Non-boolean condition in `when` statement"); - } - if (operand.mode != Addressing_Constant) { - error_node(ws->cond, "Non-constant condition in `when` statement"); - } - if (ws->body == NULL || ws->body->kind != AstNode_BlockStmt) { - error_node(ws->cond, "Invalid body for `when` statement"); - } else { - if (operand.value.kind == ExactValue_Bool && - operand.value.value_bool) { - check_local_collect_entities(c, ws->body->BlockStmt.stmts, delayed_entities, dof); - } else if (ws->else_stmt) { - switch (ws->else_stmt->kind) { - case AstNode_BlockStmt: - check_local_collect_entities(c, ws->else_stmt->BlockStmt.stmts, delayed_entities, dof); - break; - case AstNode_WhenStmt: - check_local_collect_entities_from_when_stmt(c, &ws->else_stmt->WhenStmt, delayed_entities, dof); - break; - default: - error_node(ws->else_stmt, "Invalid `else` statement in `when` statement"); - break; - } - } - } -} - -// NOTE(bill): The `dof` is for use within records -void check_local_collect_entities(Checker *c, AstNodeArray nodes, DelayedEntities *delayed_entities, DelayedOtherFields *dof) { - for_array(i, nodes) { - AstNode *node = nodes.e[i]; - switch (node->kind) { - case_ast_node(ws, WhenStmt, node); - // Will be handled later - case_end; - - case_ast_node(vd, ValueDecl, node); - if (vd->is_var) { - // NOTE(bill): Handled later - } else { - for_array(i, vd->names) { - AstNode *name = vd->names.e[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; - } - - AstNode *init = NULL; - if (i < vd->values.count) { - init = vd->values.e[i]; - } - - DeclInfo *d = make_declaration_info(c->allocator, c->context.scope); - Entity *e = NULL; - - AstNode *up_init = unparen_expr(init); - if (init != NULL && is_ast_node_type(up_init)) { - e = make_entity_type_name(c->allocator, d->scope, name->Ident, NULL); - d->type_expr = init; - d->init_expr = init; - } else if (init != NULL && up_init->kind == AstNode_ProcLit) { - e = make_entity_procedure(c->allocator, d->scope, name->Ident, NULL, up_init->ProcLit.tags); - d->proc_lit = init; - } else { - e = make_entity_constant(c->allocator, d->scope, name->Ident, NULL, (ExactValue){0}); - d->type_expr = vd->type; - d->init_expr = init; - } - GB_ASSERT(e != NULL); - e->identifier = name; - - add_entity_and_decl_info(c, name, e, d); - - DelayedEntity delay = {name, e, d}; - array_add(delayed_entities, delay); - } - - check_arity_match(c, vd); - } - case_end; -#if 0 - case_ast_node(pd, ProcDecl, node); - if (!ast_node_expect(pd->name, AstNode_Ident)) { - break; - } - - Entity *e = make_entity_procedure(c->allocator, c->context.scope, pd->name->Ident, NULL); - e->identifier = pd->name; - - DeclInfo *d = make_declaration_info(c->allocator, e->scope); - d->proc_lit = node; - - add_entity_and_decl_info(c, pd->name, e, d); - check_entity_decl(c, e, d, NULL, NULL); - case_end; -#endif - } - } - - // 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]; - switch (node->kind) { - case_ast_node(ws, WhenStmt, node); - check_local_collect_entities_from_when_stmt(c, ws, delayed_entities, dof); - case_end; - } - } -} - -void check_scope_decls(Checker *c, AstNodeArray nodes, isize reserve_size, DelayedOtherFields *dof) { - DelayedEntities delayed_entities; - array_init_reserve(&delayed_entities, heap_allocator(), reserve_size); - check_local_collect_entities(c, nodes, &delayed_entities, dof); - - for_array(i, delayed_entities) { - DelayedEntity delayed = delayed_entities.e[i]; - if (delayed.entity->kind == Entity_TypeName) { - check_entity_decl(c, delayed.entity, delayed.decl, NULL); - } - } - for_array(i, delayed_entities) { - DelayedEntity delayed = delayed_entities.e[i]; - if (delayed.entity->kind == Entity_Constant) { - add_entity_and_decl_info(c, delayed.ident, delayed.entity, delayed.decl); - check_entity_decl(c, delayed.entity, delayed.decl, NULL); - } - } - - array_free(&delayed_entities); -} - - -bool check_is_assignable_to_using_subtype(Type *dst, Type *src) { - bool src_is_ptr; - Type *prev_src = src; - src = type_deref(src); - src_is_ptr = src != prev_src; - src = base_type(src); - - if (is_type_struct(src)) { - for (isize i = 0; i < src->Record.field_count; i++) { - Entity *f = src->Record.fields[i]; - if (f->kind == Entity_Variable && (f->flags & EntityFlag_Anonymous)) { - if (are_types_identical(dst, f->type)) { - return true; - } - if (src_is_ptr && is_type_pointer(dst)) { - if (are_types_identical(type_deref(dst), f->type)) { - return true; - } - } - bool ok = check_is_assignable_to_using_subtype(dst, f->type); - if (ok) { - return true; - } - } - } - } - return false; -} - - -bool check_is_assignable_to(Checker *c, Operand *operand, Type *type) { - if (operand->mode == Addressing_Invalid || - type == t_invalid) { - return true; - } - - if (operand->mode == Addressing_Builtin) { - return false; - } - - Type *s = operand->type; - - if (are_types_identical(s, type)) { - return true; - } - - Type *src = base_type(s); - Type *dst = base_type(type); - - if (is_type_untyped(src)) { - switch (dst->kind) { - case Type_Basic: - if (operand->mode == Addressing_Constant) { - return check_value_is_expressible(c, operand->value, dst, NULL); - } - if (src->kind == Type_Basic && src->Basic.kind == Basic_UntypedBool) { - return is_type_boolean(dst); - } - break; - } - if (type_has_nil(dst)) { - return operand->mode == Addressing_Value && operand->type == t_untyped_nil; - } - } - - if (are_types_identical(dst, src) && (!is_type_named(dst) || !is_type_named(src))) { - return true; - } - - if (is_type_maybe(dst)) { - Type *elem = base_type(dst)->Maybe.elem; - return are_types_identical(elem, s); - } - - if (is_type_untyped_nil(src)) { - return type_has_nil(dst); - } - - // ^T <- rawptr - // TODO(bill): Should C-style (not C++) pointer cast be allowed? - // if (is_type_pointer(dst) && is_type_rawptr(src)) { - // return true; - // } - - // rawptr <- ^T - if (is_type_rawptr(dst) && is_type_pointer(src)) { - // TODO(bill): Handle this properly - if (dst != type) { - return false; - } - return true; - } - - - - if (dst->kind == Type_Array && src->kind == Type_Array) { - if (are_types_identical(dst->Array.elem, src->Array.elem)) { - return dst->Array.count == src->Array.count; - } - } - - if (dst->kind == Type_Slice && src->kind == Type_Slice) { - if (are_types_identical(dst->Slice.elem, src->Slice.elem)) { - return true; - } - } - - if (is_type_union(dst)) { - for (isize i = 0; i < dst->Record.field_count; i++) { - Entity *f = dst->Record.fields[i]; - if (are_types_identical(f->type, s)) { - return true; - } - } - } - - - if (is_type_any(dst)) { - // NOTE(bill): Anything can cast to `Any` - add_type_info_type(c, s); - return true; - } - - return false; -} - - -// NOTE(bill): `content_name` is for debugging and error messages -void check_assignment(Checker *c, Operand *operand, Type *type, String context_name) { - check_not_tuple(c, operand); - if (operand->mode == Addressing_Invalid) { - return; - } - - if (is_type_untyped(operand->type)) { - Type *target_type = type; - - if (type == NULL || is_type_any(type) || is_type_untyped_nil(type)) { - if (type == NULL && base_type(operand->type) == t_untyped_nil) { - error_node(operand->expr, "Use of untyped nil in %.*s", LIT(context_name)); - operand->mode = Addressing_Invalid; - return; - } - - add_type_info_type(c, type); - target_type = default_type(operand->type); - } - convert_to_typed(c, operand, target_type, 0); - if (operand->mode == Addressing_Invalid) { - return; - } - } - - if (type != NULL) { - if (!check_is_assignable_to(c, operand, type)) { - gbString type_str = type_to_string(type); - gbString op_type_str = type_to_string(operand->type); - gbString expr_str = expr_to_string(operand->expr); - - if (operand->mode == Addressing_Builtin) { - // TODO(bill): is this a good enough error message? - error_node(operand->expr, - "Cannot assign builtin procedure `%s` in %.*s", - expr_str, - LIT(context_name)); - } else { - // TODO(bill): is this a good enough error message? - error_node(operand->expr, - "Cannot assign value `%s` of type `%s` to `%s` in %.*s", - expr_str, - op_type_str, - type_str, - LIT(context_name)); - } - operand->mode = Addressing_Invalid; - - gb_string_free(expr_str); - gb_string_free(op_type_str); - gb_string_free(type_str); - return; - } - } -} - - -void populate_using_entity_map(Checker *c, AstNode *node, Type *t, MapEntity *entity_map) { - t = base_type(type_deref(t)); - gbString str = expr_to_string(node); - - if (t->kind == Type_Record) { - for (isize i = 0; i < t->Record.field_count; i++) { - Entity *f = t->Record.fields[i]; - GB_ASSERT(f->kind == Entity_Variable); - String name = f->token.string; - HashKey key = hash_string(name); - Entity **found = map_entity_get(entity_map, key); - if (found != NULL) { - Entity *e = *found; - // TODO(bill): Better type error - error(e->token, "`%.*s` is already declared in `%s`", LIT(name), str); - } else { - map_entity_set(entity_map, key, f); - add_entity(c, c->context.scope, NULL, f); - if (f->flags & EntityFlag_Anonymous) { - populate_using_entity_map(c, node, f->type, entity_map); - } - } - } - } - - gb_string_free(str); -} - - -void check_fields(Checker *c, AstNode *node, AstNodeArray 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); - - isize other_field_index = 0; - Entity *using_index_expr = NULL; - - if (node->kind == AstNode_UnionType) { - isize field_index = 0; - fields[field_index++] = make_entity_type_name(c->allocator, c->context.scope, empty_token, NULL); - for_array(decl_index, decls) { - AstNode *decl = decls.e[decl_index]; - if (decl->kind != AstNode_Field) { - continue; - } - - ast_node(f, Field, decl); - Type *base_type = check_type_extra(c, f->type, NULL); - - for_array(name_index, f->names) { - AstNode *name = f->names.e[name_index]; - if (!ast_node_expect(name, AstNode_Ident)) { - continue; - } - - Token name_token = name->Ident; - - Type *type = make_type_named(c->allocator, name_token.string, base_type, NULL); - Entity *e = make_entity_type_name(c->allocator, c->context.scope, name_token, type); - type->Named.type_name = e; - add_entity(c, c->context.scope, name, e); - - if (str_eq(name_token.string, str_lit("_"))) { - 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) { - // TODO(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); - fields[field_index++] = e; - } - add_entity_use(c, name, e); - } - } - } else { - isize field_index = 0; - for_array(decl_index, decls) { - AstNode *decl = decls.e[decl_index]; - if (decl->kind != AstNode_Field) { - continue; - } - ast_node(f, Field, decl); - - Type *type = check_type_extra(c, f->type, NULL); - - if (f->is_using) { - if (f->names.count > 1) { - error_node(f->names.e[0], "Cannot apply `using` to more than one of the same type"); - } - } - - for_array(name_index, f->names) { - AstNode *name = f->names.e[name_index]; - if (!ast_node_expect(name, AstNode_Ident)) { - continue; - } - - Token name_token = name->Ident; - - Entity *e = make_entity_field(c->allocator, c->context.scope, name_token, type, f->is_using, cast(i32)field_index); - e->identifier = name; - if (str_eq(name_token.string, str_lit("_"))) { - fields[field_index++] = e; - } else { - HashKey key = hash_string(name_token.string); - if (map_entity_get(&entity_map, key) != NULL) { - // TODO(bill): Scope checking already checks the declaration - error(name_token, "`%.*s` is already declared in this type", LIT(name_token.string)); - } else { - map_entity_set(&entity_map, key, e); - fields[field_index++] = e; - add_entity(c, c->context.scope, name, e); - } - add_entity_use(c, name, e); - } - } - - - if (f->is_using) { - Type *t = base_type(type_deref(type)); - if (!is_type_struct(t) && !is_type_raw_union(t) && - f->names.count >= 1 && - f->names.e[0]->kind == AstNode_Ident) { - Token name_token = f->names.e[0]->Ident; - if (is_type_indexable(t)) { - bool ok = true; - for_array(emi, entity_map.entries) { - Entity *e = entity_map.entries.e[emi].value; - if (e->kind == Entity_Variable && e->flags & EntityFlag_Anonymous) { - if (is_type_indexable(e->type)) { - if (e->identifier != f->names.e[0]) { - ok = false; - using_index_expr = e; - break; - } - } - } - } - if (ok) { - using_index_expr = fields[field_index-1]; - } else { - fields[field_index-1]->flags &= ~EntityFlag_Anonymous; - error(name_token, "Previous `using` for an index expression `%.*s`", LIT(name_token.string)); - } - } else { - error(name_token, "`using` on a field `%.*s` must be a `struct` or `raw_union`", LIT(name_token.string)); - continue; - } - } - - populate_using_entity_map(c, node, type, &entity_map); - } - } - } - - gb_temp_arena_memory_end(tmp); -} - - -// TODO(bill): Cleanup struct field reordering -// TODO(bill): Inline sorting procedure? -gb_global BaseTypeSizes __checker_sizes = {0}; -gb_global gbAllocator __checker_allocator = {0}; - -GB_COMPARE_PROC(cmp_struct_entity_size) { - // Rule: - // Biggest to smallest alignment - // if same alignment: biggest to smallest size - // if same size: order by source order - Entity *x = *(Entity **)a; - Entity *y = *(Entity **)b; - GB_ASSERT(x != NULL); - GB_ASSERT(y != NULL); - GB_ASSERT(x->kind == Entity_Variable); - GB_ASSERT(y->kind == Entity_Variable); - i64 xa = type_align_of(__checker_sizes, __checker_allocator, x->type); - i64 ya = type_align_of(__checker_sizes, __checker_allocator, y->type); - i64 xs = type_size_of(__checker_sizes, __checker_allocator, x->type); - i64 ys = type_size_of(__checker_sizes, __checker_allocator, y->type); - - if (xa == ya) { - if (xs == ys) { - i32 diff = x->Variable.field_index - y->Variable.field_index; - return diff < 0 ? -1 : diff > 0; - } - return xs > ys ? -1 : xs < ys; - } - return xa > ya ? -1 : xa < ya; -} - -void check_struct_type(Checker *c, Type *struct_type, AstNode *node) { - GB_ASSERT(is_type_struct(struct_type)); - ast_node(st, StructType, node); - - isize field_count = 0; - for_array(field_index, st->fields) { - AstNode *field = st->fields.e[field_index]; - switch (field->kind) { - case_ast_node(f, Field, field); - field_count += f->names.count; - case_end; - } - } - - Entity **fields = gb_alloc_array(c->allocator, Entity *, field_count); - - check_fields(c, node, st->fields, fields, field_count, str_lit("struct")); - - struct_type->Record.struct_is_packed = st->is_packed; - struct_type->Record.struct_is_ordered = st->is_ordered; - struct_type->Record.fields = fields; - struct_type->Record.fields_in_src_order = fields; - struct_type->Record.field_count = field_count; - - if (!st->is_packed && !st->is_ordered) { - // NOTE(bill): Reorder fields for reduced size/performance - - Entity **reordered_fields = gb_alloc_array(c->allocator, Entity *, field_count); - for (isize i = 0; i < field_count; i++) { - reordered_fields[i] = struct_type->Record.fields_in_src_order[i]; - } - - // NOTE(bill): Hacky thing - // TODO(bill): Probably make an inline sorting procedure rather than use global variables - __checker_sizes = c->sizes; - __checker_allocator = c->allocator; - // NOTE(bill): compound literal order must match source not layout - gb_sort_array(reordered_fields, field_count, cmp_struct_entity_size); - - for (isize i = 0; i < field_count; i++) { - reordered_fields[i]->Variable.field_index = i; - } - - struct_type->Record.fields = reordered_fields; - } - - type_set_offsets(c->sizes, c->allocator, struct_type); -} - -void check_union_type(Checker *c, Type *union_type, AstNode *node) { - GB_ASSERT(is_type_union(union_type)); - ast_node(ut, UnionType, node); - - isize field_count = 1; - for_array(field_index, ut->fields) { - AstNode *field = ut->fields.e[field_index]; - switch (field->kind) { - case_ast_node(f, Field, field); - field_count += f->names.count; - case_end; - } - } - - Entity **fields = gb_alloc_array(c->allocator, Entity *, field_count); - - check_fields(c, node, ut->fields, fields, field_count, str_lit("union")); - - union_type->Record.fields = fields; - union_type->Record.field_count = field_count; -} - -void check_raw_union_type(Checker *c, Type *union_type, AstNode *node) { - GB_ASSERT(node->kind == AstNode_RawUnionType); - GB_ASSERT(is_type_raw_union(union_type)); - ast_node(ut, RawUnionType, node); - - isize field_count = 0; - for_array(field_index, ut->fields) { - AstNode *field = ut->fields.e[field_index]; - switch (field->kind) { - case_ast_node(f, Field, field); - field_count += f->names.count; - case_end; - } - } - - Entity **fields = gb_alloc_array(c->allocator, Entity *, field_count); - - check_fields(c, node, ut->fields, fields, field_count, str_lit("raw_union")); - - union_type->Record.fields = fields; - union_type->Record.field_count = field_count; -} - -// GB_COMPARE_PROC(cmp_enum_order) { -// // Rule: -// // Biggest to smallest alignment -// // if same alignment: biggest to smallest size -// // if same size: order by source order -// Entity *x = *(Entity **)a; -// Entity *y = *(Entity **)b; -// GB_ASSERT(x != NULL); -// GB_ASSERT(y != NULL); -// GB_ASSERT(x->kind == Entity_Constant); -// GB_ASSERT(y->kind == Entity_Constant); -// GB_ASSERT(x->Constant.value.kind == ExactValue_Integer); -// GB_ASSERT(y->Constant.value.kind == ExactValue_Integer); -// i64 i = x->Constant.value.value_integer; -// i64 j = y->Constant.value.value_integer; - -// return i < j ? -1 : i > j; -// } - -void check_enum_type(Checker *c, Type *enum_type, Type *named_type, AstNode *node) { - ast_node(et, EnumType, node); - GB_ASSERT(is_type_enum(enum_type)); - - gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&c->tmp_arena); - - Type *base_type = t_int; - if (et->base_type != NULL) { - base_type = check_type(c, et->base_type); - } - - if (base_type == NULL || !(is_type_integer(base_type) || is_type_float(base_type))) { - error_node(node, "Base type for enumeration must be numeric"); - return; - } - - // 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)); - - Entity **fields = gb_alloc_array(c->allocator, Entity *, et->fields.count); - isize field_index = 0; - - Type *constant_type = enum_type; - if (named_type != NULL) { - constant_type = named_type; - } - - AstNode *prev_expr = NULL; - - i64 iota = 0; - - for_array(i, et->fields) { - AstNode *field = et->fields.e[i]; - AstNode *ident = NULL; - if (field->kind == AstNode_FieldValue) { - ast_node(fv, FieldValue, field); - if (fv->field == NULL || fv->field->kind != AstNode_Ident) { - error_node(field, "An enum field's name must be an identifier"); - continue; - } - ident = fv->field; - prev_expr = fv->value; - } else if (field->kind == AstNode_Ident) { - ident = field; - } else { - error_node(field, "An enum field's name must be an identifier"); - continue; - } - String name = ident->Ident.string; - - if (str_ne(name, str_lit("_"))) { - ExactValue v = make_exact_value_integer(iota); - Entity *e = make_entity_constant(c->allocator, c->context.scope, ident->Ident, constant_type, v); - e->identifier = ident; - e->flags |= EntityFlag_Visited; - - - AstNode *init = prev_expr; - if (init == NULL) { - error_node(field, "Missing initial expression for enumeration, e.g. iota"); - continue; - } - - ExactValue context_iota = c->context.iota; - c->context.iota = e->Constant.value; - e->Constant.value = (ExactValue){0}; - - Operand operand = {0}; - check_expr(c, &operand, init); - - check_init_constant(c, e, &operand); - c->context.iota = context_iota; - - if (operand.mode == Addressing_Constant) { - HashKey key = hash_string(name); - if (map_entity_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); - add_entity(c, c->context.scope, NULL, e); - fields[field_index++] = e; - add_entity_use(c, field, e); - } - } - } - iota++; - } - - GB_ASSERT(field_index <= et->fields.count); - - enum_type->Record.fields = fields; - enum_type->Record.field_count = field_index; - - gb_temp_arena_memory_end(tmp); -} - - -Type *check_get_params(Checker *c, Scope *scope, AstNodeArray params, bool *is_variadic_) { - if (params.count == 0) { - return NULL; - } - - isize variable_count = 0; - for_array(i, params) { - AstNode *field = params.e[i]; - if (ast_node_expect(field, AstNode_Field)) { - ast_node(f, Field, field); - variable_count += f->names.count; - } - } - - bool is_variadic = false; - 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) { - continue; - } - ast_node(p, Field, params.e[i]); - AstNode *type_expr = p->type; - if (type_expr) { - 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"); - } - } - - Type *type = check_type(c, type_expr); - 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->is_using); - add_entity(c, scope, name, param); - variables[variable_index++] = param; - } - } - } - } - - variable_count = variable_index; - - if (is_variadic) { - GB_ASSERT(params.count > 0); - // NOTE(bill): Change last variadic parameter to be a slice - // Custom Calling convention for variadic parameters - Entity *end = variables[variable_count-1]; - end->type = make_type_slice(c->allocator, end->type); - } - - Type *tuple = make_type_tuple(c->allocator); - tuple->Tuple.variables = variables; - tuple->Tuple.variable_count = variable_count; - - if (is_variadic_) *is_variadic_ = is_variadic; - - return tuple; -} - -Type *check_get_results(Checker *c, Scope *scope, AstNodeArray results) { - if (results.count == 0) { - return NULL; - } - Type *tuple = make_type_tuple(c->allocator); - - Entity **variables = gb_alloc_array(c->allocator, Entity *, results.count); - isize variable_index = 0; - for_array(i, results) { - AstNode *item = results.e[i]; - Type *type = check_type(c, item); - Token token = ast_node_token(item); - token.string = str_lit(""); // NOTE(bill): results are not named - // TODO(bill): Should I have named results? - Entity *param = make_entity_param(c->allocator, scope, token, type, false); - // NOTE(bill): No need to record - variables[variable_index++] = param; - } - tuple->Tuple.variables = variables; - tuple->Tuple.variable_count = results.count; - - return tuple; -} - - -void check_procedure_type(Checker *c, Type *type, AstNode *proc_type_node) { - ast_node(pt, ProcType, proc_type_node); - - bool variadic = false; - Type *params = check_get_params(c, c->context.scope, pt->params, &variadic); - Type *results = check_get_results(c, c->context.scope, pt->results); - - isize param_count = 0; - isize result_count = 0; - if (params) param_count = params ->Tuple.variable_count; - if (results) result_count = results->Tuple.variable_count; - - type->Proc.scope = c->context.scope; - type->Proc.params = params; - type->Proc.param_count = param_count; - type->Proc.results = results; - type->Proc.result_count = result_count; - type->Proc.variadic = variadic; - type->Proc.calling_convention = pt->calling_convention; -} - - -void check_identifier(Checker *c, Operand *o, AstNode *n, Type *named_type) { - GB_ASSERT(n->kind == AstNode_Ident); - o->mode = Addressing_Invalid; - o->expr = n; - Entity *e = scope_lookup_entity(c->context.scope, n->Ident.string); - if (e == NULL) { - if (str_eq(n->Ident.string, str_lit("_"))) { - error(n->Ident, "`_` cannot be used as a value type"); - } else { - error(n->Ident, "Undeclared name: %.*s", LIT(n->Ident.string)); - } - o->type = t_invalid; - o->mode = Addressing_Invalid; - if (named_type != NULL) { - set_base_type(named_type, t_invalid); - } - return; - } - add_entity_use(c, n, e); - - check_entity_decl(c, e, NULL, named_type); - - if (e->type == NULL) { - compiler_error("Compiler error: How did this happen? type: %s; identifier: %.*s\n", type_to_string(e->type), LIT(n->Ident.string)); - return; - } - - - Type *type = e->type; - - switch (e->kind) { - case Entity_Constant: - if (type == t_invalid) { - o->type = t_invalid; - return; - } - if (e == e_iota) { - if (c->context.iota.kind == ExactValue_Invalid) { - error(e->token, "Use of `iota` outside a enumeration is not allowed"); - return; - } - o->value = c->context.iota; - } else { - o->value = e->Constant.value; - } - if (o->value.kind == ExactValue_Invalid) { - return; - } - o->mode = Addressing_Constant; - break; - - case Entity_Variable: - e->flags |= EntityFlag_Used; - if (type == t_invalid) { - o->type = t_invalid; - return; - } - #if 0 - if (e->Variable.param) { - o->mode = Addressing_Value; - } else { - o->mode = Addressing_Variable; - } - #else - o->mode = Addressing_Variable; - if (e->Variable.is_immutable) { - o->mode = Addressing_Value; - } - #endif - break; - - case Entity_TypeName: { - o->mode = Addressing_Type; -#if 1 - // TODO(bill): Fix cyclical dependancy checker -#endif - } break; - - case Entity_Procedure: - o->mode = Addressing_Value; - break; - - case Entity_Builtin: - o->builtin_id = e->Builtin.id; - o->mode = Addressing_Builtin; - break; - - case Entity_ImportName: - error_node(n, "Use of import `%.*s` not in selector", LIT(e->ImportName.name)); - return; - - case Entity_Nil: - o->mode = Addressing_Value; - break; - - case Entity_ImplicitValue: - o->mode = Addressing_Value; - break; - - default: - compiler_error("Compiler error: Unknown EntityKind"); - break; - } - - o->type = type; -} - -i64 check_array_count(Checker *c, AstNode *e) { - if (e == NULL) { - return 0; - } - Operand o = {0}; - check_expr(c, &o, e); - if (o.mode != Addressing_Constant) { - if (o.mode != Addressing_Invalid) { - error_node(e, "Array count must be a constant"); - } - return 0; - } - Type *type = base_type(base_enum_type(o.type)); - if (is_type_untyped(type) || is_type_integer(type)) { - if (o.value.kind == ExactValue_Integer) { - i64 count = o.value.value_integer; - if (count >= 0) { - return count; - } - error_node(e, "Invalid array count"); - return 0; - } - } - - error_node(e, "Array count must be an integer"); - return 0; -} - -Type *check_type_extra(Checker *c, AstNode *e, Type *named_type) { - ExactValue null_value = {ExactValue_Invalid}; - Type *type = NULL; - gbString err_str = NULL; - - if (e == NULL) { - type = t_invalid; - goto end; - } - - switch (e->kind) { - case_ast_node(i, Ident, e); - Operand o = {0}; - check_identifier(c, &o, e, named_type); - - switch (o.mode) { - case Addressing_Invalid: - break; - case Addressing_Type: { - type = o.type; - goto end; - } break; - case Addressing_NoValue: - err_str = expr_to_string(e); - error_node(e, "`%s` used as a type", err_str); - break; - default: - err_str = expr_to_string(e); - error_node(e, "`%s` used as a type when not a type", err_str); - break; - } - case_end; - - case_ast_node(se, SelectorExpr, e); - Operand o = {0}; - check_selector(c, &o, e); - - switch (o.mode) { - case Addressing_Invalid: - break; - case Addressing_Type: - GB_ASSERT(o.type != NULL); - type = o.type; - goto end; - case Addressing_NoValue: - err_str = expr_to_string(e); - error_node(e, "`%s` used as a type", err_str); - break; - default: - err_str = expr_to_string(e); - error_node(e, "`%s` is not a type", err_str); - break; - } - case_end; - - case_ast_node(pe, ParenExpr, e); - type = check_type_extra(c, pe->expr, named_type); - goto end; - case_end; - - case_ast_node(ue, UnaryExpr, e); - if (ue->op.kind == Token_Pointer) { - type = make_type_pointer(c->allocator, check_type(c, ue->expr)); - goto end; - } else if (ue->op.kind == Token_Maybe) { - type = make_type_maybe(c->allocator, check_type(c, ue->expr)); - goto end; - } - case_end; - - case_ast_node(ht, HelperType, e); - type = check_type(c, ht->type); - goto end; - case_end; - - case_ast_node(pt, PointerType, e); - Type *elem = check_type(c, pt->type); - type = make_type_pointer(c->allocator, elem); - goto end; - case_end; - - case_ast_node(mt, MaybeType, e); - Type *elem = check_type(c, mt->type); - type = make_type_maybe(c->allocator, elem); - goto end; - case_end; - - case_ast_node(at, ArrayType, e); - if (at->count != NULL) { - Type *elem = check_type_extra(c, at->elem, NULL); - type = make_type_array(c->allocator, elem, check_array_count(c, at->count)); - } else { - Type *elem = check_type(c, at->elem); - type = make_type_slice(c->allocator, elem); - } - goto end; - case_end; - - - case_ast_node(vt, VectorType, e); - Type *elem = check_type(c, vt->elem); - Type *be = base_type(elem); - i64 count = check_array_count(c, vt->count); - if (!is_type_boolean(be) && !is_type_numeric(be)) { - err_str = type_to_string(elem); - error_node(vt->elem, "Vector element type must be numerical or a boolean, got `%s`", err_str); - } - type = make_type_vector(c->allocator, elem, count); - goto end; - case_end; - - case_ast_node(st, StructType, e); - type = make_type_struct(c->allocator); - set_base_type(named_type, type); - check_open_scope(c, e); - check_struct_type(c, type, e); - check_close_scope(c); - type->Record.node = e; - goto end; - case_end; - - case_ast_node(ut, UnionType, e); - type = make_type_union(c->allocator); - set_base_type(named_type, type); - check_open_scope(c, e); - check_union_type(c, type, e); - check_close_scope(c); - type->Record.node = e; - goto end; - case_end; - - case_ast_node(rut, RawUnionType, e); - type = make_type_raw_union(c->allocator); - set_base_type(named_type, type); - check_open_scope(c, e); - check_raw_union_type(c, type, e); - check_close_scope(c); - type->Record.node = e; - goto end; - case_end; - - case_ast_node(et, EnumType, e); - type = make_type_enum(c->allocator); - set_base_type(named_type, type); - check_open_scope(c, e); - check_enum_type(c, type, named_type, e); - check_close_scope(c); - type->Record.node = e; - goto end; - case_end; - - case_ast_node(pt, ProcType, e); - type = alloc_type(c->allocator, Type_Proc); - set_base_type(named_type, type); - check_open_scope(c, e); - check_procedure_type(c, type, e); - check_close_scope(c); - goto end; - case_end; - - - case_ast_node(ce, CallExpr, e); - Operand o = {0}; - check_expr_or_type(c, &o, e); - if (o.mode == Addressing_Type) { - type = o.type; - goto end; - } - case_end; - } - err_str = expr_to_string(e); - error_node(e, "`%s` is not a type", err_str); - - type = t_invalid; -end: - gb_string_free(err_str); - - if (type == NULL) { - type = t_invalid; - } - - if (is_type_named(type)) { - if (type->Named.base == NULL) { - gbString name = type_to_string(type); - error_node(e, "Invalid type definition of %s", name); - gb_string_free(name); - type->Named.base = t_invalid; - } - } - - if (is_type_typed(type)) { - add_type_and_value(&c->info, e, Addressing_Type, type, null_value); - } else { - gbString name = type_to_string(type); - error_node(e, "Invalid type definition of %s", name); - gb_string_free(name); - type = t_invalid; - } - set_base_type(named_type, type); - - - - return type; -} - - -bool check_unary_op(Checker *c, Operand *o, Token op) { - // TODO(bill): Handle errors correctly - Type *type = base_type(base_enum_type(base_vector_type(o->type))); - gbString str = NULL; - switch (op.kind) { - case Token_Add: - case Token_Sub: - if (!is_type_numeric(type)) { - str = expr_to_string(o->expr); - error(op, "Operator `%.*s` is not allowed with `%s`", LIT(op.string), str); - gb_string_free(str); - } - break; - - case Token_Xor: - if (!is_type_integer(type)) { - error(op, "Operator `%.*s` is only allowed with integers", LIT(op.string)); - } - break; - - case Token_Not: - if (!is_type_boolean(type)) { - str = expr_to_string(o->expr); - error(op, "Operator `%.*s` is only allowed on boolean expression", LIT(op.string)); - gb_string_free(str); - } - break; - - default: - error(op, "Unknown operator `%.*s`", LIT(op.string)); - return false; - } - - return true; -} - -bool check_binary_op(Checker *c, Operand *o, Token op) { - // TODO(bill): Handle errors correctly - Type *type = base_type(base_enum_type(base_vector_type(o->type))); - switch (op.kind) { - case Token_Sub: - case Token_SubEq: - if (!is_type_numeric(type) && !is_type_pointer(type)) { - error(op, "Operator `%.*s` is only allowed with numeric or pointer expressions", LIT(op.string)); - return false; - } - if (is_type_pointer(type)) { - o->type = t_int; - } - if (base_type(type) == t_rawptr) { - gbString str = type_to_string(type); - error_node(o->expr, "Invalid pointer type for pointer arithmetic: `%s`", str); - gb_string_free(str); - return false; - } - break; - - case Token_Add: - case Token_Mul: - case Token_Quo: - case Token_AddEq: - case Token_MulEq: - case Token_QuoEq: - if (!is_type_numeric(type)) { - error(op, "Operator `%.*s` is only allowed with numeric expressions", LIT(op.string)); - return false; - } - break; - - case Token_And: - case Token_Or: - case Token_AndEq: - case Token_OrEq: - if (!is_type_integer(type) && !is_type_boolean(type)) { - error(op, "Operator `%.*s` is only allowed with integers or booleans", LIT(op.string)); - return false; - } - break; - - case Token_Mod: - case Token_Xor: - case Token_AndNot: - case Token_ModEq: - case Token_XorEq: - case Token_AndNotEq: - if (!is_type_integer(type)) { - error(op, "Operator `%.*s` is only allowed with integers", LIT(op.string)); - return false; - } - break; - - case Token_CmpAnd: - case Token_CmpOr: - case Token_CmpAndEq: - case Token_CmpOrEq: - if (!is_type_boolean(type)) { - error(op, "Operator `%.*s` is only allowed with boolean expressions", LIT(op.string)); - return false; - } - break; - - default: - error(op, "Unknown operator `%.*s`", LIT(op.string)); - return false; - } - - return true; - -} -bool check_value_is_expressible(Checker *c, ExactValue in_value, Type *type, ExactValue *out_value) { - if (in_value.kind == ExactValue_Invalid) { - // NOTE(bill): There's already been an error - return true; - } - - type = base_type(base_enum_type(type)); - - if (is_type_boolean(type)) { - return in_value.kind == ExactValue_Bool; - } else if (is_type_string(type)) { - return in_value.kind == ExactValue_String; - } else if (is_type_integer(type)) { - ExactValue v = exact_value_to_integer(in_value); - if (v.kind != ExactValue_Integer) { - return false; - } - if (out_value) *out_value = v; - i64 i = v.value_integer; - u64 u = *cast(u64 *)&i; - i64 s = 8*type_size_of(c->sizes, c->allocator, type); - u64 umax = ~0ull; - if (s < 64) { - umax = (1ull << s) - 1ull; - } else { - // TODO(bill): I NEED A PROPER BIG NUMBER LIBRARY THAT CAN SUPPORT 128 bit integers and floats - s = 64; - } - i64 imax = (1ll << (s-1ll)); - - - switch (type->Basic.kind) { - case Basic_i8: - case Basic_i16: - case Basic_i32: - case Basic_i64: - // case Basic_i128: - case Basic_int: - return gb_is_between(i, -imax, imax-1); - - case Basic_u8: - case Basic_u16: - case Basic_u32: - case Basic_u64: - // case Basic_u128: - case Basic_uint: - return !(u < 0 || u > umax); - - case Basic_UntypedInteger: - return true; - - default: GB_PANIC("Compiler error: Unknown integer type!"); break; - } - } else if (is_type_float(type)) { - ExactValue v = exact_value_to_float(in_value); - if (v.kind != ExactValue_Float) { - return false; - } - - switch (type->Basic.kind) { - // case Basic_f16: - case Basic_f32: - case Basic_f64: - // case Basic_f128: - if (out_value) *out_value = v; - return true; - - case Basic_UntypedFloat: - return true; - } - } else if (is_type_pointer(type)) { - if (in_value.kind == ExactValue_Pointer) { - return true; - } - if (in_value.kind == ExactValue_Integer) { - return true; - } - if (out_value) *out_value = in_value; - } - - - return false; -} - -void check_is_expressible(Checker *c, Operand *o, Type *type) { - GB_ASSERT(is_type_constant_type(type)); - GB_ASSERT(o->mode == Addressing_Constant); - if (!check_value_is_expressible(c, o->value, type, &o->value)) { - gbString a = expr_to_string(o->expr); - gbString b = type_to_string(type); - if (is_type_numeric(o->type) && is_type_numeric(type)) { - if (!is_type_integer(o->type) && is_type_integer(type)) { - error_node(o->expr, "`%s` truncated to `%s`", a, b); - } else { - error_node(o->expr, "`%s = %lld` overflows `%s`", a, o->value.value_integer, b); - } - } else { - error_node(o->expr, "Cannot convert `%s` to `%s`", a, b); - } - - gb_string_free(b); - gb_string_free(a); - o->mode = Addressing_Invalid; - } -} - -bool check_is_expr_vector_index(Checker *c, AstNode *expr) { - // HACK(bill): Handle this correctly. Maybe with a custom AddressingMode - expr = unparen_expr(expr); - if (expr->kind == AstNode_IndexExpr) { - ast_node(ie, IndexExpr, expr); - Type *t = type_deref(type_of_expr(&c->info, ie->expr)); - if (t != NULL) { - return is_type_vector(t); - } - } - return false; -} - -bool check_is_vector_elem(Checker *c, AstNode *expr) { - // HACK(bill): Handle this correctly. Maybe with a custom AddressingMode - expr = unparen_expr(expr); - if (expr->kind == AstNode_SelectorExpr) { - ast_node(se, SelectorExpr, expr); - Type *t = type_deref(type_of_expr(&c->info, se->expr)); - if (t != NULL && is_type_vector(t)) { - return true; - } - } - return false; -} - -void check_unary_expr(Checker *c, Operand *o, Token op, AstNode *node) { - switch (op.kind) { - case Token_Pointer: { // Pointer address - if (o->mode == Addressing_Type) { - o->type = make_type_pointer(c->allocator, o->type); - return; - } - - if (o->mode != Addressing_Variable || - check_is_expr_vector_index(c, o->expr) || - check_is_vector_elem(c, o->expr)) { - if (ast_node_expect(node, AstNode_UnaryExpr)) { - ast_node(ue, UnaryExpr, node); - gbString str = expr_to_string(ue->expr); - error(op, "Cannot take the pointer address of `%s`", str); - gb_string_free(str); - } - o->mode = Addressing_Invalid; - return; - } - o->mode = Addressing_Value; - o->type = make_type_pointer(c->allocator, o->type); - return; - } - - case Token_Maybe: { // Make maybe - Type *t = default_type(o->type); - - if (o->mode == Addressing_Type) { - o->type = make_type_pointer(c->allocator, t); - return; - } - - bool is_value = - o->mode == Addressing_Variable || - o->mode == Addressing_Value || - o->mode == Addressing_Constant; - - if (!is_value || is_type_untyped(t)) { - if (ast_node_expect(node, AstNode_UnaryExpr)) { - ast_node(ue, UnaryExpr, node); - gbString str = expr_to_string(ue->expr); - error(op, "Cannot convert `%s` to a maybe", str); - gb_string_free(str); - } - o->mode = Addressing_Invalid; - return; - } - o->mode = Addressing_Value; - o->type = make_type_maybe(c->allocator, t); - return; - } - } - - if (!check_unary_op(c, o, op)) { - o->mode = Addressing_Invalid; - return; - } - - if (o->mode == Addressing_Constant) { - Type *type = base_type(o->type); - if (!is_type_constant_type(o->type)) { - gbString xt = type_to_string(o->type); - gbString err_str = expr_to_string(node); - error(op, "Invalid type, `%s`, for constant unary expression `%s`", xt, err_str); - gb_string_free(err_str); - gb_string_free(xt); - o->mode = Addressing_Invalid; - return; - } - - - i32 precision = 0; - if (is_type_unsigned(type)) { - precision = cast(i32)(8 * type_size_of(c->sizes, c->allocator, type)); - } - o->value = exact_unary_operator_value(op.kind, o->value, precision); - - if (is_type_typed(type)) { - if (node != NULL) { - o->expr = node; - } - check_is_expressible(c, o, type); - } - return; - } - - o->mode = Addressing_Value; -} - -void check_comparison(Checker *c, Operand *x, Operand *y, Token op) { - gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&c->tmp_arena); - - gbString err_str = NULL; - - if (check_is_assignable_to(c, x, y->type) || - check_is_assignable_to(c, y, x->type)) { - Type *err_type = x->type; - bool defined = false; - switch (op.kind) { - case Token_CmpEq: - case Token_NotEq: - defined = is_type_comparable(x->type); - break; - case Token_Lt: - case Token_Gt: - case Token_LtEq: - case Token_GtEq: { - defined = is_type_ordered(x->type); - } break; - } - - // CLEANUP(bill) NOTE(bill): there is an auto assignment to `any` which needs to be checked - if (is_type_any(x->type) && !is_type_any(y->type)) { - err_type = x->type; - defined = false; - } else if (is_type_any(y->type) && !is_type_any(x->type)) { - err_type = y->type; - defined = false; - } - - if (!defined) { - gbString type_string = type_to_string(err_type); - err_str = gb_string_make(c->tmp_allocator, - gb_bprintf("operator `%.*s` not defined for type `%s`", LIT(op.string), type_string)); - gb_string_free(type_string); - } - } else { - gbString xt = type_to_string(x->type); - gbString yt = type_to_string(y->type); - err_str = gb_string_make(c->tmp_allocator, - gb_bprintf("mismatched types `%s` and `%s`", xt, yt)); - gb_string_free(yt); - gb_string_free(xt); - } - - if (err_str != NULL) { - error_node(x->expr, "Cannot compare expression, %s", err_str); - x->type = t_untyped_bool; - } else { - if (x->mode == Addressing_Constant && - y->mode == Addressing_Constant) { - x->value = make_exact_value_bool(compare_exact_values(op.kind, x->value, y->value)); - } else { - x->mode = Addressing_Value; - - update_expr_type(c, x->expr, default_type(x->type), true); - update_expr_type(c, y->expr, default_type(y->type), true); - } - - if (is_type_vector(base_type(y->type))) { - x->type = make_type_vector(c->allocator, t_bool, base_type(y->type)->Vector.count); - } else { - x->type = t_untyped_bool; - } - } - - if (err_str != NULL) { - gb_string_free(err_str); - }; - - gb_temp_arena_memory_end(tmp); -} - -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}; - if (x->mode == Addressing_Constant) { - x_val = exact_value_to_integer(x->value); - } - - bool x_is_untyped = is_type_untyped(x->type); - if (!(is_type_integer(base_enum_type(x->type)) || (x_is_untyped && x_val.kind == ExactValue_Integer))) { - gbString err_str = expr_to_string(x->expr); - error_node(node, "Shifted operand `%s` must be an integer", err_str); - gb_string_free(err_str); - x->mode = Addressing_Invalid; - return; - } - - if (is_type_unsigned(base_enum_type(y->type))) { - - } else if (is_type_untyped(y->type)) { - convert_to_typed(c, y, t_untyped_integer, 0); - if (y->mode == Addressing_Invalid) { - x->mode = Addressing_Invalid; - return; - } - } else { - gbString err_str = expr_to_string(y->expr); - error_node(node, "Shift amount `%s` must be an unsigned integer", err_str); - gb_string_free(err_str); - x->mode = Addressing_Invalid; - return; - } - - - if (x->mode == Addressing_Constant) { - if (y->mode == Addressing_Constant) { - ExactValue y_val = exact_value_to_integer(y->value); - if (y_val.kind != ExactValue_Integer) { - gbString err_str = expr_to_string(y->expr); - error_node(node, "Shift amount `%s` must be an unsigned integer", err_str); - gb_string_free(err_str); - x->mode = Addressing_Invalid; - return; - } - - u64 amount = cast(u64)y_val.value_integer; - if (amount > 1074) { - gbString err_str = expr_to_string(y->expr); - error_node(node, "Shift amount too large: `%s`", err_str); - gb_string_free(err_str); - x->mode = Addressing_Invalid; - return; - } - - if (!is_type_integer(base_enum_type(x->type))) { - // NOTE(bill): It could be an untyped float but still representable - // as an integer - x->type = t_untyped_integer; - } - - x->value = exact_value_shift(be->op.kind, x_val, make_exact_value_integer(amount)); - - if (is_type_typed(x->type)) { - check_is_expressible(c, x, base_type(base_enum_type(x->type))); - } - return; - } - - if (x_is_untyped) { - ExprInfo *info = map_expr_info_get(&c->info.untyped, hash_pointer(x->expr)); - if (info != NULL) { - info->is_lhs = true; - } - x->mode = Addressing_Value; - return; - } - } - - if (y->mode == Addressing_Constant && y->value.value_integer < 0) { - gbString err_str = expr_to_string(y->expr); - error_node(node, "Shift amount cannot be negative: `%s`", err_str); - gb_string_free(err_str); - } - - x->mode = Addressing_Value; -} - -bool check_is_castable_to(Checker *c, Operand *operand, Type *y) { - if (check_is_assignable_to(c, operand, y)) { - return true; - } - - Type *x = operand->type; - Type *xb = base_type(base_enum_type(x)); - Type *yb = base_type(base_enum_type(y)); - if (are_types_identical(xb, yb)) { - return true; - } - - - // Cast between booleans and integers - if (is_type_boolean(xb) || is_type_integer(xb)) { - if (is_type_boolean(yb) || is_type_integer(yb)) { - return true; - } - } - - // Cast between numbers - if (is_type_integer(xb) || is_type_float(xb)) { - if (is_type_integer(yb) || is_type_float(yb)) { - return true; - } - } - - // Cast between pointers - if (is_type_pointer(xb) && is_type_pointer(yb)) { - return true; - } - - // (u)int <-> pointer - if (is_type_int_or_uint(xb) && is_type_rawptr(yb)) { - return true; - } - if (is_type_rawptr(xb) && is_type_int_or_uint(yb)) { - return true; - } - - // []byte/[]u8 <-> string - if (is_type_u8_slice(xb) && is_type_string(yb)) { - return true; - } - if (is_type_string(xb) && is_type_u8_slice(yb)) { - if (is_type_typed(xb)) { - return true; - } - } - - // proc <-> proc - if (is_type_proc(xb) && is_type_proc(yb)) { - return true; - } - - // proc -> rawptr - if (is_type_proc(xb) && is_type_rawptr(yb)) { - return true; - } - // rawptr -> proc - if (is_type_rawptr(xb) && is_type_proc(yb)) { - return true; - } - - return false; -} - -String check_down_cast_name(Type *dst_, Type *src_) { - String result = {0}; - Type *dst = type_deref(dst_); - Type *src = type_deref(src_); - Type *dst_s = base_type(dst); - GB_ASSERT(is_type_struct(dst_s) || is_type_raw_union(dst_s)); - for (isize i = 0; i < dst_s->Record.field_count; i++) { - Entity *f = dst_s->Record.fields[i]; - GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field); - if (f->flags & EntityFlag_Anonymous) { - if (are_types_identical(f->type, src_)) { - return f->token.string; - } - if (are_types_identical(type_deref(f->type), src_)) { - return f->token.string; - } - - if (!is_type_pointer(f->type)) { - result = check_down_cast_name(f->type, src_); - if (result.len > 0) { - return result; - } - } - } - } - - return result; -} - -Operand check_ptr_addition(Checker *c, TokenKind op, Operand *ptr, Operand *offset, AstNode *node) { - GB_ASSERT(node->kind == AstNode_BinaryExpr); - ast_node(be, BinaryExpr, node); - GB_ASSERT(is_type_pointer(ptr->type)); - GB_ASSERT(is_type_integer(offset->type)); - GB_ASSERT(op == Token_Add || op == Token_Sub); - - Operand operand = {0}; - operand.mode = Addressing_Value; - operand.type = ptr->type; - operand.expr = node; - - if (base_type(ptr->type) == t_rawptr) { - gbString str = type_to_string(ptr->type); - error_node(node, "Invalid pointer type for pointer arithmetic: `%s`", str); - gb_string_free(str); - operand.mode = Addressing_Invalid; - return operand; - } - - - if (ptr->mode == Addressing_Constant && offset->mode == Addressing_Constant) { - i64 elem_size = type_size_of(c->sizes, c->allocator, ptr->type); - i64 ptr_val = ptr->value.value_pointer; - i64 offset_val = exact_value_to_integer(offset->value).value_integer; - i64 new_ptr_val = ptr_val; - if (op == Token_Add) { - new_ptr_val += elem_size*offset_val; - } else { - new_ptr_val -= elem_size*offset_val; - } - operand.mode = Addressing_Constant; - operand.value = make_exact_value_pointer(new_ptr_val); - } - - return operand; -} - -void check_binary_expr(Checker *c, Operand *x, AstNode *node) { - GB_ASSERT(node->kind == AstNode_BinaryExpr); - Operand y_ = {0}, *y = &y_; - - ast_node(be, BinaryExpr, node); - - if (be->op.kind == Token_as) { - check_expr(c, x, be->left); - Type *type = check_type(c, be->right); - if (x->mode == Addressing_Invalid) { - return; - } - - bool is_const_expr = x->mode == Addressing_Constant; - bool can_convert = false; - - Type *bt = base_type(type); - if (is_const_expr && is_type_constant_type(bt)) { - if (bt->kind == Type_Basic) { - if (check_value_is_expressible(c, x->value, bt, &x->value)) { - can_convert = true; - } - } - } else if (check_is_castable_to(c, x, type)) { - if (x->mode != Addressing_Constant) { - x->mode = Addressing_Value; - } - can_convert = true; - } - - if (!can_convert) { - gbString expr_str = expr_to_string(x->expr); - gbString to_type = type_to_string(type); - gbString from_type = type_to_string(x->type); - error_node(x->expr, "Cannot cast `%s` as `%s` from `%s`", expr_str, to_type, from_type); - gb_string_free(from_type); - gb_string_free(to_type); - gb_string_free(expr_str); - - x->mode = Addressing_Invalid; - return; - } - - if (is_type_untyped(x->type)) { - Type *final_type = type; - if (is_const_expr && !is_type_constant_type(type)) { - final_type = default_type(x->type); - } - update_expr_type(c, x->expr, final_type, true); - } - - x->type = type; - return; - } else if (be->op.kind == Token_transmute) { - check_expr(c, x, be->left); - Type *type = check_type(c, be->right); - if (x->mode == Addressing_Invalid) { - return; - } - - if (x->mode == Addressing_Constant) { - gbString expr_str = expr_to_string(x->expr); - error_node(x->expr, "Cannot transmute constant expression: `%s`", expr_str); - gb_string_free(expr_str); - x->mode = Addressing_Invalid; - return; - } - - if (is_type_untyped(x->type)) { - gbString expr_str = expr_to_string(x->expr); - error_node(x->expr, "Cannot transmute untyped expression: `%s`", expr_str); - gb_string_free(expr_str); - x->mode = Addressing_Invalid; - return; - } - - i64 srcz = type_size_of(c->sizes, c->allocator, x->type); - i64 dstz = type_size_of(c->sizes, c->allocator, type); - if (srcz != dstz) { - gbString expr_str = expr_to_string(x->expr); - gbString type_str = type_to_string(type); - error_node(x->expr, "Cannot transmute `%s` to `%s`, %lld vs %lld bytes", expr_str, type_str, srcz, dstz); - gb_string_free(type_str); - gb_string_free(expr_str); - x->mode = Addressing_Invalid; - return; - } - - x->type = type; - - return; - } else if (be->op.kind == Token_down_cast) { - check_expr(c, x, be->left); - Type *type = check_type(c, be->right); - if (x->mode == Addressing_Invalid) { - return; - } - - if (x->mode == Addressing_Constant) { - gbString expr_str = expr_to_string(node); - error_node(node, "Cannot `down_cast` a constant expression: `%s`", expr_str); - gb_string_free(expr_str); - x->mode = Addressing_Invalid; - return; - } - - if (is_type_untyped(x->type)) { - gbString expr_str = expr_to_string(node); - error_node(node, "Cannot `down_cast` an untyped expression: `%s`", expr_str); - gb_string_free(expr_str); - x->mode = Addressing_Invalid; - return; - } - - if (!(is_type_pointer(x->type) && is_type_pointer(type))) { - gbString expr_str = expr_to_string(node); - error_node(node, "Can only `down_cast` pointers: `%s`", expr_str); - gb_string_free(expr_str); - x->mode = Addressing_Invalid; - return; - } - - Type *src = type_deref(x->type); - Type *dst = type_deref(type); - Type *bsrc = base_type(src); - Type *bdst = base_type(dst); - - if (!(is_type_struct(bsrc) || is_type_raw_union(bsrc))) { - gbString expr_str = expr_to_string(node); - error_node(node, "Can only `down_cast` pointer from structs or unions: `%s`", expr_str); - gb_string_free(expr_str); - x->mode = Addressing_Invalid; - return; - } - - if (!(is_type_struct(bdst) || is_type_raw_union(bdst))) { - gbString expr_str = expr_to_string(node); - error_node(node, "Can only `down_cast` pointer to structs or unions: `%s`", expr_str); - gb_string_free(expr_str); - x->mode = Addressing_Invalid; - return; - } - - String param_name = check_down_cast_name(dst, src); - if (param_name.len == 0) { - gbString expr_str = expr_to_string(node); - error_node(node, "Illegal `down_cast`: `%s`", expr_str); - gb_string_free(expr_str); - x->mode = Addressing_Invalid; - return; - } - - x->mode = Addressing_Value; - x->type = type; - return; - } else if (be->op.kind == Token_union_cast) { - check_expr(c, x, be->left); - Type *type = check_type(c, be->right); - if (x->mode == Addressing_Invalid) { - return; - } - - if (x->mode == Addressing_Constant) { - gbString expr_str = expr_to_string(node); - error_node(node, "Cannot `union_cast` a constant expression: `%s`", expr_str); - gb_string_free(expr_str); - x->mode = Addressing_Invalid; - return; - } - - if (is_type_untyped(x->type)) { - gbString expr_str = expr_to_string(node); - error_node(node, "Cannot `union_cast` an untyped expression: `%s`", expr_str); - gb_string_free(expr_str); - x->mode = Addressing_Invalid; - return; - } - - bool src_is_ptr = is_type_pointer(x->type); - bool dst_is_ptr = is_type_pointer(type); - Type *src = type_deref(x->type); - Type *dst = type_deref(type); - Type *bsrc = base_type(src); - Type *bdst = base_type(dst); - - if (src_is_ptr != dst_is_ptr) { - gbString src_type_str = type_to_string(x->type); - gbString dst_type_str = type_to_string(type); - error_node(node, "Invalid `union_cast` types: `%s` and `%s`", src_type_str, dst_type_str); - gb_string_free(dst_type_str); - gb_string_free(src_type_str); - x->mode = Addressing_Invalid; - return; - } - - if (!is_type_union(src)) { - error_node(node, "`union_cast` can only operate on unions"); - x->mode = Addressing_Invalid; - return; - } - - bool ok = false; - for (isize i = 1; i < bsrc->Record.field_count; i++) { - Entity *f = bsrc->Record.fields[i]; - if (are_types_identical(f->type, dst)) { - ok = true; - break; - } - } - - if (!ok) { - gbString expr_str = expr_to_string(node); - gbString dst_type_str = type_to_string(type); - error_node(node, "Cannot `union_cast` `%s` to `%s`", expr_str, dst_type_str); - gb_string_free(dst_type_str); - gb_string_free(expr_str); - x->mode = Addressing_Invalid; - return; - } - - Entity **variables = gb_alloc_array(c->allocator, Entity *, 2); - variables[0] = make_entity_param(c->allocator, NULL, empty_token, type, false); - variables[1] = make_entity_param(c->allocator, NULL, empty_token, t_bool, false); - - Type *tuple = make_type_tuple(c->allocator); - tuple->Tuple.variables = variables; - tuple->Tuple.variable_count = 2; - - x->type = tuple; - x->mode = Addressing_Value; - return; - } - - check_expr(c, x, be->left); - check_expr(c, y, be->right); - if (x->mode == Addressing_Invalid) { - return; - } - if (y->mode == Addressing_Invalid) { - x->mode = Addressing_Invalid; - x->expr = y->expr; - return; - } - - Token op = be->op; - - if (token_is_shift(op)) { - check_shift(c, x, y, node); - return; - } - - if (op.kind == Token_Add || op.kind == Token_Sub) { - if (is_type_pointer(x->type) && is_type_integer(base_enum_type(y->type))) { - *x = check_ptr_addition(c, op.kind, x, y, node); - return; - } else if (is_type_integer(base_enum_type(x->type)) && is_type_pointer(y->type)) { - if (op.kind == Token_Sub) { - gbString lhs = expr_to_string(x->expr); - gbString rhs = expr_to_string(y->expr); - error_node(node, "Invalid pointer arithmetic, did you mean `%s %.*s %s`?", rhs, LIT(op.string), lhs); - gb_string_free(rhs); - gb_string_free(lhs); - x->mode = Addressing_Invalid; - return; - } - *x = check_ptr_addition(c, op.kind, y, x, node); - return; - } - } - - - convert_to_typed(c, x, y->type, 0); - if (x->mode == Addressing_Invalid) { - return; - } - convert_to_typed(c, y, x->type, 0); - if (y->mode == Addressing_Invalid) { - x->mode = Addressing_Invalid; - return; - } - - if (token_is_comparison(op)) { - check_comparison(c, x, y, op); - return; - } - - if (!are_types_identical(x->type, y->type)) { - if (x->type != t_invalid && - y->type != t_invalid) { - gbString xt = type_to_string(x->type); - gbString yt = type_to_string(y->type); - gbString expr_str = expr_to_string(x->expr); - error(op, "Mismatched types in binary expression `%s` : `%s` vs `%s`", expr_str, xt, yt); - gb_string_free(expr_str); - gb_string_free(yt); - gb_string_free(xt); - } - x->mode = Addressing_Invalid; - return; - } - - if (!check_binary_op(c, x, op)) { - x->mode = Addressing_Invalid; - return; - } - - switch (op.kind) { - case Token_Quo: - case Token_Mod: - case Token_QuoEq: - case Token_ModEq: - if ((x->mode == Addressing_Constant || is_type_integer(x->type)) && - y->mode == Addressing_Constant) { - bool fail = false; - switch (y->value.kind) { - case ExactValue_Integer: - if (y->value.value_integer == 0) { - fail = true; - } - break; - case ExactValue_Float: - if (y->value.value_float == 0.0) { - fail = true; - } - break; - } - - if (fail) { - error_node(y->expr, "Division by zero not allowed"); - x->mode = Addressing_Invalid; - return; - } - } - } - - if (x->mode == Addressing_Constant && - y->mode == Addressing_Constant) { - ExactValue a = x->value; - ExactValue b = y->value; - - Type *type = base_type(x->type); - if (is_type_pointer(type)) { - GB_ASSERT(op.kind == Token_Sub); - i64 bytes = a.value_pointer - b.value_pointer; - i64 diff = bytes/type_size_of(c->sizes, c->allocator, type); - x->value = make_exact_value_pointer(diff); - return; - } - - if (!is_type_constant_type(type)) { - gbString xt = type_to_string(x->type); - gbString err_str = expr_to_string(node); - error(op, "Invalid type, `%s`, for constant binary expression `%s`", xt, err_str); - gb_string_free(err_str); - gb_string_free(xt); - x->mode = Addressing_Invalid; - return; - } - - if (op.kind == Token_Quo && is_type_integer(type)) { - op.kind = Token_QuoEq; // NOTE(bill): Hack to get division of integers - } - x->value = exact_binary_operator_value(op.kind, a, b); - if (is_type_typed(type)) { - if (node != NULL) { - x->expr = node; - } - check_is_expressible(c, x, type); - } - return; - } - - x->mode = Addressing_Value; -} - - -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); - if (found == NULL) { - return; - } - - switch (e->kind) { - case_ast_node(ue, UnaryExpr, e); - if (found->value.kind != ExactValue_Invalid) { - break; - } - update_expr_type(c, ue->expr, type, final); - case_end; - - case_ast_node(be, BinaryExpr, e); - if (found->value.kind != ExactValue_Invalid) { - break; - } - if (!token_is_comparison(be->op)) { - if (token_is_shift(be->op)) { - update_expr_type(c, be->left, type, final); - } else { - update_expr_type(c, be->left, type, final); - update_expr_type(c, be->right, type, final); - } - } - case_end; - } - - if (!final && is_type_untyped(type)) { - found->type = base_type(type); - map_expr_info_set(&c->info.untyped, key, *found); - } else { - ExprInfo old = *found; - map_expr_info_remove(&c->info.untyped, key); - - if (old.is_lhs && !is_type_integer(type)) { - gbString expr_str = expr_to_string(e); - gbString type_str = type_to_string(type); - error_node(e, "Shifted operand %s must be an integer, got %s", expr_str, type_str); - gb_string_free(type_str); - gb_string_free(expr_str); - return; - } - - add_type_and_value(&c->info, e, found->mode, type, found->value); - } -} - -void update_expr_value(Checker *c, AstNode *e, ExactValue value) { - ExprInfo *found = map_expr_info_get(&c->info.untyped, hash_pointer(e)); - if (found) { - found->value = value; - } -} - -void convert_untyped_error(Checker *c, Operand *operand, Type *target_type) { - gbString expr_str = expr_to_string(operand->expr); - gbString type_str = type_to_string(target_type); - char *extra_text = ""; - - if (operand->mode == Addressing_Constant) { - if (operand->value.value_integer == 0) { - if (str_ne(make_string_c(expr_str), str_lit("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`?"; - } - } - } - error_node(operand->expr, "Cannot convert `%s` to `%s`%s", expr_str, type_str, extra_text); - - gb_string_free(type_str); - gb_string_free(expr_str); - operand->mode = Addressing_Invalid; -} - -// NOTE(bill): Set initial level to 0 -void convert_to_typed(Checker *c, Operand *operand, Type *target_type, i32 level) { - GB_ASSERT_NOT_NULL(target_type); - if (operand->mode == Addressing_Invalid || - is_type_typed(operand->type) || - target_type == t_invalid) { - return; - } - - if (is_type_untyped(target_type)) { - GB_ASSERT(operand->type->kind == Type_Basic); - GB_ASSERT(target_type->kind == Type_Basic); - BasicKind x_kind = operand->type->Basic.kind; - BasicKind y_kind = target_type->Basic.kind; - if (is_type_numeric(operand->type) && is_type_numeric(target_type)) { - if (x_kind < y_kind) { - operand->type = target_type; - update_expr_type(c, operand->expr, target_type, false); - } - } else if (x_kind != y_kind) { - convert_untyped_error(c, operand, target_type); - } - return; - } - - Type *t = base_type(base_enum_type(target_type)); - switch (t->kind) { - case Type_Basic: - if (operand->mode == Addressing_Constant) { - check_is_expressible(c, operand, t); - if (operand->mode == Addressing_Invalid) { - return; - } - update_expr_value(c, operand->expr, operand->value); - } else { - switch (operand->type->Basic.kind) { - case Basic_UntypedBool: - if (!is_type_boolean(target_type)) { - convert_untyped_error(c, operand, target_type); - return; - } - break; - case Basic_UntypedInteger: - case Basic_UntypedFloat: - case Basic_UntypedRune: - if (!is_type_numeric(target_type)) { - convert_untyped_error(c, operand, target_type); - return; - } - break; - - case Basic_UntypedNil: - if (!type_has_nil(target_type)) { - convert_untyped_error(c, operand, target_type); - return; - } - break; - } - } - break; - - case Type_Maybe: - if (is_type_untyped_nil(operand->type)) { - // Okay - } else if (level == 0) { - convert_to_typed(c, operand, t->Maybe.elem, level+1); - return; - } - - default: - if (!is_type_untyped_nil(operand->type) || !type_has_nil(target_type)) { - convert_untyped_error(c, operand, target_type); - return; - } - break; - } - - - - operand->type = target_type; -} - -bool check_index_value(Checker *c, AstNode *index_value, i64 max_count, i64 *value) { - Operand operand = {Addressing_Invalid}; - check_expr(c, &operand, index_value); - if (operand.mode == Addressing_Invalid) { - if (value) *value = 0; - return false; - } - - convert_to_typed(c, &operand, t_int, 0); - if (operand.mode == Addressing_Invalid) { - if (value) *value = 0; - return false; - } - - if (!is_type_integer(base_enum_type(operand.type))) { - gbString expr_str = expr_to_string(operand.expr); - error_node(operand.expr, "Index `%s` must be an integer", expr_str); - gb_string_free(expr_str); - if (value) *value = 0; - return false; - } - - if (operand.mode == Addressing_Constant && - (c->context.stmt_state_flags & StmtStateFlag_bounds_check) != 0) { - i64 i = exact_value_to_integer(operand.value).value_integer; - if (i < 0) { - gbString expr_str = expr_to_string(operand.expr); - error_node(operand.expr, "Index `%s` cannot be a negative value", expr_str); - gb_string_free(expr_str); - if (value) *value = 0; - return false; - } - - if (max_count >= 0) { // NOTE(bill): Do array bound checking - if (value) *value = i; - if (i >= max_count) { - gbString expr_str = expr_to_string(operand.expr); - error_node(operand.expr, "Index `%s` is out of bounds range 0..<%lld", expr_str, max_count); - gb_string_free(expr_str); - return false; - } - - return true; - } - } - - // NOTE(bill): It's alright :D - if (value) *value = -1; - return true; -} - -Entity *check_selector(Checker *c, Operand *operand, AstNode *node) { - ast_node(se, SelectorExpr, node); - - 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 - - AstNode *op_expr = se->expr; - AstNode *selector = unparen_expr(se->selector); - if (selector == NULL) { - goto error; - } - - if (ast_node_expect(selector, AstNode_Ident)) { - - } - - if (op_expr->kind == AstNode_Ident) { - String name = op_expr->Ident.string; - Entity *e = scope_lookup_entity(c->context.scope, name); - add_entity_use(c, op_expr, e); - expr_entity = e; - if (e != NULL && e->kind == Entity_ImportName && - selector->kind == AstNode_Ident) { - String sel_name = selector->Ident.string; - check_op_expr = false; - entity = scope_lookup_entity(e->ImportName.scope, sel_name); - if (entity == NULL) { - error_node(op_expr, "`%.*s` is not declared by `%.*s`", LIT(sel_name), LIT(name)); - goto error; - } - if (entity->type == NULL) { // Not setup yet - check_entity_decl(c, entity, NULL, NULL); - } - GB_ASSERT(entity->type != NULL); - - b32 is_not_exported = true; - Entity **found = map_entity_get(&e->ImportName.scope->implicit, hash_string(sel_name)); - if (found == NULL) { - is_not_exported = false; - } else { - Entity *f = *found; - if (f->kind == Entity_ImportName) { - is_not_exported = true; - } - } - - if (is_not_exported) { - gbString sel_str = expr_to_string(selector); - error_node(op_expr, "`%s` is not exported by `%.*s`", sel_str, LIT(name)); - gb_string_free(sel_str); - // NOTE(bill): Not really an error so don't goto error - } - - add_entity_use(c, selector, entity); - } - } - if (check_op_expr) { - check_expr_base(c, operand, op_expr, NULL); - if (operand->mode == Addressing_Invalid) { - goto error; - } - } - - - if (entity == NULL && selector->kind == AstNode_Ident) { - sel = lookup_field(c->allocator, operand->type, selector->Ident.string, operand->mode == Addressing_Type); - entity = sel.entity; - } - if (entity == NULL) { - gbString op_str = expr_to_string(op_expr); - gbString type_str = type_to_string(operand->type); - gbString sel_str = expr_to_string(selector); - error_node(op_expr, "`%s` (`%s`) has no field `%s`", op_str, type_str, sel_str); - gb_string_free(sel_str); - gb_string_free(type_str); - gb_string_free(op_str); - goto error; - } - - if (expr_entity != NULL && expr_entity->kind == Entity_Constant && entity->kind != Entity_Constant) { - gbString op_str = expr_to_string(op_expr); - gbString type_str = type_to_string(operand->type); - gbString sel_str = expr_to_string(selector); - error_node(op_expr, "Cannot access non-constant field `%s` from `%s`", sel_str, op_str); - gb_string_free(sel_str); - gb_string_free(type_str); - gb_string_free(op_str); - goto error; - } - - - add_entity_use(c, selector, entity); - - switch (entity->kind) { - case Entity_Constant: - operand->mode = Addressing_Constant; - operand->value = entity->Constant.value; - break; - case Entity_Variable: - // TODO(bill): This is the rule I need? - if (sel.indirect || operand->mode != Addressing_Value) { - operand->mode = Addressing_Variable; - } - break; - case Entity_TypeName: - operand->mode = Addressing_Type; - break; - case Entity_Procedure: - operand->mode = Addressing_Value; - break; - case Entity_Builtin: - operand->mode = Addressing_Builtin; - operand->builtin_id = entity->Builtin.id; - break; - - // NOTE(bill): These cases should never be hit but are here for sanity reasons - case Entity_Nil: - operand->mode = Addressing_Value; - break; - case Entity_ImplicitValue: - operand->mode = Addressing_Value; - break; - } - - operand->type = entity->type; - operand->expr = node; - - return entity; - -error: - operand->mode = Addressing_Invalid; - operand->expr = node; - return NULL; -} - -bool check_builtin_procedure(Checker *c, Operand *operand, AstNode *call, i32 id) { - GB_ASSERT(call->kind == AstNode_CallExpr); - ast_node(ce, CallExpr, call); - BuiltinProc *bp = &builtin_procs[id]; - { - char *err = NULL; - if (ce->args.count < bp->arg_count) { - err = "Too few"; - } else if (ce->args.count > bp->arg_count && !bp->variadic) { - err = "Too many"; - } - - if (err) { - ast_node(proc, Ident, ce->proc); - error(ce->close, "`%s` arguments for `%.*s`, expected %td, got %td", - err, LIT(proc->string), - bp->arg_count, ce->args.count); - return false; - } - } - - switch (id) { - case BuiltinProc_new: - case BuiltinProc_new_slice: - case BuiltinProc_size_of: - case BuiltinProc_align_of: - case BuiltinProc_offset_of: - case BuiltinProc_type_info: - // 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]); - } - - switch (id) { - default: - GB_PANIC("Implement builtin procedure: %.*s", LIT(builtin_procs[id].name)); - break; - - case BuiltinProc_new: { - // new :: proc(Type) -> ^Type - Operand op = {0}; - check_expr_or_type(c, &op, ce->args.e[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`"); - return false; - } - operand->mode = Addressing_Value; - operand->type = make_type_pointer(c->allocator, type); - } break; - case BuiltinProc_new_slice: { - // new_slice :: proc(Type, len: int) -> []Type - Operand op = {0}; - check_expr_or_type(c, &op, ce->args.e[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`"); - return false; - } - - check_expr(c, &op, ce->args.e[1]); - if (op.mode == Addressing_Invalid) { - return false; - } - if (!is_type_integer(base_enum_type(op.type))) { - gbString type_str = type_to_string(op.type); - error_node(call, "Length for `new_slice` must be an integer, got `%s`", type_str); - gb_string_free(type_str); - return false; - } - - operand->mode = Addressing_Value; - operand->type = make_type_slice(c->allocator, type); - } break; - - case BuiltinProc_size_of: { - // size_of :: proc(Type) -> untyped int - Type *type = check_type(c, ce->args.e[0]); - if (type == NULL || type == t_invalid) { - error_node(ce->args.e[0], "Expected a type for `size_of`"); - return false; - } - - operand->mode = Addressing_Constant; - operand->value = make_exact_value_integer(type_size_of(c->sizes, c->allocator, type)); - operand->type = t_untyped_integer; - - } break; - - case BuiltinProc_size_of_val: - // size_of_val :: proc(val: Type) -> untyped int - check_assignment(c, operand, NULL, str_lit("argument of `size_of_val`")); - if (operand->mode == Addressing_Invalid) { - return false; - } - - operand->mode = Addressing_Constant; - operand->value = make_exact_value_integer(type_size_of(c->sizes, c->allocator, operand->type)); - operand->type = t_untyped_integer; - break; - - case BuiltinProc_align_of: { - // align_of :: proc(Type) -> untyped int - Type *type = check_type(c, ce->args.e[0]); - if (type == NULL || type == t_invalid) { - error_node(ce->args.e[0], "Expected a type for `align_of`"); - return false; - } - operand->mode = Addressing_Constant; - operand->value = make_exact_value_integer(type_align_of(c->sizes, c->allocator, type)); - operand->type = t_untyped_integer; - } break; - - case BuiltinProc_align_of_val: - // align_of_val :: proc(val: Type) -> untyped int - check_assignment(c, operand, NULL, str_lit("argument of `align_of_val`")); - if (operand->mode == Addressing_Invalid) { - return false; - } - - operand->mode = Addressing_Constant; - operand->value = make_exact_value_integer(type_align_of(c->sizes, c->allocator, operand->type)); - operand->type = t_untyped_integer; - break; - - case BuiltinProc_offset_of: { - // offset_of :: proc(Type, field) -> untyped int - Operand op = {0}; - Type *bt = check_type(c, ce->args.e[0]); - Type *type = base_type(bt); - if (type == NULL || type == t_invalid) { - error_node(ce->args.e[0], "Expected a type for `offset_of`"); - return false; - } - - AstNode *field_arg = unparen_expr(ce->args.e[1]); - if (field_arg == NULL || - field_arg->kind != AstNode_Ident) { - error_node(field_arg, "Expected an identifier for field argument"); - return false; - } - if (is_type_array(type) || is_type_vector(type)) { - error_node(field_arg, "Invalid type for `offset_of`"); - return false; - } - - - ast_node(arg, Ident, field_arg); - 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], - "`%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], - "Field `%.*s` is embedded via a pointer in `%s`", LIT(arg->string), type_str); - gb_string_free(type_str); - return false; - } - - operand->mode = Addressing_Constant; - operand->value = make_exact_value_integer(type_offset_of_from_selection(c->sizes, c->allocator, type, sel)); - operand->type = t_untyped_integer; - } break; - - case BuiltinProc_offset_of_val: { - // offset_of_val :: proc(val: expression) -> untyped int - AstNode *arg = unparen_expr(ce->args.e[0]); - if (arg->kind != AstNode_SelectorExpr) { - gbString str = expr_to_string(arg); - error_node(arg, "`%s` is not a selector expression", str); - return false; - } - ast_node(s, SelectorExpr, arg); - - check_expr(c, operand, s->expr); - if (operand->mode == Addressing_Invalid) { - return false; - } - - Type *type = operand->type; - if (base_type(type)->kind == Type_Pointer) { - Type *p = base_type(type); - if (is_type_struct(p)) { - type = p->Pointer.elem; - } - } - if (is_type_array(type) || is_type_vector(type)) { - error_node(arg, "Invalid type for `offset_of_val`"); - return false; - } - - ast_node(i, Ident, s->selector); - Selection sel = lookup_field(c->allocator, type, i->string, operand->mode == Addressing_Type); - if (sel.entity == NULL) { - gbString type_str = type_to_string(type); - error_node(arg, - "`%s` has no field named `%.*s`", type_str, LIT(i->string)); - return false; - } - if (sel.indirect) { - gbString type_str = type_to_string(type); - error_node(ce->args.e[0], - "Field `%.*s` is embedded via a pointer in `%s`", LIT(i->string), type_str); - gb_string_free(type_str); - return false; - } - - operand->mode = Addressing_Constant; - // IMPORTANT TODO(bill): Fix for anonymous fields - operand->value = make_exact_value_integer(type_offset_of_from_selection(c->sizes, c->allocator, type, sel)); - operand->type = t_untyped_integer; - } break; - - case BuiltinProc_type_of_val: - // type_of_val :: proc(val: Type) -> type(Type) - check_assignment(c, operand, NULL, str_lit("argument of `type_of_val`")); - if (operand->mode == Addressing_Invalid || operand->mode == Addressing_Builtin) { - return false; - } - operand->mode = Addressing_Type; - break; - - - case BuiltinProc_type_info: { - // type_info :: proc(Type) -> ^Type_Info - if (c->context.scope->is_global) { - compiler_error("`type_info` Cannot be declared within a #shared_global_scope due to how the internals of the compiler works"); - } - - // NOTE(bill): The type information may not be setup yet - init_preload(c); - AstNode *expr = ce->args.e[0]; - Type *type = check_type(c, expr); - if (type == NULL || type == t_invalid) { - error_node(expr, "Invalid argument to `type_info`"); - return false; - } - - add_type_info_type(c, type); - - operand->mode = Addressing_Value; - operand->type = t_type_info_ptr; - } break; - - case BuiltinProc_type_info_of_val: { - // type_info_of_val :: proc(val: Type) -> ^Type_Info - if (c->context.scope->is_global) { - compiler_error("`type_info` Cannot be declared within a #shared_global_scope due to how the internals of the compiler works"); - } - - // NOTE(bill): The type information may not be setup yet - init_preload(c); - AstNode *expr = ce->args.e[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; - add_type_info_type(c, operand->type); - - operand->mode = Addressing_Value; - operand->type = t_type_info_ptr; - } break; - - - - case BuiltinProc_compile_assert: - // compile_assert :: proc(cond: bool) - - if (!is_type_boolean(operand->type) && operand->mode != Addressing_Constant) { - gbString str = expr_to_string(ce->args.e[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]); - error_node(call, "Compile time assertion: `%s`", str); - gb_string_free(str); - } - break; - - case BuiltinProc_assert: - // assert :: proc(cond: bool) - - if (!is_type_boolean(operand->type)) { - gbString str = expr_to_string(ce->args.e[0]); - error_node(call, "`%s` is not a boolean", str); - gb_string_free(str); - return false; - } - - operand->mode = Addressing_NoValue; - break; - - case BuiltinProc_panic: - // panic :: proc(msg: string) - - if (!is_type_string(operand->type)) { - gbString str = expr_to_string(ce->args.e[0]); - error_node(call, "`%s` is not a string", str); - gb_string_free(str); - return false; - } - - operand->mode = Addressing_NoValue; - break; - - case BuiltinProc_copy: { - // copy :: proc(x, y: []Type) -> int - Type *dest_type = NULL, *src_type = NULL; - - Type *d = base_type(operand->type); - if (d->kind == Type_Slice) { - dest_type = d->Slice.elem; - } - Operand op = {0}; - check_expr(c, &op, ce->args.e[1]); - if (op.mode == Addressing_Invalid) { - return false; - } - Type *s = base_type(op.type); - if (s->kind == Type_Slice) { - src_type = s->Slice.elem; - } - - if (dest_type == NULL || src_type == NULL) { - error_node(call, "`copy` only expects slices as arguments"); - return false; - } - - 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_str = type_to_string(dest_type); - gbString s_str = type_to_string(src_type); - error_node(call, - "Arguments to `copy`, %s, %s, have different elem types: %s vs %s", - d_arg, s_arg, d_str, s_str); - gb_string_free(s_str); - gb_string_free(d_str); - gb_string_free(s_arg); - gb_string_free(d_arg); - return false; - } - - operand->type = t_int; // Returns number of elems copied - operand->mode = Addressing_Value; - } break; - - #if 0 - case BuiltinProc_append: { - // append :: proc(x : ^[]Type, y : Type) -> bool - Type *x_type = NULL, *y_type = NULL; - x_type = base_type(operand->type); - - Operand op = {0}; - check_expr(c, &op, ce->args.e[1]); - if (op.mode == Addressing_Invalid) { - return false; - } - y_type = base_type(op.type); - - if (!(is_type_pointer(x_type) && is_type_slice(x_type->Pointer.elem))) { - error_node(call, "First argument to `append` must be a pointer to a slice"); - return false; - } - - Type *elem_type = x_type->Pointer.elem->Slice.elem; - if (!check_is_assignable_to(c, &op, elem_type)) { - gbString d_arg = expr_to_string(ce->args.e[0]); - gbString s_arg = expr_to_string(ce->args.e[1]); - gbString d_str = type_to_string(elem_type); - gbString s_str = type_to_string(y_type); - error_node(call, - "Arguments to `append`, %s, %s, have different element types: %s vs %s", - d_arg, s_arg, d_str, s_str); - gb_string_free(s_str); - gb_string_free(d_str); - gb_string_free(s_arg); - gb_string_free(d_arg); - return false; - } - - operand->type = t_bool; // Returns if it was successful - operand->mode = Addressing_Value; - } break; - #endif - - case BuiltinProc_swizzle: { - // swizzle :: proc(v: {N}T, T...) -> {M}T - Type *vector_type = base_type(operand->type); - if (!is_type_vector(vector_type)) { - gbString type_str = type_to_string(operand->type); - error_node(call, - "You can only `swizzle` a vector, got `%s`", - type_str); - gb_string_free(type_str); - return false; - } - - isize max_count = vector_type->Vector.count; - isize arg_count = 0; - for_array(i, ce->args) { - if (i == 0) { - continue; - } - AstNode *arg = ce->args.e[i]; - Operand op = {0}; - check_expr(c, &op, arg); - if (op.mode == Addressing_Invalid) { - return false; - } - Type *arg_type = base_type(op.type); - if (!is_type_integer(arg_type) || op.mode != Addressing_Constant) { - error_node(op.expr, "Indices to `swizzle` must be constant integers"); - return false; - } - - if (op.value.value_integer < 0) { - error_node(op.expr, "Negative `swizzle` index"); - return false; - } - - if (max_count <= op.value.value_integer) { - error_node(op.expr, "`swizzle` index exceeds vector length"); - return false; - } - - arg_count++; - } - - if (arg_count > max_count) { - error_node(call, "Too many `swizzle` indices, %td > %td", arg_count, max_count); - return false; - } - - Type *elem_type = vector_type->Vector.elem; - operand->type = make_type_vector(c->allocator, elem_type, arg_count); - operand->mode = Addressing_Value; - } break; - -#if 0 - case BuiltinProc_ptr_offset: { - // ptr_offset :: proc(ptr: ^T, offset: int) -> ^T - // ^T cannot be rawptr - Type *ptr_type = base_type(operand->type); - if (!is_type_pointer(ptr_type)) { - gbString type_str = type_to_string(operand->type); - defer (gb_string_free(type_str)); - error_node(call, - "Expected a pointer to `ptr_offset`, got `%s`", - type_str); - return false; - } - - if (ptr_type == t_rawptr) { - error_node(call, - "`rawptr` cannot have pointer arithmetic"); - return false; - } - - AstNode *offset = ce->args.e[1]; - Operand op = {0}; - check_expr(c, &op, offset); - if (op.mode == Addressing_Invalid) - return false; - Type *offset_type = base_type(op.type); - if (!is_type_integer(offset_type)) { - error_node(op.expr, "Pointer offsets for `ptr_offset` must be an integer"); - return false; - } - - if (operand->mode == Addressing_Constant && - op.mode == Addressing_Constant) { - i64 ptr = operand->value.value_pointer; - i64 elem_size = type_size_of(c->sizes, c->allocator, ptr_type->Pointer.elem); - ptr += elem_size * op.value.value_integer; - operand->value.value_pointer = ptr; - } else { - operand->mode = Addressing_Value; - } - - } break; - - case BuiltinProc_ptr_sub: { - // ptr_sub :: proc(a, b: ^T) -> int - // ^T cannot be rawptr - Type *ptr_type = base_type(operand->type); - if (!is_type_pointer(ptr_type)) { - gbString type_str = type_to_string(operand->type); - defer (gb_string_free(type_str)); - error_node(call, - "Expected a pointer to `ptr_add`, got `%s`", - type_str); - return false; - } - - if (ptr_type == t_rawptr) { - error_node(call, - "`rawptr` cannot have pointer arithmetic"); - return false; - } - AstNode *offset = ce->args[1]; - Operand op = {0}; - check_expr(c, &op, offset); - if (op.mode == Addressing_Invalid) - return false; - if (!is_type_pointer(op.type)) { - gbString type_str = type_to_string(operand->type); - defer (gb_string_free(type_str)); - error_node(call, - "Expected a pointer to `ptr_add`, got `%s`", - type_str); - return false; - } - - if (base_type(op.type) == t_rawptr) { - error_node(call, - "`rawptr` cannot have pointer arithmetic"); - return false; - } - - if (!are_types_identical(operand->type, op.type)) { - gbString a = type_to_string(operand->type); - gbString b = type_to_string(op.type); - defer (gb_string_free(a)); - defer (gb_string_free(b)); - error_node(op.expr, - "`ptr_sub` requires to pointer of the same type. Got `%s` and `%s`.", a, b); - return false; - } - - operand->type = t_int; - - if (operand->mode == Addressing_Constant && - op.mode == Addressing_Constant) { - u8 *ptr_a = cast(u8 *)operand->value.value_pointer; - u8 *ptr_b = cast(u8 *)op.value.value_pointer; - isize elem_size = type_size_of(c->sizes, c->allocator, ptr_type->Pointer.elem); - operand->value = make_exact_value_integer((ptr_a - ptr_b) / elem_size); - } else { - operand->mode = Addressing_Value; - } - } break; -#endif - - case BuiltinProc_slice_ptr: { - // slice_ptr :: proc(a: ^T, len: int) -> []T - // ^T cannot be rawptr - Type *ptr_type = base_type(operand->type); - if (!is_type_pointer(ptr_type)) { - gbString type_str = type_to_string(operand->type); - error_node(call, - "Expected a pointer to `slice_ptr`, got `%s`", - type_str); - gb_string_free(type_str); - return false; - } - - if (ptr_type == t_rawptr) { - error_node(call, - "`rawptr` cannot have pointer arithmetic"); - return false; - } - - AstNode *len = ce->args.e[1]; - - Operand op = {0}; - check_expr(c, &op, len); - if (op.mode == Addressing_Invalid) - return false; - if (!is_type_integer(op.type)) { - gbString type_str = type_to_string(operand->type); - error_node(call, - "Length for `slice_ptr` must be an integer, got `%s`", - type_str); - gb_string_free(type_str); - return false; - } - - operand->type = make_type_slice(c->allocator, ptr_type->Pointer.elem); - operand->mode = Addressing_Value; - } break; - - case BuiltinProc_min: { - // min :: proc(a, b: comparable) -> comparable - Type *type = base_type(operand->type); - if (!is_type_comparable(type) || !(is_type_numeric(type) || is_type_string(type))) { - gbString type_str = type_to_string(operand->type); - error_node(call, - "Expected a comparable numeric type to `min`, got `%s`", - type_str); - gb_string_free(type_str); - return false; - } - - AstNode *other_arg = ce->args.e[1]; - Operand a = *operand; - Operand b = {0}; - check_expr(c, &b, other_arg); - if (b.mode == Addressing_Invalid) { - return false; - } - if (!is_type_comparable(b.type) || !(is_type_numeric(b.type) || is_type_string(b.type))) { - gbString type_str = type_to_string(b.type); - error_node(call, - "Expected a comparable numeric type to `min`, got `%s`", - type_str); - gb_string_free(type_str); - return false; - } - - if (a.mode == Addressing_Constant && - b.mode == Addressing_Constant) { - ExactValue x = a.value; - ExactValue y = b.value; - - operand->mode = Addressing_Constant; - if (compare_exact_values(Token_Lt, x, y)) { - operand->value = x; - operand->type = a.type; - } else { - operand->value = y; - operand->type = b.type; - } - } else { - operand->mode = Addressing_Value; - operand->type = type; - - convert_to_typed(c, &a, b.type, 0); - if (a.mode == Addressing_Invalid) { - return false; - } - convert_to_typed(c, &b, a.type, 0); - if (b.mode == Addressing_Invalid) { - return false; - } - - if (!are_types_identical(operand->type, b.type)) { - gbString type_a = type_to_string(a.type); - gbString type_b = type_to_string(b.type); - error_node(call, - "Mismatched types to `min`, `%s` vs `%s`", - type_a, type_b); - gb_string_free(type_b); - gb_string_free(type_a); - return false; - } - } - - } break; - - case BuiltinProc_max: { - // min :: proc(a, b: comparable) -> comparable - Type *type = base_type(operand->type); - if (!is_type_comparable(type) || !(is_type_numeric(type) || is_type_string(type))) { - gbString type_str = type_to_string(operand->type); - error_node(call, - "Expected a comparable numeric or string type to `max`, got `%s`", - type_str); - gb_string_free(type_str); - return false; - } - - AstNode *other_arg = ce->args.e[1]; - Operand a = *operand; - Operand b = {0}; - check_expr(c, &b, other_arg); - if (b.mode == Addressing_Invalid) { - return false; - } - if (!is_type_comparable(b.type) || !(is_type_numeric(b.type) || is_type_string(b.type))) { - gbString type_str = type_to_string(b.type); - error_node(call, - "Expected a comparable numeric or string type to `max`, got `%s`", - type_str); - gb_string_free(type_str); - return false; - } - - if (a.mode == Addressing_Constant && - b.mode == Addressing_Constant) { - ExactValue x = a.value; - ExactValue y = b.value; - - operand->mode = Addressing_Constant; - if (compare_exact_values(Token_Gt, x, y)) { - operand->value = x; - operand->type = a.type; - } else { - operand->value = y; - operand->type = b.type; - } - } else { - operand->mode = Addressing_Value; - operand->type = type; - - convert_to_typed(c, &a, b.type, 0); - if (a.mode == Addressing_Invalid) { - return false; - } - convert_to_typed(c, &b, a.type, 0); - if (b.mode == Addressing_Invalid) { - return false; - } - - if (!are_types_identical(operand->type, b.type)) { - gbString type_a = type_to_string(a.type); - gbString type_b = type_to_string(b.type); - error_node(call, - "Mismatched types to `max`, `%s` vs `%s`", - type_a, type_b); - gb_string_free(type_b); - gb_string_free(type_a); - return false; - } - } - - } break; - - case BuiltinProc_abs: { - // abs :: proc(n: numeric) -> numeric - Type *type = base_type(operand->type); - if (!is_type_numeric(type)) { - gbString type_str = type_to_string(operand->type); - error_node(call, - "Expected a numeric type to `abs`, got `%s`", - type_str); - gb_string_free(type_str); - return false; - } - - if (operand->mode == Addressing_Constant) { - switch (operand->value.kind) { - case ExactValue_Integer: - operand->value.value_integer = gb_abs(operand->value.value_integer); - break; - case ExactValue_Float: - operand->value.value_float = gb_abs(operand->value.value_float); - break; - default: - GB_PANIC("Invalid numeric constant"); - break; - } - } else { - operand->mode = Addressing_Value; - } - - operand->type = type; - } break; - - case BuiltinProc_clamp: { - // clamp :: proc(a, min, max: comparable) -> comparable - Type *type = base_type(operand->type); - if (!is_type_comparable(type) || !(is_type_numeric(type) || is_type_string(type))) { - gbString type_str = type_to_string(operand->type); - error_node(call, - "Expected a comparable numeric or string type to `clamp`, got `%s`", - type_str); - gb_string_free(type_str); - return false; - } - - AstNode *min_arg = ce->args.e[1]; - AstNode *max_arg = ce->args.e[2]; - Operand x = *operand; - Operand y = {0}; - Operand z = {0}; - - check_expr(c, &y, min_arg); - if (y.mode == Addressing_Invalid) { - return false; - } - if (!is_type_comparable(y.type) || !(is_type_numeric(y.type) || is_type_string(y.type))) { - gbString type_str = type_to_string(y.type); - error_node(call, - "Expected a comparable numeric or string type to `clamp`, got `%s`", - type_str); - gb_string_free(type_str); - return false; - } - - check_expr(c, &z, max_arg); - if (z.mode == Addressing_Invalid) { - return false; - } - if (!is_type_comparable(z.type) || !(is_type_numeric(z.type) || is_type_string(z.type))) { - gbString type_str = type_to_string(z.type); - error_node(call, - "Expected a comparable numeric or string type to `clamp`, got `%s`", - type_str); - gb_string_free(type_str); - return false; - } - - if (x.mode == Addressing_Constant && - y.mode == Addressing_Constant && - z.mode == Addressing_Constant) { - ExactValue a = x.value; - ExactValue b = y.value; - ExactValue c = z.value; - - operand->mode = Addressing_Constant; - if (compare_exact_values(Token_Lt, a, b)) { - operand->value = b; - operand->type = y.type; - } else if (compare_exact_values(Token_Gt, a, c)) { - operand->value = c; - operand->type = z.type; - } else { - operand->value = a; - operand->type = x.type; - } - } else { - operand->mode = Addressing_Value; - operand->type = type; - - convert_to_typed(c, &x, y.type, 0); - if (x.mode == Addressing_Invalid) { return false; } - convert_to_typed(c, &y, x.type, 0); - if (y.mode == Addressing_Invalid) { return false; } - convert_to_typed(c, &x, z.type, 0); - if (x.mode == Addressing_Invalid) { return false; } - convert_to_typed(c, &z, x.type, 0); - if (z.mode == Addressing_Invalid) { return false; } - convert_to_typed(c, &y, z.type, 0); - if (y.mode == Addressing_Invalid) { return false; } - convert_to_typed(c, &z, y.type, 0); - if (z.mode == Addressing_Invalid) { return false; } - - if (!are_types_identical(x.type, y.type) || !are_types_identical(x.type, z.type)) { - gbString type_x = type_to_string(x.type); - gbString type_y = type_to_string(y.type); - gbString type_z = type_to_string(z.type); - error_node(call, - "Mismatched types to `clamp`, `%s`, `%s`, `%s`", - type_x, type_y, type_z); - gb_string_free(type_z); - gb_string_free(type_y); - gb_string_free(type_x); - return false; - } - } - } break; - } - - return true; -} - - -void check_call_arguments(Checker *c, Operand *operand, Type *proc_type, AstNode *call) { - GB_ASSERT(call->kind == AstNode_CallExpr); - GB_ASSERT(proc_type->kind == Type_Proc); - ast_node(ce, CallExpr, call); - - isize param_count = 0; - bool variadic = proc_type->Proc.variadic; - bool vari_expand = (ce->ellipsis.pos.line != 0); - - if (proc_type->Proc.params != NULL) { - param_count = proc_type->Proc.params->Tuple.variable_count; - if (variadic) { - param_count--; - } - } - - if (vari_expand && !variadic) { - error(ce->ellipsis, - "Cannot use `..` in call to a non-variadic procedure: `%.*s`", - LIT(ce->proc->Ident.string)); - return; - } - - if (ce->args.count == 0 && param_count == 0) { - return; - } - - gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&c->tmp_arena); - - Array(Operand) operands; - array_init_reserve(&operands, c->tmp_allocator, 2*param_count); - - for_array(i, ce->args) { - Operand o = {0}; - check_multi_expr(c, &o, ce->args.e[i]); - if (o.type->kind != Type_Tuple) { - array_add(&operands, o); - } else { - TypeTuple *tuple = &o.type->Tuple; - if (variadic && i >= param_count) { - error_node(ce->args.e[i], "`..` in a variadic procedure cannot be applied to a %td-valued expression", tuple->variable_count); - operand->mode = Addressing_Invalid; - goto end; - } - for (isize j = 0; j < tuple->variable_count; j++) { - o.type = tuple->variables[j]->type; - array_add(&operands, o); - } - } - } - - i32 error_code = 0; - if (operands.count < param_count) { - error_code = -1; - } else if (!variadic && operands.count > param_count) { - error_code = +1; - } - if (error_code != 0) { - char *err_fmt = "Too many arguments for `%s`, expected %td arguments"; - if (error_code < 0) { - err_fmt = "Too few arguments for `%s`, expected %td arguments"; - } - - gbString proc_str = expr_to_string(ce->proc); - error_node(call, err_fmt, proc_str, param_count); - gb_string_free(proc_str); - operand->mode = Addressing_Invalid; - goto end; - } - - 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 *arg_type = sig_params[operand_index]->type; - Operand o = operands.e[operand_index]; - if (variadic) { - o = operands.e[operand_index]; - } - check_assignment(c, &o, arg_type, str_lit("argument")); - } - - 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.e[operand_index]; - if (vari_expand) { - variadic_expand = true; - t = slice; - if (operand_index != param_count) { - error_node(o.expr, "`..` in a variadic procedure can only have one variadic argument at the end"); - break; - } - } - check_assignment(c, &o, t, str_lit("argument")); - } - } -end: - gb_temp_arena_memory_end(tmp); -} - - -Entity *find_using_index_expr(Type *t) { - t = base_type(t); - if (t->kind != Type_Record) { - return NULL; - } - - for (isize i = 0; i < t->Record.field_count; i++) { - Entity *f = t->Record.fields[i]; - if (f->kind == Entity_Variable && - f->flags & (EntityFlag_Anonymous|EntityFlag_Field)) { - if (is_type_indexable(f->type)) { - return f; - } - Entity *res = find_using_index_expr(f->type); - if (res != NULL) { - return res; - } - } - } - return NULL; -} - -ExprKind check_call_expr(Checker *c, Operand *operand, AstNode *call) { - GB_ASSERT(call->kind == AstNode_CallExpr); - ast_node(ce, CallExpr, call); - check_expr_or_type(c, operand, ce->proc); - - if (operand->mode == Addressing_Invalid) { - for_array(i, ce->args) { - check_expr_base(c, operand, ce->args.e[i], NULL); - } - operand->mode = Addressing_Invalid; - operand->expr = call; - return Expr_Stmt; - } - - - if (operand->mode == Addressing_Builtin) { - i32 id = operand->builtin_id; - if (!check_builtin_procedure(c, operand, call, id)) { - operand->mode = Addressing_Invalid; - } - operand->expr = call; - return builtin_procs[id].kind; - } - - Type *proc_type = base_type(operand->type); - if (proc_type == NULL || proc_type->kind != Type_Proc || - !(operand->mode == Addressing_Value || operand->mode == Addressing_Variable)) { - AstNode *e = operand->expr; - gbString str = expr_to_string(e); - error_node(e, "Cannot call a non-procedure: `%s`", str); - gb_string_free(str); - - operand->mode = Addressing_Invalid; - operand->expr = call; - - return Expr_Stmt; - } - - check_call_arguments(c, operand, proc_type, call); - - switch (proc_type->Proc.result_count) { - case 0: - operand->mode = Addressing_NoValue; - break; - case 1: - operand->mode = Addressing_Value; - operand->type = proc_type->Proc.results->Tuple.variables[0]->type; - break; - default: - operand->mode = Addressing_Value; - operand->type = proc_type->Proc.results; - break; - } - - operand->expr = call; - return Expr_Stmt; -} - -void check_expr_with_type_hint(Checker *c, Operand *o, AstNode *e, Type *t) { - check_expr_base(c, o, e, t); - check_not_tuple(c, o); - char *err_str = NULL; - switch (o->mode) { - case Addressing_NoValue: - err_str = "used as a value"; - break; - case Addressing_Type: - err_str = "is not an expression"; - break; - case Addressing_Builtin: - err_str = "must be called"; - break; - } - if (err_str != NULL) { - gbString str = expr_to_string(e); - error_node(e, "`%s` %s", str, err_str); - gb_string_free(str); - o->mode = Addressing_Invalid; - } -} - -bool check_set_index_data(Operand *o, Type *t, i64 *max_count) { - t = base_type(type_deref(t)); - - switch (t->kind) { - case Type_Basic: - if (is_type_string(t)) { - if (o->mode == Addressing_Constant) { - *max_count = o->value.value_string.len; - } - if (o->mode != Addressing_Variable) { - o->mode = Addressing_Value; - } - o->type = t_u8; - return true; - } - break; - - case Type_Array: - *max_count = t->Array.count; - if (o->mode != Addressing_Variable) { - o->mode = Addressing_Value; - } - o->type = t->Array.elem; - return true; - - case Type_Vector: - *max_count = t->Vector.count; - if (o->mode != Addressing_Variable) { - o->mode = Addressing_Value; - } - o->type = t->Vector.elem; - return true; - - - case Type_Slice: - o->type = t->Slice.elem; - o->mode = Addressing_Variable; - return true; - } - - return false; -} - - -bool check_is_giving(AstNode *node, AstNode **give_expr) { - switch (node->kind) { - case_ast_node(es, ExprStmt, node); - if (es->expr->kind == AstNode_GiveExpr) { - if (give_expr) *give_expr = es->expr; - return true; - } - case_end; - - case_ast_node(ge, GiveExpr, node); - if (give_expr) *give_expr = node; - return true; - case_end; - - case_ast_node(be, BlockExpr, node); - // Iterate backwards - for (isize n = be->stmts.count-1; n >= 0; n--) { - AstNode *stmt = be->stmts.e[n]; - if (stmt->kind == AstNode_EmptyStmt) { - continue; - } - if (stmt->kind == AstNode_ExprStmt && stmt->ExprStmt.expr->kind == AstNode_GiveExpr) { - if (give_expr) *give_expr = stmt->ExprStmt.expr; - return true; - } - } - case_end; - } - - if (give_expr) *give_expr = NULL; - return false; -} - -ExprKind check__expr_base(Checker *c, Operand *o, AstNode *node, Type *type_hint) { - ExprKind kind = Expr_Stmt; - - o->mode = Addressing_Invalid; - o->type = t_invalid; - - switch (node->kind) { - default: - goto error; - break; - - case_ast_node(be, BadExpr, node) - goto error; - case_end; - - case_ast_node(i, IntervalExpr, node); - error_node(node, "Invalid use of an interval expression"); - goto error; - case_end; - - case_ast_node(i, Ident, node); - check_identifier(c, o, node, type_hint); - case_end; - - case_ast_node(bl, BasicLit, node); - Type *t = t_invalid; - switch (bl->kind) { - case Token_Integer: t = t_untyped_integer; break; - case Token_Float: t = t_untyped_float; break; - case Token_String: t = t_untyped_string; break; - case Token_Rune: t = t_untyped_rune; break; - default: GB_PANIC("Unknown literal"); break; - } - o->mode = Addressing_Constant; - o->type = t; - o->value = make_exact_value_from_basic_literal(*bl); - case_end; - - case_ast_node(pl, ProcLit, node); - Type *type = check_type(c, pl->type); - if (type == NULL || !is_type_proc(type)) { - gbString str = expr_to_string(node); - error_node(node, "Invalid procedure literal `%s`", str); - gb_string_free(str); - check_close_scope(c); - goto error; - } - if (pl->tags != 0) { - error_node(node, "A procedure literal cannot have tags"); - pl->tags = 0; // TODO(bill): Should I zero this?! - } - - check_open_scope(c, pl->type); - check_procedure_later(c, c->curr_ast_file, empty_token, c->context.decl, type, pl->body, pl->tags); - // check_proc_body(c, empty_token, c->context.decl, type, pl->body); - check_close_scope(c); - - o->mode = Addressing_Value; - o->type = type; - case_end; - - case_ast_node(ge, GiveExpr, node); - if (c->proc_stack.count == 0) { - error_node(node, "A give expression is only allowed within a procedure"); - goto error; - } - - if (ge->results.count == 0) { - error_node(node, "`give` has no results"); - goto error; - } - - gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&c->tmp_arena); - - Array(Operand) operands; - array_init_reserve(&operands, c->tmp_allocator, 2*ge->results.count); - - for_array(i, ge->results) { - AstNode *rhs = ge->results.e[i]; - Operand o = {0}; - check_multi_expr(c, &o, rhs); - if (!is_operand_value(o)) { - error_node(rhs, "Expected a value for a `give`"); - continue; - } - if (o.type->kind != Type_Tuple) { - array_add(&operands, o); - } else { - TypeTuple *tuple = &o.type->Tuple; - for (isize j = 0; j < tuple->variable_count; j++) { - o.type = tuple->variables[j]->type; - array_add(&operands, o); - } - } - } - - if (operands.count == 0) { - error_node(node, "`give` has no value"); - gb_temp_arena_memory_end(tmp); - goto error; - } else if (operands.count == 1) { - Operand operand = operands.e[0]; - if (type_hint != NULL) { - convert_to_typed(c, &operand, type_hint, 0); - } - o->type = default_type(operand.type); - o->mode = Addressing_Value; - } else { - Type *tuple = make_type_tuple(c->allocator); - - Entity **variables = gb_alloc_array(c->allocator, Entity *, operands.count); - isize variable_index = 0; - for_array(i, operands) { - Operand operand = operands.e[i]; - // Type *type = default_type(operand.type); - Type *type = operand.type; - switch (operand.mode) { - case Addressing_Constant: - variables[variable_index++] = make_entity_constant(c->allocator, NULL, empty_token, type, operand.value); - break; - default: - variables[variable_index++] = make_entity_param(c->allocator, NULL, empty_token, type, false); - break; - } - } - tuple->Tuple.variables = variables; - tuple->Tuple.variable_count = operands.count; - - o->type = tuple; - o->mode = Addressing_Value; - } - gb_temp_arena_memory_end(tmp); - case_end; - - case_ast_node(be, BlockExpr, node); - if (c->proc_stack.count == 0) { - error_node(node, "A block expression is only allowed within a procedure"); - goto error; - } - - for (isize i = be->stmts.count-1; i >= 0; i--) { - if (be->stmts.e[i]->kind != AstNode_EmptyStmt) { - break; - } - be->stmts.count--; - } - - if (be->stmts.count == 0) { - error_node(node, "Empty block expression"); - goto error; - } - - check_open_scope(c, node); - check_stmt_list(c, be->stmts, Stmt_GiveAllowed); - check_close_scope(c); - - AstNode *give_node = NULL; - if (!check_is_giving(node, &give_node) || give_node == NULL) { - error_node(node, "Missing give statement at end of block expression"); - goto error; - } - - GB_ASSERT(give_node != NULL && give_node->kind == AstNode_GiveExpr); - be->give_node = give_node; - - Type *type = type_of_expr(&c->info, give_node); - if (type == NULL) { - goto error; - } else if (type == t_invalid) { - o->type = t_invalid; - o->mode = Addressing_Invalid; - } else { - o->type = type; - o->mode = Addressing_Value; - } - case_end; - - case_ast_node(ie, IfExpr, node); - if (c->proc_stack.count == 0) { - error_node(node, "An if expression is only allowed within a procedure"); - goto error; - } - - check_open_scope(c, node); - - if (ie->init != NULL) { - check_stmt(c, ie->init, 0); - } - - Operand operand = {Addressing_Invalid}; - check_expr(c, &operand, ie->cond); - if (operand.mode != Addressing_Invalid && !is_type_boolean(operand.type)) { - error_node(ie->cond, "Non-boolean condition in if expression"); - } - - - Operand x = {Addressing_Invalid}; - Operand y = {Addressing_Invalid}; - Type *if_type = NULL; - Type *else_type = NULL; - check_expr(c, &x, ie->body); - if_type = x.type; - - if (ie->else_expr != NULL) { - switch (ie->else_expr->kind) { - case AstNode_IfExpr: - case AstNode_BlockExpr: - check_expr(c, &y, ie->else_expr); - else_type = y.type; - break; - default: - error_node(ie->else_expr, "Invalid else expression in if expression"); - break; - } - } else { - error_node(ie->else_expr, "An if expression must have an else expression"); - check_close_scope(c); - goto error; - } - - check_close_scope(c); - - if (if_type == NULL || if_type == t_invalid || - else_type == NULL || else_type == t_invalid) { - goto error; - } - - convert_to_typed(c, &x, y.type, 0); - if (x.mode == Addressing_Invalid) { - goto error; - } - convert_to_typed(c, &y, x.type, 0); - if (y.mode == Addressing_Invalid) { - x.mode = Addressing_Invalid; - goto error; - } - - - if (!are_types_identical(if_type, else_type)) { - gbString its = type_to_string(if_type); - gbString ets = type_to_string(else_type); - error_node(node, "Mismatched types in if expression, %s vs %s", its, ets); - gb_string_free(ets); - gb_string_free(its); - goto error; - } - - o->type = if_type; - o->mode = Addressing_Value; - case_end; - - case_ast_node(cl, CompoundLit, node); - Type *type = type_hint; - bool ellipsis_array = false; - bool is_constant = true; - if (cl->type != NULL) { - type = NULL; - - // [..]Type - if (cl->type->kind == AstNode_ArrayType && cl->type->ArrayType.count != NULL) { - if (cl->type->ArrayType.count->kind == AstNode_Ellipsis) { - type = make_type_array(c->allocator, check_type(c, cl->type->ArrayType.elem), -1); - ellipsis_array = true; - } - } - - if (type == NULL) { - type = check_type(c, cl->type); - } - } - - if (type == NULL) { - error_node(node, "Missing type in compound literal"); - goto error; - } - - Type *t = base_type(type); - switch (t->kind) { - case Type_Record: { - if (!is_type_struct(t)) { - if (cl->elems.count != 0) { - error_node(node, "Illegal compound literal"); - } - break; - } - if (cl->elems.count == 0) { - break; // NOTE(bill): No need to init - } - { // Checker values - isize field_count = t->Record.field_count; - if (cl->elems.e[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]; - if (elem->kind != AstNode_FieldValue) { - error_node(elem, "Mixture of `field = value` and value elements in a structure literal is not allowed"); - continue; - } - ast_node(fv, FieldValue, elem); - if (fv->field->kind != AstNode_Ident) { - gbString expr_str = expr_to_string(fv->field); - error_node(elem, "Invalid field name `%s` in structure literal", expr_str); - gb_string_free(expr_str); - continue; - } - String name = fv->field->Ident.string; - - Selection sel = lookup_field(c->allocator, type, name, o->mode == Addressing_Type); - if (sel.entity == NULL) { - error_node(elem, "Unknown field `%.*s` in structure literal", LIT(name)); - continue; - } - - if (sel.index.count > 1) { - error_node(elem, "Cannot assign to an anonymous field `%.*s` in a structure literal (at the moment)", LIT(name)); - continue; - } - - Entity *field = t->Record.fields[sel.index.e[0]]; - add_entity_use(c, fv->field, field); - - if (fields_visited[sel.index.e[0]]) { - error_node(elem, "Duplicate field `%.*s` in structure literal", LIT(name)); - continue; - } - - fields_visited[sel.index.e[0]] = true; - check_expr(c, o, fv->value); - - if (base_type(field->type) == t_any) { - is_constant = false; - } - if (is_constant) { - is_constant = o->mode == Addressing_Constant; - } - - - check_assignment(c, o, field->type, str_lit("structure literal")); - } - } else { - for_array(index, cl->elems) { - AstNode *elem = cl->elems.e[index]; - if (elem->kind == AstNode_FieldValue) { - error_node(elem, "Mixture of `field = value` and value elements in a structure literal is not allowed"); - continue; - } - Entity *field = t->Record.fields_in_src_order[index]; - - check_expr(c, o, elem); - if (index >= field_count) { - error_node(o->expr, "Too many values in structure literal, expected %td", field_count); - break; - } - - if (base_type(field->type) == t_any) { - is_constant = false; - } - if (is_constant) { - is_constant = o->mode == Addressing_Constant; - } - - check_assignment(c, o, field->type, str_lit("structure literal")); - } - if (cl->elems.count < field_count) { - error(cl->close, "Too few values in structure literal, expected %td, got %td", field_count, cl->elems.count); - } - } - } - - } break; - - case Type_Slice: - case Type_Array: - case Type_Vector: - { - Type *elem_type = NULL; - String context_name = {0}; - if (t->kind == Type_Slice) { - elem_type = t->Slice.elem; - context_name = str_lit("slice literal"); - } else if (t->kind == Type_Vector) { - elem_type = t->Vector.elem; - context_name = str_lit("vector literal"); - } else { - elem_type = t->Array.elem; - context_name = str_lit("array literal"); - } - - - i64 max = 0; - isize index = 0; - isize elem_count = cl->elems.count; - - if (base_type(elem_type) == t_any) { - is_constant = false; - } - - for (; index < elem_count; index++) { - AstNode *e = cl->elems.e[index]; - if (e->kind == AstNode_FieldValue) { - error_node(e, - "`field = value` is only allowed in struct literals"); - continue; - } - - if (t->kind == Type_Array && - t->Array.count >= 0 && - index >= t->Array.count) { - error_node(e, "Index %lld is out of bounds (>= %lld) for array literal", index, t->Array.count); - } - if (t->kind == Type_Vector && - t->Vector.count >= 0 && - index >= t->Vector.count) { - error_node(e, "Index %lld is out of bounds (>= %lld) for vector literal", index, t->Vector.count); - } - - Operand operand = {0}; - check_expr_with_type_hint(c, &operand, e, elem_type); - check_assignment(c, &operand, elem_type, context_name); - - if (is_constant) { - is_constant = operand.mode == Addressing_Constant; - } - } - if (max < index) { - max = index; - } - - 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); - } - } - - if (t->kind == Type_Array && ellipsis_array) { - t->Array.count = max; - } - } break; - - default: { - gbString str = type_to_string(type); - error_node(node, "Invalid compound literal type `%s`", str); - gb_string_free(str); - goto error; - } break; - } - - if (is_constant) { - o->mode = Addressing_Constant; - o->value = make_exact_value_compound(node); - } else { - o->mode = Addressing_Value; - } - o->type = type; - case_end; - - case_ast_node(pe, ParenExpr, node); - kind = check_expr_base(c, o, pe->expr, type_hint); - o->expr = node; - case_end; - - - case_ast_node(te, TagExpr, node); - // TODO(bill): Tag expressions - error_node(node, "Tag expressions are not supported yet"); - kind = check_expr_base(c, o, te->expr, type_hint); - o->expr = node; - case_end; - - case_ast_node(re, RunExpr, node); - // TODO(bill): Tag expressions - kind = check_expr_base(c, o, re->expr, type_hint); - o->expr = node; - case_end; - - - case_ast_node(ue, UnaryExpr, node); - check_expr(c, o, ue->expr); - if (o->mode == Addressing_Invalid) { - goto error; - } - check_unary_expr(c, o, ue->op, node); - if (o->mode == Addressing_Invalid) { - goto error; - } - case_end; - - - case_ast_node(be, BinaryExpr, node); - check_binary_expr(c, o, node); - if (o->mode == Addressing_Invalid) { - goto error; - } - case_end; - - - - case_ast_node(se, SelectorExpr, node); - check_selector(c, o, node); - case_end; - - - case_ast_node(ie, IndexExpr, node); - check_expr(c, o, ie->expr); - if (o->mode == Addressing_Invalid) { - goto error; - } - - Type *t = base_type(type_deref(o->type)); - bool is_const = o->mode == Addressing_Constant; - - i64 max_count = -1; - bool valid = check_set_index_data(o, t, &max_count); - - if (is_const) { - valid = false; - } - - if (!valid && (is_type_struct(t) || is_type_raw_union(t))) { - Entity *found = find_using_index_expr(t); - if (found != NULL) { - valid = check_set_index_data(o, found->type, &max_count); - } - } - - if (!valid) { - gbString str = expr_to_string(o->expr); - if (is_const) { - error_node(o->expr, "Cannot index a constant `%s`", str); - } else { - error_node(o->expr, "Cannot index `%s`", str); - } - gb_string_free(str); - goto error; - } - - if (ie->index == NULL) { - gbString str = expr_to_string(o->expr); - error_node(o->expr, "Missing index for `%s`", str); - gb_string_free(str); - goto error; - } - - i64 index = 0; - bool ok = check_index_value(c, ie->index, max_count, &index); - - case_end; - - - - case_ast_node(se, SliceExpr, node); - check_expr(c, o, se->expr); - if (o->mode == Addressing_Invalid) { - goto error; - } - - bool valid = false; - i64 max_count = -1; - Type *t = base_type(type_deref(o->type)); - switch (t->kind) { - case Type_Basic: - if (is_type_string(t)) { - valid = true; - if (o->mode == Addressing_Constant) { - max_count = o->value.value_string.len; - } - o->type = t_string; - } - break; - - case Type_Array: - valid = true; - max_count = t->Array.count; - if (o->mode != Addressing_Variable) { - gbString str = expr_to_string(node); - error_node(node, "Cannot slice array `%s`, value is not addressable", str); - gb_string_free(str); - goto error; - } - o->type = make_type_slice(c->allocator, t->Array.elem); - break; - - case Type_Slice: - valid = true; - break; - } - - if (!valid) { - gbString str = expr_to_string(o->expr); - error_node(o->expr, "Cannot slice `%s`", str); - gb_string_free(str); - goto error; - } - - o->mode = Addressing_Value; - - i64 indices[2] = {0}; - AstNode *nodes[2] = {se->low, se->high}; - for (isize i = 0; i < gb_count_of(nodes); i++) { - i64 index = max_count; - if (nodes[i] != NULL) { - i64 capacity = -1; - if (max_count >= 0) - capacity = max_count; - i64 j = 0; - if (check_index_value(c, nodes[i], capacity, &j)) { - index = j; - } - } else if (i == 0) { - index = 0; - } - indices[i] = index; - } - - for (isize i = 0; i < gb_count_of(indices); i++) { - i64 a = indices[i]; - for (isize j = i+1; j < gb_count_of(indices); j++) { - i64 b = indices[j]; - if (a > b && b >= 0) { - error(se->close, "Invalid slice indices: [%td > %td]", a, b); - } - } - } - - case_end; - - - case_ast_node(ce, CallExpr, node); - return check_call_expr(c, o, node); - case_end; - - case_ast_node(de, DerefExpr, node); - check_expr_or_type(c, o, de->expr); - if (o->mode == Addressing_Invalid) { - goto error; - } else { - Type *t = base_type(o->type); - if (t->kind == Type_Pointer) { - o->mode = Addressing_Variable; - o->type = t->Pointer.elem; - } else { - gbString str = expr_to_string(o->expr); - error_node(o->expr, "Cannot dereference `%s`", str); - gb_string_free(str); - goto error; - } - } - case_end; - - case_ast_node(de, DemaybeExpr, node); - check_expr_or_type(c, o, de->expr); - if (o->mode == Addressing_Invalid) { - goto error; - } else { - Type *t = base_type(o->type); - if (t->kind == Type_Maybe) { - Entity **variables = gb_alloc_array(c->allocator, Entity *, 2); - Type *elem = t->Maybe.elem; - Token tok = make_token_ident(str_lit("")); - variables[0] = make_entity_param(c->allocator, NULL, tok, elem, false); - variables[1] = make_entity_param(c->allocator, NULL, tok, t_bool, false); - - Type *tuple = make_type_tuple(c->allocator); - tuple->Tuple.variables = variables; - tuple->Tuple.variable_count = 2; - - o->type = tuple; - o->mode = Addressing_Variable; - } else { - gbString str = expr_to_string(o->expr); - error_node(o->expr, "Cannot demaybe `%s`", str); - gb_string_free(str); - goto error; - } - } - case_end; - - case AstNode_ProcType: - case AstNode_PointerType: - case AstNode_MaybeType: - case AstNode_ArrayType: - case AstNode_VectorType: - case AstNode_StructType: - case AstNode_UnionType: - case AstNode_RawUnionType: - case AstNode_EnumType: - o->mode = Addressing_Type; - o->type = check_type(c, node); - break; - } - - kind = Expr_Expr; - o->expr = node; - return kind; - -error: - o->mode = Addressing_Invalid; - o->expr = node; - return kind; -} - -ExprKind check_expr_base(Checker *c, Operand *o, AstNode *node, Type *type_hint) { - ExprKind kind = check__expr_base(c, o, node, type_hint); - Type *type = NULL; - ExactValue value = {ExactValue_Invalid}; - switch (o->mode) { - case Addressing_Invalid: - type = t_invalid; - break; - case Addressing_NoValue: - type = NULL; - break; - case Addressing_Constant: - type = o->type; - value = o->value; - break; - default: - type = o->type; - break; - } - - if (type != NULL && is_type_untyped(type)) { - add_untyped(&c->info, node, false, o->mode, type, value); - } else { - add_type_and_value(&c->info, node, o->mode, type, value); - } - return kind; -} - - -void check_multi_expr(Checker *c, Operand *o, AstNode *e) { - gbString err_str = NULL; - check_expr_base(c, o, e, NULL); - switch (o->mode) { - default: - return; // NOTE(bill): Valid - - case Addressing_NoValue: - err_str = expr_to_string(e); - error_node(e, "`%s` used as value", err_str); - break; - case Addressing_Type: - err_str = expr_to_string(e); - error_node(e, "`%s` is not an expression", err_str); - break; - } - gb_string_free(err_str); - o->mode = Addressing_Invalid; -} - -void check_not_tuple(Checker *c, Operand *o) { - if (o->mode == Addressing_Value) { - // NOTE(bill): Tuples are not first class thus never named - if (o->type->kind == Type_Tuple) { - isize count = o->type->Tuple.variable_count; - GB_ASSERT(count != 1); - error_node(o->expr, - "%td-valued tuple found where single value expected", count); - o->mode = Addressing_Invalid; - } - } -} - -void check_expr(Checker *c, Operand *o, AstNode *e) { - check_multi_expr(c, o, e); - check_not_tuple(c, o); -} - - -void check_expr_or_type(Checker *c, Operand *o, AstNode *e) { - check_expr_base(c, o, e, NULL); - check_not_tuple(c, o); - if (o->mode == Addressing_NoValue) { - gbString str = expr_to_string(o->expr); - error_node(o->expr, "`%s` used as value or type", str); - gb_string_free(str); - o->mode = Addressing_Invalid; - } -} - - -gbString write_expr_to_string(gbString str, AstNode *node); - -gbString write_params_to_string(gbString str, AstNodeArray params, char *sep) { - for_array(i, params) { - ast_node(p, Field, params.e[i]); - if (i > 0) { - str = gb_string_appendc(str, sep); - } - - str = write_expr_to_string(str, params.e[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 str; -} - - -gbString write_expr_to_string(gbString str, AstNode *node) { - if (node == NULL) - return str; - - if (is_ast_node_stmt(node)) { - GB_ASSERT("stmt passed to write_expr_to_string"); - } - - switch (node->kind) { - default: - str = gb_string_appendc(str, "(BadExpr)"); - break; - - case_ast_node(i, Ident, node); - str = string_append_token(str, *i); - case_end; - - case_ast_node(bl, BasicLit, node); - str = string_append_token(str, *bl); - case_end; - - case_ast_node(pl, ProcLit, node); - str = write_expr_to_string(str, pl->type); - case_end; - - case_ast_node(cl, CompoundLit, node); - str = write_expr_to_string(str, cl->type); - str = gb_string_appendc(str, "{"); - for_array(i, cl->elems) { - if (i > 0) { - str = gb_string_appendc(str, ", "); - } - str = write_expr_to_string(str, cl->elems.e[i]); - } - str = gb_string_appendc(str, "}"); - case_end; - - case_ast_node(be, BlockExpr, node); - str = gb_string_appendc(str, "block expression"); - case_end; - case_ast_node(ie, IfExpr, node); - str = gb_string_appendc(str, "if expression"); - case_end; - - case_ast_node(te, TagExpr, node); - str = gb_string_appendc(str, "#"); - str = string_append_token(str, te->name); - str = write_expr_to_string(str, te->expr); - case_end; - - case_ast_node(ue, UnaryExpr, node); - str = string_append_token(str, ue->op); - str = write_expr_to_string(str, ue->expr); - case_end; - - case_ast_node(de, DerefExpr, node); - str = write_expr_to_string(str, de->expr); - str = gb_string_appendc(str, "^"); - case_end; - - case_ast_node(de, DemaybeExpr, node); - str = write_expr_to_string(str, de->expr); - str = gb_string_appendc(str, "?"); - case_end; - - case_ast_node(be, BinaryExpr, node); - str = write_expr_to_string(str, be->left); - str = gb_string_appendc(str, " "); - str = string_append_token(str, be->op); - str = gb_string_appendc(str, " "); - str = write_expr_to_string(str, be->right); - case_end; - - case_ast_node(pe, ParenExpr, node); - str = gb_string_appendc(str, "("); - str = write_expr_to_string(str, pe->expr); - str = gb_string_appendc(str, ")"); - case_end; - - case_ast_node(se, SelectorExpr, node); - str = write_expr_to_string(str, se->expr); - str = gb_string_appendc(str, "."); - str = write_expr_to_string(str, se->selector); - case_end; - - case_ast_node(ie, IndexExpr, node); - str = write_expr_to_string(str, ie->expr); - str = gb_string_appendc(str, "["); - str = write_expr_to_string(str, ie->index); - str = gb_string_appendc(str, "]"); - case_end; - - case_ast_node(se, SliceExpr, node); - str = write_expr_to_string(str, se->expr); - str = gb_string_appendc(str, "["); - str = write_expr_to_string(str, se->low); - str = gb_string_appendc(str, ":"); - str = write_expr_to_string(str, se->high); - str = gb_string_appendc(str, "]"); - case_end; - - case_ast_node(e, Ellipsis, node); - str = gb_string_appendc(str, ".."); - case_end; - - case_ast_node(fv, FieldValue, node); - str = write_expr_to_string(str, fv->field); - str = gb_string_appendc(str, " = "); - str = write_expr_to_string(str, fv->value); - case_end; - - case_ast_node(pt, PointerType, node); - str = gb_string_appendc(str, "^"); - str = write_expr_to_string(str, pt->type); - case_end; - - case_ast_node(mt, MaybeType, node); - str = gb_string_appendc(str, "?"); - str = write_expr_to_string(str, mt->type); - case_end; - - case_ast_node(at, ArrayType, node); - str = gb_string_appendc(str, "["); - str = write_expr_to_string(str, at->count); - str = gb_string_appendc(str, "]"); - str = write_expr_to_string(str, at->elem); - case_end; - - case_ast_node(vt, VectorType, node); - str = gb_string_appendc(str, "[vector "); - str = write_expr_to_string(str, vt->count); - str = gb_string_appendc(str, "]"); - str = write_expr_to_string(str, vt->elem); - case_end; - - case_ast_node(p, Field, node); - if (p->is_using) { - str = gb_string_appendc(str, "using "); - } - for_array(i, p->names) { - AstNode *name = p->names.e[i]; - if (i > 0) { - str = gb_string_appendc(str, ", "); - } - str = write_expr_to_string(str, name); - } - - str = gb_string_appendc(str, ": "); - str = write_expr_to_string(str, p->type); - case_end; - - case_ast_node(ce, CallExpr, node); - str = write_expr_to_string(str, ce->proc); - str = gb_string_appendc(str, "("); - - for_array(i, ce->args) { - AstNode *arg = ce->args.e[i]; - if (i > 0) { - str = gb_string_appendc(str, ", "); - } - str = write_expr_to_string(str, arg); - } - str = gb_string_appendc(str, ")"); - case_end; - - case_ast_node(pt, ProcType, node); - str = gb_string_appendc(str, "proc("); - str = write_params_to_string(str, pt->params, ", "); - str = gb_string_appendc(str, ")"); - case_end; - - case_ast_node(st, StructType, node); - str = gb_string_appendc(str, "struct "); - if (st->is_packed) str = gb_string_appendc(str, "#packed "); - if (st->is_ordered) str = gb_string_appendc(str, "#ordered "); - for_array(i, st->fields) { - if (i > 0) { - str = gb_string_appendc(str, "; "); - } - str = write_expr_to_string(str, st->fields.e[i]); - } - // str = write_params_to_string(str, st->decl_list, ", "); - str = gb_string_appendc(str, "}"); - case_end; - - case_ast_node(st, RawUnionType, node); - str = gb_string_appendc(str, "raw_union {"); - for_array(i, st->fields) { - if (i > 0) { - str = gb_string_appendc(str, "; "); - } - str = write_expr_to_string(str, st->fields.e[i]); - } - // str = write_params_to_string(str, st->decl_list, ", "); - str = gb_string_appendc(str, "}"); - case_end; - - case_ast_node(st, UnionType, node); - str = gb_string_appendc(str, "union {"); - for_array(i, st->fields) { - if (i > 0) { - str = gb_string_appendc(str, "; "); - } - str = write_expr_to_string(str, st->fields.e[i]); - } - // str = write_params_to_string(str, st->decl_list, ", "); - str = gb_string_appendc(str, "}"); - case_end; - - case_ast_node(et, EnumType, node); - str = gb_string_appendc(str, "enum "); - if (et->base_type != NULL) { - str = write_expr_to_string(str, et->base_type); - str = gb_string_appendc(str, " "); - } - str = gb_string_appendc(str, "{"); - str = gb_string_appendc(str, "}"); - case_end; - - case_ast_node(ht, HelperType, node); - str = gb_string_appendc(str, "type "); - str = write_expr_to_string(str, ht->type); - case_end; - } - - return str; -} - -gbString expr_to_string(AstNode *expression) { - return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression); -} diff --git a/src/checker/stmt.c b/src/checker/stmt.c deleted file mode 100644 index b6bf9b1d0..000000000 --- a/src/checker/stmt.c +++ /dev/null @@ -1,1301 +0,0 @@ -void check_stmt_list(Checker *c, AstNodeArray stmts, u32 flags) { - if (stmts.count == 0) { - return; - } - - check_scope_decls(c, stmts, 1.2*stmts.count, NULL); - - bool ft_ok = (flags & Stmt_FallthroughAllowed) != 0; - flags &= ~Stmt_FallthroughAllowed; - - isize max = stmts.count; - for (isize i = stmts.count-1; i >= 0; i--) { - if (stmts.e[i]->kind != AstNode_EmptyStmt) { - break; - } - max--; - } - for (isize i = 0; i < max; i++) { - AstNode *n = stmts.e[i]; - if (n->kind == AstNode_EmptyStmt) { - continue; - } - u32 new_flags = flags; - if (ft_ok && i+1 == max) { - new_flags |= Stmt_FallthroughAllowed; - } - - if (i+1 < max) { - switch (n->kind) { - case AstNode_ReturnStmt: - error_node(n, "Statements after this `return` are never executed"); - break; - case AstNode_ExprStmt: - if (n->ExprStmt.expr->kind == AstNode_GiveExpr) { - error_node(n, "A `give` must be the last statement in a block"); - } - break; - } - } - - check_stmt(c, n, new_flags); - } - -} - -bool check_is_terminating_list(AstNodeArray stmts) { - // Iterate backwards - for (isize n = stmts.count-1; n >= 0; n--) { - AstNode *stmt = stmts.e[n]; - if (stmt->kind != AstNode_EmptyStmt) { - return check_is_terminating(stmt); - } - } - - return false; -} - -bool check_has_break_list(AstNodeArray stmts, bool implicit) { - for_array(i, stmts) { - AstNode *stmt = stmts.e[i]; - if (check_has_break(stmt, implicit)) { - return true; - } - } - return false; -} - - -bool check_has_break(AstNode *stmt, bool implicit) { - switch (stmt->kind) { - case AstNode_BranchStmt: - if (stmt->BranchStmt.token.kind == Token_break) { - return implicit; - } - break; - case AstNode_BlockStmt: - return check_has_break_list(stmt->BlockStmt.stmts, implicit); - - case AstNode_IfStmt: - if (check_has_break(stmt->IfStmt.body, implicit) || - (stmt->IfStmt.else_stmt != NULL && check_has_break(stmt->IfStmt.else_stmt, implicit))) { - return true; - } - break; - - case AstNode_CaseClause: - return check_has_break_list(stmt->CaseClause.stmts, implicit); - } - - return false; -} - - - -// NOTE(bill): The last expression has to be a `return` statement -// TODO(bill): This is a mild hack and should be probably handled properly -// TODO(bill): Warn/err against code after `return` that it won't be executed -bool check_is_terminating(AstNode *node) { - switch (node->kind) { - case_ast_node(rs, ReturnStmt, node); - return true; - case_end; - - case_ast_node(bs, BlockStmt, node); - return check_is_terminating_list(bs->stmts); - case_end; - - case_ast_node(es, ExprStmt, node); - return check_is_terminating(es->expr); - case_end; - - case_ast_node(is, IfStmt, node); - if (is->else_stmt != NULL) { - if (check_is_terminating(is->body) && - check_is_terminating(is->else_stmt)) { - return true; - } - } - case_end; - - case_ast_node(ws, WhenStmt, node); - if (ws->else_stmt != NULL) { - if (check_is_terminating(ws->body) && - check_is_terminating(ws->else_stmt)) { - return true; - } - } - case_end; - - case_ast_node(ws, WhileStmt, node); - if (ws->cond != NULL && !check_has_break(ws->body, true)) { - return check_is_terminating(ws->body); - } - case_end; - - case_ast_node(rs, ForStmt, node); - if (!check_has_break(rs->body, true)) { - return check_is_terminating(rs->body); - } - case_end; - - 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]; - ast_node(cc, CaseClause, clause); - if (cc->list.count == 0) { - has_default = true; - } - if (!check_is_terminating_list(cc->stmts) || - check_has_break_list(cc->stmts, true)) { - return false; - } - } - return has_default; - case_end; - - 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]; - ast_node(cc, CaseClause, clause); - if (cc->list.count == 0) { - has_default = true; - } - if (!check_is_terminating_list(cc->stmts) || - check_has_break_list(cc->stmts, true)) { - return false; - } - } - return has_default; - case_end; - - case_ast_node(pa, PushAllocator, node); - return check_is_terminating(pa->body); - case_end; - case_ast_node(pc, PushContext, node); - return check_is_terminating(pc->body); - case_end; - } - - return false; -} - -Type *check_assignment_variable(Checker *c, Operand *op_a, AstNode *lhs) { - if (op_a->mode == Addressing_Invalid || - op_a->type == t_invalid) { - return NULL; - } - - AstNode *node = unparen_expr(lhs); - - // NOTE(bill): Ignore assignments to `_` - if (node->kind == AstNode_Ident && - str_eq(node->Ident.string, str_lit("_"))) { - add_entity_definition(&c->info, node, NULL); - check_assignment(c, op_a, NULL, str_lit("assignment to `_` identifier")); - if (op_a->mode == Addressing_Invalid) - return NULL; - return op_a->type; - } - - Entity *e = NULL; - bool used = false; - if (node->kind == AstNode_Ident) { - ast_node(i, Ident, node); - e = scope_lookup_entity(c->context.scope, i->string); - if (e != NULL && e->kind == Entity_Variable) { - used = (e->flags & EntityFlag_Used) != 0; // TODO(bill): Make backup just in case - } - } - - - Operand op_b = {Addressing_Invalid}; - check_expr(c, &op_b, lhs); - if (e) { - e->flags |= EntityFlag_Used*used; - } - - if (op_b.mode == Addressing_Invalid || - op_b.type == t_invalid) { - return NULL; - } - - switch (op_b.mode) { - case Addressing_Invalid: - return NULL; - case Addressing_Variable: - break; - default: { - if (op_b.expr->kind == AstNode_SelectorExpr) { - // NOTE(bill): Extra error checks - Operand op_c = {Addressing_Invalid}; - ast_node(se, SelectorExpr, op_b.expr); - check_expr(c, &op_c, se->expr); - } - - gbString str = expr_to_string(op_b.expr); - switch (op_b.mode) { - case Addressing_Value: - error_node(op_b.expr, "Cannot assign to `%s`", str); - break; - default: - error_node(op_b.expr, "Cannot assign to `%s`", str); - break; - } - gb_string_free(str); - } break; - } - - check_assignment(c, op_a, op_b.type, str_lit("assignment")); - if (op_a->mode == Addressing_Invalid) { - return NULL; - } - - return op_a->type; -} - -bool check_valid_type_match_type(Type *type, bool *is_union_ptr, bool *is_any) { - if (is_type_pointer(type)) { - *is_union_ptr = is_type_union(type_deref(type)); - return *is_union_ptr; - } - if (is_type_any(type)) { - *is_any = true; - return *is_any; - } - return false; -} - -void check_stmt_internal(Checker *c, AstNode *node, u32 flags); -void check_stmt(Checker *c, AstNode *node, u32 flags) { - u32 prev_stmt_state_flags = c->context.stmt_state_flags; - - if (node->stmt_state_flags != 0) { - u32 in = node->stmt_state_flags; - u32 out = c->context.stmt_state_flags; - - if (in & StmtStateFlag_bounds_check) { - out |= StmtStateFlag_bounds_check; - out &= ~StmtStateFlag_no_bounds_check; - } else if (in & StmtStateFlag_no_bounds_check) { - out |= StmtStateFlag_no_bounds_check; - out &= ~StmtStateFlag_bounds_check; - } - - c->context.stmt_state_flags = out; - } - - check_stmt_internal(c, node, flags); - - c->context.stmt_state_flags = prev_stmt_state_flags; -} - - - -typedef 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) { - Operand operand = {Addressing_Invalid}; - check_expr(c, &operand, ws->cond); - if (operand.mode != Addressing_Constant || !is_type_boolean(operand.type)) { - error_node(ws->cond, "Non-constant boolean `when` condition"); - return; - } - if (ws->body == NULL || ws->body->kind != AstNode_BlockStmt) { - error_node(ws->cond, "Invalid body for `when` statement"); - return; - } - if (operand.value.kind == ExactValue_Bool && - operand.value.value_bool) { - check_stmt_list(c, ws->body->BlockStmt.stmts, flags); - } else if (ws->else_stmt) { - switch (ws->else_stmt->kind) { - case AstNode_BlockStmt: - check_stmt_list(c, ws->else_stmt->BlockStmt.stmts, flags); - break; - case AstNode_WhenStmt: - check_when_stmt(c, &ws->else_stmt->WhenStmt, flags); - break; - default: - error_node(ws->else_stmt, "Invalid `else` statement in `when` statement"); - break; - } - } -} - -void check_stmt_internal(Checker *c, AstNode *node, u32 flags) { - u32 mod_flags = flags & (~Stmt_FallthroughAllowed); - switch (node->kind) { - case_ast_node(_, EmptyStmt, node); case_end; - case_ast_node(_, BadStmt, node); case_end; - case_ast_node(_, BadDecl, node); case_end; - - case_ast_node(es, ExprStmt, node) - Operand operand = {Addressing_Invalid}; - ExprKind kind = check_expr_base(c, &operand, es->expr, NULL); - switch (operand.mode) { - case Addressing_Type: - error_node(node, "Is not an expression"); - break; - case Addressing_NoValue: - return; - default: { - if (kind == Expr_Stmt) { - return; - } - if (operand.expr->kind == AstNode_CallExpr) { - return; - } - if (operand.expr->kind == AstNode_GiveExpr) { - if ((flags&Stmt_GiveAllowed) != 0) { - return; - } - error_node(node, "Illegal use of `give`"); - } - gbString expr_str = expr_to_string(operand.expr); - error_node(node, "Expression is not used: `%s`", expr_str); - gb_string_free(expr_str); - } break; - } - case_end; - - case_ast_node(ts, TagStmt, node); - // TODO(bill): Tag Statements - error_node(node, "Tag statements are not supported yet"); - check_stmt(c, ts->stmt, flags); - case_end; - - case_ast_node(as, AssignStmt, node); - switch (as->op.kind) { - case Token_Eq: { - // a, b, c = 1, 2, 3; // Multisided - if (as->lhs.count == 0) { - error(as->op, "Missing lhs in assignment statement"); - return; - } - - gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&c->tmp_arena); - - // NOTE(bill): If there is a bad syntax error, rhs > lhs which would mean there would need to be - // an extra allocation - Array(Operand) operands; - array_init_reserve(&operands, c->tmp_allocator, 2 * as->lhs.count); - - for_array(i, as->rhs) { - AstNode *rhs = as->rhs.e[i]; - Operand o = {0}; - check_multi_expr(c, &o, rhs); - if (o.type->kind != Type_Tuple) { - array_add(&operands, o); - } else { - TypeTuple *tuple = &o.type->Tuple; - for (isize j = 0; j < tuple->variable_count; j++) { - o.type = tuple->variables[j]->type; - array_add(&operands, o); - } - } - } - - isize lhs_count = as->lhs.count; - isize rhs_count = operands.count; - - isize operand_count = gb_min(as->lhs.count, operands.count); - for (isize i = 0; i < operand_count; i++) { - AstNode *lhs = as->lhs.e[i]; - check_assignment_variable(c, &operands.e[i], lhs); - } - if (lhs_count != rhs_count) { - error_node(as->lhs.e[0], "Assignment count mismatch `%td` = `%td`", lhs_count, rhs_count); - } - - gb_temp_arena_memory_end(tmp); - } break; - - default: { - // a += 1; // Single-sided - Token op = as->op; - if (as->lhs.count != 1 || as->rhs.count != 1) { - error(op, "Assignment operation `%.*s` requires single-valued expressions", LIT(op.string)); - return; - } - if (!gb_is_between(op.kind, Token__AssignOpBegin+1, Token__AssignOpEnd-1)) { - error(op, "Unknown Assignment operation `%.*s`", LIT(op.string)); - return; - } - // TODO(bill): Check if valid assignment operator - Operand operand = {Addressing_Invalid}; - AstNode binary_expr = {AstNode_BinaryExpr}; - ast_node(be, BinaryExpr, &binary_expr); - 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]; - - 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]); - } break; - } - case_end; - - case_ast_node(bs, BlockStmt, node); - check_open_scope(c, node); - check_stmt_list(c, bs->stmts, mod_flags); - check_close_scope(c); - case_end; - - case_ast_node(is, IfStmt, node); - check_open_scope(c, node); - - if (is->init != NULL) { - check_stmt(c, is->init, 0); - } - - Operand operand = {Addressing_Invalid}; - check_expr(c, &operand, is->cond); - if (operand.mode != Addressing_Invalid && !is_type_boolean(operand.type)) { - error_node(is->cond, "Non-boolean condition in `if` statement"); - } - - check_stmt(c, is->body, mod_flags); - - if (is->else_stmt != NULL) { - switch (is->else_stmt->kind) { - case AstNode_IfStmt: - case AstNode_BlockStmt: - check_stmt(c, is->else_stmt, mod_flags); - break; - default: - error_node(is->else_stmt, "Invalid `else` statement in `if` statement"); - break; - } - } - - check_close_scope(c); - case_end; - - case_ast_node(ws, WhenStmt, node); - check_when_stmt(c, ws, flags); - case_end; - - case_ast_node(rs, ReturnStmt, node); - GB_ASSERT(c->proc_stack.count > 0); - - if (c->in_defer) { - error(rs->token, "You cannot `return` within a defer statement"); - // TODO(bill): Should I break here? - break; - } - - - Type *proc_type = c->proc_stack.e[c->proc_stack.count-1]; - isize result_count = 0; - if (proc_type->Proc.results) { - result_count = proc_type->Proc.results->Tuple.variable_count; - } - - if (result_count > 0) { - Entity **variables = NULL; - if (proc_type->Proc.results != NULL) { - TypeTuple *tuple = &proc_type->Proc.results->Tuple; - variables = tuple->variables; - } - if (rs->results.count == 0) { - error_node(node, "Expected %td return values, got 0", result_count); - } else { - check_init_variables(c, variables, result_count, - rs->results, str_lit("return statement")); - } - } else if (rs->results.count > 0) { - error_node(rs->results.e[0], "No return values expected"); - } - case_end; - - case_ast_node(ws, WhileStmt, node); - u32 new_flags = mod_flags | Stmt_BreakAllowed | Stmt_ContinueAllowed; - check_open_scope(c, node); - - if (ws->init != NULL) { - check_stmt(c, ws->init, 0); - } - if (ws->cond) { - Operand operand = {Addressing_Invalid}; - check_expr(c, &operand, ws->cond); - if (operand.mode != Addressing_Invalid && - !is_type_boolean(operand.type)) { - error_node(ws->cond, "Non-boolean condition in `while` statement"); - } - } - check_stmt(c, ws->body, new_flags); - - check_close_scope(c); - case_end; - - case_ast_node(rs, ForStmt, node); - u32 new_flags = mod_flags | Stmt_BreakAllowed | Stmt_ContinueAllowed; - check_open_scope(c, node); - - Type *val = NULL; - Type *idx = NULL; - Entity *entities[2] = {0}; - isize entity_count = 0; - - - if (rs->expr != NULL && rs->expr->kind == AstNode_IntervalExpr) { - ast_node(ie, IntervalExpr, rs->expr); - Operand x = {Addressing_Invalid}; - Operand y = {Addressing_Invalid}; - - check_expr(c, &x, ie->left); - if (x.mode == Addressing_Invalid) { - goto skip_expr; - } - check_expr(c, &y, ie->right); - if (y.mode == Addressing_Invalid) { - goto skip_expr; - } - - convert_to_typed(c, &x, y.type, 0); - if (x.mode == Addressing_Invalid) { - goto skip_expr; - } - convert_to_typed(c, &y, x.type, 0); - if (y.mode == Addressing_Invalid) { - goto skip_expr; - } - - convert_to_typed(c, &x, default_type(y.type), 0); - if (x.mode == Addressing_Invalid) { - goto skip_expr; - } - convert_to_typed(c, &y, default_type(x.type), 0); - if (y.mode == Addressing_Invalid) { - goto skip_expr; - } - - if (!are_types_identical(x.type, y.type)) { - if (x.type != t_invalid && - y.type != t_invalid) { - gbString xt = type_to_string(x.type); - gbString yt = type_to_string(y.type); - gbString expr_str = expr_to_string(x.expr); - error(ie->op, "Mismatched types in interval expression `%s` : `%s` vs `%s`", expr_str, xt, yt); - gb_string_free(expr_str); - gb_string_free(yt); - gb_string_free(xt); - } - goto skip_expr; - } - - Type *type = x.type; - Type *bt = base_type(base_enum_type(type)); - - if (!is_type_integer(bt) && !is_type_float(bt) && !is_type_pointer(bt)) { - error(ie->op, "Only numerical and pointer types are allowed within interval expressions"); - goto skip_expr; - } - - if (x.mode == Addressing_Constant && - y.mode == Addressing_Constant) { - ExactValue a = x.value; - ExactValue b = y.value; - - GB_ASSERT(are_types_identical(x.type, y.type)); - - bool ok = compare_exact_values(Token_Lt, a, b); - if (!ok) { - // TODO(bill): Better error message - error(ie->op, "Invalid interval range"); - goto skip_expr; - } - } - - add_type_and_value(&c->info, ie->left, x.mode, x.type, x.value); - add_type_and_value(&c->info, ie->right, y.mode, y.type, y.value); - val = type; - idx = t_int; - } else { - Operand operand = {Addressing_Invalid}; - check_expr(c, &operand, rs->expr); - - if (operand.mode != Addressing_Invalid) { - Type *t = base_type(type_deref(operand.type)); - switch (t->kind) { - case Type_Basic: - if (is_type_string(t)) { - val = t_rune; - idx = t_int; - } - break; - case Type_Array: - val = t->Array.elem; - idx = t_int; - break; - case Type_Slice: - val = t->Array.elem; - idx = t_int; - break; - } - } - - if (val == NULL) { - gbString s = expr_to_string(operand.expr); - gbString t = type_to_string(operand.type); - error_node(operand.expr, "Cannot iterate over `%s` of type `%s`", s, t); - gb_string_free(t); - gb_string_free(s); - } - } - - skip_expr: - AstNode *lhs[2] = {rs->value, rs->index}; - Type * rhs[2] = {val, idx}; - - for (isize i = 0; i < 2; i++) { - if (lhs[i] == NULL) { - continue; - } - AstNode *name = lhs[i]; - Type * type = rhs[i]; - - Entity *entity = NULL; - if (name->kind == AstNode_Ident) { - Token token = name->Ident; - String str = token.string; - Entity *found = NULL; - - if (str_ne(str, str_lit("_"))) { - found = current_scope_lookup_entity(c->context.scope, str); - } - if (found == NULL) { - entity = make_entity_variable(c->allocator, c->context.scope, token, type); - entity->Variable.is_immutable = true; - add_entity_definition(&c->info, name, entity); - } else { - TokenPos pos = found->token.pos; - error(token, - "Redeclaration of `%.*s` in this scope\n" - "\tat %.*s(%td:%td)", - LIT(str), LIT(pos.file), pos.line, pos.column); - entity = found; - } - } else { - error_node(name, "A variable declaration must be an identifier"); - } - - if (entity == NULL) { - entity = make_entity_dummy_variable(c->allocator, c->global_scope, ast_node_token(name)); - } - - entities[entity_count++] = entity; - - if (type == NULL) { - entity->type = t_invalid; - entity->flags |= EntityFlag_Used; - } - } - - for (isize i = 0; i < entity_count; i++) { - add_entity(c, c->context.scope, entities[i]->identifier, entities[i]); - } - - check_stmt(c, rs->body, new_flags); - - check_close_scope(c); - case_end; - - case_ast_node(ms, MatchStmt, node); - Operand x = {0}; - - mod_flags |= Stmt_BreakAllowed; - check_open_scope(c, node); - - if (ms->init != NULL) { - check_stmt(c, ms->init, 0); - } - if (ms->tag != NULL) { - check_expr(c, &x, ms->tag); - check_assignment(c, &x, NULL, str_lit("match expression")); - } else { - x.mode = Addressing_Constant; - x.type = t_bool; - x.value = make_exact_value_bool(true); - - Token token = {0}; - token.pos = ast_node_token(ms->body).pos; - token.string = str_lit("true"); - x.expr = make_ident(c->curr_ast_file, token); - } - - // NOTE(bill): Check for multiple defaults - AstNode *first_default = NULL; - ast_node(bs, BlockStmt, ms->body); - for_array(i, bs->stmts) { - AstNode *stmt = bs->stmts.e[i]; - AstNode *default_stmt = NULL; - if (stmt->kind == AstNode_CaseClause) { - ast_node(cc, CaseClause, stmt); - if (cc->list.count == 0) { - default_stmt = stmt; - } - } else { - error_node(stmt, "Invalid AST - expected case clause"); - } - - if (default_stmt != NULL) { - if (first_default != NULL) { - TokenPos pos = ast_node_token(first_default).pos; - error_node(stmt, - "multiple `default` clauses\n" - "\tfirst at %.*s(%td:%td)", - LIT(pos.file), pos.line, pos.column); - } else { - first_default = default_stmt; - } - } - } - - MapTypeAndToken seen = {0}; // NOTE(bill): Multimap - map_type_and_token_init(&seen, heap_allocator()); - - for_array(i, bs->stmts) { - AstNode *stmt = bs->stmts.e[i]; - if (stmt->kind != AstNode_CaseClause) { - // NOTE(bill): error handled by above multiple default checker - continue; - } - ast_node(cc, CaseClause, stmt); - - - for_array(j, cc->list) { - AstNode *expr = cc->list.e[j]; - Operand y = {0}; - Operand z = {0}; - Token eq = {Token_CmpEq}; - - check_expr(c, &y, expr); - if (x.mode == Addressing_Invalid || - y.mode == Addressing_Invalid) { - continue; - } - convert_to_typed(c, &y, x.type, 0); - if (y.mode == Addressing_Invalid) { - continue; - } - - z = y; - check_comparison(c, &z, &x, eq); - if (z.mode == Addressing_Invalid) { - continue; - } - if (y.mode != Addressing_Constant) { - continue; - } - - if (y.value.kind != ExactValue_Invalid) { - HashKey key = hash_exact_value(y.value); - TypeAndToken *found = map_type_and_token_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); - TypeAndToken *taps = gb_alloc_array(c->tmp_allocator, TypeAndToken, count); - - map_type_and_token_multi_get_all(&seen, key, taps); - bool continue_outer = false; - - for (isize i = 0; i < count; i++) { - TypeAndToken tap = taps[i]; - if (are_types_identical(y.type, tap.type)) { - TokenPos pos = tap.token.pos; - gbString expr_str = expr_to_string(y.expr); - error_node(y.expr, - "Duplicate case `%s`\n" - "\tprevious case at %.*s(%td:%td)", - expr_str, - LIT(pos.file), pos.line, pos.column); - gb_string_free(expr_str); - continue_outer = true; - break; - } - } - - gb_temp_arena_memory_end(tmp); - - if (continue_outer) { - continue; - } - } - TypeAndToken tap = {y.type, ast_node_token(y.expr)}; - map_type_and_token_multi_insert(&seen, key, tap); - } - } - - check_open_scope(c, stmt); - u32 ft_flags = mod_flags; - if (i+1 < bs->stmts.count) { - ft_flags |= Stmt_FallthroughAllowed; - } - check_stmt_list(c, cc->stmts, ft_flags); - check_close_scope(c); - } - - map_type_and_token_destroy(&seen); - - check_close_scope(c); - case_end; - - case_ast_node(ms, TypeMatchStmt, node); - Operand x = {0}; - - mod_flags |= Stmt_BreakAllowed; - check_open_scope(c, node); - - bool is_union_ptr = false; - bool is_any = false; - - check_expr(c, &x, ms->tag); - check_assignment(c, &x, NULL, str_lit("type match expression")); - if (!check_valid_type_match_type(x.type, &is_union_ptr, &is_any)) { - gbString str = type_to_string(x.type); - error_node(x.expr, - "Invalid type for this type match expression, got `%s`", str); - gb_string_free(str); - break; - } - - - // NOTE(bill): Check for multiple defaults - AstNode *first_default = NULL; - ast_node(bs, BlockStmt, ms->body); - for_array(i, bs->stmts) { - AstNode *stmt = bs->stmts.e[i]; - AstNode *default_stmt = NULL; - if (stmt->kind == AstNode_CaseClause) { - ast_node(cc, CaseClause, stmt); - if (cc->list.count == 0) { - default_stmt = stmt; - } - } else { - error_node(stmt, "Invalid AST - expected case clause"); - } - - if (default_stmt != NULL) { - if (first_default != NULL) { - TokenPos pos = ast_node_token(first_default).pos; - error_node(stmt, - "Multiple `default` clauses\n" - "\tfirst at %.*s(%td:%td)", LIT(pos.file), pos.line, pos.column); - } else { - first_default = default_stmt; - } - } - } - - if (ms->var->kind != AstNode_Ident) { - break; - } - - - MapBool seen = {0}; - map_bool_init(&seen, heap_allocator()); - - for_array(i, bs->stmts) { - AstNode *stmt = bs->stmts.e[i]; - if (stmt->kind != AstNode_CaseClause) { - // NOTE(bill): error handled by above multiple default checker - continue; - } - ast_node(cc, CaseClause, stmt); - - // TODO(bill): Make robust - Type *bt = base_type(type_deref(x.type)); - - - AstNode *type_expr = cc->list.count > 0 ? cc->list.e[0] : NULL; - Type *case_type = NULL; - if (type_expr != NULL) { // Otherwise it's a default expression - Operand y = {0}; - check_expr_or_type(c, &y, type_expr); - - if (is_union_ptr) { - GB_ASSERT(is_type_union(bt)); - bool tag_type_found = false; - for (isize i = 0; i < bt->Record.field_count; i++) { - Entity *f = bt->Record.fields[i]; - if (are_types_identical(f->type, y.type)) { - tag_type_found = true; - break; - } - } - if (!tag_type_found) { - gbString type_str = type_to_string(y.type); - error_node(y.expr, - "Unknown tag type, got `%s`", type_str); - gb_string_free(type_str); - continue; - } - case_type = y.type; - } else if (is_any) { - case_type = y.type; - } else { - GB_PANIC("Unknown type to type match statement"); - } - - HashKey key = hash_pointer(y.type); - bool *found = map_bool_get(&seen, key); - if (found) { - TokenPos pos = cc->token.pos; - gbString expr_str = expr_to_string(y.expr); - error_node(y.expr, - "Duplicate type case `%s`\n" - "\tprevious type case at %.*s(%td:%td)", - expr_str, - LIT(pos.file), pos.line, pos.column); - gb_string_free(expr_str); - break; - } - map_bool_set(&seen, key, cast(bool)true); - } - - check_open_scope(c, stmt); - if (case_type != NULL) { - add_type_info_type(c, case_type); - - // NOTE(bill): Dummy type - Type *tt = case_type; - if (is_union_ptr) { - tt = make_type_pointer(c->allocator, case_type); - add_type_info_type(c, tt); - } - Entity *tag_var = make_entity_variable(c->allocator, c->context.scope, ms->var->Ident, tt); - tag_var->flags |= EntityFlag_Used; - tag_var->Variable.is_immutable = true; - add_entity(c, c->context.scope, ms->var, tag_var); - add_entity_use(c, ms->var, tag_var); - } - check_stmt_list(c, cc->stmts, mod_flags); - check_close_scope(c); - } - map_bool_destroy(&seen); - - check_close_scope(c); - case_end; - - - case_ast_node(ds, DeferStmt, node); - if (is_ast_node_decl(ds->stmt)) { - error(ds->token, "You cannot defer a declaration"); - } else { - bool out_in_defer = c->in_defer; - c->in_defer = true; - check_stmt(c, ds->stmt, 0); - c->in_defer = out_in_defer; - } - case_end; - - case_ast_node(bs, BranchStmt, node); - Token token = bs->token; - switch (token.kind) { - case Token_break: - if ((flags & Stmt_BreakAllowed) == 0) { - error(token, "`break` only allowed in loops or `match` statements"); - } - break; - case Token_continue: - if ((flags & Stmt_ContinueAllowed) == 0) { - error(token, "`continue` only allowed in loops"); - } - break; - case Token_fallthrough: - if ((flags & Stmt_FallthroughAllowed) == 0) { - error(token, "`fallthrough` statement in illegal position"); - } - break; - default: - error(token, "Invalid AST: Branch Statement `%.*s`", LIT(token.string)); - break; - } - case_end; - - case_ast_node(us, UsingStmt, node); - switch (us->node->kind) { - case_ast_node(es, ExprStmt, us->node); - // TODO(bill): Allow for just a LHS expression list rather than this silly code - Entity *e = NULL; - - bool is_selector = false; - AstNode *expr = unparen_expr(es->expr); - if (expr->kind == AstNode_Ident) { - String name = expr->Ident.string; - e = scope_lookup_entity(c->context.scope, name); - } else if (expr->kind == AstNode_SelectorExpr) { - Operand o = {0}; - e = check_selector(c, &o, expr); - is_selector = true; - } - - if (e == NULL) { - error(us->token, "`using` applied to an unknown entity"); - return; - } - - switch (e->kind) { - case Entity_TypeName: { - Type *t = base_type(e->type); - if (is_type_union(t)) { - for (isize i = 0; i < t->Record.field_count; i++) { - Entity *f = t->Record.fields[i]; - Entity *found = scope_insert_entity(c->context.scope, f); - if (found != NULL) { - gbString expr_str = expr_to_string(expr); - error(us->token, "Namespace collision while `using` `%s` of: %.*s", expr_str, LIT(found->token.string)); - gb_string_free(expr_str); - return; - } - f->using_parent = e; - } - } else if (is_type_enum(t)) { - for (isize i = 0; i < t->Record.field_count; i++) { - Entity *f = t->Record.fields[i]; - Entity *found = scope_insert_entity(c->context.scope, f); - if (found != NULL) { - gbString expr_str = expr_to_string(expr); - error(us->token, "Namespace collision while `using` `%s` of: %.*s", expr_str, LIT(found->token.string)); - gb_string_free(expr_str); - return; - } - f->using_parent = e; - } - - } else { - error(us->token, "`using` can be only applied to `union` or `enum` type entities"); - } - } break; - - case Entity_ImportName: { - Scope *scope = e->ImportName.scope; - for_array(i, scope->elements.entries) { - Entity *decl = scope->elements.entries.e[i].value; - Entity *found = scope_insert_entity(c->context.scope, decl); - if (found != NULL) { - gbString expr_str = expr_to_string(expr); - error(us->token, - "Namespace collision while `using` `%s` of: %.*s\n" - "\tat %.*s(%td:%td)\n" - "\tat %.*s(%td:%td)", - expr_str, LIT(found->token.string), - LIT(found->token.pos.file), found->token.pos.line, found->token.pos.column, - LIT(decl->token.pos.file), decl->token.pos.line, decl->token.pos.column - ); - gb_string_free(expr_str); - return; - } - } - } break; - - case Entity_Variable: { - 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)); - GB_ASSERT(found != NULL); - for_array(i, (*found)->elements.entries) { - Entity *f = (*found)->elements.entries.e[i].value; - if (f->kind == Entity_Variable) { - Entity *uvar = make_entity_using_variable(c->allocator, e, f->token, f->type); - if (is_selector) { - uvar->using_expr = expr; - } - Entity *prev = scope_insert_entity(c->context.scope, uvar); - if (prev != NULL) { - gbString expr_str = expr_to_string(expr); - error(us->token, "Namespace collision while `using` `%s` of: %.*s", expr_str, LIT(prev->token.string)); - gb_string_free(expr_str); - return; - } - } - } - } else { - error(us->token, "`using` can only be applied to variables of type struct or raw_union"); - return; - } - } break; - - case Entity_Constant: - error(us->token, "`using` cannot be applied to a constant"); - break; - - case Entity_Procedure: - case Entity_Builtin: - error(us->token, "`using` cannot be applied to a procedure"); - break; - - case Entity_ImplicitValue: - error(us->token, "`using` cannot be applied to an implicit value"); - break; - - case Entity_Nil: - error(us->token, "`using` cannot be applied to `nil`"); - break; - - case Entity_Invalid: - error(us->token, "`using` cannot be applied to an invalid entity"); - break; - - default: - GB_PANIC("TODO(bill): `using` other expressions?"); - } - case_end; - - case_ast_node(vd, ValueDecl, us->node); - if (!vd->is_var) { - error_node(us->node, "`using` can only be applied to a variable declaration"); - return; - } - - if (vd->names.count > 1 && vd->type != NULL) { - error(us->token, "`using` can only be applied to one variable of the same type"); - } - - check_var_decl_node(c, vd); - - for_array(name_index, vd->names) { - AstNode *item = vd->names.e[name_index]; - if (item->kind != AstNode_Ident) { - // TODO(bill): Handle error here??? - continue; - } - ast_node(i, Ident, item); - String name = i->string; - Entity *e = scope_lookup_entity(c->context.scope, name); - 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)); - GB_ASSERT(found != NULL); - for_array(i, (*found)->elements.entries) { - Entity *f = (*found)->elements.entries.e[i].value; - if (f->kind == Entity_Variable) { - Entity *uvar = make_entity_using_variable(c->allocator, e, f->token, f->type); - Entity *prev = scope_insert_entity(c->context.scope, uvar); - if (prev != NULL) { - error(us->token, "Namespace collision while `using` `%.*s` of: %.*s", LIT(name), LIT(prev->token.string)); - return; - } - } - } - } else { - error(us->token, "`using` can only be applied to variables of type struct or raw_union"); - return; - } - } - case_end; - - default: - error(us->token, "Invalid AST: Using Statement"); - break; - } - case_end; - - - - case_ast_node(pa, PushAllocator, node); - Operand op = {0}; - 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); - case_end; - - - case_ast_node(pa, PushContext, node); - Operand op = {0}; - 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); - case_end; - - - case_ast_node(vd, ValueDecl, node); - if (vd->is_var) { - isize entity_count = vd->names.count; - isize entity_index = 0; - Entity **entities = gb_alloc_array(c->allocator, Entity *, entity_count); - - for_array(i, vd->names) { - AstNode *name = vd->names.e[i]; - Entity *entity = NULL; - if (name->kind == AstNode_Ident) { - Token token = name->Ident; - String str = token.string; - Entity *found = NULL; - // NOTE(bill): Ignore assignments to `_` - if (str_ne(str, str_lit("_"))) { - found = current_scope_lookup_entity(c->context.scope, str); - } - if (found == NULL) { - entity = make_entity_variable(c->allocator, c->context.scope, token, NULL); - add_entity_definition(&c->info, name, entity); - } else { - TokenPos pos = found->token.pos; - error(token, - "Redeclaration of `%.*s` in this scope\n" - "\tat %.*s(%td:%td)", - LIT(str), LIT(pos.file), pos.line, pos.column); - entity = found; - } - } else { - error_node(name, "A variable declaration must be an identifier"); - } - if (entity == NULL) { - entity = make_entity_dummy_variable(c->allocator, c->global_scope, ast_node_token(name)); - } - entities[entity_index++] = entity; - } - - Type *init_type = NULL; - if (vd->type) { - init_type = check_type_extra(c, vd->type, NULL); - if (init_type == NULL) { - init_type = t_invalid; - } - } - - for (isize i = 0; i < entity_count; i++) { - Entity *e = entities[i]; - GB_ASSERT(e != NULL); - if (e->flags & EntityFlag_Visited) { - e->type = t_invalid; - continue; - } - e->flags |= EntityFlag_Visited; - - if (e->type == NULL) - e->type = init_type; - } - check_arity_match(c, vd); - - check_init_variables(c, entities, entity_count, vd->values, str_lit("variable declaration")); - - for_array(i, vd->names) { - if (entities[i] != NULL) { - add_entity(c, c->context.scope, vd->names.e[i], entities[i]); - } - } - } else { - // NOTE(bill): Handled elsewhere - } - case_end; - } -} diff --git a/src/checker/types.c b/src/checker/types.c deleted file mode 100644 index 779924cd4..000000000 --- a/src/checker/types.c +++ /dev/null @@ -1,1703 +0,0 @@ -typedef struct Scope Scope; - -typedef enum BasicKind { - Basic_Invalid, - Basic_bool, - Basic_i8, - Basic_u8, - Basic_i16, - Basic_u16, - Basic_i32, - Basic_u32, - Basic_i64, - Basic_u64, - // Basic_i128, - // Basic_u128, - // Basic_f16, - Basic_f32, - Basic_f64, - // Basic_f128, - Basic_int, - Basic_uint, - Basic_rawptr, - Basic_string, // ^u8 + int - Basic_any, // ^Type_Info + rawptr - - Basic_UntypedBool, - Basic_UntypedInteger, - Basic_UntypedFloat, - Basic_UntypedString, - Basic_UntypedRune, - Basic_UntypedNil, - - Basic_Count, - - Basic_byte = Basic_u8, - Basic_rune = Basic_i32, -} BasicKind; - -typedef enum BasicFlag { - BasicFlag_Boolean = GB_BIT(0), - BasicFlag_Integer = GB_BIT(1), - BasicFlag_Unsigned = GB_BIT(2), - BasicFlag_Float = GB_BIT(3), - BasicFlag_Pointer = GB_BIT(4), - BasicFlag_String = GB_BIT(5), - BasicFlag_Rune = GB_BIT(6), - BasicFlag_Untyped = GB_BIT(7), - - BasicFlag_Numeric = BasicFlag_Integer | BasicFlag_Float, - BasicFlag_Ordered = BasicFlag_Numeric | BasicFlag_String | BasicFlag_Pointer, - BasicFlag_ConstantType = BasicFlag_Boolean | BasicFlag_Numeric | BasicFlag_Pointer | BasicFlag_String | BasicFlag_Rune, -} BasicFlag; - -typedef struct BasicType { - BasicKind kind; - u32 flags; - i64 size; // -1 if arch. dep. - String name; -} BasicType; - -typedef enum TypeRecordKind { - TypeRecord_Invalid, - - TypeRecord_Struct, - TypeRecord_RawUnion, - TypeRecord_Union, // Tagged - TypeRecord_Enum, - - TypeRecord_Count, -} TypeRecordKind; - -typedef struct TypeRecord { - TypeRecordKind kind; - - // All record types - // Theses are arrays - Entity **fields; // Entity_Variable (otherwise Entity_TypeName if union) - i32 field_count; // == offset_count is struct - AstNode *node; - - i64 * struct_offsets; - bool struct_are_offsets_set; - bool struct_is_packed; - bool struct_is_ordered; - Entity **fields_in_src_order; // Entity_Variable - - Type * enum_base_type; -} TypeRecord; - -#define TYPE_KINDS \ - TYPE_KIND(Basic, BasicType) \ - TYPE_KIND(Pointer, struct { Type *elem; }) \ - TYPE_KIND(Array, struct { Type *elem; i64 count; }) \ - TYPE_KIND(Vector, struct { Type *elem; i64 count; }) \ - TYPE_KIND(Slice, struct { Type *elem; }) \ - TYPE_KIND(Maybe, struct { Type *elem; }) \ - TYPE_KIND(Record, TypeRecord) \ - TYPE_KIND(Named, struct { \ - String name; \ - Type * base; \ - Entity *type_name; /* Entity_TypeName */ \ - }) \ - TYPE_KIND(Tuple, struct { \ - Entity **variables; /* Entity_Variable */ \ - i32 variable_count; \ - bool are_offsets_set; \ - i64 * offsets; \ - }) \ - TYPE_KIND(Proc, struct { \ - Scope *scope; \ - Type * params; /* Type_Tuple */ \ - Type * results; /* Type_Tuple */ \ - i32 param_count; \ - i32 result_count; \ - bool variadic; \ - ProcCallingConvention calling_convention; \ - }) - - - -typedef 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")}, -#define TYPE_KIND(k, ...) {cast(u8 *)#k, gb_size_of(#k)-1}, - TYPE_KINDS -#undef TYPE_KIND -}; - -#define TYPE_KIND(k, ...) typedef __VA_ARGS__ GB_JOIN2(Type, k); - TYPE_KINDS -#undef TYPE_KIND - -typedef struct Type { - TypeKind kind; - union { -#define TYPE_KIND(k, ...) GB_JOIN2(Type, k) k; - TYPE_KINDS -#undef TYPE_KIND - }; - bool failure; -} Type; - -// NOTE(bill): Internal sizes of certain types -// string: 2*word_size (ptr+len) -// slice: 3*word_size (ptr+len+cap) -// array: count*size_of(elem) aligned - -// NOTE(bill): Alignment of structures and other types are to be compatible with C - -typedef struct BaseTypeSizes { - i64 word_size; - i64 max_align; -} BaseTypeSizes; - -typedef Array(isize) Array_isize; - -typedef struct Selection { - Entity * entity; - Array_isize index; - bool indirect; // Set if there was a pointer deref anywhere down the line -} Selection; -Selection empty_selection = {0}; - -Selection make_selection(Entity *entity, Array_isize index, bool indirect) { - Selection s = {entity, index, indirect}; - return s; -} - -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 - if (s->index.e == NULL) { - array_init(&s->index, heap_allocator()); - } - array_add(&s->index, index); -} - - - -#define STR_LIT(x) {cast(u8 *)(x), gb_size_of(x)-1} -gb_global Type basic_types[] = { - {Type_Basic, {Basic_Invalid, 0, 0, STR_LIT("invalid type")}}, - {Type_Basic, {Basic_bool, BasicFlag_Boolean, 1, STR_LIT("bool")}}, - {Type_Basic, {Basic_i8, BasicFlag_Integer, 1, STR_LIT("i8")}}, - {Type_Basic, {Basic_u8, BasicFlag_Integer | BasicFlag_Unsigned, 1, STR_LIT("u8")}}, - {Type_Basic, {Basic_i16, BasicFlag_Integer, 2, STR_LIT("i16")}}, - {Type_Basic, {Basic_u16, BasicFlag_Integer | BasicFlag_Unsigned, 2, STR_LIT("u16")}}, - {Type_Basic, {Basic_i32, BasicFlag_Integer, 4, STR_LIT("i32")}}, - {Type_Basic, {Basic_u32, BasicFlag_Integer | BasicFlag_Unsigned, 4, STR_LIT("u32")}}, - {Type_Basic, {Basic_i64, BasicFlag_Integer, 8, STR_LIT("i64")}}, - {Type_Basic, {Basic_u64, BasicFlag_Integer | BasicFlag_Unsigned, 8, STR_LIT("u64")}}, - // {Type_Basic, {Basic_i128, BasicFlag_Integer, 16, STR_LIT("i128")}}, - // {Type_Basic, {Basic_u128, BasicFlag_Integer | BasicFlag_Unsigned, 16, STR_LIT("u128")}}, - // {Type_Basic, {Basic_f16, BasicFlag_Float, 2, STR_LIT("f16")}}, - {Type_Basic, {Basic_f32, BasicFlag_Float, 4, STR_LIT("f32")}}, - {Type_Basic, {Basic_f64, BasicFlag_Float, 8, STR_LIT("f64")}}, - // {Type_Basic, {Basic_f128, BasicFlag_Float, 16, STR_LIT("f128")}}, - {Type_Basic, {Basic_int, BasicFlag_Integer, -1, STR_LIT("int")}}, - {Type_Basic, {Basic_uint, BasicFlag_Integer | BasicFlag_Unsigned, -1, STR_LIT("uint")}}, - {Type_Basic, {Basic_rawptr, BasicFlag_Pointer, -1, STR_LIT("rawptr")}}, - {Type_Basic, {Basic_string, BasicFlag_String, -1, STR_LIT("string")}}, - {Type_Basic, {Basic_any, 0, -1, STR_LIT("any")}}, - {Type_Basic, {Basic_UntypedBool, BasicFlag_Boolean | BasicFlag_Untyped, 0, STR_LIT("untyped bool")}}, - {Type_Basic, {Basic_UntypedInteger, BasicFlag_Integer | BasicFlag_Untyped, 0, STR_LIT("untyped integer")}}, - {Type_Basic, {Basic_UntypedFloat, BasicFlag_Float | BasicFlag_Untyped, 0, STR_LIT("untyped float")}}, - {Type_Basic, {Basic_UntypedString, BasicFlag_String | BasicFlag_Untyped, 0, STR_LIT("untyped string")}}, - {Type_Basic, {Basic_UntypedRune, BasicFlag_Integer | BasicFlag_Untyped, 0, STR_LIT("untyped rune")}}, - {Type_Basic, {Basic_UntypedNil, BasicFlag_Untyped, 0, STR_LIT("untyped nil")}}, -}; - -gb_global Type basic_type_aliases[] = { - {Type_Basic, {Basic_byte, BasicFlag_Integer | BasicFlag_Unsigned, 1, STR_LIT("byte")}}, - {Type_Basic, {Basic_rune, BasicFlag_Integer, 4, STR_LIT("rune")}}, -}; - -gb_global Type *t_invalid = &basic_types[Basic_Invalid]; -gb_global Type *t_bool = &basic_types[Basic_bool]; -gb_global Type *t_i8 = &basic_types[Basic_i8]; -gb_global Type *t_u8 = &basic_types[Basic_u8]; -gb_global Type *t_i16 = &basic_types[Basic_i16]; -gb_global Type *t_u16 = &basic_types[Basic_u16]; -gb_global Type *t_i32 = &basic_types[Basic_i32]; -gb_global Type *t_u32 = &basic_types[Basic_u32]; -gb_global Type *t_i64 = &basic_types[Basic_i64]; -gb_global Type *t_u64 = &basic_types[Basic_u64]; -// gb_global Type *t_i128 = &basic_types[Basic_i128]; -// gb_global Type *t_u128 = &basic_types[Basic_u128]; -// gb_global Type *t_f16 = &basic_types[Basic_f16]; -gb_global Type *t_f32 = &basic_types[Basic_f32]; -gb_global Type *t_f64 = &basic_types[Basic_f64]; -// gb_global Type *t_f128 = &basic_types[Basic_f128]; -gb_global Type *t_int = &basic_types[Basic_int]; -gb_global Type *t_uint = &basic_types[Basic_uint]; -gb_global Type *t_rawptr = &basic_types[Basic_rawptr]; -gb_global Type *t_string = &basic_types[Basic_string]; -gb_global Type *t_any = &basic_types[Basic_any]; -gb_global Type *t_untyped_bool = &basic_types[Basic_UntypedBool]; -gb_global Type *t_untyped_integer = &basic_types[Basic_UntypedInteger]; -gb_global Type *t_untyped_float = &basic_types[Basic_UntypedFloat]; -gb_global Type *t_untyped_string = &basic_types[Basic_UntypedString]; -gb_global Type *t_untyped_rune = &basic_types[Basic_UntypedRune]; -gb_global Type *t_untyped_nil = &basic_types[Basic_UntypedNil]; -gb_global Type *t_byte = &basic_type_aliases[0]; -gb_global Type *t_rune = &basic_type_aliases[1]; - - -gb_global Type *t_u8_ptr = NULL; -gb_global Type *t_int_ptr = NULL; - -gb_global Type *t_type_info = NULL; -gb_global Type *t_type_info_ptr = NULL; -gb_global Type *t_type_info_member = NULL; -gb_global Type *t_type_info_member_ptr = NULL; - -gb_global Type *t_type_info_named = NULL; -gb_global Type *t_type_info_integer = NULL; -gb_global Type *t_type_info_float = NULL; -gb_global Type *t_type_info_any = NULL; -gb_global Type *t_type_info_string = NULL; -gb_global Type *t_type_info_boolean = NULL; -gb_global Type *t_type_info_pointer = NULL; -gb_global Type *t_type_info_maybe = NULL; -gb_global Type *t_type_info_procedure = NULL; -gb_global Type *t_type_info_array = NULL; -gb_global Type *t_type_info_slice = NULL; -gb_global Type *t_type_info_vector = NULL; -gb_global Type *t_type_info_tuple = NULL; -gb_global Type *t_type_info_struct = NULL; -gb_global Type *t_type_info_union = NULL; -gb_global Type *t_type_info_raw_union = NULL; -gb_global Type *t_type_info_enum = NULL; - - -gb_global Type *t_type_info_named_ptr = NULL; -gb_global Type *t_type_info_integer_ptr = NULL; -gb_global Type *t_type_info_float_ptr = NULL; -gb_global Type *t_type_info_any_ptr = NULL; -gb_global Type *t_type_info_string_ptr = NULL; -gb_global Type *t_type_info_boolean_ptr = NULL; -gb_global Type *t_type_info_pointer_ptr = NULL; -gb_global Type *t_type_info_maybe_ptr = NULL; -gb_global Type *t_type_info_procedure_ptr = NULL; -gb_global Type *t_type_info_array_ptr = NULL; -gb_global Type *t_type_info_slice_ptr = NULL; -gb_global Type *t_type_info_vector_ptr = NULL; -gb_global Type *t_type_info_tuple_ptr = NULL; -gb_global Type *t_type_info_struct_ptr = NULL; -gb_global Type *t_type_info_union_ptr = NULL; -gb_global Type *t_type_info_raw_union_ptr = NULL; -gb_global Type *t_type_info_enum_ptr = NULL; - - - -gb_global Type *t_allocator = NULL; -gb_global Type *t_allocator_ptr = NULL; -gb_global Type *t_context = NULL; -gb_global Type *t_context_ptr = NULL; - - - - - - -gbString type_to_string(Type *type); - -Type *base_type(Type *t) { - for (;;) { - if (t == NULL) { - break; - } - if (t->kind != Type_Named) { - break; - } - if (t == t->Named.base) { - return t_invalid; - } - t = t->Named.base; - } - return t; -} - -Type *base_enum_type(Type *t) { - Type *bt = base_type(t); - if (bt != NULL && - bt->kind == Type_Record && - bt->Record.kind == TypeRecord_Enum) { - return bt->Record.enum_base_type; - } - return t; -} - -void set_base_type(Type *t, Type *base) { - if (t && t->kind == Type_Named) { - t->Named.base = base; - } -} - - -Type *alloc_type(gbAllocator a, TypeKind kind) { - Type *t = gb_alloc_item(a, Type); - t->kind = kind; - return t; -} - - -Type *make_type_basic(gbAllocator a, BasicType basic) { - Type *t = alloc_type(a, Type_Basic); - t->Basic = basic; - return t; -} - -Type *make_type_pointer(gbAllocator a, Type *elem) { - Type *t = alloc_type(a, Type_Pointer); - t->Pointer.elem = elem; - return t; -} - -Type *make_type_maybe(gbAllocator a, Type *elem) { - Type *t = alloc_type(a, Type_Maybe); - t->Maybe.elem = elem; - return t; -} - -Type *make_type_array(gbAllocator a, Type *elem, i64 count) { - Type *t = alloc_type(a, Type_Array); - t->Array.elem = elem; - t->Array.count = count; - return t; -} - -Type *make_type_vector(gbAllocator a, Type *elem, i64 count) { - Type *t = alloc_type(a, Type_Vector); - t->Vector.elem = elem; - t->Vector.count = count; - return t; -} - -Type *make_type_slice(gbAllocator a, Type *elem) { - Type *t = alloc_type(a, Type_Slice); - t->Array.elem = elem; - return t; -} - - -Type *make_type_struct(gbAllocator a) { - Type *t = alloc_type(a, Type_Record); - t->Record.kind = TypeRecord_Struct; - return t; -} - -Type *make_type_union(gbAllocator a) { - Type *t = alloc_type(a, Type_Record); - t->Record.kind = TypeRecord_Union; - return t; -} - -Type *make_type_raw_union(gbAllocator a) { - Type *t = alloc_type(a, Type_Record); - t->Record.kind = TypeRecord_RawUnion; - return t; -} - -Type *make_type_enum(gbAllocator a) { - Type *t = alloc_type(a, Type_Record); - t->Record.kind = TypeRecord_Enum; - return t; -} - - - - - -Type *make_type_named(gbAllocator a, String name, Type *base, Entity *type_name) { - Type *t = alloc_type(a, Type_Named); - t->Named.name = name; - t->Named.base = base; - t->Named.type_name = type_name; - return t; -} - -Type *make_type_tuple(gbAllocator a) { - Type *t = alloc_type(a, Type_Tuple); - return t; -} - -Type *make_type_proc(gbAllocator a, Scope *scope, Type *params, isize param_count, Type *results, isize result_count, bool variadic, ProcCallingConvention calling_convention) { - Type *t = alloc_type(a, Type_Proc); - - if (variadic) { - if (param_count == 0) { - GB_PANIC("variadic procedure must have at least one parameter"); - } - GB_ASSERT(params != NULL && params->kind == Type_Tuple); - Entity *e = params->Tuple.variables[param_count-1]; - if (base_type(e->type)->kind != Type_Slice) { - // NOTE(bill): For custom calling convention - GB_PANIC("variadic parameter must be of type slice"); - } - } - - t->Proc.scope = scope; - t->Proc.params = params; - t->Proc.param_count = param_count; - t->Proc.results = results; - t->Proc.result_count = result_count; - t->Proc.variadic = variadic; - t->Proc.calling_convention = calling_convention; - return t; -} - - -Type *type_deref(Type *t) { - if (t != NULL) { - Type *bt = base_type(t); - if (bt == NULL) - return NULL; - if (bt != NULL && bt->kind == Type_Pointer) - return bt->Pointer.elem; - } - return t; -} - -bool is_type_named(Type *t) { - if (t->kind == Type_Basic) { - return true; - } - return t->kind == Type_Named; -} -bool is_type_boolean(Type *t) { - t = base_type(t); - if (t->kind == Type_Basic) { - return (t->Basic.flags & BasicFlag_Boolean) != 0; - } - return false; -} -bool is_type_integer(Type *t) { - t = base_type(t); - if (t->kind == Type_Basic) { - return (t->Basic.flags & BasicFlag_Integer) != 0; - } - return false; -} -bool is_type_unsigned(Type *t) { - t = base_type(t); - if (t->kind == Type_Basic) { - return (t->Basic.flags & BasicFlag_Unsigned) != 0; - } - return false; -} -bool is_type_numeric(Type *t) { - t = base_type(t); - if (t->kind == Type_Basic) { - return (t->Basic.flags & BasicFlag_Numeric) != 0; - } - if (t->kind == Type_Vector) { - return is_type_numeric(t->Vector.elem); - } - return false; -} -bool is_type_string(Type *t) { - t = base_type(t); - if (t->kind == Type_Basic) { - return (t->Basic.flags & BasicFlag_String) != 0; - } - return false; -} -bool is_type_typed(Type *t) { - t = base_type(t); - if (t == NULL) { - return false; - } - if (t->kind == Type_Basic) { - return (t->Basic.flags & BasicFlag_Untyped) == 0; - } - return true; -} -bool is_type_untyped(Type *t) { - t = base_type(t); - if (t->kind == Type_Basic) { - return (t->Basic.flags & BasicFlag_Untyped) != 0; - } - return false; -} -bool is_type_ordered(Type *t) { - t = base_type(t); - if (t->kind == Type_Basic) { - return (t->Basic.flags & BasicFlag_Ordered) != 0; - } - if (t->kind == Type_Pointer) { - return true; - } - return false; -} -bool is_type_constant_type(Type *t) { - t = base_type(base_enum_type(t)); - if (t->kind == Type_Basic) { - return (t->Basic.flags & BasicFlag_ConstantType) != 0; - } - return false; -} -bool is_type_float(Type *t) { - t = base_type(t); - if (t->kind == Type_Basic) { - return (t->Basic.flags & BasicFlag_Float) != 0; - } - return false; -} -bool is_type_f32(Type *t) { - t = base_type(t); - if (t->kind == Type_Basic) { - return t->Basic.kind == Basic_f32; - } - return false; -} -bool is_type_f64(Type *t) { - t = base_type(t); - if (t->kind == Type_Basic) { - return t->Basic.kind == Basic_f64; - } - return false; -} -bool is_type_pointer(Type *t) { - t = base_type(t); - if (t->kind == Type_Basic) { - return (t->Basic.flags & BasicFlag_Pointer) != 0; - } - return t->kind == Type_Pointer; -} -bool is_type_maybe(Type *t) { - t = base_type(t); - return t->kind == Type_Maybe; -} -bool is_type_tuple(Type *t) { - t = base_type(t); - return t->kind == Type_Tuple; -} - - -bool is_type_int_or_uint(Type *t) { - if (t->kind == Type_Basic) { - return (t->Basic.kind == Basic_int) || (t->Basic.kind == Basic_uint); - } - return false; -} -bool is_type_rawptr(Type *t) { - if (t->kind == Type_Basic) { - return t->Basic.kind == Basic_rawptr; - } - return false; -} -bool is_type_u8(Type *t) { - if (t->kind == Type_Basic) { - return t->Basic.kind == Basic_u8; - } - return false; -} -bool is_type_array(Type *t) { - t = base_type(t); - return t->kind == Type_Array; -} -bool is_type_slice(Type *t) { - t = base_type(t); - return t->kind == Type_Slice; -} -bool is_type_u8_slice(Type *t) { - t = base_type(t); - if (t->kind == Type_Slice) { - return is_type_u8(t->Slice.elem); - } - return false; -} -bool is_type_vector(Type *t) { - t = base_type(t); - return t->kind == Type_Vector; -} -bool is_type_proc(Type *t) { - t = base_type(t); - return t->kind == Type_Proc; -} -Type *base_vector_type(Type *t) { - if (is_type_vector(t)) { - t = base_type(t); - return t->Vector.elem; - } - return t; -} - - -bool is_type_struct(Type *t) { - t = base_type(t); - return (t->kind == Type_Record && t->Record.kind == TypeRecord_Struct); -} -bool is_type_union(Type *t) { - t = base_type(t); - return (t->kind == Type_Record && t->Record.kind == TypeRecord_Union); -} -bool is_type_raw_union(Type *t) { - t = base_type(t); - return (t->kind == Type_Record && t->Record.kind == TypeRecord_RawUnion); -} -bool is_type_enum(Type *t) { - t = base_type(t); - return (t->kind == Type_Record && t->Record.kind == TypeRecord_Enum); -} - - -bool is_type_any(Type *t) { - t = base_type(t); - return (t->kind == Type_Basic && t->Basic.kind == Basic_any); -} -bool is_type_untyped_nil(Type *t) { - t = base_type(t); - return (t->kind == Type_Basic && t->Basic.kind == Basic_UntypedNil); -} - - - -bool is_type_indexable(Type *t) { - return is_type_array(t) || is_type_slice(t) || is_type_vector(t) || is_type_string(t); -} - - -bool type_has_nil(Type *t) { - t = base_type(t); - switch (t->kind) { - case Type_Basic: - return is_type_rawptr(t); - case Type_Slice: - case Type_Proc: - case Type_Pointer: - case Type_Maybe: - return true; - } - return false; -} - - -bool is_type_comparable(Type *t) { - t = base_type(t); - switch (t->kind) { - case Type_Basic: - return t->kind != Basic_UntypedNil; - case Type_Pointer: - return true; - case Type_Record: { - if (false && is_type_struct(t)) { - // TODO(bill): Should I even allow this? - for (isize i = 0; i < t->Record.field_count; i++) { - if (!is_type_comparable(t->Record.fields[i]->type)) - return false; - } - } else if (is_type_enum(t)) { - return is_type_comparable(base_enum_type(t)); - } - return false; - } break; - case Type_Array: - return false; - // return is_type_comparable(t->Array.elem); - case Type_Vector: - return is_type_comparable(t->Vector.elem); - case Type_Proc: - return true; - } - return false; -} - -bool are_types_identical(Type *x, Type *y) { - if (x == y) { - return true; - } - - if ((x == NULL && y != NULL) || - (x != NULL && y == NULL)) { - return false; - } - - switch (x->kind) { - case Type_Basic: - if (y->kind == Type_Basic) { - return x->Basic.kind == y->Basic.kind; - } - break; - - case Type_Array: - if (y->kind == Type_Array) { - return (x->Array.count == y->Array.count) && are_types_identical(x->Array.elem, y->Array.elem); - } - break; - - case Type_Vector: - if (y->kind == Type_Vector) { - return (x->Vector.count == y->Vector.count) && are_types_identical(x->Vector.elem, y->Vector.elem); - } - break; - - case Type_Slice: - if (y->kind == Type_Slice) { - return are_types_identical(x->Slice.elem, y->Slice.elem); - } - break; - - case Type_Record: - if (y->kind == Type_Record) { - if (x->Record.kind == y->Record.kind) { - switch (x->Record.kind) { - case TypeRecord_Struct: - case TypeRecord_RawUnion: - case TypeRecord_Union: - if (x->Record.field_count == y->Record.field_count && - x->Record.struct_is_packed == y->Record.struct_is_packed && - x->Record.struct_is_ordered == y->Record.struct_is_ordered) { - for (isize i = 0; i < x->Record.field_count; i++) { - if (!are_types_identical(x->Record.fields[i]->type, y->Record.fields[i]->type)) { - return false; - } - if (str_ne(x->Record.fields[i]->token.string, y->Record.fields[i]->token.string)) { - return false; - } - } - return true; - } - break; - case TypeRecord_Enum: - return x == y; // NOTE(bill): All enums are unique - } - } - } - break; - - case Type_Pointer: - if (y->kind == Type_Pointer) { - return are_types_identical(x->Pointer.elem, y->Pointer.elem); - } - break; - - case Type_Maybe: - if (y->kind == Type_Maybe) { - return are_types_identical(x->Maybe.elem, y->Maybe.elem); - } - break; - - case Type_Named: - if (y->kind == Type_Named) { - return x->Named.base == y->Named.base; - } - break; - - case Type_Tuple: - if (y->kind == Type_Tuple) { - if (x->Tuple.variable_count == y->Tuple.variable_count) { - for (isize i = 0; i < x->Tuple.variable_count; i++) { - if (!are_types_identical(x->Tuple.variables[i]->type, y->Tuple.variables[i]->type)) { - return false; - } - } - return true; - } - } - break; - - case Type_Proc: - if (y->kind == Type_Proc) { - return x->Proc.calling_convention == y->Proc.calling_convention && - are_types_identical(x->Proc.params, y->Proc.params) && - are_types_identical(x->Proc.results, y->Proc.results); - } - break; - } - - - return false; -} - - -Type *default_type(Type *type) { - if (type == NULL) { - return t_invalid; - } - if (type->kind == Type_Basic) { - switch (type->Basic.kind) { - case Basic_UntypedBool: return t_bool; - case Basic_UntypedInteger: return t_int; - case Basic_UntypedFloat: return t_f64; - case Basic_UntypedString: return t_string; - case Basic_UntypedRune: return t_rune; - } - } - return type; -} - -// NOTE(bill): Valid Compile time execution #run type -bool is_type_cte_safe(Type *type) { - type = default_type(base_type(type)); - switch (type->kind) { - case Type_Basic: - switch (type->Basic.kind) { - case Basic_rawptr: - case Basic_any: - return false; - } - return true; - - case Type_Pointer: - return false; - - case Type_Array: - return is_type_cte_safe(type->Array.elem); - - case Type_Vector: // NOTE(bill): This should always to be true but this is for sanity reasons - return is_type_cte_safe(type->Vector.elem); - - case Type_Slice: - return false; - - case Type_Maybe: - return is_type_cte_safe(type->Maybe.elem); - - case Type_Record: { - if (type->Record.kind != TypeRecord_Struct) { - return false; - } - for (isize i = 0; i < type->Record.field_count; i++) { - Entity *v = type->Record.fields[i]; - if (!is_type_cte_safe(v->type)) { - return false; - } - } - return true; - } - - case Type_Tuple: { - for (isize i = 0; i < type->Tuple.variable_count; i++) { - Entity *v = type->Tuple.variables[i]; - if (!is_type_cte_safe(v->type)) { - return false; - } - } - return true; - } - - case Type_Proc: - // TODO(bill): How should I handle procedures in the CTE stage? - // return type->Proc.calling_convention == ProcCC_Odin; - return false; - } - - return false; -} - - - - -gb_global Entity *entity__any_type_info = NULL; -gb_global Entity *entity__any_data = NULL; -gb_global Entity *entity__string_data = NULL; -gb_global Entity *entity__string_count = NULL; -gb_global Entity *entity__slice_count = NULL; -gb_global Entity *entity__slice_capacity = NULL; - -Selection lookup_field_with_selection(gbAllocator a, Type *type_, String field_name, bool is_type, Selection sel); - -Selection lookup_field(gbAllocator a, Type *type_, String field_name, bool is_type) { - return lookup_field_with_selection(a, type_, field_name, is_type, empty_selection); -} - -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("_"))) { - return empty_selection; - } - - Type *type = type_deref(type_); - bool is_ptr = type != type_; - sel.indirect = sel.indirect || is_ptr; - - type = base_type(type); - - if (type->kind == Type_Basic) { - switch (type->Basic.kind) { - case Basic_any: { - String type_info_str = str_lit("type_info"); - String data_str = str_lit("data"); - if (entity__any_type_info == NULL) { - entity__any_type_info = make_entity_field(a, NULL, make_token_ident(type_info_str), t_type_info_ptr, false, 0); - } - if (entity__any_data == NULL) { - entity__any_data = make_entity_field(a, NULL, make_token_ident(data_str), t_rawptr, false, 1); - } - - if (str_eq(field_name, type_info_str)) { - selection_add_index(&sel, 0); - sel.entity = entity__any_type_info; - return sel; - } else if (str_eq(field_name, data_str)) { - selection_add_index(&sel, 1); - sel.entity = entity__any_data; - return sel; - } - } break; - case Basic_string: { - String data_str = str_lit("data"); - String count_str = str_lit("count"); - if (entity__string_data == NULL) { - entity__string_data = make_entity_field(a, NULL, make_token_ident(data_str), make_type_pointer(a, t_u8), false, 0); - } - - if (entity__string_count == NULL) { - entity__string_count = make_entity_field(a, NULL, make_token_ident(count_str), t_int, false, 1); - } - - if (str_eq(field_name, data_str)) { - selection_add_index(&sel, 0); - sel.entity = entity__string_data; - return sel; - } else if (str_eq(field_name, count_str)) { - selection_add_index(&sel, 1); - sel.entity = entity__string_count; - return sel; - } - } break; - } - - return sel; - } else if (type->kind == Type_Array) { - String count_str = str_lit("count"); - // NOTE(bill): Underlying memory address cannot be changed - if (str_eq(field_name, count_str)) { - // HACK(bill): Memory leak - sel.entity = make_entity_constant(a, NULL, make_token_ident(count_str), t_int, make_exact_value_integer(type->Array.count)); - return sel; - } - } else if (type->kind == Type_Vector) { - String count_str = str_lit("count"); - // NOTE(bill): Vectors are not addressable - if (str_eq(field_name, count_str)) { - // HACK(bill): Memory leak - sel.entity = make_entity_constant(a, NULL, make_token_ident(count_str), t_int, make_exact_value_integer(type->Vector.count)); - return sel; - } - - if (type->Vector.count <= 4 && !is_type_boolean(type->Vector.elem)) { - // HACK(bill): Memory leak - switch (type->Vector.count) { - #define _VECTOR_FIELD_CASE(_length, _name) \ - case (_length): \ - if (str_eq(field_name, str_lit(_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; \ - } \ - /*fallthrough*/ - - _VECTOR_FIELD_CASE(4, "w"); - _VECTOR_FIELD_CASE(3, "z"); - _VECTOR_FIELD_CASE(2, "y"); - _VECTOR_FIELD_CASE(1, "x"); - default: break; - - #undef _VECTOR_FIELD_CASE - } - } - - } else if (type->kind == Type_Slice) { - String data_str = str_lit("data"); - String count_str = str_lit("count"); - - if (str_eq(field_name, data_str)) { - selection_add_index(&sel, 0); - // HACK(bill): Memory leak - sel.entity = make_entity_field(a, NULL, make_token_ident(data_str), make_type_pointer(a, type->Slice.elem), false, 0); - return sel; - } else if (str_eq(field_name, count_str)) { - selection_add_index(&sel, 1); - if (entity__slice_count == NULL) { - entity__slice_count = make_entity_field(a, NULL, make_token_ident(count_str), t_int, false, 1); - } - - sel.entity = entity__slice_count; - return sel; - } - } - - if (type->kind != Type_Record) { - return sel; - } - if (is_type) { - if (is_type_union(type)) { - // NOTE(bill): The subtype for a union are stored in the fields - // as they are "kind of" like variables but not - for (isize i = 0; i < type->Record.field_count; i++) { - Entity *f = type->Record.fields[i]; - GB_ASSERT(f->kind == Entity_TypeName); - String str = f->token.string; - - if (str_eq(field_name, str)) { - sel.entity = f; - selection_add_index(&sel, i); - return sel; - } - } - } else if (is_type_enum(type)) { - for (isize i = 0; i < type->Record.field_count; i++) { - Entity *f = type->Record.fields[i]; - GB_ASSERT(f->kind == Entity_Constant); - String str = f->token.string; - - if (str_eq(field_name, str)) { - sel.entity = f; - selection_add_index(&sel, i); - return sel; - } - } - } - } else if (!is_type_union(type)) { - for (isize i = 0; i < type->Record.field_count; i++) { - Entity *f = type->Record.fields[i]; - GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field); - String str = f->token.string; - if (str_eq(field_name, str)) { - selection_add_index(&sel, i); // HACK(bill): Leaky memory - sel.entity = f; - return sel; - } - - if (f->flags & EntityFlag_Anonymous) { - isize prev_count = sel.index.count; - selection_add_index(&sel, i); // HACK(bill): Leaky memory - - sel = lookup_field_with_selection(a, f->type, field_name, is_type, sel); - - if (sel.entity != NULL) { - if (is_type_pointer(f->type)) { - sel.indirect = true; - } - return sel; - } - sel.index.count = prev_count; - } - } - } - - return sel; -} - - -typedef struct TypePath { - Array(Type *) 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 - array_init(&tp->path, heap_allocator()); -} - -void type_path_free(TypePath *tp) { - array_free(&tp->path); -} - -TypePath *type_path_push(TypePath *tp, Type *t) { - GB_ASSERT(tp != NULL); - - for_array(i, tp->path) { - if (tp->path.e[i] == t) { - // TODO(bill): - GB_ASSERT(is_type_named(t)); - Entity *e = t->Named.type_name; - error(e->token, "Illegal declaration cycle of `%.*s`", LIT(t->Named.name)); - // NOTE(bill): Print cycle, if it's deep enough - for (isize j = 0; j < tp->path.count; j++) { - Type *t = tp->path.e[j]; - GB_ASSERT(is_type_named(t)); - Entity *e = t->Named.type_name; - error(e->token, "\t%.*s refers to", LIT(t->Named.name)); - } - // NOTE(bill): This will only print if the path count > 1 - error(e->token, "\t%.*s", LIT(t->Named.name)); - tp->failure = true; - t->failure = true; - - // NOTE(bill): Just quit immediately - // TODO(bill): Try and solve this gracefully - // gb_exit(1); - } - } - - if (!tp->failure) { - array_add(&tp->path, t); - } - return tp; -} - -void type_path_pop(TypePath *tp) { - if (tp != NULL) { - array_pop(&tp->path); - } -} - - -#define FAILURE_SIZE 0 -#define FAILURE_ALIGNMENT 0 - - -i64 type_size_of(BaseTypeSizes s, gbAllocator allocator, Type *t); -i64 type_align_of(BaseTypeSizes s, gbAllocator allocator, Type *t); -i64 type_offset_of(BaseTypeSizes s, gbAllocator allocator, Type *t, i64 index); - -i64 type_size_of_internal (BaseTypeSizes s, gbAllocator allocator, Type *t, TypePath *path); -i64 type_align_of_internal(BaseTypeSizes s, gbAllocator allocator, Type *t, TypePath *path); - -i64 align_formula(i64 size, i64 align) { - if (align > 0) { - i64 result = size + align-1; - return result - result%align; - } - return size; -} - -i64 type_size_of(BaseTypeSizes s, gbAllocator allocator, Type *t) { - i64 size; - TypePath path = {0}; - type_path_init(&path); - size = type_size_of_internal(s, allocator, t, &path); - type_path_free(&path); - return size; -} - -i64 type_align_of(BaseTypeSizes s, gbAllocator allocator, Type *t) { - i64 align; - TypePath path = {0}; - type_path_init(&path); - align = type_align_of_internal(s, allocator, t, &path); - type_path_free(&path); - return align; -} - - -i64 type_align_of_internal(BaseTypeSizes s, gbAllocator allocator, Type *t, TypePath *path) { - if (t->failure) { - return FAILURE_ALIGNMENT; - } - t = base_type(t); - - switch (t->kind) { - case Type_Array: { - Type *elem = t->Array.elem; - type_path_push(path, elem); - if (path->failure) { - return FAILURE_ALIGNMENT; - } - i64 align = type_align_of_internal(s, allocator, t->Array.elem, path); - type_path_pop(path); - return align; - } - case Type_Vector: { - Type *elem = t->Vector.elem; - type_path_push(path, elem); - if (path->failure) { - return FAILURE_ALIGNMENT; - } - i64 size = type_size_of_internal(s, allocator, t->Vector.elem, path); - type_path_pop(path); - i64 count = gb_max(prev_pow2(t->Vector.count), 1); - i64 total = size * count; - return gb_clamp(total, 1, s.max_align); - } break; - - case Type_Tuple: { - i64 max = 1; - for (isize i = 0; i < t->Tuple.variable_count; i++) { - i64 align = type_align_of_internal(s, allocator, t->Tuple.variables[i]->type, path); - if (max < align) { - max = align; - } - } - return max; - } break; - - case Type_Maybe: { - Type *elem = t->Maybe.elem; - type_path_push(path, elem); - if (path->failure) { - return FAILURE_ALIGNMENT; - } - i64 align = gb_max(type_align_of_internal(s, allocator, t->Maybe.elem, path), type_align_of_internal(s, allocator, t_bool, path)); - type_path_pop(path); - return align; - } - - case Type_Record: { - switch (t->Record.kind) { - case TypeRecord_Struct: - if (t->Record.field_count > 0) { - // TODO(bill): What is this supposed to be? - if (t->Record.struct_is_packed) { - i64 max = s.word_size; - for (isize i = 0; i < t->Record.field_count; i++) { - Type *field_type = t->Record.fields[i]->type; - type_path_push(path, field_type); - if (path->failure) { - return FAILURE_ALIGNMENT; - } - i64 align = type_align_of_internal(s, allocator, field_type, path); - type_path_pop(path); - if (max < align) { - max = align; - } - } - return max; - } - Type *field_type = t->Record.fields[0]->type; - type_path_push(path, field_type); - if (path->failure) { - return FAILURE_ALIGNMENT; - } - i64 align = type_align_of_internal(s, allocator, field_type, path); - type_path_pop(path); - return align; - } - break; - case TypeRecord_Union: { - i64 max = 1; - // NOTE(bill): field zero is null - for (isize i = 1; i < t->Record.field_count; i++) { - Type *field_type = t->Record.fields[i]->type; - type_path_push(path, field_type); - if (path->failure) { - return FAILURE_ALIGNMENT; - } - i64 align = type_align_of_internal(s, allocator, field_type, path); - type_path_pop(path); - if (max < align) { - max = align; - } - } - return max; - } break; - case TypeRecord_RawUnion: { - i64 max = 1; - for (isize i = 0; i < t->Record.field_count; i++) { - Type *field_type = t->Record.fields[i]->type; - type_path_push(path, field_type); - if (path->failure) { - return FAILURE_ALIGNMENT; - } - i64 align = type_align_of_internal(s, allocator, field_type, path); - type_path_pop(path); - if (max < align) { - max = align; - } - } - return max; - } break; - } - } break; - } - - // return gb_clamp(next_pow2(type_size_of(s, allocator, t)), 1, s.max_align); - // NOTE(bill): Things that are bigger than s.word_size, are actually comprised of smaller types - // TODO(bill): Is this correct for 128-bit types (integers)? - return gb_clamp(next_pow2(type_size_of_internal(s, allocator, t, path)), 1, s.word_size); -} - -i64 *type_set_offsets_of(BaseTypeSizes s, gbAllocator allocator, Entity **fields, isize field_count, bool is_packed) { - i64 *offsets = gb_alloc_array(allocator, i64, field_count); - i64 curr_offset = 0; - if (is_packed) { - for (isize i = 0; i < field_count; i++) { - offsets[i] = curr_offset; - curr_offset += type_size_of(s, allocator, fields[i]->type); - } - - } else { - for (isize i = 0; i < field_count; i++) { - i64 align = type_align_of(s, allocator, fields[i]->type); - curr_offset = align_formula(curr_offset, align); - offsets[i] = curr_offset; - curr_offset += type_size_of(s, allocator, fields[i]->type); - } - } - return offsets; -} - -bool type_set_offsets(BaseTypeSizes s, gbAllocator allocator, Type *t) { - t = base_type(t); - if (is_type_struct(t)) { - if (!t->Record.struct_are_offsets_set) { - t->Record.struct_offsets = type_set_offsets_of(s, allocator, t->Record.fields, t->Record.field_count, t->Record.struct_is_packed); - t->Record.struct_are_offsets_set = true; - return true; - } - } else if (is_type_tuple(t)) { - if (!t->Tuple.are_offsets_set) { - t->Tuple.offsets = type_set_offsets_of(s, allocator, t->Tuple.variables, t->Tuple.variable_count, false); - t->Tuple.are_offsets_set = true; - return true; - } - } else { - GB_PANIC("Invalid type for setting offsets"); - } - return false; -} - -i64 type_size_of_internal(BaseTypeSizes s, gbAllocator allocator, Type *t, TypePath *path) { - if (t->failure) { - return FAILURE_SIZE; - } - t = base_type(t); - switch (t->kind) { - case Type_Basic: { - GB_ASSERT(is_type_typed(t)); - BasicKind kind = t->Basic.kind; - i64 size = t->Basic.size; - if (size > 0) { - return size; - } - switch (kind) { - case Basic_string: return 2*s.word_size; - case Basic_any: return 2*s.word_size; - - case Basic_int: case Basic_uint: case Basic_rawptr: - return s.word_size; - } - } break; - - case Type_Array: { - i64 count, align, size, alignment; - count = t->Array.count; - if (count == 0) { - return 0; - } - align = type_align_of_internal(s, allocator, t->Array.elem, path); - if (path->failure) { - return FAILURE_SIZE; - } - size = type_size_of_internal(s, allocator, t->Array.elem, path); - alignment = align_formula(size, align); - return alignment*(count-1) + size; - } break; - - case Type_Vector: { - i64 count, bit_size, total_size_in_bits, total_size; - count = t->Vector.count; - if (count == 0) { - return 0; - } - type_path_push(path, t->Vector.elem); - if (path->failure) { - return FAILURE_SIZE; - } - bit_size = 8*type_size_of_internal(s, allocator, t->Vector.elem, path); - type_path_pop(path); - if (is_type_boolean(t->Vector.elem)) { - bit_size = 1; // NOTE(bill): LLVM can store booleans as 1 bit because a boolean _is_ an `i1` - // Silly LLVM spec - } - total_size_in_bits = bit_size * count; - total_size = (total_size_in_bits+7)/8; - return total_size; - } break; - - - case Type_Slice: // ptr + count - return 2 * s.word_size; - - case Type_Maybe: { // value + bool - i64 align, size; - Type *elem = t->Maybe.elem; - align = type_align_of_internal(s, allocator, elem, path); - if (path->failure) { - return FAILURE_SIZE; - } - size = align_formula(type_size_of_internal(s, allocator, elem, path), align); - size += type_size_of_internal(s, allocator, t_bool, path); - return align_formula(size, align); - } - - case Type_Tuple: { - i64 count, align, size; - count = t->Tuple.variable_count; - if (count == 0) { - return 0; - } - align = type_align_of_internal(s, allocator, t, path); - type_set_offsets(s, allocator, t); - size = t->Tuple.offsets[count-1] + type_size_of_internal(s, allocator, t->Tuple.variables[count-1]->type, path); - return align_formula(size, align); - } break; - - case Type_Record: { - switch (t->Record.kind) { - case TypeRecord_Struct: { - i64 count = t->Record.field_count; - if (count == 0) { - return 0; - } - i64 align = type_align_of_internal(s, allocator, t, path); - if (path->failure) { - return FAILURE_SIZE; - } - type_set_offsets(s, allocator, t); - i64 size = t->Record.struct_offsets[count-1] + type_size_of_internal(s, allocator, t->Record.fields[count-1]->type, path); - return align_formula(size, align); - } break; - - case TypeRecord_Union: { - i64 count = t->Record.field_count; - i64 align = type_align_of_internal(s, allocator, t, path); - if (path->failure) { - return FAILURE_SIZE; - } - i64 max = 0; - // NOTE(bill): Zeroth field is invalid - for (isize i = 1; i < count; i++) { - i64 size = type_size_of_internal(s, allocator, t->Record.fields[i]->type, path); - if (max < size) { - max = size; - } - } - // NOTE(bill): Align to int - isize size = align_formula(max, s.word_size); - size += type_size_of_internal(s, allocator, t_int, path); - return align_formula(size, align); - } break; - - case TypeRecord_RawUnion: { - i64 count = t->Record.field_count; - i64 align = type_align_of_internal(s, allocator, t, path); - if (path->failure) { - return FAILURE_SIZE; - } - i64 max = 0; - for (isize i = 0; i < count; i++) { - i64 size = type_size_of_internal(s, allocator, t->Record.fields[i]->type, path); - if (max < size) { - max = size; - } - } - // TODO(bill): Is this how it should work? - return align_formula(max, align); - } break; - } - } break; - } - - // Catch all - return s.word_size; -} - -i64 type_offset_of(BaseTypeSizes s, gbAllocator allocator, Type *t, isize index) { - t = base_type(t); - if (t->kind == Type_Record && t->Record.kind == TypeRecord_Struct) { - type_set_offsets(s, allocator, t); - if (gb_is_between(index, 0, t->Record.field_count-1)) { - return t->Record.struct_offsets[index]; - } - } else if (t->kind == Type_Tuple) { - type_set_offsets(s, allocator, t); - if (gb_is_between(index, 0, t->Tuple.variable_count-1)) { - return t->Tuple.offsets[index]; - } - } else if (t->kind == Type_Basic) { - if (t->Basic.kind == Basic_string) { - switch (index) { - case 0: return 0; - case 1: return s.word_size; - } - } else if (t->Basic.kind == Basic_any) { - switch (index) { - case 0: return 0; - case 1: return s.word_size; - } - } - } else if (t->kind == Type_Slice) { - switch (index) { - case 0: return 0; - case 1: return 1*s.word_size; - case 2: return 2*s.word_size; - } - } - return 0; -} - - -i64 type_offset_of_from_selection(BaseTypeSizes s, gbAllocator allocator, Type *type, Selection sel) { - GB_ASSERT(sel.indirect == false); - - Type *t = type; - i64 offset = 0; - for_array(i, sel.index) { - isize index = sel.index.e[i]; - t = base_type(t); - offset += type_offset_of(s, allocator, t, index); - if (t->kind == Type_Record && t->Record.kind == TypeRecord_Struct) { - t = t->Record.fields[index]->type; - } else { - // NOTE(bill): string/any/slices don't have record fields so this case doesn't need to be handled - } - } - return offset; -} - - - -gbString write_type_to_string(gbString str, Type *type) { - if (type == NULL) { - return gb_string_appendc(str, ""); - } - - switch (type->kind) { - case Type_Basic: - str = gb_string_append_length(str, type->Basic.name.text, type->Basic.name.len); - break; - - case Type_Pointer: - str = gb_string_appendc(str, "^"); - str = write_type_to_string(str, type->Pointer.elem); - break; - - case Type_Maybe: - str = gb_string_appendc(str, "?"); - str = write_type_to_string(str, type->Maybe.elem); - break; - - case Type_Array: - str = gb_string_appendc(str, gb_bprintf("[%td]", type->Array.count)); - str = write_type_to_string(str, type->Array.elem); - break; - - case Type_Vector: - str = gb_string_appendc(str, gb_bprintf("[vector %td]", type->Vector.count)); - str = write_type_to_string(str, type->Vector.elem); - break; - - case Type_Slice: - str = gb_string_appendc(str, "[]"); - str = write_type_to_string(str, type->Array.elem); - break; - - case Type_Record: { - switch (type->Record.kind) { - case TypeRecord_Struct: - str = gb_string_appendc(str, "struct"); - if (type->Record.struct_is_packed) { - str = gb_string_appendc(str, " #packed"); - } - if (type->Record.struct_is_ordered) { - str = gb_string_appendc(str, " #ordered"); - } - str = gb_string_appendc(str, " {"); - for (isize i = 0; i < type->Record.field_count; i++) { - Entity *f = type->Record.fields[i]; - GB_ASSERT(f->kind == Entity_Variable); - if (i > 0) - str = gb_string_appendc(str, "; "); - str = gb_string_append_length(str, f->token.string.text, f->token.string.len); - str = gb_string_appendc(str, ": "); - str = write_type_to_string(str, f->type); - } - str = gb_string_appendc(str, "}"); - break; - - case TypeRecord_Union: - str = gb_string_appendc(str, "union{"); - for (isize i = 1; i < type->Record.field_count; i++) { - Entity *f = type->Record.fields[i]; - GB_ASSERT(f->kind == Entity_TypeName); - if (i > 1) { - str = gb_string_appendc(str, "; "); - } - str = gb_string_append_length(str, f->token.string.text, f->token.string.len); - str = gb_string_appendc(str, ": "); - str = write_type_to_string(str, base_type(f->type)); - } - str = gb_string_appendc(str, "}"); - break; - - case TypeRecord_RawUnion: - str = gb_string_appendc(str, "raw_union{"); - for (isize i = 0; i < type->Record.field_count; i++) { - Entity *f = type->Record.fields[i]; - GB_ASSERT(f->kind == Entity_Variable); - if (i > 0) { - str = gb_string_appendc(str, ", "); - } - str = gb_string_append_length(str, f->token.string.text, f->token.string.len); - str = gb_string_appendc(str, ": "); - str = write_type_to_string(str, f->type); - } - str = gb_string_appendc(str, "}"); - break; - } - } break; - - - case Type_Named: - if (type->Named.type_name != NULL) { - str = gb_string_append_length(str, type->Named.name.text, type->Named.name.len); - } else { - // NOTE(bill): Just in case - str = gb_string_appendc(str, ""); - } - break; - - case Type_Tuple: - if (type->Tuple.variable_count > 0) { - for (isize i = 0; i < type->Tuple.variable_count; i++) { - Entity *var = type->Tuple.variables[i]; - if (var != NULL) { - GB_ASSERT(var->kind == Entity_Variable); - if (i > 0) - str = gb_string_appendc(str, ", "); - str = write_type_to_string(str, var->type); - } - } - } - break; - - case Type_Proc: - str = gb_string_appendc(str, "proc("); - if (type->Proc.params) - str = write_type_to_string(str, type->Proc.params); - str = gb_string_appendc(str, ")"); - if (type->Proc.results) { - str = gb_string_appendc(str, " -> "); - str = write_type_to_string(str, type->Proc.results); - } - switch (type->Proc.calling_convention) { - case ProcCC_Odin: - // str = gb_string_appendc(str, " #cc_odin"); - break; - case ProcCC_C: - str = gb_string_appendc(str, " #cc_c"); - break; - case ProcCC_Std: - str = gb_string_appendc(str, " #cc_std"); - break; - case ProcCC_Fast: - str = gb_string_appendc(str, " #cc_fast"); - break; - } - break; - } - - return str; -} - - -gbString type_to_string(Type *type) { - gbString str = gb_string_make(gb_heap_allocator(), ""); - return write_type_to_string(str, type); -} - - diff --git a/src/entity.c b/src/entity.c new file mode 100644 index 000000000..17fb70e06 --- /dev/null +++ b/src/entity.c @@ -0,0 +1,190 @@ +typedef struct Scope Scope; +typedef struct Checker Checker; +typedef struct Type Type; +typedef enum BuiltinProcId BuiltinProcId; +typedef enum ImplicitValueId ImplicitValueId; + +#define ENTITY_KINDS \ + ENTITY_KIND(Invalid) \ + ENTITY_KIND(Constant) \ + ENTITY_KIND(Variable) \ + ENTITY_KIND(TypeName) \ + ENTITY_KIND(Procedure) \ + ENTITY_KIND(Builtin) \ + ENTITY_KIND(ImportName) \ + ENTITY_KIND(Nil) \ + ENTITY_KIND(ImplicitValue) \ + ENTITY_KIND(Count) + +typedef enum EntityKind { +#define ENTITY_KIND(k) GB_JOIN2(Entity_, k), + ENTITY_KINDS +#undef ENTITY_KIND +} EntityKind; + +String const entity_strings[] = { +#define ENTITY_KIND(k) {cast(u8 *)#k, gb_size_of(#k)-1}, + ENTITY_KINDS +#undef ENTITY_KIND +}; + +typedef enum EntityFlag { + EntityFlag_Visited = 1<<0, + EntityFlag_Used = 1<<1, + EntityFlag_Anonymous = 1<<2, + EntityFlag_Field = 1<<3, + EntityFlag_Param = 1<<4, + EntityFlag_VectorElem = 1<<5, +} EntityFlag; + +typedef struct Entity Entity; +struct Entity { + EntityKind kind; + u32 flags; + Token token; + Scope * scope; + Type * type; + AstNode * identifier; // Can be NULL + + // TODO(bill): Cleanup how `using` works for entities + Entity * using_parent; + AstNode * using_expr; + + union { + struct { + ExactValue value; + } Constant; + struct { + i32 field_index; + i32 field_src_index; + bool is_immutable; + } Variable; + i32 TypeName; + struct { + bool is_foreign; + String foreign_name; + String link_name; + u64 tags; + } Procedure; + struct { + BuiltinProcId id; + } Builtin; + struct { + String path; + String name; + Scope *scope; + bool used; + } ImportName; + i32 Nil; + struct { + // TODO(bill): Should this be a user-level construct rather than compiler-level? + ImplicitValueId id; + Entity * backing; + } ImplicitValue; + }; +}; + + +Entity *e_iota = NULL; + + +Entity *alloc_entity(gbAllocator a, EntityKind kind, Scope *scope, Token token, Type *type) { + Entity *entity = gb_alloc_item(a, Entity); + entity->kind = kind; + entity->scope = scope; + entity->token = token; + entity->type = type; + return entity; +} + +Entity *make_entity_variable(gbAllocator a, Scope *scope, Token token, Type *type) { + Entity *entity = alloc_entity(a, Entity_Variable, scope, token, type); + return entity; +} + +Entity *make_entity_using_variable(gbAllocator a, Entity *parent, Token token, Type *type) { + GB_ASSERT(parent != NULL); + Entity *entity = alloc_entity(a, Entity_Variable, parent->scope, token, type); + entity->using_parent = parent; + entity->flags |= EntityFlag_Anonymous; + return entity; +} + + +Entity *make_entity_constant(gbAllocator a, Scope *scope, Token token, Type *type, ExactValue value) { + Entity *entity = alloc_entity(a, Entity_Constant, scope, token, type); + entity->Constant.value = value; + return entity; +} + +Entity *make_entity_type_name(gbAllocator a, Scope *scope, Token token, Type *type) { + Entity *entity = alloc_entity(a, Entity_TypeName, scope, token, type); + return entity; +} + +Entity *make_entity_param(gbAllocator a, Scope *scope, Token token, Type *type, bool anonymous) { + Entity *entity = make_entity_variable(a, scope, token, type); + entity->flags |= EntityFlag_Used; + entity->flags |= EntityFlag_Anonymous*(anonymous != 0); + entity->flags |= EntityFlag_Param; + return entity; +} + +Entity *make_entity_field(gbAllocator a, Scope *scope, Token token, Type *type, bool anonymous, i32 field_src_index) { + Entity *entity = make_entity_variable(a, scope, token, type); + entity->Variable.field_src_index = field_src_index; + entity->Variable.field_index = field_src_index; + entity->flags |= EntityFlag_Field; + entity->flags |= EntityFlag_Anonymous*(anonymous != 0); + return entity; +} + +Entity *make_entity_vector_elem(gbAllocator a, Scope *scope, Token token, Type *type, i32 field_src_index) { + Entity *entity = make_entity_variable(a, scope, token, type); + entity->Variable.field_src_index = field_src_index; + entity->Variable.field_index = field_src_index; + entity->flags |= EntityFlag_Field; + entity->flags |= EntityFlag_VectorElem; + return entity; +} + +Entity *make_entity_procedure(gbAllocator a, Scope *scope, Token token, Type *signature_type, u64 tags) { + Entity *entity = alloc_entity(a, Entity_Procedure, scope, token, signature_type); + entity->Procedure.tags = tags; + return entity; +} + +Entity *make_entity_builtin(gbAllocator a, Scope *scope, Token token, Type *type, BuiltinProcId id) { + Entity *entity = alloc_entity(a, Entity_Builtin, scope, token, type); + entity->Builtin.id = id; + return entity; +} + +Entity *make_entity_import_name(gbAllocator a, Scope *scope, Token token, Type *type, + String path, String name, Scope *import_scope) { + Entity *entity = alloc_entity(a, Entity_ImportName, scope, token, type); + entity->ImportName.path = path; + entity->ImportName.name = name; + entity->ImportName.scope = import_scope; + return entity; +} + +Entity *make_entity_nil(gbAllocator a, String name, Type *type) { + Token token = make_token_ident(name); + Entity *entity = alloc_entity(a, Entity_Nil, NULL, token, type); + return entity; +} + +Entity *make_entity_implicit_value(gbAllocator a, String name, Type *type, ImplicitValueId id) { + Token token = make_token_ident(name); + Entity *entity = alloc_entity(a, Entity_ImplicitValue, NULL, token, type); + entity->ImplicitValue.id = id; + return entity; +} + + +Entity *make_entity_dummy_variable(gbAllocator a, Scope *scope, Token token) { + token.string = str_lit("_"); + return make_entity_variable(a, scope, token, NULL); +} + diff --git a/src/main.c b/src/main.c index 9148636ae..157667b52 100644 --- a/src/main.c +++ b/src/main.c @@ -9,7 +9,7 @@ extern "C" { #include "tokenizer.c" #include "parser.c" // #include "printer.c" -#include "checker/checker.c" +#include "checker.c" // #include "ssa.c" #include "ir.c" #include "ir_opt.c" diff --git a/src/types.c b/src/types.c new file mode 100644 index 000000000..779924cd4 --- /dev/null +++ b/src/types.c @@ -0,0 +1,1703 @@ +typedef struct Scope Scope; + +typedef enum BasicKind { + Basic_Invalid, + Basic_bool, + Basic_i8, + Basic_u8, + Basic_i16, + Basic_u16, + Basic_i32, + Basic_u32, + Basic_i64, + Basic_u64, + // Basic_i128, + // Basic_u128, + // Basic_f16, + Basic_f32, + Basic_f64, + // Basic_f128, + Basic_int, + Basic_uint, + Basic_rawptr, + Basic_string, // ^u8 + int + Basic_any, // ^Type_Info + rawptr + + Basic_UntypedBool, + Basic_UntypedInteger, + Basic_UntypedFloat, + Basic_UntypedString, + Basic_UntypedRune, + Basic_UntypedNil, + + Basic_Count, + + Basic_byte = Basic_u8, + Basic_rune = Basic_i32, +} BasicKind; + +typedef enum BasicFlag { + BasicFlag_Boolean = GB_BIT(0), + BasicFlag_Integer = GB_BIT(1), + BasicFlag_Unsigned = GB_BIT(2), + BasicFlag_Float = GB_BIT(3), + BasicFlag_Pointer = GB_BIT(4), + BasicFlag_String = GB_BIT(5), + BasicFlag_Rune = GB_BIT(6), + BasicFlag_Untyped = GB_BIT(7), + + BasicFlag_Numeric = BasicFlag_Integer | BasicFlag_Float, + BasicFlag_Ordered = BasicFlag_Numeric | BasicFlag_String | BasicFlag_Pointer, + BasicFlag_ConstantType = BasicFlag_Boolean | BasicFlag_Numeric | BasicFlag_Pointer | BasicFlag_String | BasicFlag_Rune, +} BasicFlag; + +typedef struct BasicType { + BasicKind kind; + u32 flags; + i64 size; // -1 if arch. dep. + String name; +} BasicType; + +typedef enum TypeRecordKind { + TypeRecord_Invalid, + + TypeRecord_Struct, + TypeRecord_RawUnion, + TypeRecord_Union, // Tagged + TypeRecord_Enum, + + TypeRecord_Count, +} TypeRecordKind; + +typedef struct TypeRecord { + TypeRecordKind kind; + + // All record types + // Theses are arrays + Entity **fields; // Entity_Variable (otherwise Entity_TypeName if union) + i32 field_count; // == offset_count is struct + AstNode *node; + + i64 * struct_offsets; + bool struct_are_offsets_set; + bool struct_is_packed; + bool struct_is_ordered; + Entity **fields_in_src_order; // Entity_Variable + + Type * enum_base_type; +} TypeRecord; + +#define TYPE_KINDS \ + TYPE_KIND(Basic, BasicType) \ + TYPE_KIND(Pointer, struct { Type *elem; }) \ + TYPE_KIND(Array, struct { Type *elem; i64 count; }) \ + TYPE_KIND(Vector, struct { Type *elem; i64 count; }) \ + TYPE_KIND(Slice, struct { Type *elem; }) \ + TYPE_KIND(Maybe, struct { Type *elem; }) \ + TYPE_KIND(Record, TypeRecord) \ + TYPE_KIND(Named, struct { \ + String name; \ + Type * base; \ + Entity *type_name; /* Entity_TypeName */ \ + }) \ + TYPE_KIND(Tuple, struct { \ + Entity **variables; /* Entity_Variable */ \ + i32 variable_count; \ + bool are_offsets_set; \ + i64 * offsets; \ + }) \ + TYPE_KIND(Proc, struct { \ + Scope *scope; \ + Type * params; /* Type_Tuple */ \ + Type * results; /* Type_Tuple */ \ + i32 param_count; \ + i32 result_count; \ + bool variadic; \ + ProcCallingConvention calling_convention; \ + }) + + + +typedef 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")}, +#define TYPE_KIND(k, ...) {cast(u8 *)#k, gb_size_of(#k)-1}, + TYPE_KINDS +#undef TYPE_KIND +}; + +#define TYPE_KIND(k, ...) typedef __VA_ARGS__ GB_JOIN2(Type, k); + TYPE_KINDS +#undef TYPE_KIND + +typedef struct Type { + TypeKind kind; + union { +#define TYPE_KIND(k, ...) GB_JOIN2(Type, k) k; + TYPE_KINDS +#undef TYPE_KIND + }; + bool failure; +} Type; + +// NOTE(bill): Internal sizes of certain types +// string: 2*word_size (ptr+len) +// slice: 3*word_size (ptr+len+cap) +// array: count*size_of(elem) aligned + +// NOTE(bill): Alignment of structures and other types are to be compatible with C + +typedef struct BaseTypeSizes { + i64 word_size; + i64 max_align; +} BaseTypeSizes; + +typedef Array(isize) Array_isize; + +typedef struct Selection { + Entity * entity; + Array_isize index; + bool indirect; // Set if there was a pointer deref anywhere down the line +} Selection; +Selection empty_selection = {0}; + +Selection make_selection(Entity *entity, Array_isize index, bool indirect) { + Selection s = {entity, index, indirect}; + return s; +} + +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 + if (s->index.e == NULL) { + array_init(&s->index, heap_allocator()); + } + array_add(&s->index, index); +} + + + +#define STR_LIT(x) {cast(u8 *)(x), gb_size_of(x)-1} +gb_global Type basic_types[] = { + {Type_Basic, {Basic_Invalid, 0, 0, STR_LIT("invalid type")}}, + {Type_Basic, {Basic_bool, BasicFlag_Boolean, 1, STR_LIT("bool")}}, + {Type_Basic, {Basic_i8, BasicFlag_Integer, 1, STR_LIT("i8")}}, + {Type_Basic, {Basic_u8, BasicFlag_Integer | BasicFlag_Unsigned, 1, STR_LIT("u8")}}, + {Type_Basic, {Basic_i16, BasicFlag_Integer, 2, STR_LIT("i16")}}, + {Type_Basic, {Basic_u16, BasicFlag_Integer | BasicFlag_Unsigned, 2, STR_LIT("u16")}}, + {Type_Basic, {Basic_i32, BasicFlag_Integer, 4, STR_LIT("i32")}}, + {Type_Basic, {Basic_u32, BasicFlag_Integer | BasicFlag_Unsigned, 4, STR_LIT("u32")}}, + {Type_Basic, {Basic_i64, BasicFlag_Integer, 8, STR_LIT("i64")}}, + {Type_Basic, {Basic_u64, BasicFlag_Integer | BasicFlag_Unsigned, 8, STR_LIT("u64")}}, + // {Type_Basic, {Basic_i128, BasicFlag_Integer, 16, STR_LIT("i128")}}, + // {Type_Basic, {Basic_u128, BasicFlag_Integer | BasicFlag_Unsigned, 16, STR_LIT("u128")}}, + // {Type_Basic, {Basic_f16, BasicFlag_Float, 2, STR_LIT("f16")}}, + {Type_Basic, {Basic_f32, BasicFlag_Float, 4, STR_LIT("f32")}}, + {Type_Basic, {Basic_f64, BasicFlag_Float, 8, STR_LIT("f64")}}, + // {Type_Basic, {Basic_f128, BasicFlag_Float, 16, STR_LIT("f128")}}, + {Type_Basic, {Basic_int, BasicFlag_Integer, -1, STR_LIT("int")}}, + {Type_Basic, {Basic_uint, BasicFlag_Integer | BasicFlag_Unsigned, -1, STR_LIT("uint")}}, + {Type_Basic, {Basic_rawptr, BasicFlag_Pointer, -1, STR_LIT("rawptr")}}, + {Type_Basic, {Basic_string, BasicFlag_String, -1, STR_LIT("string")}}, + {Type_Basic, {Basic_any, 0, -1, STR_LIT("any")}}, + {Type_Basic, {Basic_UntypedBool, BasicFlag_Boolean | BasicFlag_Untyped, 0, STR_LIT("untyped bool")}}, + {Type_Basic, {Basic_UntypedInteger, BasicFlag_Integer | BasicFlag_Untyped, 0, STR_LIT("untyped integer")}}, + {Type_Basic, {Basic_UntypedFloat, BasicFlag_Float | BasicFlag_Untyped, 0, STR_LIT("untyped float")}}, + {Type_Basic, {Basic_UntypedString, BasicFlag_String | BasicFlag_Untyped, 0, STR_LIT("untyped string")}}, + {Type_Basic, {Basic_UntypedRune, BasicFlag_Integer | BasicFlag_Untyped, 0, STR_LIT("untyped rune")}}, + {Type_Basic, {Basic_UntypedNil, BasicFlag_Untyped, 0, STR_LIT("untyped nil")}}, +}; + +gb_global Type basic_type_aliases[] = { + {Type_Basic, {Basic_byte, BasicFlag_Integer | BasicFlag_Unsigned, 1, STR_LIT("byte")}}, + {Type_Basic, {Basic_rune, BasicFlag_Integer, 4, STR_LIT("rune")}}, +}; + +gb_global Type *t_invalid = &basic_types[Basic_Invalid]; +gb_global Type *t_bool = &basic_types[Basic_bool]; +gb_global Type *t_i8 = &basic_types[Basic_i8]; +gb_global Type *t_u8 = &basic_types[Basic_u8]; +gb_global Type *t_i16 = &basic_types[Basic_i16]; +gb_global Type *t_u16 = &basic_types[Basic_u16]; +gb_global Type *t_i32 = &basic_types[Basic_i32]; +gb_global Type *t_u32 = &basic_types[Basic_u32]; +gb_global Type *t_i64 = &basic_types[Basic_i64]; +gb_global Type *t_u64 = &basic_types[Basic_u64]; +// gb_global Type *t_i128 = &basic_types[Basic_i128]; +// gb_global Type *t_u128 = &basic_types[Basic_u128]; +// gb_global Type *t_f16 = &basic_types[Basic_f16]; +gb_global Type *t_f32 = &basic_types[Basic_f32]; +gb_global Type *t_f64 = &basic_types[Basic_f64]; +// gb_global Type *t_f128 = &basic_types[Basic_f128]; +gb_global Type *t_int = &basic_types[Basic_int]; +gb_global Type *t_uint = &basic_types[Basic_uint]; +gb_global Type *t_rawptr = &basic_types[Basic_rawptr]; +gb_global Type *t_string = &basic_types[Basic_string]; +gb_global Type *t_any = &basic_types[Basic_any]; +gb_global Type *t_untyped_bool = &basic_types[Basic_UntypedBool]; +gb_global Type *t_untyped_integer = &basic_types[Basic_UntypedInteger]; +gb_global Type *t_untyped_float = &basic_types[Basic_UntypedFloat]; +gb_global Type *t_untyped_string = &basic_types[Basic_UntypedString]; +gb_global Type *t_untyped_rune = &basic_types[Basic_UntypedRune]; +gb_global Type *t_untyped_nil = &basic_types[Basic_UntypedNil]; +gb_global Type *t_byte = &basic_type_aliases[0]; +gb_global Type *t_rune = &basic_type_aliases[1]; + + +gb_global Type *t_u8_ptr = NULL; +gb_global Type *t_int_ptr = NULL; + +gb_global Type *t_type_info = NULL; +gb_global Type *t_type_info_ptr = NULL; +gb_global Type *t_type_info_member = NULL; +gb_global Type *t_type_info_member_ptr = NULL; + +gb_global Type *t_type_info_named = NULL; +gb_global Type *t_type_info_integer = NULL; +gb_global Type *t_type_info_float = NULL; +gb_global Type *t_type_info_any = NULL; +gb_global Type *t_type_info_string = NULL; +gb_global Type *t_type_info_boolean = NULL; +gb_global Type *t_type_info_pointer = NULL; +gb_global Type *t_type_info_maybe = NULL; +gb_global Type *t_type_info_procedure = NULL; +gb_global Type *t_type_info_array = NULL; +gb_global Type *t_type_info_slice = NULL; +gb_global Type *t_type_info_vector = NULL; +gb_global Type *t_type_info_tuple = NULL; +gb_global Type *t_type_info_struct = NULL; +gb_global Type *t_type_info_union = NULL; +gb_global Type *t_type_info_raw_union = NULL; +gb_global Type *t_type_info_enum = NULL; + + +gb_global Type *t_type_info_named_ptr = NULL; +gb_global Type *t_type_info_integer_ptr = NULL; +gb_global Type *t_type_info_float_ptr = NULL; +gb_global Type *t_type_info_any_ptr = NULL; +gb_global Type *t_type_info_string_ptr = NULL; +gb_global Type *t_type_info_boolean_ptr = NULL; +gb_global Type *t_type_info_pointer_ptr = NULL; +gb_global Type *t_type_info_maybe_ptr = NULL; +gb_global Type *t_type_info_procedure_ptr = NULL; +gb_global Type *t_type_info_array_ptr = NULL; +gb_global Type *t_type_info_slice_ptr = NULL; +gb_global Type *t_type_info_vector_ptr = NULL; +gb_global Type *t_type_info_tuple_ptr = NULL; +gb_global Type *t_type_info_struct_ptr = NULL; +gb_global Type *t_type_info_union_ptr = NULL; +gb_global Type *t_type_info_raw_union_ptr = NULL; +gb_global Type *t_type_info_enum_ptr = NULL; + + + +gb_global Type *t_allocator = NULL; +gb_global Type *t_allocator_ptr = NULL; +gb_global Type *t_context = NULL; +gb_global Type *t_context_ptr = NULL; + + + + + + +gbString type_to_string(Type *type); + +Type *base_type(Type *t) { + for (;;) { + if (t == NULL) { + break; + } + if (t->kind != Type_Named) { + break; + } + if (t == t->Named.base) { + return t_invalid; + } + t = t->Named.base; + } + return t; +} + +Type *base_enum_type(Type *t) { + Type *bt = base_type(t); + if (bt != NULL && + bt->kind == Type_Record && + bt->Record.kind == TypeRecord_Enum) { + return bt->Record.enum_base_type; + } + return t; +} + +void set_base_type(Type *t, Type *base) { + if (t && t->kind == Type_Named) { + t->Named.base = base; + } +} + + +Type *alloc_type(gbAllocator a, TypeKind kind) { + Type *t = gb_alloc_item(a, Type); + t->kind = kind; + return t; +} + + +Type *make_type_basic(gbAllocator a, BasicType basic) { + Type *t = alloc_type(a, Type_Basic); + t->Basic = basic; + return t; +} + +Type *make_type_pointer(gbAllocator a, Type *elem) { + Type *t = alloc_type(a, Type_Pointer); + t->Pointer.elem = elem; + return t; +} + +Type *make_type_maybe(gbAllocator a, Type *elem) { + Type *t = alloc_type(a, Type_Maybe); + t->Maybe.elem = elem; + return t; +} + +Type *make_type_array(gbAllocator a, Type *elem, i64 count) { + Type *t = alloc_type(a, Type_Array); + t->Array.elem = elem; + t->Array.count = count; + return t; +} + +Type *make_type_vector(gbAllocator a, Type *elem, i64 count) { + Type *t = alloc_type(a, Type_Vector); + t->Vector.elem = elem; + t->Vector.count = count; + return t; +} + +Type *make_type_slice(gbAllocator a, Type *elem) { + Type *t = alloc_type(a, Type_Slice); + t->Array.elem = elem; + return t; +} + + +Type *make_type_struct(gbAllocator a) { + Type *t = alloc_type(a, Type_Record); + t->Record.kind = TypeRecord_Struct; + return t; +} + +Type *make_type_union(gbAllocator a) { + Type *t = alloc_type(a, Type_Record); + t->Record.kind = TypeRecord_Union; + return t; +} + +Type *make_type_raw_union(gbAllocator a) { + Type *t = alloc_type(a, Type_Record); + t->Record.kind = TypeRecord_RawUnion; + return t; +} + +Type *make_type_enum(gbAllocator a) { + Type *t = alloc_type(a, Type_Record); + t->Record.kind = TypeRecord_Enum; + return t; +} + + + + + +Type *make_type_named(gbAllocator a, String name, Type *base, Entity *type_name) { + Type *t = alloc_type(a, Type_Named); + t->Named.name = name; + t->Named.base = base; + t->Named.type_name = type_name; + return t; +} + +Type *make_type_tuple(gbAllocator a) { + Type *t = alloc_type(a, Type_Tuple); + return t; +} + +Type *make_type_proc(gbAllocator a, Scope *scope, Type *params, isize param_count, Type *results, isize result_count, bool variadic, ProcCallingConvention calling_convention) { + Type *t = alloc_type(a, Type_Proc); + + if (variadic) { + if (param_count == 0) { + GB_PANIC("variadic procedure must have at least one parameter"); + } + GB_ASSERT(params != NULL && params->kind == Type_Tuple); + Entity *e = params->Tuple.variables[param_count-1]; + if (base_type(e->type)->kind != Type_Slice) { + // NOTE(bill): For custom calling convention + GB_PANIC("variadic parameter must be of type slice"); + } + } + + t->Proc.scope = scope; + t->Proc.params = params; + t->Proc.param_count = param_count; + t->Proc.results = results; + t->Proc.result_count = result_count; + t->Proc.variadic = variadic; + t->Proc.calling_convention = calling_convention; + return t; +} + + +Type *type_deref(Type *t) { + if (t != NULL) { + Type *bt = base_type(t); + if (bt == NULL) + return NULL; + if (bt != NULL && bt->kind == Type_Pointer) + return bt->Pointer.elem; + } + return t; +} + +bool is_type_named(Type *t) { + if (t->kind == Type_Basic) { + return true; + } + return t->kind == Type_Named; +} +bool is_type_boolean(Type *t) { + t = base_type(t); + if (t->kind == Type_Basic) { + return (t->Basic.flags & BasicFlag_Boolean) != 0; + } + return false; +} +bool is_type_integer(Type *t) { + t = base_type(t); + if (t->kind == Type_Basic) { + return (t->Basic.flags & BasicFlag_Integer) != 0; + } + return false; +} +bool is_type_unsigned(Type *t) { + t = base_type(t); + if (t->kind == Type_Basic) { + return (t->Basic.flags & BasicFlag_Unsigned) != 0; + } + return false; +} +bool is_type_numeric(Type *t) { + t = base_type(t); + if (t->kind == Type_Basic) { + return (t->Basic.flags & BasicFlag_Numeric) != 0; + } + if (t->kind == Type_Vector) { + return is_type_numeric(t->Vector.elem); + } + return false; +} +bool is_type_string(Type *t) { + t = base_type(t); + if (t->kind == Type_Basic) { + return (t->Basic.flags & BasicFlag_String) != 0; + } + return false; +} +bool is_type_typed(Type *t) { + t = base_type(t); + if (t == NULL) { + return false; + } + if (t->kind == Type_Basic) { + return (t->Basic.flags & BasicFlag_Untyped) == 0; + } + return true; +} +bool is_type_untyped(Type *t) { + t = base_type(t); + if (t->kind == Type_Basic) { + return (t->Basic.flags & BasicFlag_Untyped) != 0; + } + return false; +} +bool is_type_ordered(Type *t) { + t = base_type(t); + if (t->kind == Type_Basic) { + return (t->Basic.flags & BasicFlag_Ordered) != 0; + } + if (t->kind == Type_Pointer) { + return true; + } + return false; +} +bool is_type_constant_type(Type *t) { + t = base_type(base_enum_type(t)); + if (t->kind == Type_Basic) { + return (t->Basic.flags & BasicFlag_ConstantType) != 0; + } + return false; +} +bool is_type_float(Type *t) { + t = base_type(t); + if (t->kind == Type_Basic) { + return (t->Basic.flags & BasicFlag_Float) != 0; + } + return false; +} +bool is_type_f32(Type *t) { + t = base_type(t); + if (t->kind == Type_Basic) { + return t->Basic.kind == Basic_f32; + } + return false; +} +bool is_type_f64(Type *t) { + t = base_type(t); + if (t->kind == Type_Basic) { + return t->Basic.kind == Basic_f64; + } + return false; +} +bool is_type_pointer(Type *t) { + t = base_type(t); + if (t->kind == Type_Basic) { + return (t->Basic.flags & BasicFlag_Pointer) != 0; + } + return t->kind == Type_Pointer; +} +bool is_type_maybe(Type *t) { + t = base_type(t); + return t->kind == Type_Maybe; +} +bool is_type_tuple(Type *t) { + t = base_type(t); + return t->kind == Type_Tuple; +} + + +bool is_type_int_or_uint(Type *t) { + if (t->kind == Type_Basic) { + return (t->Basic.kind == Basic_int) || (t->Basic.kind == Basic_uint); + } + return false; +} +bool is_type_rawptr(Type *t) { + if (t->kind == Type_Basic) { + return t->Basic.kind == Basic_rawptr; + } + return false; +} +bool is_type_u8(Type *t) { + if (t->kind == Type_Basic) { + return t->Basic.kind == Basic_u8; + } + return false; +} +bool is_type_array(Type *t) { + t = base_type(t); + return t->kind == Type_Array; +} +bool is_type_slice(Type *t) { + t = base_type(t); + return t->kind == Type_Slice; +} +bool is_type_u8_slice(Type *t) { + t = base_type(t); + if (t->kind == Type_Slice) { + return is_type_u8(t->Slice.elem); + } + return false; +} +bool is_type_vector(Type *t) { + t = base_type(t); + return t->kind == Type_Vector; +} +bool is_type_proc(Type *t) { + t = base_type(t); + return t->kind == Type_Proc; +} +Type *base_vector_type(Type *t) { + if (is_type_vector(t)) { + t = base_type(t); + return t->Vector.elem; + } + return t; +} + + +bool is_type_struct(Type *t) { + t = base_type(t); + return (t->kind == Type_Record && t->Record.kind == TypeRecord_Struct); +} +bool is_type_union(Type *t) { + t = base_type(t); + return (t->kind == Type_Record && t->Record.kind == TypeRecord_Union); +} +bool is_type_raw_union(Type *t) { + t = base_type(t); + return (t->kind == Type_Record && t->Record.kind == TypeRecord_RawUnion); +} +bool is_type_enum(Type *t) { + t = base_type(t); + return (t->kind == Type_Record && t->Record.kind == TypeRecord_Enum); +} + + +bool is_type_any(Type *t) { + t = base_type(t); + return (t->kind == Type_Basic && t->Basic.kind == Basic_any); +} +bool is_type_untyped_nil(Type *t) { + t = base_type(t); + return (t->kind == Type_Basic && t->Basic.kind == Basic_UntypedNil); +} + + + +bool is_type_indexable(Type *t) { + return is_type_array(t) || is_type_slice(t) || is_type_vector(t) || is_type_string(t); +} + + +bool type_has_nil(Type *t) { + t = base_type(t); + switch (t->kind) { + case Type_Basic: + return is_type_rawptr(t); + case Type_Slice: + case Type_Proc: + case Type_Pointer: + case Type_Maybe: + return true; + } + return false; +} + + +bool is_type_comparable(Type *t) { + t = base_type(t); + switch (t->kind) { + case Type_Basic: + return t->kind != Basic_UntypedNil; + case Type_Pointer: + return true; + case Type_Record: { + if (false && is_type_struct(t)) { + // TODO(bill): Should I even allow this? + for (isize i = 0; i < t->Record.field_count; i++) { + if (!is_type_comparable(t->Record.fields[i]->type)) + return false; + } + } else if (is_type_enum(t)) { + return is_type_comparable(base_enum_type(t)); + } + return false; + } break; + case Type_Array: + return false; + // return is_type_comparable(t->Array.elem); + case Type_Vector: + return is_type_comparable(t->Vector.elem); + case Type_Proc: + return true; + } + return false; +} + +bool are_types_identical(Type *x, Type *y) { + if (x == y) { + return true; + } + + if ((x == NULL && y != NULL) || + (x != NULL && y == NULL)) { + return false; + } + + switch (x->kind) { + case Type_Basic: + if (y->kind == Type_Basic) { + return x->Basic.kind == y->Basic.kind; + } + break; + + case Type_Array: + if (y->kind == Type_Array) { + return (x->Array.count == y->Array.count) && are_types_identical(x->Array.elem, y->Array.elem); + } + break; + + case Type_Vector: + if (y->kind == Type_Vector) { + return (x->Vector.count == y->Vector.count) && are_types_identical(x->Vector.elem, y->Vector.elem); + } + break; + + case Type_Slice: + if (y->kind == Type_Slice) { + return are_types_identical(x->Slice.elem, y->Slice.elem); + } + break; + + case Type_Record: + if (y->kind == Type_Record) { + if (x->Record.kind == y->Record.kind) { + switch (x->Record.kind) { + case TypeRecord_Struct: + case TypeRecord_RawUnion: + case TypeRecord_Union: + if (x->Record.field_count == y->Record.field_count && + x->Record.struct_is_packed == y->Record.struct_is_packed && + x->Record.struct_is_ordered == y->Record.struct_is_ordered) { + for (isize i = 0; i < x->Record.field_count; i++) { + if (!are_types_identical(x->Record.fields[i]->type, y->Record.fields[i]->type)) { + return false; + } + if (str_ne(x->Record.fields[i]->token.string, y->Record.fields[i]->token.string)) { + return false; + } + } + return true; + } + break; + case TypeRecord_Enum: + return x == y; // NOTE(bill): All enums are unique + } + } + } + break; + + case Type_Pointer: + if (y->kind == Type_Pointer) { + return are_types_identical(x->Pointer.elem, y->Pointer.elem); + } + break; + + case Type_Maybe: + if (y->kind == Type_Maybe) { + return are_types_identical(x->Maybe.elem, y->Maybe.elem); + } + break; + + case Type_Named: + if (y->kind == Type_Named) { + return x->Named.base == y->Named.base; + } + break; + + case Type_Tuple: + if (y->kind == Type_Tuple) { + if (x->Tuple.variable_count == y->Tuple.variable_count) { + for (isize i = 0; i < x->Tuple.variable_count; i++) { + if (!are_types_identical(x->Tuple.variables[i]->type, y->Tuple.variables[i]->type)) { + return false; + } + } + return true; + } + } + break; + + case Type_Proc: + if (y->kind == Type_Proc) { + return x->Proc.calling_convention == y->Proc.calling_convention && + are_types_identical(x->Proc.params, y->Proc.params) && + are_types_identical(x->Proc.results, y->Proc.results); + } + break; + } + + + return false; +} + + +Type *default_type(Type *type) { + if (type == NULL) { + return t_invalid; + } + if (type->kind == Type_Basic) { + switch (type->Basic.kind) { + case Basic_UntypedBool: return t_bool; + case Basic_UntypedInteger: return t_int; + case Basic_UntypedFloat: return t_f64; + case Basic_UntypedString: return t_string; + case Basic_UntypedRune: return t_rune; + } + } + return type; +} + +// NOTE(bill): Valid Compile time execution #run type +bool is_type_cte_safe(Type *type) { + type = default_type(base_type(type)); + switch (type->kind) { + case Type_Basic: + switch (type->Basic.kind) { + case Basic_rawptr: + case Basic_any: + return false; + } + return true; + + case Type_Pointer: + return false; + + case Type_Array: + return is_type_cte_safe(type->Array.elem); + + case Type_Vector: // NOTE(bill): This should always to be true but this is for sanity reasons + return is_type_cte_safe(type->Vector.elem); + + case Type_Slice: + return false; + + case Type_Maybe: + return is_type_cte_safe(type->Maybe.elem); + + case Type_Record: { + if (type->Record.kind != TypeRecord_Struct) { + return false; + } + for (isize i = 0; i < type->Record.field_count; i++) { + Entity *v = type->Record.fields[i]; + if (!is_type_cte_safe(v->type)) { + return false; + } + } + return true; + } + + case Type_Tuple: { + for (isize i = 0; i < type->Tuple.variable_count; i++) { + Entity *v = type->Tuple.variables[i]; + if (!is_type_cte_safe(v->type)) { + return false; + } + } + return true; + } + + case Type_Proc: + // TODO(bill): How should I handle procedures in the CTE stage? + // return type->Proc.calling_convention == ProcCC_Odin; + return false; + } + + return false; +} + + + + +gb_global Entity *entity__any_type_info = NULL; +gb_global Entity *entity__any_data = NULL; +gb_global Entity *entity__string_data = NULL; +gb_global Entity *entity__string_count = NULL; +gb_global Entity *entity__slice_count = NULL; +gb_global Entity *entity__slice_capacity = NULL; + +Selection lookup_field_with_selection(gbAllocator a, Type *type_, String field_name, bool is_type, Selection sel); + +Selection lookup_field(gbAllocator a, Type *type_, String field_name, bool is_type) { + return lookup_field_with_selection(a, type_, field_name, is_type, empty_selection); +} + +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("_"))) { + return empty_selection; + } + + Type *type = type_deref(type_); + bool is_ptr = type != type_; + sel.indirect = sel.indirect || is_ptr; + + type = base_type(type); + + if (type->kind == Type_Basic) { + switch (type->Basic.kind) { + case Basic_any: { + String type_info_str = str_lit("type_info"); + String data_str = str_lit("data"); + if (entity__any_type_info == NULL) { + entity__any_type_info = make_entity_field(a, NULL, make_token_ident(type_info_str), t_type_info_ptr, false, 0); + } + if (entity__any_data == NULL) { + entity__any_data = make_entity_field(a, NULL, make_token_ident(data_str), t_rawptr, false, 1); + } + + if (str_eq(field_name, type_info_str)) { + selection_add_index(&sel, 0); + sel.entity = entity__any_type_info; + return sel; + } else if (str_eq(field_name, data_str)) { + selection_add_index(&sel, 1); + sel.entity = entity__any_data; + return sel; + } + } break; + case Basic_string: { + String data_str = str_lit("data"); + String count_str = str_lit("count"); + if (entity__string_data == NULL) { + entity__string_data = make_entity_field(a, NULL, make_token_ident(data_str), make_type_pointer(a, t_u8), false, 0); + } + + if (entity__string_count == NULL) { + entity__string_count = make_entity_field(a, NULL, make_token_ident(count_str), t_int, false, 1); + } + + if (str_eq(field_name, data_str)) { + selection_add_index(&sel, 0); + sel.entity = entity__string_data; + return sel; + } else if (str_eq(field_name, count_str)) { + selection_add_index(&sel, 1); + sel.entity = entity__string_count; + return sel; + } + } break; + } + + return sel; + } else if (type->kind == Type_Array) { + String count_str = str_lit("count"); + // NOTE(bill): Underlying memory address cannot be changed + if (str_eq(field_name, count_str)) { + // HACK(bill): Memory leak + sel.entity = make_entity_constant(a, NULL, make_token_ident(count_str), t_int, make_exact_value_integer(type->Array.count)); + return sel; + } + } else if (type->kind == Type_Vector) { + String count_str = str_lit("count"); + // NOTE(bill): Vectors are not addressable + if (str_eq(field_name, count_str)) { + // HACK(bill): Memory leak + sel.entity = make_entity_constant(a, NULL, make_token_ident(count_str), t_int, make_exact_value_integer(type->Vector.count)); + return sel; + } + + if (type->Vector.count <= 4 && !is_type_boolean(type->Vector.elem)) { + // HACK(bill): Memory leak + switch (type->Vector.count) { + #define _VECTOR_FIELD_CASE(_length, _name) \ + case (_length): \ + if (str_eq(field_name, str_lit(_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; \ + } \ + /*fallthrough*/ + + _VECTOR_FIELD_CASE(4, "w"); + _VECTOR_FIELD_CASE(3, "z"); + _VECTOR_FIELD_CASE(2, "y"); + _VECTOR_FIELD_CASE(1, "x"); + default: break; + + #undef _VECTOR_FIELD_CASE + } + } + + } else if (type->kind == Type_Slice) { + String data_str = str_lit("data"); + String count_str = str_lit("count"); + + if (str_eq(field_name, data_str)) { + selection_add_index(&sel, 0); + // HACK(bill): Memory leak + sel.entity = make_entity_field(a, NULL, make_token_ident(data_str), make_type_pointer(a, type->Slice.elem), false, 0); + return sel; + } else if (str_eq(field_name, count_str)) { + selection_add_index(&sel, 1); + if (entity__slice_count == NULL) { + entity__slice_count = make_entity_field(a, NULL, make_token_ident(count_str), t_int, false, 1); + } + + sel.entity = entity__slice_count; + return sel; + } + } + + if (type->kind != Type_Record) { + return sel; + } + if (is_type) { + if (is_type_union(type)) { + // NOTE(bill): The subtype for a union are stored in the fields + // as they are "kind of" like variables but not + for (isize i = 0; i < type->Record.field_count; i++) { + Entity *f = type->Record.fields[i]; + GB_ASSERT(f->kind == Entity_TypeName); + String str = f->token.string; + + if (str_eq(field_name, str)) { + sel.entity = f; + selection_add_index(&sel, i); + return sel; + } + } + } else if (is_type_enum(type)) { + for (isize i = 0; i < type->Record.field_count; i++) { + Entity *f = type->Record.fields[i]; + GB_ASSERT(f->kind == Entity_Constant); + String str = f->token.string; + + if (str_eq(field_name, str)) { + sel.entity = f; + selection_add_index(&sel, i); + return sel; + } + } + } + } else if (!is_type_union(type)) { + for (isize i = 0; i < type->Record.field_count; i++) { + Entity *f = type->Record.fields[i]; + GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field); + String str = f->token.string; + if (str_eq(field_name, str)) { + selection_add_index(&sel, i); // HACK(bill): Leaky memory + sel.entity = f; + return sel; + } + + if (f->flags & EntityFlag_Anonymous) { + isize prev_count = sel.index.count; + selection_add_index(&sel, i); // HACK(bill): Leaky memory + + sel = lookup_field_with_selection(a, f->type, field_name, is_type, sel); + + if (sel.entity != NULL) { + if (is_type_pointer(f->type)) { + sel.indirect = true; + } + return sel; + } + sel.index.count = prev_count; + } + } + } + + return sel; +} + + +typedef struct TypePath { + Array(Type *) 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 + array_init(&tp->path, heap_allocator()); +} + +void type_path_free(TypePath *tp) { + array_free(&tp->path); +} + +TypePath *type_path_push(TypePath *tp, Type *t) { + GB_ASSERT(tp != NULL); + + for_array(i, tp->path) { + if (tp->path.e[i] == t) { + // TODO(bill): + GB_ASSERT(is_type_named(t)); + Entity *e = t->Named.type_name; + error(e->token, "Illegal declaration cycle of `%.*s`", LIT(t->Named.name)); + // NOTE(bill): Print cycle, if it's deep enough + for (isize j = 0; j < tp->path.count; j++) { + Type *t = tp->path.e[j]; + GB_ASSERT(is_type_named(t)); + Entity *e = t->Named.type_name; + error(e->token, "\t%.*s refers to", LIT(t->Named.name)); + } + // NOTE(bill): This will only print if the path count > 1 + error(e->token, "\t%.*s", LIT(t->Named.name)); + tp->failure = true; + t->failure = true; + + // NOTE(bill): Just quit immediately + // TODO(bill): Try and solve this gracefully + // gb_exit(1); + } + } + + if (!tp->failure) { + array_add(&tp->path, t); + } + return tp; +} + +void type_path_pop(TypePath *tp) { + if (tp != NULL) { + array_pop(&tp->path); + } +} + + +#define FAILURE_SIZE 0 +#define FAILURE_ALIGNMENT 0 + + +i64 type_size_of(BaseTypeSizes s, gbAllocator allocator, Type *t); +i64 type_align_of(BaseTypeSizes s, gbAllocator allocator, Type *t); +i64 type_offset_of(BaseTypeSizes s, gbAllocator allocator, Type *t, i64 index); + +i64 type_size_of_internal (BaseTypeSizes s, gbAllocator allocator, Type *t, TypePath *path); +i64 type_align_of_internal(BaseTypeSizes s, gbAllocator allocator, Type *t, TypePath *path); + +i64 align_formula(i64 size, i64 align) { + if (align > 0) { + i64 result = size + align-1; + return result - result%align; + } + return size; +} + +i64 type_size_of(BaseTypeSizes s, gbAllocator allocator, Type *t) { + i64 size; + TypePath path = {0}; + type_path_init(&path); + size = type_size_of_internal(s, allocator, t, &path); + type_path_free(&path); + return size; +} + +i64 type_align_of(BaseTypeSizes s, gbAllocator allocator, Type *t) { + i64 align; + TypePath path = {0}; + type_path_init(&path); + align = type_align_of_internal(s, allocator, t, &path); + type_path_free(&path); + return align; +} + + +i64 type_align_of_internal(BaseTypeSizes s, gbAllocator allocator, Type *t, TypePath *path) { + if (t->failure) { + return FAILURE_ALIGNMENT; + } + t = base_type(t); + + switch (t->kind) { + case Type_Array: { + Type *elem = t->Array.elem; + type_path_push(path, elem); + if (path->failure) { + return FAILURE_ALIGNMENT; + } + i64 align = type_align_of_internal(s, allocator, t->Array.elem, path); + type_path_pop(path); + return align; + } + case Type_Vector: { + Type *elem = t->Vector.elem; + type_path_push(path, elem); + if (path->failure) { + return FAILURE_ALIGNMENT; + } + i64 size = type_size_of_internal(s, allocator, t->Vector.elem, path); + type_path_pop(path); + i64 count = gb_max(prev_pow2(t->Vector.count), 1); + i64 total = size * count; + return gb_clamp(total, 1, s.max_align); + } break; + + case Type_Tuple: { + i64 max = 1; + for (isize i = 0; i < t->Tuple.variable_count; i++) { + i64 align = type_align_of_internal(s, allocator, t->Tuple.variables[i]->type, path); + if (max < align) { + max = align; + } + } + return max; + } break; + + case Type_Maybe: { + Type *elem = t->Maybe.elem; + type_path_push(path, elem); + if (path->failure) { + return FAILURE_ALIGNMENT; + } + i64 align = gb_max(type_align_of_internal(s, allocator, t->Maybe.elem, path), type_align_of_internal(s, allocator, t_bool, path)); + type_path_pop(path); + return align; + } + + case Type_Record: { + switch (t->Record.kind) { + case TypeRecord_Struct: + if (t->Record.field_count > 0) { + // TODO(bill): What is this supposed to be? + if (t->Record.struct_is_packed) { + i64 max = s.word_size; + for (isize i = 0; i < t->Record.field_count; i++) { + Type *field_type = t->Record.fields[i]->type; + type_path_push(path, field_type); + if (path->failure) { + return FAILURE_ALIGNMENT; + } + i64 align = type_align_of_internal(s, allocator, field_type, path); + type_path_pop(path); + if (max < align) { + max = align; + } + } + return max; + } + Type *field_type = t->Record.fields[0]->type; + type_path_push(path, field_type); + if (path->failure) { + return FAILURE_ALIGNMENT; + } + i64 align = type_align_of_internal(s, allocator, field_type, path); + type_path_pop(path); + return align; + } + break; + case TypeRecord_Union: { + i64 max = 1; + // NOTE(bill): field zero is null + for (isize i = 1; i < t->Record.field_count; i++) { + Type *field_type = t->Record.fields[i]->type; + type_path_push(path, field_type); + if (path->failure) { + return FAILURE_ALIGNMENT; + } + i64 align = type_align_of_internal(s, allocator, field_type, path); + type_path_pop(path); + if (max < align) { + max = align; + } + } + return max; + } break; + case TypeRecord_RawUnion: { + i64 max = 1; + for (isize i = 0; i < t->Record.field_count; i++) { + Type *field_type = t->Record.fields[i]->type; + type_path_push(path, field_type); + if (path->failure) { + return FAILURE_ALIGNMENT; + } + i64 align = type_align_of_internal(s, allocator, field_type, path); + type_path_pop(path); + if (max < align) { + max = align; + } + } + return max; + } break; + } + } break; + } + + // return gb_clamp(next_pow2(type_size_of(s, allocator, t)), 1, s.max_align); + // NOTE(bill): Things that are bigger than s.word_size, are actually comprised of smaller types + // TODO(bill): Is this correct for 128-bit types (integers)? + return gb_clamp(next_pow2(type_size_of_internal(s, allocator, t, path)), 1, s.word_size); +} + +i64 *type_set_offsets_of(BaseTypeSizes s, gbAllocator allocator, Entity **fields, isize field_count, bool is_packed) { + i64 *offsets = gb_alloc_array(allocator, i64, field_count); + i64 curr_offset = 0; + if (is_packed) { + for (isize i = 0; i < field_count; i++) { + offsets[i] = curr_offset; + curr_offset += type_size_of(s, allocator, fields[i]->type); + } + + } else { + for (isize i = 0; i < field_count; i++) { + i64 align = type_align_of(s, allocator, fields[i]->type); + curr_offset = align_formula(curr_offset, align); + offsets[i] = curr_offset; + curr_offset += type_size_of(s, allocator, fields[i]->type); + } + } + return offsets; +} + +bool type_set_offsets(BaseTypeSizes s, gbAllocator allocator, Type *t) { + t = base_type(t); + if (is_type_struct(t)) { + if (!t->Record.struct_are_offsets_set) { + t->Record.struct_offsets = type_set_offsets_of(s, allocator, t->Record.fields, t->Record.field_count, t->Record.struct_is_packed); + t->Record.struct_are_offsets_set = true; + return true; + } + } else if (is_type_tuple(t)) { + if (!t->Tuple.are_offsets_set) { + t->Tuple.offsets = type_set_offsets_of(s, allocator, t->Tuple.variables, t->Tuple.variable_count, false); + t->Tuple.are_offsets_set = true; + return true; + } + } else { + GB_PANIC("Invalid type for setting offsets"); + } + return false; +} + +i64 type_size_of_internal(BaseTypeSizes s, gbAllocator allocator, Type *t, TypePath *path) { + if (t->failure) { + return FAILURE_SIZE; + } + t = base_type(t); + switch (t->kind) { + case Type_Basic: { + GB_ASSERT(is_type_typed(t)); + BasicKind kind = t->Basic.kind; + i64 size = t->Basic.size; + if (size > 0) { + return size; + } + switch (kind) { + case Basic_string: return 2*s.word_size; + case Basic_any: return 2*s.word_size; + + case Basic_int: case Basic_uint: case Basic_rawptr: + return s.word_size; + } + } break; + + case Type_Array: { + i64 count, align, size, alignment; + count = t->Array.count; + if (count == 0) { + return 0; + } + align = type_align_of_internal(s, allocator, t->Array.elem, path); + if (path->failure) { + return FAILURE_SIZE; + } + size = type_size_of_internal(s, allocator, t->Array.elem, path); + alignment = align_formula(size, align); + return alignment*(count-1) + size; + } break; + + case Type_Vector: { + i64 count, bit_size, total_size_in_bits, total_size; + count = t->Vector.count; + if (count == 0) { + return 0; + } + type_path_push(path, t->Vector.elem); + if (path->failure) { + return FAILURE_SIZE; + } + bit_size = 8*type_size_of_internal(s, allocator, t->Vector.elem, path); + type_path_pop(path); + if (is_type_boolean(t->Vector.elem)) { + bit_size = 1; // NOTE(bill): LLVM can store booleans as 1 bit because a boolean _is_ an `i1` + // Silly LLVM spec + } + total_size_in_bits = bit_size * count; + total_size = (total_size_in_bits+7)/8; + return total_size; + } break; + + + case Type_Slice: // ptr + count + return 2 * s.word_size; + + case Type_Maybe: { // value + bool + i64 align, size; + Type *elem = t->Maybe.elem; + align = type_align_of_internal(s, allocator, elem, path); + if (path->failure) { + return FAILURE_SIZE; + } + size = align_formula(type_size_of_internal(s, allocator, elem, path), align); + size += type_size_of_internal(s, allocator, t_bool, path); + return align_formula(size, align); + } + + case Type_Tuple: { + i64 count, align, size; + count = t->Tuple.variable_count; + if (count == 0) { + return 0; + } + align = type_align_of_internal(s, allocator, t, path); + type_set_offsets(s, allocator, t); + size = t->Tuple.offsets[count-1] + type_size_of_internal(s, allocator, t->Tuple.variables[count-1]->type, path); + return align_formula(size, align); + } break; + + case Type_Record: { + switch (t->Record.kind) { + case TypeRecord_Struct: { + i64 count = t->Record.field_count; + if (count == 0) { + return 0; + } + i64 align = type_align_of_internal(s, allocator, t, path); + if (path->failure) { + return FAILURE_SIZE; + } + type_set_offsets(s, allocator, t); + i64 size = t->Record.struct_offsets[count-1] + type_size_of_internal(s, allocator, t->Record.fields[count-1]->type, path); + return align_formula(size, align); + } break; + + case TypeRecord_Union: { + i64 count = t->Record.field_count; + i64 align = type_align_of_internal(s, allocator, t, path); + if (path->failure) { + return FAILURE_SIZE; + } + i64 max = 0; + // NOTE(bill): Zeroth field is invalid + for (isize i = 1; i < count; i++) { + i64 size = type_size_of_internal(s, allocator, t->Record.fields[i]->type, path); + if (max < size) { + max = size; + } + } + // NOTE(bill): Align to int + isize size = align_formula(max, s.word_size); + size += type_size_of_internal(s, allocator, t_int, path); + return align_formula(size, align); + } break; + + case TypeRecord_RawUnion: { + i64 count = t->Record.field_count; + i64 align = type_align_of_internal(s, allocator, t, path); + if (path->failure) { + return FAILURE_SIZE; + } + i64 max = 0; + for (isize i = 0; i < count; i++) { + i64 size = type_size_of_internal(s, allocator, t->Record.fields[i]->type, path); + if (max < size) { + max = size; + } + } + // TODO(bill): Is this how it should work? + return align_formula(max, align); + } break; + } + } break; + } + + // Catch all + return s.word_size; +} + +i64 type_offset_of(BaseTypeSizes s, gbAllocator allocator, Type *t, isize index) { + t = base_type(t); + if (t->kind == Type_Record && t->Record.kind == TypeRecord_Struct) { + type_set_offsets(s, allocator, t); + if (gb_is_between(index, 0, t->Record.field_count-1)) { + return t->Record.struct_offsets[index]; + } + } else if (t->kind == Type_Tuple) { + type_set_offsets(s, allocator, t); + if (gb_is_between(index, 0, t->Tuple.variable_count-1)) { + return t->Tuple.offsets[index]; + } + } else if (t->kind == Type_Basic) { + if (t->Basic.kind == Basic_string) { + switch (index) { + case 0: return 0; + case 1: return s.word_size; + } + } else if (t->Basic.kind == Basic_any) { + switch (index) { + case 0: return 0; + case 1: return s.word_size; + } + } + } else if (t->kind == Type_Slice) { + switch (index) { + case 0: return 0; + case 1: return 1*s.word_size; + case 2: return 2*s.word_size; + } + } + return 0; +} + + +i64 type_offset_of_from_selection(BaseTypeSizes s, gbAllocator allocator, Type *type, Selection sel) { + GB_ASSERT(sel.indirect == false); + + Type *t = type; + i64 offset = 0; + for_array(i, sel.index) { + isize index = sel.index.e[i]; + t = base_type(t); + offset += type_offset_of(s, allocator, t, index); + if (t->kind == Type_Record && t->Record.kind == TypeRecord_Struct) { + t = t->Record.fields[index]->type; + } else { + // NOTE(bill): string/any/slices don't have record fields so this case doesn't need to be handled + } + } + return offset; +} + + + +gbString write_type_to_string(gbString str, Type *type) { + if (type == NULL) { + return gb_string_appendc(str, ""); + } + + switch (type->kind) { + case Type_Basic: + str = gb_string_append_length(str, type->Basic.name.text, type->Basic.name.len); + break; + + case Type_Pointer: + str = gb_string_appendc(str, "^"); + str = write_type_to_string(str, type->Pointer.elem); + break; + + case Type_Maybe: + str = gb_string_appendc(str, "?"); + str = write_type_to_string(str, type->Maybe.elem); + break; + + case Type_Array: + str = gb_string_appendc(str, gb_bprintf("[%td]", type->Array.count)); + str = write_type_to_string(str, type->Array.elem); + break; + + case Type_Vector: + str = gb_string_appendc(str, gb_bprintf("[vector %td]", type->Vector.count)); + str = write_type_to_string(str, type->Vector.elem); + break; + + case Type_Slice: + str = gb_string_appendc(str, "[]"); + str = write_type_to_string(str, type->Array.elem); + break; + + case Type_Record: { + switch (type->Record.kind) { + case TypeRecord_Struct: + str = gb_string_appendc(str, "struct"); + if (type->Record.struct_is_packed) { + str = gb_string_appendc(str, " #packed"); + } + if (type->Record.struct_is_ordered) { + str = gb_string_appendc(str, " #ordered"); + } + str = gb_string_appendc(str, " {"); + for (isize i = 0; i < type->Record.field_count; i++) { + Entity *f = type->Record.fields[i]; + GB_ASSERT(f->kind == Entity_Variable); + if (i > 0) + str = gb_string_appendc(str, "; "); + str = gb_string_append_length(str, f->token.string.text, f->token.string.len); + str = gb_string_appendc(str, ": "); + str = write_type_to_string(str, f->type); + } + str = gb_string_appendc(str, "}"); + break; + + case TypeRecord_Union: + str = gb_string_appendc(str, "union{"); + for (isize i = 1; i < type->Record.field_count; i++) { + Entity *f = type->Record.fields[i]; + GB_ASSERT(f->kind == Entity_TypeName); + if (i > 1) { + str = gb_string_appendc(str, "; "); + } + str = gb_string_append_length(str, f->token.string.text, f->token.string.len); + str = gb_string_appendc(str, ": "); + str = write_type_to_string(str, base_type(f->type)); + } + str = gb_string_appendc(str, "}"); + break; + + case TypeRecord_RawUnion: + str = gb_string_appendc(str, "raw_union{"); + for (isize i = 0; i < type->Record.field_count; i++) { + Entity *f = type->Record.fields[i]; + GB_ASSERT(f->kind == Entity_Variable); + if (i > 0) { + str = gb_string_appendc(str, ", "); + } + str = gb_string_append_length(str, f->token.string.text, f->token.string.len); + str = gb_string_appendc(str, ": "); + str = write_type_to_string(str, f->type); + } + str = gb_string_appendc(str, "}"); + break; + } + } break; + + + case Type_Named: + if (type->Named.type_name != NULL) { + str = gb_string_append_length(str, type->Named.name.text, type->Named.name.len); + } else { + // NOTE(bill): Just in case + str = gb_string_appendc(str, ""); + } + break; + + case Type_Tuple: + if (type->Tuple.variable_count > 0) { + for (isize i = 0; i < type->Tuple.variable_count; i++) { + Entity *var = type->Tuple.variables[i]; + if (var != NULL) { + GB_ASSERT(var->kind == Entity_Variable); + if (i > 0) + str = gb_string_appendc(str, ", "); + str = write_type_to_string(str, var->type); + } + } + } + break; + + case Type_Proc: + str = gb_string_appendc(str, "proc("); + if (type->Proc.params) + str = write_type_to_string(str, type->Proc.params); + str = gb_string_appendc(str, ")"); + if (type->Proc.results) { + str = gb_string_appendc(str, " -> "); + str = write_type_to_string(str, type->Proc.results); + } + switch (type->Proc.calling_convention) { + case ProcCC_Odin: + // str = gb_string_appendc(str, " #cc_odin"); + break; + case ProcCC_C: + str = gb_string_appendc(str, " #cc_c"); + break; + case ProcCC_Std: + str = gb_string_appendc(str, " #cc_std"); + break; + case ProcCC_Fast: + str = gb_string_appendc(str, " #cc_fast"); + break; + } + break; + } + + return str; +} + + +gbString type_to_string(Type *type) { + gbString str = gb_string_make(gb_heap_allocator(), ""); + return write_type_to_string(str, type); +} + + -- cgit v1.2.3