Uploaded image for project: 'Swift'
  1. Swift
  2. SR-8451

Swift's optional lifting/promotion is overzealous

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Resolved
    • Priority: Medium
    • Resolution: Duplicate
    • Component/s: None
    • Labels:
      None
    • Environment:
      • swift 4.1 & recent swift 4.2 snapshots on Mac and Linux.

      Description

      Here's a Swift bug that was hiding a real SwiftNIO bug:

      struct SelectorEventSet: OptionSet, Equatable {
          typealias RawValue = UInt8
      
          let rawValue: RawValue
      
          static let _none = SelectorEventSet(rawValue: 0)
          static let reset = SelectorEventSet(rawValue: 1 << 0)
          static let readEOF = SelectorEventSet(rawValue: 1 << 1)
          static let read = SelectorEventSet(rawValue: 1 << 2)
          static let write = SelectorEventSet(rawValue: 1 << 3)
      
          init(rawValue: SelectorEventSet.RawValue) {
              self.rawValue = rawValue
          }
      }
      
      func test(_ ev: SelectorEventSet) {
          guard ev != .none else { // note how I "forgot" the underscore in front of `._none`
              return
          }
          print("not none")
      }
      
      test(._none)
      

      in the line

          guard ev != .none else {
      

      we're comparing ev which is a non-optional SelectorEventSet to .none. I meant to write ._none and the compiler didn't complain at all. .none is the one from Optional.none. So even though ev is non-optional so will never fall into the guard else branch after being lifted to an optional, the Swift compiler lifts ev which is of type SelectorEventSet to Optional<SelectorEventSet>.some(ev) and then compares that to Optional<SelectorEventSet.none (which will never be the same).

      Arguably the compiler should not do the optional promotion here because the other side is non-optional and should error. At the very least it should warn that my guard ev != .none doesn't make any sense because it can't hit the else branch.

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                Unassigned
                Reporter:
                jw Johannes Weiss
              • Votes:
                0 Vote for this issue
                Watchers:
                2 Start watching this issue

                Dates

                • Created:
                  Updated:
                  Resolved: