#if feature(...): conditional compilation based on enabled features

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.

6 Likes

Adding something like this for compiler development purposes seems reasonable. Maybe we could integrate it into the command line options system, so that adding a flag like -enable-blah automatically makes _feature(enable_blah) available?

8 Likes

I'd really love to see something like this!

Another feature I'd love to see is a single "pragma" that you could add to a module to enable experimental language features, instead of them all being independent command line flags that get passed to the driver.

1 Like