Skip to content

Commit 4c45885

Browse files
committed
[Name lookup] Diagnose attempts to reference not-yet-declared local variables.
Until the point where ASTScope-based unqualified name lookup is the default, unqualified name lookup can still find names declared *after* the source location. The 'hasType' check no longer makes sense, so actually check the source location of the entity we found.
1 parent e089345 commit 4c45885

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed

lib/Sema/TypeCheckConstraints.cpp

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -474,8 +474,12 @@ resolveDeclRefExpr(UnresolvedDeclRefExpr *UDRE, DeclContext *DC) {
474474
ValueDecl *D = Result.Decl;
475475
if (!D->hasType()) validateDecl(D);
476476

477-
if (!D->hasType()) {
478-
assert(D->getDeclContext()->isLocalContext());
477+
// FIXME: The source-location checks won't make sense once
478+
// EnableASTScopeLookup is the default.
479+
if (Loc.isValid() && D->getLoc().isValid() &&
480+
D->getDeclContext()->isLocalContext() &&
481+
D->getDeclContext() == DC &&
482+
Context.SourceMgr.isBeforeInBuffer(Loc, D->getLoc())) {
479483
if (!D->isInvalid()) {
480484
diagnose(Loc, diag::use_local_before_declaration, Name);
481485
diagnose(D, diag::decl_declared_here, Name);

test/expr/capture/order.swift

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,11 +78,14 @@ func outOfOrderEnum() {
7878
}
7979

8080
func captureInClosure() {
81-
var x = { (i: Int) in
82-
currentTotal += i // expected-error{{use of local variable 'currentTotal' before its declaration}}
81+
let x = { (i: Int) in
82+
currentTotal += i // expected-error{{cannot capture 'currentTotal' before it is declared}}
8383
}
8484

8585
var currentTotal = 0 // expected-note{{'currentTotal' declared here}}
86+
87+
_ = x
88+
currentTotal += 1
8689
}
8790

8891
class X {

0 commit comments

Comments
 (0)