[swift-evolution] Proposal proposal: @pure keyword

Angelo Villegas gelo.web at gmail.com
Sat Jan 9 07:16:23 CST 2016


I'm not yet really familiar with this term but correct me if I'm wrong, "pure" (function wise) means functions won't have access to global or static, and mutable variables through their arguments, right?




On Sat, Jan 9, 2016 at 12:54 AM -0800, "Andrew Bennett via swift-evolution" <swift-evolution at swift.org> wrote:










I'd like to discuss adding a @pure keyword, and see what it requires and how possible it is to  include.
I'd like to use the annotation @pure on functions, methods and closures.
This will allow us to make more guarantees about what a protocol does, and what it cannot do. It will also allow APIs like `.map` and `.forEach` to have a meaningful distinction. It could also allow for something like an assert to be removed as an optimisation with no side-effects in a release build.
If something is pure it can be annotated with @pure, if it is not-pure this will be a compile-time error. The compiler could automatically add this annotation in the interface.
A function, method or closure is pure if: * all functions, methods and closures it calls are also pure (this includes referencing self from a method or property) * it only externally references let variables of pure type, let properties on those variables, and methods/computer-properties marked as pure.
A computed property can be marked as pure like this:@pure var test: A
A function/method/closure signature is marked as pure like this:(a: A, b: A -> B) @pure -> B
If the function/method/closure is only pure if an argument is pure (similar to @rethrows), then you could do this:(start: A, a: A -> B) @pure(b) -> B
Potentially this could be extended to allow a pure closure to be composed of other pure closures:func compose(a: A -> B, b: B -> C) @pure -> A @pure(a,b) -> C {    return { b(a($0)) }}
Of course this doesn't preclude you from requiring some of those closures to be pure:func compose(a: A @pure -> B, b: B -> C) @pure -> A @pure(b) -> C {    return { b(a($0)) }}
Impact on existing code:No negative impact as if automatic annotation was allowed it would only happen where it was safe to do so. If it was not allowed then libraries could be slowly annotated to be marked as pure.

c and objective-c would not be marked as pure.

Pure functions can be safely removed by the optimiser if their result is not used. From this perspective assert and print should not be marked as pure (they would have to be an exception anyway).

Ideally existing libraries would be annotated, the more the better, but this can be a gradual process.










-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160109/ee69187b/attachment.html>


More information about the swift-evolution mailing list