[swift-evolution] Proposal: Introduce User-defined "Dynamic Member Lookup" Types

Chris Lattner clattner at nondot.org
Tue Nov 28 22:54:38 CST 2017


> On Nov 28, 2017, at 10:12 AM, Paul Cantrell <cantrell at pobox.com> wrote:
> Chris wrote:
>> Paul wrote:
>>> An “always use parens” bridge to Ruby has bad ergonomics
>>> Zero-arg Ruby methods are a mixture of property-like things that would certainly not use parens in Swift, and function-like things that certainly would:
>>> 
>>>     // Idiomatic Swift:
>>>     post.author.name.reversed()
>>> 
>>>     // Swift bridging to Ruby…
>>> 
>>>     // …if no-args methods •must• use parens:
>>>     post.author().name().reverse()
>>> 
>>>     // …if no-args methods •can’t• use parens:
>>>     post.author.name.reverse
>>> 
>>> If the goal is to make Swift mostly feel like Swift even when bridging to Ruby, then the bridge needs to support both access forms.
>> 
>> Ok, that can certainly be implemented by the two proposals I have in flight.  No obvious problem there.
> 
> 
> Chris, can you elaborate? I think the proposal precludes this; I must be missing something!

There are two proposals in flight: one that allows specifying runtime behavior for “a.b” syntax and one that allows specifying runtime behavior for “a(x)” and “a.b(x)” syntax (“DynamicCallableWithKeywordsToo”, which needs to be renamed obviously).

For your use case, you’d implement both of them.  If someone wrote

	a.b().c

Then you’d look up and call a zero-argument method named “b” on the a object.  However if someone wrote:

	a.b.c

Then you’d do the same thing (in the implementation of the DynamicMemberLookupProtocol).  This approach allows the human writing code at your bridge to use whatever syntax “feels best” to them given the specific API in question that they are using.

You could even have “a.b” syntax fall back to finding Ruby ivars as well, though I don’t know if that is actually a good idea in practice for a Ruby bridge.

> As I read the proposal, the dynamic member subscript for post.author returns either a property value or a DynamicCallable, depending on whether the thing is a property or a method — but post.author and post.author() would both look identical to that subscript implementation, and there’s no distinction on the Ruby side, so the subscript can’t know which one to return.

“post.author" always invokes the DynamicMemberLookupProtocol proposal.
“post.author()” would invoke the “DynamicCallableWithKeywordsToo” hook in the dynamic callable proposal:
https://gist.github.com/lattner/a6257f425f55fe39fd6ac7a2354d693d <https://gist.github.com/lattner/a6257f425f55fe39fd6ac7a2354d693d>

-Chris

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


More information about the swift-evolution mailing list