Skip to content

Type inference for default expressions (SE-347) generic closure issue #63749

@stephencelis

Description

@stephencelis

Description

There seem to be some edge cases around identity functions that cause problems for SE-0347.

Steps to reproduce

A simple example:

struct S<A, B> {
  func f<C, D>(
    a2c: (A) -> C = { $0 },  // 🛑
    b2d: (B) -> D = { $0 }   // 🛑
  ) -> S<C, D> {
    .init()
  }
}

🛑 Unable to infer type of a closure parameter '$0' in the current context

While it'd be nice for this to work, the limitation is somewhat understandable. Making things more explicit, gets the base method compiling:

struct S<A, B> {
  func f<C, D>(
    a2c: (A) -> C = { (a: A) -> A in a },  // ✅
    b2d: (B) -> D = { (b: B) -> B in b }   // ✅
  ) -> S<C, D> {
    .init()
  }
}

// or even flipping it:

struct S<A, B> {
  func f<C, D>(
    a2c: (A) -> C = { (c: C) -> C in c },  // ✅
    b2d: (B) -> D = { (d: D) -> D in d }   // ✅
  ) -> S<C, D> {
    .init()
  }
}

But actual use leads to ambiguity if generics are unknown:

let s1 = S<Int, Int>()

let s2 = s1.f(a2c: { $0 + 1 }, b2d: { $0 + 1 })  // ✅
let s3 = s1.f(a2c: { $0 + 1 })  // 🛑 Generic parameter 'D' could not be inferred
let s4 = s1.f(b2d: { $0 + 1 })  // 🛑 Generic parameter 'C' could not be inferred
let s5 = s1.f()  // 🛑 Generic parameter 'C' could not be inferred
                 // 🛑 Generic parameter 'D' could not be inferred

Expected behavior

I expect the above to compile.

Environment

  • Swift compiler version info
    swift-driver version: 1.75.1 Apple Swift version 5.8 (swiftlang-5.8.0.117.11 clang-1403.0.22.8.60)
    Target: arm64-apple-macosx13.0
    
  • Xcode version info
    Xcode 14.3
    Build version 14E5197f
    

Metadata

Metadata

Assignees

No one assigned

    Labels

    closuresFeature: closurescompilerThe Swift compiler itselfdefault argumentsFeature: default arguments for value parametersfeatureA feature request or implementationgenericsFeature: generic declarations and typestype checkerArea → compiler: Semantic analysistype inferenceFeature: type inference

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions