An important goal for upstreaming experimental features like differentiable programming is to have developers try them out in their libraries. For differentiable programming, we already have a frontend feature gate (swiftc -enable-experimental-differentiable-programming
), but there's no way yet to conditionally compile code that uses the feature.
I propose that we add a new syntax in the #if
condition expression: _feature(...)
. Similar to platform conditions, _feature(...)
will evaluate to true
if the specified language feature is enabled, and false
otherwise. If the language feature is undefined, an error will be produced.
For example, if we were to add a derivative for ElementaryFunctions.cos(_:)
to swift-numerics, we can make it conditionally compiled only when -enable-experimental-differentiable-programming
is enabled.
#if _feature(DifferentiableProgramming)
public extension ElementaryFunctions where Self: Differentiable {
@derivative(of: cos)
func cosDerivative(_ x: Self) -> (value: Self, differential: @differentiable(linear) (Self) -> Self) {
(value: cos(x), differential: { v in -sin(x) * v })
}
}
#endif // _feature(DifferentiableProgramming)
Swift does not yet have a story around "optional features", so I'm not yet proposing to include this syntax formally in Swift. However, I feel that adding this (underscored) syntax will likely be very useful for other experimental features.