Skip to content

Commit ea21d2b

Browse files
committed
add error for shadowing a type
closes #61
1 parent 32821e7 commit ea21d2b

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

src/analyze.cpp

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2072,6 +2072,18 @@ static VariableTableEntry *add_local_var(CodeGen *g, AstNode *source_node, Block
20722072
if (existing_var) {
20732073
add_node_error(g, source_node, buf_sprintf("redeclaration of variable '%s'", buf_ptr(name)));
20742074
variable_entry->type = g->builtin_types.entry_invalid;
2075+
} else {
2076+
auto primitive_table_entry = g->primitive_type_table.maybe_get(name);
2077+
TypeTableEntry *type;
2078+
if (primitive_table_entry) {
2079+
type = primitive_table_entry->value;
2080+
} else {
2081+
type = find_container(context, name);
2082+
}
2083+
if (type) {
2084+
add_node_error(g, source_node, buf_sprintf("variable shadows type '%s'", buf_ptr(&type->name)));
2085+
variable_entry->type = g->builtin_types.entry_invalid;
2086+
}
20752087
}
20762088

20772089
context->variable_table.put(&variable_entry->name, variable_entry);

test/run_tests.cpp

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1501,6 +1501,16 @@ const foo = []u16{.x = 1024,};
15011501
add_compile_fail_case("type variables must be constant", R"SOURCE(
15021502
var foo = u8;
15031503
)SOURCE", 1, ".tmp_source.zig:2:1: error: variable of type 'type' must be constant");
1504+
1505+
add_compile_fail_case("variables shadowing types", R"SOURCE(
1506+
struct Foo {}
1507+
struct Bar {}
1508+
1509+
fn f(Foo: i32) => {
1510+
var Bar : i32;
1511+
}
1512+
)SOURCE", 2, ".tmp_source.zig:5:6: error: variable shadows type 'Foo'",
1513+
".tmp_source.zig:6:5: error: variable shadows type 'Bar'");
15041514
}
15051515

15061516
static void print_compiler_invocation(TestCase *test_case) {

0 commit comments

Comments
 (0)