[swift-evolution] [Pitch] Introduce User-defined "Dynamic Member Lookup" Types
Paul Cantrell
cantrell at pobox.com
Thu Nov 16 15:45:32 CST 2017
[Arg, I keep sending these with the wrong from address and getting bounced! Excited for Discourse…]
> On Nov 16, 2017, at 12:00 AM, Brent Royal-Gordon via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>
>> On Nov 14, 2017, at 11:29 PM, Chris Lattner via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>>
>> extension PyVal {
>> subscript(dynamicMember member: String) -> PyVal {
>> get {
>> let result = PyObject_GetAttrString(borrowedPyObject, member)!
>> return PyRef(owned: result) // PyObject_GetAttrString returns +1 result.
>> }
>> set {
>> PyObject_SetAttrString(borrowedPyObject, member,
>> newValue.toPython().borrowedPyObject)
>> }
>> }
>> }
>
> This looks great for Python, but let's talk about some other languages for a moment.
>
> * Ruby and Perl don't have the "call a method by fetching a closure property and invoking it" behavior you're relying on here. Instead, Ruby has a syntax for settable "overloads" of methods (i.e. you can write `def someMember` and `def someMember= (newValue)`), while Perl supports lvalue methods (but sometimes uses getter and setter method pairs instead). How do you envision these behaviors being bridged to Swift? I worry that this protocol may not be sufficient, and that we may need a design which can distinguish between looking up methods and looking up properties.
I’ve never pried the lid of Ruby’s implementation of method dispatch, but I’m pretty sure that if foo defines a bar method, then
foo.bar(…args…)
is fully equivalent to:
foo.method(:bar).call(…args…)
IOW, there is an intermediate Method object that would fit the shape of the proposed callable protocol.
If foo instead doesn’t actually declare the bar method, but instead handles it via method_missing or __send__, then foo.method(:bar) raises an exception. However, it would be trivial to write a deferred invocation wrapper that also fits the shape of the proposed protocols and calls foo.send(“bar”, …args…) at the appropriate time.
In short, I don’t think there’s a problem here.
In the example you bring up:
> you can write `def someMember` and `def someMember= (newValue)`)
…there is no overloading. The = is _part of the method name_, i.e. there is a `someMember` method and a `someMember=` method. The following are equivalent:
foo.bar = 3 # just sugar
foo.bar=(3)
foo.send("bar=", 3)
Ruby allows ?, !, and = as the last char of method names, and AFAIK other than the special sugar around setters, they are just parts of the method name with no further semantic significance.
> * Ruby looks up members using symbols, which essentially play the same role as selectors in Objective-C—they're uniqued strings which are used for fast member dispatch. In some cases, you might see non-negligible speed improvements by only looking up the symbol once. Is there a way this design could accommodate that? For instance, could the type of the index be specified by an associated type, so Ruby could use a RbSymbol instead of a String? Or do you think that would be overkill?
Good question. The language gets its symbol speedup by canonicalizing symbols at compile time when possible, and that failing, when symbolicated instead of when dispatched:
one_zillion.times { foo.some_long_method_name } # fastest
# only ~1.5x slower than prev, despite one extra method dispatch:
one_zillion.times { foo.send(:some_long_method_name) }
# performance identical to previous:
symbol = string.to_sym
one_zillion.times { foo.send(symbol) }
# ~2x slower:
one_zillion.times { foo.send(string) }
(Those are based on actual benchmarks.)
Swift should be able to do the same optimizations. Making the method name a string would preclude that.
>
> * Generally, you've talked about properties (in this proposal) and methods (in the `DynamicCallable` proposal), but what about subscripts? Obviously you can just specify a `subscript(Pythonable) -> PyVal` on `PyVal` for the simple case, but what if the subscript takes multiple indices or has labels? Do we need a `DynamicSubscriptable` protocol?
>
> * Let's step away from bridging entirely and just think about Swift for a moment. There are cases where we'd like to make *semi*-dynamic proxies which wrap another type and allow operations based on what's statically known about that type. Think, for example, of the appearance proxy in UIKit: This is an object attached to UIView subclasses which lets you (in essence) set default values for all instances. We currently just pretend it's an instance of `Self`, which mostly works because of Objective-C, but a Swift-native version would probably prefer to return a `UIAppearance<Self>` object which used its knowledge of `Self` to expose `Self`'s properties on itself. Is there a way we could design this feature, or a related feature, to cover that kind of use case? That is, to allow a limited set of keys—perhaps even key-path-based when you want static control—with a different type for each key, *or* to allow any key with some common type, depending on your type's needs?
Per my question about whether native methods shadow dynamic ones, one might be able to achieve some of this using a mix of statically typed, statically declared methods + dynamic members.
>
> * Actually, for that matter, let's talk about key paths. In principle, you can already think of member lookup in Swift—or at least property and subscript lookup—as though it always worked by constructing a key path and using `subscript(keyPath:)` to access it. Is there some way we could model this feature as extending the set of keys available on a given type—perhaps in a way that allowed compile-time-limited and strongly-typed sets of keys, like I mention with the `UIAppearance` example, in addition to the open-ended, type-erased sets you need—and then looking things up by key path? (Sorry if this is a little vague—I know very little about how key paths are implemented.)
>
> * An implementation-level question about Swift: Internally, the compiler seems to be moving towards thinking of parameter labels as part of the identifier, rather than having them label the individual arguments. How do you see that jibing with what you're proposing here?
>
> --
> Brent Royal-Gordon
> Architechies
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org <mailto:swift-evolution at swift.org>
> https://lists.swift.org/mailman/listinfo/swift-evolution
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20171116/4a8f6822/attachment.html>
More information about the swift-evolution
mailing list