Skip to content

Commit 99116c9

Browse files
Change error diagnosed for when self isn't available in scope (#59140)
Diagnose different error for when `self` cannot be found in scope Co-authored-by: Hamish Knight <[email protected]>
1 parent 0591246 commit 99116c9

File tree

3 files changed

+36
-4
lines changed

3 files changed

+36
-4
lines changed

include/swift/AST/DiagnosticsSema.def

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -905,6 +905,8 @@ ERROR(cannot_find_in_scope,none,
905905
ERROR(cannot_find_in_scope_corrected,none,
906906
"cannot %select{find|find operator}1 %0 in scope; did you mean '%2'?",
907907
(DeclNameRef, bool, StringRef))
908+
ERROR(cannot_find_self_in_scope,none,
909+
"cannot find 'self' in scope; did you mean to use it in a type or extension context?", ())
908910
NOTE(confusable_character,none,
909911
"%select{identifier|operator}0 '%1' contains possibly confused characters; "
910912
"did you mean to use '%2'?",

lib/Sema/PreCheckExpr.cpp

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -586,10 +586,19 @@ Expr *TypeChecker::resolveDeclRefExpr(UnresolvedDeclRefExpr *UDRE,
586586
}
587587

588588
auto emitBasicError = [&] {
589-
Context.Diags
590-
.diagnose(Loc, diag::cannot_find_in_scope, Name,
591-
Name.isOperator())
592-
.highlight(UDRE->getSourceRange());
589+
590+
if (Name.isSimpleName(Context.Id_self)) {
591+
// `self` gets diagnosed with a different error when it can't be found.
592+
Context.Diags
593+
.diagnose(Loc, diag::cannot_find_self_in_scope)
594+
.highlight(UDRE->getSourceRange());
595+
} else {
596+
Context.Diags
597+
.diagnose(Loc, diag::cannot_find_in_scope, Name,
598+
Name.isOperator())
599+
.highlight(UDRE->getSourceRange());
600+
}
601+
593602
if (!Context.LangOpts.DisableExperimentalClangImporterDiagnostics) {
594603
Context.getClangModuleLoader()->diagnoseTopLevelValue(
595604
Name.getFullName());

test/Sema/self_cannot_be_found.swift

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// RUN: %target-typecheck-verify-swift
2+
3+
let _ = self // expected-error {{cannot find 'self' in scope; did you mean to use it in a type or extension context?}}
4+
let s = self.b // // expected-error {{cannot find 'self' in scope; did you mean to use it in a type or extension context?}}
5+
let w = self.method() // expected-error {{cannot find 'self' in scope; did you mean to use it in a type or extension context?}}
6+
7+
struct aStruct {
8+
let b = "a"
9+
10+
func testFunc() {
11+
print(self.b)
12+
}
13+
14+
var c: String {
15+
self.b
16+
}
17+
}
18+
19+
let _ = aStruct.self
20+
let initialized = aStruct().self
21+
_ = initialized.b

0 commit comments

Comments
 (0)