swift icon indicating copy to clipboard operation
swift copied to clipboard

[CS] Diagnose misuse of CheckedCastExpr with ~=

Open jameesbrown opened this issue 1 year ago • 2 comments

Issue

When applying unwrap operator to 'as' or using 'is' in a type-cast pattern (specifically one that binds a value), the diagnostic for the resulting error could provide more guidance and suggest a fix-it.

Example with current diagnostic:

let maybeInt: Any = 1
if case let intValue as? Int = maybeInt {}
            `- error: pattern variable binding cannot appear in an expression

Fix

  1. Added diagnostic invalid_cast_in_pattern and an associated fix-it to remove !/? or replace 'is' with 'as'.
  2. Modified test/Constraints/rdar106598067.swift to account for the new diagnostic.

Example with new diagnostic:

if case let intValue as? Int = maybeInt {}
            ~~~~~~~~ ^ ~~~~~ 
                   //`- error: cannot conditionally downcast in a type-casting pattern
                   // - fix-it: remove '?'
if case let intValue as! Int = maybeInt {}
            ~~~~~~~~ ^ ~~~~~ 
                   //`- error: cannot force downcast in a type-casting pattern
                   // - fix-it: remove '!'
if case let intValue is Int = maybeInt {}
            ~~~~~~~~ ^ ~~~~
                   //`- error: use 'as' keyword to bind a matched value
                   // - fix-it: replace 'is' with 'as'

Resolves https://github.com/swiftlang/swift/issues/44631.

jameesbrown avatar Sep 23 '24 02:09 jameesbrown

@xedin Thanks for the review! Will address your comments shortly.

jameesbrown avatar Sep 23 '24 21:09 jameesbrown

Please re-request a review once you are done to help me keep track of this.

xedin avatar Sep 23 '24 21:09 xedin

@swift-ci please test

xedin avatar Sep 24 '24 16:09 xedin

@xedin Thanks for your help with this! It seems like the test failures should be fixed by https://github.com/swiftlang/swift/pull/76679.

jameesbrown avatar Sep 24 '24 19:09 jameesbrown

@swift-ci please test

xedin avatar Sep 24 '24 19:09 xedin

@swift-ci please test Windows platform

xedin avatar Sep 24 '24 21:09 xedin

https://github.com/swiftlang/swift-testing/pull/731 @swift-ci please test Windows platform

xedin avatar Sep 24 '24 21:09 xedin

@swift-ci please test macOS platform

xedin avatar Sep 25 '24 02:09 xedin