swiftlang / swift

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

[SR-13627] Derivative registration doesn't work on rethrowing functions #56062

Open rxwei opened 3 years ago

rxwei commented 3 years ago
Previous ID SR-13627
Radar rdar://problem/69733357
Original Reporter @rxwei
Type Bug
Additional Detail from JIRA | | | |------------------|-----------------| |Votes | 0 | |Component/s | Compiler | |Labels | Bug, AutoDiff | |Assignee | None | |Priority | Medium | md5: dd36f68f8af4408fe46600b0524f8839

blocks:

Issue Description:

When I try to register a derivative for a function that rethrows with a derivative that also rethrows, the type checker is unable to match the expected candidate.

Failure:
The nil-coalescing operator ?? needs a derivative in order to be differentiable. Defining the following derivative will show that the type checker has disregarded the rethrowing-ness of the derivative function, causing it to think that no candidate original functions match.

@derivative(of: ??, wrt: optional)
@usableFromInline
func _derivativeOfNilCoalescing<T: Differentiable>(
  optional: T?,
  defaultValue: @autoclosure () throws -> T
) rethrows -> (
  value: T, 
  pullback: (T.TangentVector) -> Optional<T>.TangentVector
) {
  fatalError()
}
/home/rxwei/Development/Swift/swift-source/swift/stdlib/public/Differentiation/OptionalDifferentiation.swift:85:17: error: referenced declaration '??' could not be resolved
@derivative(of: ??, wrt: optional)
                ^
Swift.??:1:13: note: candidate operator function does not have type equal to or less constrained than '<T where T : Differentiable> (optional: T?, defaultValue: @autoclosure () throws -> T) -> T?'
public func ?? <T>(optional: T?, defaultValue: @autoclosure () throws -> T) rethrows -> T
            ^
Swift.??:1:13: note: candidate operator function does not have type equal to or less constrained than '<T where T : Differentiable> (optional: T?, defaultValue: @autoclosure () throws -> T) -> T?'
public func ?? <T>(optional: T?, defaultValue: @autoclosure () throws -> T?) rethrows -> T?
            ^

For context, unlike rethrowing functions, throwing functions are okay:

func foo(x: Float) throws -> Float { x }

@derivative(of: foo)
func foo(x: Float) throws -> (value: Float, pullback: (Float) -> Float) {
  fatalError()
}
rxwei commented 3 years ago

@swift-ci create

rxwei commented 3 years ago

This is blocking SR-13624 because the derivative of ?? needs this to work.