authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2017-05-03 16:13:22-04:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2017-05-03 16:13:57-04:00
log0940d46c0160683fb5a28f66589e53ec5b64241d
tree1b762e3c124b68c00db161efe6f076f61730f4b6
parent6756c27ca48f65c7f21b7a4365ff7a80069d2441

add compile error for shadowing variable

closes #360

2 files changed, 39 insertions(+), 7 deletions(-)

src/analyze.cpp+15-7
......@@ -2289,13 +2289,21 @@ VariableTableEntry *add_variable(CodeGen *g, AstNode *source_node, Scope *parent
22892289 add_node_error(g, source_node,
22902290 buf_sprintf("variable shadows type '%s'", buf_ptr(&type->name)));
22912291 variable_entry->value->type = g->builtin_types.entry_invalid;
2292 } else if (src_tld == nullptr) {
2293 Tld *tld = find_decl(g, parent_scope, name);
2294 if (tld) {
2295 ErrorMsg *msg = add_node_error(g, source_node,
2296 buf_sprintf("redefinition of '%s'", buf_ptr(name)));
2297 add_error_note(g, msg, tld->source_node, buf_sprintf("previous definition is here"));
2298 variable_entry->value->type = g->builtin_types.entry_invalid;
2292 } else {
2293 Scope *search_scope = nullptr;
2294 if (src_tld == nullptr) {
2295 search_scope = parent_scope;
2296 } else if (src_tld->parent_scope != nullptr && src_tld->parent_scope->parent != nullptr) {
2297 search_scope = src_tld->parent_scope->parent;
2298 }
2299 if (search_scope != nullptr) {
2300 Tld *tld = find_decl(g, search_scope, name);
2301 if (tld != nullptr) {
2302 ErrorMsg *msg = add_node_error(g, source_node,
2303 buf_sprintf("redefinition of '%s'", buf_ptr(name)));
2304 add_error_note(g, msg, tld->source_node, buf_sprintf("previous definition is here"));
2305 variable_entry->value->type = g->builtin_types.entry_invalid;
2306 }
22992307 }
23002308 }
23012309 }
test/compile_errors.zig+24
......@@ -1630,4 +1630,28 @@ pub fn addCases(cases: &tests.CompileErrorContext) {
16301630 \\}
16311631 ,
16321632 ".tmp_source.zig:4:12: error: function returns address of local variable");
1633
1634 cases.add("inner struct member shadowing outer struct member",
1635 \\fn A() -> type {
1636 \\ struct {
1637 \\ b: B(),
1638 \\
1639 \\ const Self = this;
1640 \\
1641 \\ fn B() -> type {
1642 \\ struct {
1643 \\ const Self = this;
1644 \\ }
1645 \\ }
1646 \\ }
1647 \\}
1648 \\comptime {
1649 \\ assert(A().B().Self != A().Self);
1650 \\}
1651 \\fn assert(ok: bool) {
1652 \\ if (!ok) unreachable;
1653 \\}
1654 ,
1655 ".tmp_source.zig:9:17: error: redefinition of 'Self'",
1656 ".tmp_source.zig:5:9: note: previous definition is here");
16331657}