Skip to content

[CS] Diagnose misuse of CheckedCastExpr with ~= #76644

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

Merged
merged 1 commit into from
Sep 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions include/swift/AST/DiagnosticsSema.def
Original file line number Diff line number Diff line change
Expand Up @@ -1419,6 +1419,15 @@ ERROR(optional_chain_isnt_chaining,none,
())
ERROR(pattern_in_expr,none,
"%0 cannot appear in an expression", (DescriptivePatternKind))
ERROR(conditional_cast_in_type_casting_pattern,none,
"cannot conditionally downcast in a type-casting pattern",
())
ERROR(force_cast_in_type_casting_pattern,none,
"cannot force downcast in a type-casting pattern",
())
ERROR(cannot_bind_value_with_is,none,
"use 'as' keyword to bind a matched value",
())
NOTE(note_call_to_operator,none,
"in call to operator %0", (const ValueDecl *))
NOTE(note_call_to_func,none,
Expand Down
39 changes: 38 additions & 1 deletion lib/Sema/CSDiagnostics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8699,10 +8699,47 @@ bool InvalidPatternInExprFailure::diagnoseAsError() {
E = parent;
}
}
emitDiagnostic(diag::pattern_in_expr, P->getDescriptiveKind());
if (!diagnoseInvalidCheckedCast()) {
emitDiagnostic(diag::pattern_in_expr, P->getDescriptiveKind());
}
return true;
}

bool InvalidPatternInExprFailure::diagnoseInvalidCheckedCast() const {
auto *E = findParentExpr(castToExpr(getAnchor()));
// Make sure we have a CheckedCastExpr and are in an argument of `~=`.
while (E && !isa<CheckedCastExpr>(E))
E = findParentExpr(E);
auto *castExpr = cast_or_null<CheckedCastExpr>(E);
if (!castExpr)
return false;
auto *parent = findParentExpr(castExpr);
while (parent && !isa<BinaryExpr>(parent))
parent = findParentExpr(parent);
auto *BE = cast_or_null<BinaryExpr>(parent);
if (!BE || !isPatternMatchingOperator(BE->getFn()))
return false;
// Emit the appropriate diagnostic based on the cast kind.
if (auto *forced = dyn_cast<ForcedCheckedCastExpr>(castExpr)) {
emitDiagnosticAt(castExpr->getLoc(),
diag::force_cast_in_type_casting_pattern)
.fixItRemove(forced->getExclaimLoc());
return true;
}
if (auto *conditional = dyn_cast<ConditionalCheckedCastExpr>(castExpr)) {
emitDiagnosticAt(castExpr->getLoc(),
diag::conditional_cast_in_type_casting_pattern)
.fixItRemove(conditional->getQuestionLoc());
return true;
}
if (auto *isExpr = dyn_cast<IsExpr>(castExpr)) {
emitDiagnosticAt(castExpr->getLoc(), diag::cannot_bind_value_with_is)
.fixItReplace(isExpr->getAsLoc(), "as");
return true;
}
return false;
}

bool MissingContextualTypeForNil::diagnoseAsError() {
auto *expr = castToExpr<NilLiteralExpr>(getAnchor());

Expand Down
12 changes: 12 additions & 0 deletions lib/Sema/CSDiagnostics.h
Original file line number Diff line number Diff line change
Expand Up @@ -2604,6 +2604,18 @@ class InvalidPatternInExprFailure final : public FailureDiagnostic {
: FailureDiagnostic(solution, locator), P(pattern) {}

bool diagnoseAsError() override;

private:
/// Diagnose situations where a type-casting pattern that binds a value
/// expects 'as' but is given 'as!', 'as?' or 'is' instead
/// e.g:
///
/// \code
/// case let x as? Int = y
/// case let x as! Int = y
/// case let x is Int = y
/// \endcode
bool diagnoseInvalidCheckedCast() const;
};

/// Diagnose situations where there is no context to determine a
Expand Down
16 changes: 14 additions & 2 deletions test/Constraints/rdar106598067.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,22 @@
enum E: Error { case e }

// rdar://106598067 – Make sure we don't crash.
// FIXME: We ought to have a tailored diagnostic to change to 'as' instead of 'as?'
let fn = {
do {} catch let x as? E {}
// expected-error@-1 {{pattern variable binding cannot appear in an expression}}
// expected-error@-1 {{cannot conditionally downcast in a type-casting pattern}}{{23-24=}}
// expected-error@-2 {{expression pattern of type 'E?' cannot match values of type 'any Error'}}
// expected-warning@-3 {{'catch' block is unreachable because no errors are thrown in 'do' block}}
}

// https://github.com/swiftlang/swift/issues/44631
let maybeInt: Any = 1
switch maybeInt {
case let intValue as? Int: _ = intValue
// expected-error@-1 {{cannot conditionally downcast in a type-casting pattern}}{{21-22=}}
// expected-error@-2 {{expression pattern of type 'Int?' cannot match values of type 'Any'}}
case let intValue as! Int: _ = intValue
// expected-error@-1 {{cannot force downcast in a type-casting pattern}}{{21-22=}}
case let intValue is Int: _ = intValue
// expected-error@-1 {{use 'as' keyword to bind a matched value}}{{19-21=as}}
default: break
}