Skip to content

Commit c329d72

Browse files
authored
[Sema] Fix a crash in use-before-declaration case (#18466)
Check use-before-declaration early so we don't typecheck referenced decl which might depends on the reference. https://bugs.swift.org/browse/SR-7517 https://bugs.swift.org/browse/SR-8447 rdar://problem/39782719
1 parent 53d0ef8 commit c329d72

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

lib/Sema/TypeCheckConstraints.cpp

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -469,6 +469,9 @@ static bool findNonMembers(TypeChecker &TC,
469469
}
470470

471471
ValueDecl *D = Result.getValueDecl();
472+
if (!isValid(D))
473+
return false;
474+
472475
if (!D->hasInterfaceType())
473476
TC.validateDecl(D);
474477

@@ -478,9 +481,6 @@ static bool findNonMembers(TypeChecker &TC,
478481
continue;
479482
}
480483

481-
if (!isValid(D))
482-
return false;
483-
484484
if (matchesDeclRefKind(D, refKind))
485485
ResultValues.push_back(D);
486486
}

test/Sema/diag_use_before_declaration.swift

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ func test() {
1818
guard let bar = foo else {
1919
return
2020
}
21-
let foo = String(bar)
21+
let foo = String(bar) // expected-warning {{initialization of immutable value 'foo' was never used; consider replacing with assignment to '_' or removing it}}
2222
}
2323

2424
// SR-7660
@@ -30,6 +30,18 @@ class C {
3030
}
3131
}
3232

33+
// SR-7517
34+
func testExample() {
35+
let app = app2 // expected-error {{use of local variable 'app2' before its declaration}}
36+
let app2 = app // expected-note {{'app2' declared here}}
37+
}
38+
39+
// SR-8447
40+
func test_circular() {
41+
let obj = sr8447 // expected-error {{use of local variable 'sr8447' before its declaration}}
42+
let _ = obj.prop, sr8447 // expected-note {{'sr8447' declared here}} expected-error {{type annotation missing in pattern}}
43+
}
44+
3345
//===----------------------------------------------------------------------===//
3446
// Nested scope
3547
//===----------------------------------------------------------------------===//

0 commit comments

Comments
 (0)