swiftlang / swift

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

Subscript produces bad diagnostic for uninhabited types #74210

Closed stephencelis closed 1 month ago

stephencelis commented 4 months ago

Description

While Swift can compile functions and methods that take uninhabited types like Never without warning, the same is not true of subscripts.

Reproduction

func never<A>(never: Never) -> A {}  // ✅

extension Never {
  static subscript<A>(root: Never) -> A {}  // 🛑
}

Expected behavior

I expect the subscript to compile just fine.

Environment

swift-driver version: 1.90.11.1 Apple Swift version 5.10 (swiftlang-5.10.0.13 clang-1500.3.9.4) Target: arm64-apple-macosx14.0

Additional information

No response

jamieQ commented 3 months ago

this particular subscript formulation appears to produce the error today because it hits a structural check for empty accessors in the parser. this check short-circuits the logic that would otherwise attempt to interpret the empty body as an implicit getter, and possibly allow the downstream compilation steps to succeed.

using this fact, the parsing diagnostic can be side-stepped by explicitly providing an empty getter, e.g.

extension Never {
  static subscript<A>(root: Never) -> A { get{} }  // ✅ 
}

the lack of symmetry with the way functions are handled is a bit surprising, but the behavior at least appears sort of consistent with the treatment properties receive. for example you get the same parse error with something like:

extension Never {
  var n: Never {} // error: missing return in accessor expected to return 'Never'
}

in general, i'm not sure the parser actually has enough information available to determine whether a missing return can always be accurately diagnosed here, since i'm not sure if a check for an uninhabited type can be made at this point.

cc @CodaFi @hamishknight – would treating the empty accessor bodies generally as a 'success' from the parser's perspective be a reasonable thing to do to potentially address this? it would basically mean the responsibility for diagnosing missing returns would be punted to a later stage.

stephencelis commented 3 months ago

@jamieQ Relatedly, is it possible to silence this warning? https://forums.swift.org/t/suppressing-uninhabited-enum-warnings/72487

hamishknight commented 3 months ago

would treating the empty accessor bodies generally as a 'success' from the parser's perspective be a reasonable thing to do to potentially address this? it would basically mean the responsibility for diagnosing missing returns would be punted to a later stage

That sounds reasonable to me, seems like we ought to be able to use parseImplicitGetter for this case. As a nice bonus, it would be one less diagnostic ASTGen has to worry about emitting.