[swift-evolution] Proposal: Automatic Wrapper Synthesis / "deriving"
Harlan Haskins
harlan at harlanhaskins.com
Sat Dec 5 00:46:41 CST 2015
I feel like, if we implement automatic derivation for structs that wrap one value, we can just as easily implement automatic derivation for all product types for which the children conform to the protocols in question, and there’s a provided implementation for derivation by combining values.
Consider Hashable. A very common implementation of hashValue is xor-ing all the members’ hash values together.
We could actually implement this right now given Swift’s reflection system (if we were able to conditionally cast to Hashable or any protocol with a Self requirement).
Consider this:
struct HashableDerivable deriving Hashable {
let string: String // because String is already Hashable
let integer: Int // and Int is Hashable
// then HashableDerivable is trivially Hashable.
}
/// This implementation is absolutely derivable at compile time.
extension HashableDerivable: Hashable {
var hashValue: Int {
return string.hashValue ^ integer.hashValue
}
}
func ==(lhs: HashableDerivable, rhs: HashableDerivable) -> Bool {
return lhs.string == rhs.string && lhs.integer == rhs.integer
}
// one can also use Reflection to derive this at runtime
extension Mirror {
func canDeriveHashable() -> Bool {
if self.subjectType is Hashable { return true } // this is currently a compiler error
for child in self.children {
let mirror = Mirror(reflecting: child)
if !mirror.canDeriveHashable() { return false }
}
return true
}
func deriveHashValue() -> Int {
if !self.canDeriveHashable() { fatalError("Boy, I wish this didn't have to happen at runtime.") }
guard let firstChild = self.children.first as? Hashable /* also an error */ else { fatalError("no children") }
return self.children.dropFirst().reduce(firstChild.hashValue) { (hash, _: (_: String?, value: Any)) -> T in
return hash ^ (value as! Hashable).hashValue
}
}
}
Of course, this is something that can be done at compile time, which would make protocol conformance really, really simple.
We already do this, using the Mirror API, for CustomStringConvertible.
> > On Dec 4, 2015, at 4:26 PM, John McCall <rjmccall at apple.com <https://lists.swift.org/mailman/listinfo/swift-evolution>> wrote:
> >
> >> On Dec 4, 2015, at 1:19 PM, plx <plxswift at icloud.com <https://lists.swift.org/mailman/listinfo/swift-evolution>> wrote:
> >> # A `wrapper` / `deriving` Construct
> >>
> >> I'm sure a construct along these lines has been requested numerous times and is hopefully already on the roadmap.
> >>
> >> The point of this email is to put out a reasonably-*concrete* sketch as a way of soliciting community feedback on the specifics of how such a construct might look-and-work within Swift; hopefully I’ve gone far-enough to be interesting, but not too much further than that.
> >>
> >> ## Design Sketch
> >>
> >> It ought to be possible to write something like this:
> >>
> >> // an example:
> >> struct SectionIndex
> >> wrapping Int
> >> as index
> >> satisfying precondition { $0 >= 0 }
> >> deriving Equatable, Comparable, Hashable {
> >> // declaration can continue in here
> >> }
> >>
> >> ...which, when compiled, would be "expanded" along these lines:
> >>
> >> struct SectionIndex {
> >>
> >> // would have been `wrappedValue` w/out the `as index` clause
> >> let index: Int
> >>
> >> init(_ index: Int) {
> >> precondition(index >= 0)
> >> // ^ would have been assert(index >= 0)
> >> // had we used `satisfying { $0 >= 0 }`,
> >> // and omitted entirely had we omitted a `satisfying` clause
> >> self.index = index
> >> }
> >>
> >> }
> >>
> >> extension SectionIndex : Equatable {
> >> }
> >>
> >> // synthesized unless explicitly written-out
> >> func ==(lhs: SectionIndex, rhs: SectionIndex) -> Bool {
> >> return lhs.index == rhs.index
> >> }
> >>
> >> // same for Comparable, Hashable, all done in the obvious way
> >>
> >> // there’s a lot of utility in synthesizing something like this,
> >> // I can expand on it if necessary:
> >> extension SectionIndex: ValueWrapperType {
> >> typealias WrappedType = Int
> >> }
> >>
> >> ...where each method/init/subscript/etc in the derived protocols gets synthesized at compile-time, if not explicitly implemented; similarly, if not explicitly-declared, the derived protocols' typealiases can be synthesized in obvious ways, and it seems acceptable to simply fail to compile (and inform the user of the need to make an explicit-declaration) in cases where such synthesis is impossible.
> >>
> >> I think this enough to sketch the way the feature would look and how it would work.
> >
> > I’m not sure what work is being done by “wrapping X as Y” here; it seems like just another way of expressing a stored property.
> >
> > I think we’re all interested in a “deriving” proposal. However, the key problem that a serious proposal would have to address is not picking the syntax, but describing how derivation would actually work. We’d prefer not to just hard-code rules in the compiler for specific protocols.
> >
> > For example, derivation presumably involves recursively invoking the given operation on each of the stored properties (what does “on” mean? which parameters are changed, and which are passed through?) and then merging the results (how?).
> >
> > John.
>
> Apologies for leaving too much out.
>
> I meant to propose that the `deriving` in this place would enforce the wrapper type only wrapped a single stored value, warranting the distinct syntax; I seem to have edited-out both an explicit statement that this assumed a single-stored-property and to have omitted a comment in the `//declaration can continue in here` that no additional stored-properties could be declared (analogous to the rules current applied within extensions).
>
> Yes, constraining a `deriving` construct to only support wrappers containing a single stored property would, on the one hand, be somewhat limiting, but on the other hand it would seemingly allow trivial solutions to the issues you bring up:
>
> - `on` is unambiguous as there’s only one thing it can be “on"
> - there’s no ordering-of-operations to have to worry about
> - there’s no merging-of-results to have to worry about
> - i’m guessing there’s no parameters needing to getting changed (but I’m not 100% on what you mean here)
> - there’s no associated-type incoherency to worry about (unless user error introduces it)
>
> …there’s least one tricky case (if you want the wrapper to replace one of the wrapped type’s typealiases with a wrapper).
>
> …and at least for me, there’s enough value in that simplified wrapper-synthesis / deriving-type construct to take the time to check community interest.
>
> Thanks for taking the time to read and send feedback.
>
> PS:
>
> On the other hand, if this becomes writable:
>
> protocol WrapperType {
> typealias WrappedValue
> var wrappedValue: { get }
> }
>
> extension WrapperType : Equatable where WrappedValue: Equatable {
> }
>
> func ==<W:WrapperType where W.WrappedValue:Equatable>(lhs: W, rhs: W) -> Bool {
> return lhs.wrappedValue == rhs.wrappedValue
> }
>
> …etc., then it’s possible (albeit moderately unpleasant) to just write suitable glue logic out longhand on an as-needed basis (and with the caveat that all types wrapping T would potentially adopt all of T’s protocols even when potentially undesirable).
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151205/7d638166/attachment.html>
More information about the swift-evolution
mailing list