Skip to content

Commit 62d13e5

Browse files
committed
[Type checker] Allow forward references to local types.
Recent work to improve checking for forward references to local types (#16967) started rejecting code that referred to a local type before it is defined. Swift previously accepted such code, because local types can’t capture anyway, so allow it again… for now. As a separate action item, I’d like to revisit the language design here, because it’s somewhat surprising when we can vs. cannot forward-reference local declarations, and the rules differ from those of top-level code in scripts *and* top-level code for non-scripts. Fixes rdar://problem/41659447
1 parent 823d63b commit 62d13e5

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

lib/Sema/TypeCheckConstraints.cpp

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -601,10 +601,14 @@ resolveDeclRefExpr(UnresolvedDeclRefExpr *UDRE, DeclContext *DC) {
601601
auto isValid = [&](ValueDecl *D) {
602602
// FIXME: The source-location checks won't make sense once
603603
// EnableASTScopeLookup is the default.
604+
//
605+
// Note that we allow forward references to types, because they cannot
606+
// capture.
604607
if (Loc.isValid() && D->getLoc().isValid() &&
605608
D->getDeclContext()->isLocalContext() &&
606609
D->getDeclContext() == DC &&
607-
Context.SourceMgr.isBeforeInBuffer(Loc, D->getLoc())) {
610+
Context.SourceMgr.isBeforeInBuffer(Loc, D->getLoc()) &&
611+
!isa<TypeDecl>(D)) {
608612
localDeclAfterUse = D;
609613
return false;
610614
}

test/Compatibility/local_types.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
// RUN: %target-typecheck-verify-swift
2+
3+
func foo() {
4+
// Okay to reference a type declared later in the same function.
5+
_ = Visitor()
6+
struct Visitor { }
7+
}

0 commit comments

Comments
 (0)