<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<div name="messageBodySection" style="font-size: 14px; font-family: -apple-system, BlinkMacSystemFont, sans-serif;">Object that are functions too, Amazing! I wanted that in Javascript for a while!</div>
<div name="messageReplySection" style="font-size: 14px; font-family: -apple-system, BlinkMacSystemFont, sans-serif;"><br />
On Nov 10, 2017, 1:04 PM -0500, Joe Groff via swift-evolution <swift-evolution@swift.org>, wrote:<br />
<blockquote type="cite" style="margin: 5px 5px; padding-left: 10px; border-left: thin solid #1abc9c;">I don't like the idea of some calls having wildly different semantics from others; it's difficult enough to tell what exactly a call might be doing already. Since we also lack the more obvious static "Callable" protocol idea to give even well-typed call syntax to user-defined types, this also seems like it'd be easily abused for that purpose too.<br />
<br />
I think a much better general solution to the problem of "make dynamic systems interact with type systems" is something like F#'s type providers which lets you write your own importers that look at dynamic information from a database, dynamic language VM, or some other system and generate type information usable by the compiler. Integration at the importer level could let you produce more well-typed Swift declarations by looking at the runtime information you get by importing a Python module.<br />
<br />
-Joe<br />
<br />
<blockquote type="cite" style="margin: 5px 5px; padding-left: 10px; border-left: thin solid #e67e22;">On Nov 10, 2017, at 9:37 AM, Chris Lattner via swift-evolution <swift-evolution@swift.org> wrote:<br />
<br />
Hello all,<br />
<br />
I have a couple of proposals cooking in a quest to make Swift interoperate with dynamically typed languages like Python better. Instead of baking in hard coded support for one language or the other, I’m preferring to add a few small but general purpose capabilities to Swift. This is the first, which allows a Swift type to become “callable”.<br />
<br />
The proposal is here:<br />
https://gist.github.com/lattner/a6257f425f55fe39fd6ac7a2354d693d<br />
<br />
I’ve also attached a snapshot below, but it will drift out of date as the proposal is refined. Feedback and thoughts are appreciated, thanks!<br />
<br />
-Chris<br />
<br />
<br />
<br />
<br />
<br />
Introduce user-defined dynamically "callable" types<br />
<br />
• Proposal: SE-NNNN<br />
• Author: Chris Lattner<br />
• Review Manager: TBD<br />
• Status: Awaiting implementation<br />
Introduction<br />
<br />
This proposal introduces a new DynamicCallable protocol to the standard library. Types that conform to it are "callable" with the function call syntax. It is simple syntactic sugar which allows the user to write:<br />
<br />
a = someValue(keyword1: 42, "foo", keyword2: 19)<br />
and have it be interpreted by the compiler as:<br />
<br />
a = someValue.dynamicCall(arguments<br />
: [<br />
(<br />
"keyword1", 42), ("", "foo"), ("keyword2", 19<br />
)<br />
])<br />
<br />
Other languages have analogous features (e.g. Python "callables"), but the primary motivation of this proposal is to allow elegant and natural interoperation with dynamic languages in Swift.<br />
<br />
Swift-evolution thread: Discussion thread topic for that proposal<br />
<br />
Motivation<br />
<br />
Swift is well known for being exceptional at interworking with existing C and Objective-C APIs, but its support for calling APIs written in scripting langauges like Python, Perl, and Ruby is quite lacking. These languages provide an extremely dynamic programming model where almost everything is discovered at runtime.<br />
<br />
Through the introduction of this proposal, and the related DynamicMemberLookupProtocol proposal, we seek to fix this problem. We believe we can make many common APIs feel very natural to use directly from Swift without all the complexity of implementing something like the Clang importer. For example, consider this Python code:<br />
<br />
class Dog<br />
:<br />
<br />
def __init__(self, name<br />
):<br />
<br />
self.name =<br />
name<br />
<br />
self.tricks = [] # creates a new empty list for each dog<br />
<br />
<br />
<br />
def add_trick(self, trick<br />
):<br />
<br />
self.tricks.append(trick)<br />
we would like to be able to use this from Swift like this (the comments show the corresponding syntax you would use in Python):<br />
<br />
// import DogModule<br />
// import DogModule.Dog as Dog // an alternate<br />
let Dog = Python.import(“DogModule.Dog")<br />
<br />
// dog = Dog("Brianna")<br />
let dog = Dog("Brianna")<br />
<br />
// dog.add_trick("Roll over")<br />
dog.add_trick("Roll over")<br />
<br />
// dog2 = Dog("Kaylee").add_trick("snore")<br />
let dog2 = Dog("Kaylee").add_trick("snore")<br />
Of course, this would also apply to standard Python APIs as well. Here is an example working with the Python pickleAPI and the builtin Python function open:<br />
<br />
// import pickle<br />
let pickle = Python.import("pickle"<br />
)<br />
<br />
<br />
// file = open(filename)<br />
let file = Python.open<br />
(filename)<br />
<br />
<br />
// blob = file.read()<br />
let blob = file.read<br />
()<br />
<br />
<br />
// result = pickle.loads(blob)<br />
let result = pickle.loads(blob)<br />
This can all be expressed today as library functionality written in Swift, but without this proposal, the code required is unnecessarily verbose and gross. Without it (but with the related dynamic member lookup proposal) the code would have a method name (like call) all over the code:<br />
<br />
// import pickle<br />
let pickle = Python.import("pickle") // normal method in Swift, no change.<br />
<br />
<br />
// file = open(filename)<br />
let file = Python.open.call<br />
(filename)<br />
<br />
<br />
// blob = file.read()<br />
let blob = file.read.call<br />
()<br />
<br />
<br />
// result = pickle.loads(blob)<br />
let result = pickle.loads.call<br />
(blob)<br />
<br />
<br />
// dog2 = Dog("Kaylee").add_trick("snore")<br />
let dog2 = Dog.call("Kaylee").add_trick.call("snore")<br />
While this is a syntactic sugar proposal, we believe that this expands Swift to be usable in important new domains. This sort of capability is also highly precedented in other languages, and is a generally useful language feature that could be used for other purposes as well.<br />
<br />
Proposed solution<br />
<br />
We propose introducing this protocol to the standard library:<br />
<br />
protocol DynamicCallable<br />
{<br />
<br />
associatedtype DynamicCallableArgument<br />
<br />
<br />
associatedtype DynamicCallableResult<br />
<br />
<br />
<br />
func dynamicCall(arguments: [(String, DynamicCallableArgument)]) throws -<br />
DynamicCallableResult<br />
}<br />
<br />
It also extends the language such that function call syntax - when applied to a value of DynamicCallable type - is accepted and transformed into a call to the dynamicCall member. The dynamicCall method takes a list of tuples: the first element is the keyword label (or an empty string if absent) and the second value is the formal parameter specified at the call site.<br />
<br />
Before this proposal, the Swift language has two types that participate in call syntax: functions and metatypes (for initialization). Neither of those may conform to protocols at the moment, so this introduces no possible ambiguity into the language.<br />
<br />
It is worth noting that this does not introduce the ability to provide dynamicly callable static/class members. We don't believe that this is important given the goal of supporting dynamic languages like Python, but if there is a usecase discovered in the future, it could be explored as future work. Such future work should keep in mind that call syntax on metatypes is already meaningful, and that ambiguity would have to be resolved somehow.<br />
<br />
Discussion<br />
<br />
While the signature for dynamicCall is highly general we expect the most common use will be clients who are programming against concrete types that implement this proposal. One very nice aspect of this is that, as a result of Swift's existing subtyping mechanics, implementations of this type can choose whether they can actually throw an error or not. For example, consider this silly implementation:<br />
<br />
struct ParameterSummer : DynamicCallable<br />
{<br />
<br />
func dynamicCall(arguments: [(String, Int)]) -> Int<br />
{<br />
<br />
return arguments.reduce(0) { $0+$1<br />
.1 }<br />
}<br />
}<br />
<br />
<br />
let x = ParameterSummer<br />
()<br />
<br />
print(x(1, 7, 12)) // prints 20<br />
Because ParameterSummer's implementation of dynamicCall does not throw, the call site is known not to throw either, so the print doesn't need to be marked with try.<br />
<br />
Example Usage<br />
<br />
A more realistic (and motivating) example comes from a prototype Python interop layer. While the concrete details of this use case are subject to change and not important for this proposal, it is perhaps useful to have a concrete example to see how this comes together.<br />
<br />
That prototype currently has two types which model Python values, one of which handles Python exceptions and one of which does not. Their conformances would look like this, enabling the use cases described in the Motivation section above:<br />
<br />
extension ThrowingPyRef: DynamicCallable<br />
{<br />
<br />
func dynamicCall(arguments: [(String, PythonConvertible)]) throws<br />
<br />
<br />
-<br />
PythonConvertible {<br />
<br />
// Make sure state errors are not around.<br />
assert(PyErr_Occurred() == nil, "Python threw an error but wasn't handled"<br />
)<br />
<br />
<br />
// Count how many keyword arguments are in the list.<br />
let numKeywords = arguments.reduce(0<br />
) {<br />
<br />
$0 + ($1.0.isEmpty ? 0 : 1<br />
)<br />
}<br />
<br />
<br />
let kwdict = numKeywords != 0 ? PyDict_New() : nil<br />
<br />
<br />
<br />
// Non-keyword arguments are passed as a tuple of values.<br />
let argTuple = PyTuple_New(arguments.count-numKeywords)!<br />
<br />
<br />
var nonKeywordIndex = 0<br />
<br />
<br />
for (keyword, argValue) in<br />
arguments {<br />
<br />
if keyword.isEmpty<br />
{<br />
<br />
PyTuple_SetItem(argTuple, nonKeywordIndex, argValue.toPython<br />
())<br />
nonKeywordIndex<br />
+= 1<br />
<br />
}<br />
else<br />
{<br />
<br />
PyDict_SetItem(kwdict!, keyword.toPython(), argValue.toPython<br />
())<br />
}<br />
}<br />
<br />
<br />
// Python calls always return a non-null value when successful. If the<br />
// Python function produces the equivalent of C "void", it returns the None<br />
// value. A null result of PyObjectCall happens when there is an error,<br />
// like 'self' not being a Python callable.<br />
guard let resultPtr = PyObject_Call(state, argTuple, kwdict) else<br />
{<br />
<br />
throw PythonError.invalidCall(self<br />
)<br />
}<br />
<br />
<br />
let result = PyRef(owned<br />
: resultPtr)<br />
<br />
<br />
// Translate a Python exception into a Swift error if one was thrown.<br />
if let exception = PyErr_Occurred<br />
() {<br />
<br />
PyErr_Clear<br />
()<br />
<br />
throw PythonError.exception(PyRef(borrowed<br />
: exception))<br />
}<br />
<br />
<br />
return<br />
result<br />
}<br />
}<br />
<br />
<br />
extension PyRef: DynamicCallable<br />
{<br />
<br />
func dynamicCall(arguments: [(String<br />
, PythonConvertible)])<br />
<br />
-<br />
PythonConvertible {<br />
<br />
// Same as above, but internally aborts instead of throwing Swift<br />
// errors.<br />
}<br />
}<br />
<br />
Source compatibility<br />
<br />
This is a strictly additive proposal with no source breaking changes.<br />
<br />
Effect on ABI stability<br />
<br />
This is a strictly additive proposal with no ABI breaking changes.<br />
<br />
Effect on API resilience<br />
<br />
This has no impact on API resilience which is not already captured by other language features.<br />
<br />
Alternatives considered<br />
<br />
A few alternatives were considered:<br />
<br />
Add ability to reject parameter labels<br />
<br />
The implementation above does not allow an implementation to staticly reject argument labels. If this was important to add, we could add another protocol to model this, along the lines of:<br />
<br />
/// A type conforming just to this protocol would not accept parameter<br />
/// labels in its calls.<br />
protocol DynamicCallable<br />
{<br />
<br />
associatedtype DynamicCallableArgument<br />
<br />
<br />
associatedtype DynamicCallableResult<br />
<br />
<br />
<br />
func dynamicCall(arguments: [DynamicCallableArgument]) throws -<br />
DynamicCallableResult<br />
}<br />
<br />
<br />
/// A type conforming to this protocol does allow optional parameter<br />
/// labels.<br />
protocol DynamicCallableWithKeywordsToo : DynamicCallable<br />
{<br />
<br />
func dynamicCall(arguments: [(String, DynamicCallableArgument)]) throws -<br />
DynamicCallableResult<br />
}<br />
<br />
This would allow a type to implement one or the other based on their capabilities. This proposal is going with a very simple design, but if there is demand for this, the author is happy to switch.<br />
<br />
Staticly checking for exact signatures<br />
<br />
This protocol does not allow a type to specify an exact signature for the callable - a specific number of parameters with specific types. If we went down that route, the best approach would be to introduce a new declaration kind (which would end up being very similar to get-only subscripts) since, in general, a type could want multiple concrete callable signatures, and those signatures should participate in overload resolution.<br />
<br />
While such a feature could be interesting for some use cases, it is almost entirely orthogonal from this proposal: it addresses different use cases and does not solve the needs of this proposal. It does not address our needs because even a variadic callable declaration would not provide access to the keyword argument labels we need.<br />
<br />
Direct language support for Python<br />
<br />
We considered implementing something analogous to the Clang importer for Python, which would add a first class Python specific type(s) to Swift language or standard library. We rejected this option because it would be significantly more invasive in the compiler, would set the precedent for all other dynamic languages to get first class language support, and because that first class support doesn't substantially improve the experience of working with Python over existing Swift with a couple small "generally useful" extensions like this one.<br />
<br />
Naming<br />
<br />
The most fertile ground for bikeshedding is the naming of the protocol and the members. We welcome other ideas and suggestions for naming, but here are some thoughts on obvious options to consider:<br />
<br />
We considered but rejected the name CustomCallable, because the existing Custom* protocols in the standard library (CustomStringConvertible, CustomReflectable, etc) provide a way to override and custom existing builtin abilities of Swift. In contrast, this feature grants a new capability to a type.<br />
<br />
We considered but rejected a name like ExpressibleByCalling to fit with the ExpressibleBy* family of protocols (like ExpressibleByFloatLiteral, ExpressibleByStringLiteral, etc). This name family is specifically used by literal syntax, and calls are not literals. Additionally the type itself is not "expressible by calling" - instead, instances of the type may be called.<br />
<br />
On member and associated type naming, we intentionally gave these long and verbose names so they stay out of the way of user code completion. The members of this protocol are really just compiler interoperability glue. If there was a Swift attribute to disable the members from showing up in code completion, we would use it (such an attribute would also be useful for the LiteralConvertible and other compiler magic protocols).<br />
<br />
<br />
_______________________________________________<br />
swift-evolution mailing list<br />
swift-evolution@swift.org<br />
https://lists.swift.org/mailman/listinfo/swift-evolution<br /></blockquote>
<br />
_______________________________________________<br />
swift-evolution mailing list<br />
swift-evolution@swift.org<br />
https://lists.swift.org/mailman/listinfo/swift-evolution<br /></blockquote>
<div></div>
</div>
</body>
</html>