Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change error diagnosed for when self isn't available in scope #59140

Merged
merged 10 commits into from
Jun 3, 2022
2 changes: 2 additions & 0 deletions include/swift/AST/DiagnosticsSema.def
Original file line number Diff line number Diff line change
Expand Up @@ -905,6 +905,8 @@ ERROR(cannot_find_in_scope,none,
ERROR(cannot_find_in_scope_corrected,none,
"cannot %select{find|find operator}1 %0 in scope; did you mean '%2'?",
(DeclNameRef, bool, StringRef))
ERROR(cannot_find_self_in_scope,none,
"cannot find 'self' in scope; did you mean to use it in a type or extension context?", ())
NOTE(confusable_character,none,
"%select{identifier|operator}0 '%1' contains possibly confused characters; "
"did you mean to use '%2'?",
Expand Down
17 changes: 13 additions & 4 deletions lib/Sema/PreCheckExpr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -586,10 +586,19 @@ Expr *TypeChecker::resolveDeclRefExpr(UnresolvedDeclRefExpr *UDRE,
}

auto emitBasicError = [&] {
Context.Diags
.diagnose(Loc, diag::cannot_find_in_scope, Name,
Name.isOperator())
.highlight(UDRE->getSourceRange());

if (Name.isSimpleName(Context.Id_self)) {
// `self` gets diagnosed with a different error when it can't be found.
Context.Diags
.diagnose(Loc, diag::cannot_find_self_in_scope)
.highlight(UDRE->getSourceRange());
} else {
Context.Diags
.diagnose(Loc, diag::cannot_find_in_scope, Name,
Name.isOperator())
.highlight(UDRE->getSourceRange());
}

if (!Context.LangOpts.DisableExperimentalClangImporterDiagnostics) {
Context.getClangModuleLoader()->diagnoseTopLevelValue(
Name.getFullName());
Expand Down
21 changes: 21 additions & 0 deletions test/Sema/self_cannot_be_found.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// RUN: %target-typecheck-verify-swift

let _ = self // expected-error {{cannot find 'self' in scope; did you mean to use it in a type or extension context?}}
let s = self.b // // expected-error {{cannot find 'self' in scope; did you mean to use it in a type or extension context?}}
let w = self.method() // expected-error {{cannot find 'self' in scope; did you mean to use it in a type or extension context?}}

struct aStruct {
let b = "a"

func testFunc() {
print(self.b)
}

var c: String {
self.b
}
}

let _ = aStruct.self
let initialized = aStruct().self
_ = initialized.b