Skip to content

[SR-16011] Undefined behavior when switching over a frozen enum imported from C #58272

@grynspan

Description

@grynspan
Previous ID SR-16011
Radar None
Original Reporter @grynspan
Type Bug
Additional Detail from JIRA
Votes 0
Component/s swift
Labels Bug
Assignee None
Priority Medium

md5: 7e6f700cc048d77f075128ff58486486

Issue Description:

Given the following code:

import Foundation

func ub(_ i: Int) {
    guard let res = ComparisonResult(rawValue: i) else {
        return
    }
    switch res {
    case .orderedAscending, .orderedDescending, .orderedSame:
        print("No undefined behavior here.")
    }
}
ub(2)

The program will crash with the message:

> Fatal error: unexpected enum case 'NSComparisonResult(rawValue: 2)'

At the language level, Swift is assuming that since the `switch` is exhaustive, no `default` case is needed. However, because the enum is imported from C, it might have cases that were not visible to the Swift importer at import time, so `init(rawValue🙂` always produces an instance of `ComparisonResult` even if the input value is invalid, despite it being frozen. The issue is not specific to `ComparisonResult`, but it is an easy way to demonstrate it.

The language should probably change the synthesized initializer for an imported frozen enum such that it returns `nil` for cases that are not visible at import time.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.c interopFeature: Interoperability with CcompilerThe Swift compiler itselfenumFeature → type declarations: Swift enumeration declarationsswitch exhaustivityFeature: enforcement of exhaustivity in 'switch' statements

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions