apple / swift

The Swift Programming Language
https://swift.org
Apache License 2.0
66.24k stars 10.24k forks source link

Misleading error for expression pattern using enum #71923

Open wti opened 3 months ago

wti commented 3 months ago

Description

A "cannot match" message implies the type is wrong, when it's the expression.

// 5.9+: pattern of type 'ASC' cannot match 'Character'
// 5.8-: enum case 'c' is not a member of type 'Character'
  case ASC.c: // has to be ASC.c.self (?)

Adding to the confusion. .x works, but qualifying like Enum.x requires Enum.x.self. (Perhaps Enum.x is its own sum type in this expression context?)


Context/conseqence: After overriding ~= to support expression pattern on enum ASC, when case .c alone is ambiguous, qualifying with the enum type (ASC.c) results in the perplexing message that the enum type cannot match. As a result, the user investigates why the ~= implementation is not working, when the problem lies in the case expression.

Reproduction

func demo() {
  let ac = ASC.c // for OK case below
  _ = ac
  switch "c" as Character {
  // error message: 
  // 5.9+: pattern of type 'ASC' cannot match 'Character'
  // 5.8-: enum case 'c' is not a member of type 'Character'
  case ASC.c: 
  //case ASC.c.self: // OK
  //case ac: // OK
  //case .c: // OK, if not ambiguous
    print("ok")
  default:
    break;
  }
}
enum ASC: UInt8 {
  case c = 99
  public static func ~= (pattern: Self, value: Character) -> Bool {
    value.isASCII && pattern.rawValue == value.asciiValue
  }
}
// Another .c for switch Character, forcing `ASC.c` qualifier
// (required only to show error when `.c` alone is ambiguous)
enum Grade: UInt8 {
  case b = 98, c // if c, `case .c` -> "ambiguous use of c"
  public static func ~= (pattern: Self, value: Character) -> Bool {
    value.isASCII && pattern.rawValue == value.asciiValue
  }
}

Expected behavior

It would be nice if dot-syntax ASC.c worked here. But if that's not correct, a more explanatory error and suggestion, e.g.,

Enumeration instance required in expression context.  Consider `ASC.c.self`

Environment

Same result in 5.9, nightly, and development 1/24/2024, with similar error in 5.8-

Additional information

No response

wti commented 3 months ago

This area might be being worked on in PR https://github.com/apple/swift/pull/63388#discussion_r1096616466 by @AnthonyLatsis (apologies for the ping).