Does Swift support reflection? - ios

Does Swift support reflection? e.g. is there something like valueForKeyPath: and setValue:forKeyPath: for Swift objects?
Actually does it even have a dynamic type system, something like obj.class in Objective-C?

Looks like there's the start of some reflection support:
class Fruit {
var name="Apple"
}
reflect(Fruit()).count // 1
reflect(Fruit())[0].0 // "name"
reflect(Fruit())[0].1.summary // "Apple"
From mchambers gist, here:
https://gist.github.com/mchambers/fb9da554898dae3e54f2

If a class extends NSObject, then all of Objective-C's introspection and dynamism works. This includes:
The ability to ask a class about its methods and properties, and to invoke methods or set properties.
The ability to exchange method implementations. (add functionality to all instances).
The ability to generate and assign a new sub-class on the fly. (add functionality to a given instance)
One shortcoming of this functionality is support for Swift optional value types. For example Int properties can be enumerated and modified but Int? properties cannot. Optional types can be enumerated partially using reflect/MirrorType, but still not modified.
If a class does not extend NSObject, then only the new, very limited (and in progress?) reflection works (see reflect/MirrorType), which adds limited ability to ask a instance about its class and properties, but none of the additional features above.
When not extending NSObject, or using the '#objc' directive, Swift defaults to static- and vtable-based dispatch. This is faster, however, in the absence of a virtual machine does not allow runtime method interception. This interception is a fundamental part of Cocoa and is required for the following types of features:
Cocoa's elegant property observers. (Property observers are baked right in to the Swift language).
Non-invasively applying cross-cutting concerns like logging, transaction management (i.e Aspect Oriented Programming).
Proxies, message forwarding, etc.
Therefore its recommended that clases in Cocoa/CocoaTouch applications implemented with Swift:
Extend from NSObject. The new class dialog in Xcode steers in this direction.
Where the overhead of of a dynamic dispatch leads to performance issues, then static dispatch can be used - in tight loops with calls to methods with very small bodies, for example.
Summary:
Swift can behave like C++, with fast static/vtable dispatch and limited reflection. This makes it suitable for lower level or performance intensive applications, but without the complexity, learning curve or risk of error associated with C++
While Swift is a compiled language, the messaging style of method invocation adds the introspection and dynamism found in modern languages like Ruby and Python, just like Objective-C, but without Objective-C's legacy syntax.
Reference data: Execution overhead for method invocations:
static : < 1.1ns
vtable : ~ 1.1ns
dynamic : ~4.9ns
(actual performance depends on hardware, but the ratios will remain similar).
Also, the dynamic attribute allows us to explicitly instruct Swift that a method should use dynamic dispatch, and will therefore support interception.
public dynamic func foobar() -> AnyObject {
}

The documentation speaks about a dynamic type system, mainly about
Type and dynamicType
See Metatype Type (in Language Reference)
Example:
var clazz = TestObject.self
var instance: TestObject = clazz()
var type = instance.dynamicType
println("Type: \(type)") //Unfortunately this prints only "Type: Metatype"
Now assuming TestObject extends NSObject
var clazz: NSObject.Type = TestObject.self
var instance : NSObject = clazz()
if let testObject = instance as? TestObject {
println("yes!") //prints "yes!"
}
Currently, there is no reflection implemented.
EDIT: I was apparently wrong, see stevex's answer. There is some simple readonly reflection for properties build in, probably to allow IDEs to inspect object contents.

No reflect keyword in Swift 5, now you can use
struct Person {
var name="name"
var age = 15
}
var me = Person()
var mirror = Mirror(reflecting: me)
for case let (label?, value) in mirror.children {
print (label, value)
}

It seems that a Swift reflection API is not a high priority for Apple at the moment. But besides #stevex answer there is another function in the standard library that helps.
As of beta 6 _stdlib_getTypeName gets the mangled type name of a variable. Paste this into an empty playground:
import Foundation
class PureSwiftClass {
}
var myvar0 = NSString() // Objective-C class
var myvar1 = PureSwiftClass()
var myvar2 = 42
var myvar3 = "Hans"
println( "TypeName0 = \(_stdlib_getTypeName(myvar0))")
println( "TypeName1 = \(_stdlib_getTypeName(myvar1))")
println( "TypeName2 = \(_stdlib_getTypeName(myvar2))")
println( "TypeName3 = \(_stdlib_getTypeName(myvar3))")
The output is:
TypeName0 = NSString
TypeName1 = _TtC13__lldb_expr_014PureSwiftClass
TypeName2 = _TtSi
TypeName3 = _TtSS
Ewan Swick's blog entry helps to decipher these strings:
e.g. _TtSi stands for Swift's internal Int type.
Mike Ash has a great blog entry covering the same topic.

You might want to consider using toString() instead. It is public and works just the same as _stdlib_getTypeName() with the difference that it also works on AnyClass, e.g. in a Playground enter
class MyClass {}
toString(MyClass.self) // evaluates to "__lldb_expr_49.MyClass"

Related

How to read an array of objectes generated in a Swift framework library, in a KMM (kotlin native) shared module

I'm working on a KMM app. The shared module has a helper class, that relies on different native libraries for the android part and for the iOS part. This is implemented with the already know "expected/actual" pattern.
As said, the iOS actual class makes use of an iOS framework, that performs some calculations, and returns an array of objects. The ios framework that creates the list of objects works correctly (it was tested with unit tests). A simplified example follows below.
This is the class of the objects that are inside of the array:
public class ChildNodeIos: NSObject{
public let content:String
public let isTextNode:Bool
public init(content:String,isTextNode:Bool=false){
self.content=content
self.isTextNode=isTextNode
}
}
The helper class on the iOS side that returns the list of objects would be something like that:
#objc public class IOSCoolHelper: NSObject {
#objc public func getChildNodes(message: String) -> [ChildNodeIos] {
//build the array of child nodes here and return them
}
}
In the kotlin shared module, inside the iOS expected class, the function is called like the following:
#Serializable
data class ChildNodeKN(val content :String,val isTextNode :Boolean=false)
import com.mydomain.iosframeworks.IosCoolHelper
actual class CoolHelper actual constructor(private val someStuff: String) : ICoolHelper {
actual override fun getChildNodes(message: String): List<ChildNodeKN> {
val iosHelper= IOSCoolHelper()
val swiftarray:List<ChildNodeIos> = iosHelper.getChildNodes(message)
//I was expecting to do something like that but it does not work (the content of "array is always empty"):
val kotlinList:List<ChildNodeKN> = swiftarray as List<ChildNodeIos>
return kotlinList
}
}
}
Or maybe if the list of swift objects can not be direct be casted to the equivalent kotlin object list, I was expecting to be able to iterate over the swift list and convert it to the kotlin list, something like that:
val kotlinList=mutableListOf<ChildNodeKN>()
swiftArray.foreach{
kotlinList.add(ChildNodeKN(it.content,it.isTextNode))
}
But again, the content of the swift Array is empty. Doing a lot of tests (I can no reproduce them now), I managed to access something inside the array, but it was not an object of type ChildNodeIos, nor something I could read on the kotlin side.
Well, the question is, how to receive on the kotlin side, a list with more or less complex objects inside, that was generated on the iOS side?
I have to say, that this swift helper class has many other functions that return primitive values (strings, booleans, or int), and that is working very well.
I suppose a workaround would be instead an array with objects, to return an array with primitive types and two dimensions from the Swift side, but I would like to work with an array of objects if it is possible.
Thank you for your help
I managed to find the solution by myself. The problem was the declaration of the Swift class of the object contained in the list. I forgot the #objc declaration for the properties of the class, because if that I was not able to read the objects inside the returned array.
public class ChildNodeIos: NSObject{
#objc public let content:String
#objc public let isTextNode:Bool
public init(content:String,isTextNode:Bool=false){
self.content=content
self.isTextNode=isTextNode
}
}
And then, on the Kotlin side, I did not achieve to cast it directly to a list, but with a foreach loop it is very easy to write the iOS objects in Kotlin objects:

Why do we need NoOp types?

Note: This is not a Swift-only question, it's related in every language with Optional type.
I see some Swift projects doing that: var foo: Foo = NoOpFoo()
AFAIK this basically means "this foo does nothing" and can be also expressed as var foo: Foo? = nil
I'm wondering what can be the reason(s) behind NoOp-instead-of-Optional decision?
I can think of performance first: Optional seems to add a few more lines to assembly output (but I'm not really convinced with that).
The reason could be boilerplate of unwrapping optionals as well: but most of the examples I've seen are types that don't even return values, therefore call sites don't need to unwrap neither.
There could be historical reasons too, for example in Java it's tricky to deal with NullPointerException so NoOps may come handy... but in Swift?
Here is an example from swift-log project:
public struct Logger {
var handler: LogHandler
internal init(_ handler: LogHandler) {
self.handler = handler
}
}
public struct SwiftLogNoOpLogHandler: LogHandler { ... }
Logger is designed to work with a LogHandler; to my understanding if you pass NoOpHandler to your Logger then you should probably turn your yourLogger: Logger into myLogger: Logger? = nil
Real-world use cases and/or your personal experiences would be much appreciated!
It is the "Null object pattern", https://en.wikipedia.org/wiki/Null_object_pattern

What is #dynamicCallable in Swift?

From Apple's documentation:
The #dynamicCallable attribute lets you call named types like you call
functions using a simple syntactic sugar. The primary use case is
dynamic language interoperability.
Why would you want to use an #dynamicCallable instead of direct approch?
#dynamicCallable is a new feature of Swift 5. From Paul Hudson's article on "How to use #dynamicCallable in Swift" (emphasis mine):
SE-0216 adds a new #dynamicCallable attribute to Swift, which
brings with it the ability to mark a type as being directly callable.
It’s syntactic sugar rather than any sort of compiler magic,
effectively transforming this code:
let result = random(numberOfZeroes: 3)
Into this:
let result = random.dynamicallyCall(withKeywordArguments: ["numberOfZeroes": 3])
[...] #dynamicCallable is the natural extension of
#dynamicMemberLookup [SE-0195], and serves the same purpose: to
make it easier for Swift code to work alongside dynamic languages such
as Python and JavaScript. [...] #dynamicCallable is really flexible about which data
types its methods accept and return, allowing you to benefit from all
of Swift’s type safety while still having some wriggle room for
advanced usage.
Introduce user-defined dynamically "callable" types
Proposal: SE-0216
Authors: Chris Lattner, Dan Zheng
Review Manager: John McCall
Implementation: apple/swift#20305
Decision Notes: Rationale
Status: Implemented (Swift 5)
Introduction
This proposal is a follow-up to SE-0195 - Introduce User-defined "Dynamic Member
Lookup" Types,
which shipped in Swift 4.2. It introduces a new #dynamicCallable attribute, which marks
a type as being "callable" with normal syntax. It is simple syntactic sugar
which allows the user to write:
a = someValue(keyword1: 42, "foo", keyword2: 19)
and have it be rewritten by the compiler as:
a = someValue.dynamicallyCall(withKeywordArguments: [
"keyword1": 42, "": "foo", "keyword2": 19
])
Many other languages have analogous features (e.g. Python "callables", C++ operator(), and
functors in many other languages), but the
primary motivation of this proposal is to allow elegant and natural interoperation with
dynamic languages in Swift.
Swift-evolution threads:
- Pitch: Introduce user-defined dynamically "callable"
types.
- Pitch #2: Introduce user-defined dynamically “callable”
types.
- Current pitch thread: Pitch #3: Introduce user-defined dynamically “callable”
types
Motivation and context
Swift is exceptional at interworking with existing C and Objective-C APIs and
we would like to extend this interoperability to dynamic languages like Python,
JavaScript, Perl, and Ruby. We explored this overall goal in a long design
process wherein the Swift evolution community evaluated multiple different
implementation approaches. The conclusion was that the best approach was to put
most of the complexity into dynamic language specific bindings written as
pure-Swift libraries, but add small hooks in Swift to allow these bindings to
provide a natural experience to their clients.
SE-0195
was the first step in this process, which introduced a binding to naturally
express member lookup rules in dynamic languages.
What does interoperability with Python mean? Let's explain this by looking at
an example. Here's some simple Python code:
class Dog:
def __init__(self, name):
self.name = name
self.tricks = [] # creates a new empty list for each `Dog`
def add_trick(self, trick):
self.tricks.append(trick)
With the SE-0195 #dynamicMemberLookup feature
introduced in Swift 4.2, it is possible to implement a Python interoperability
layer
written in Swift. It interoperates with the Python runtime, and project all
Python values into a single PythonObject type. It allows us to call into the
Dog class like this:
// import DogModule.Dog as Dog
let Dog = Python.import.call(with: "DogModule.Dog")
// dog = Dog("Brianna")
let dog = Dog.call(with: "Brianna")
// dog.add_trick("Roll over")
dog.add_trick.call(with: "Roll over")
// dog2 = Dog("Kaylee").add_trick("snore")
let dog2 = Dog.call(with: "Kaylee").add_trick.call(with: "snore")
This also works with arbitrary other APIs as well. Here is an example working
with the Python pickle API and the builtin Python function open. Note that
we choose to put builtin Python functions like import and open into a
Python namespace to avoid polluting the global namespace, but other designs
are possible:
// import pickle
let pickle = Python.import.call(with: "pickle")
// file = open(filename)
let file = Python.open.call(with: filename)
// blob = file.read()
let blob = file.read.call()
// result = pickle.loads(blob)
let result = pickle.loads.call(with: blob)
This capability works well, but the syntactic burden of having to use
foo.call(with: bar, baz) instead of foo(bar, baz) is significant. Beyond
the syntactic weight, it directly harms code clarity by making code hard to
read and understand, cutting against a core value of Swift.
The proposed #dynamicCallable attribute directly solves this problem.
With it, these examples become more natural and clear, effectively matching the
original Python code in expressiveness:
// import DogModule.Dog as Dog
let Dog = Python.import("DogModule.Dog")
// dog = Dog("Brianna")
let dog = Dog("Brianna")
// dog.add_trick("Roll over")
dog.add_trick("Roll over")
// dog2 = Dog("Kaylee").add_trick("snore")
let dog2 = Dog("Kaylee").add_trick("snore")
Python builtins:
// import pickle
let pickle = Python.import("pickle")
// file = open(filename)
let file = Python.open(filename)
// blob = file.read()
let blob = file.read()
// result = pickle.loads(blob)
let result = pickle.loads(blob)
This proposal merely introduces a syntactic sugar - it does not add any new
semantic model to Swift. We believe that interoperability with scripting
languages is an important and rising need in the Swift community, particularly
as Swift makes inroads into the server development and machine learning
communities. This feature is also precedented in other languages (e.g. Scala's
Dynamic trait), and
can be used for other purposes besides language interoperability (e.g.
implementing dynamic proxy objects).
Proposed solution
We propose introducing a new #dynamicCallable attribute to the Swift language
which may be applied to structs, classes, enums, and protocols. This follows
the precedent of
SE-0195.
Before this proposal, values of these types are not valid in a call expression:
the only existing callable values in Swift are those with function types
(functions, methods, closures, etc) and metatypes (which are initializer
expressions like String(42)). Thus, it is always an error to "call" an
instance of a nominal type (like a struct, for instance).
With this proposal, types with the #dynamicCallable attribute on their
primary type declaration become "callable". They are required to implement at
least one of the following two methods for handling the call behavior:
func dynamicallyCall(withArguments: <#Arguments#>) -> <#R1#>
// `<#Arguments#>` can be any type that conforms to `ExpressibleByArrayLiteral`.
// `<#Arguments#>.ArrayLiteralElement` and the result type `<#R1#>` can be arbitrary.
func dynamicallyCall(withKeywordArguments: <#KeywordArguments#>) -> <#R2#>
// `<#KeywordArguments#>` can be any type that conforms to `ExpressibleByDictionaryLiteral`.
// `<#KeywordArguments#>.Key` must be a type that conforms to `ExpressibleByStringLiteral`.
// `<#KeywordArguments#>.Value` and the result type `<#R2#>` can be arbitrary.
// Note: in these type signatures, bracketed types like <#Arguments#> and <#KeywordArguments#>
// are not actual types, but rather any actual type that meets the specified conditions.
As stated above, <#Arguments#> and <#KeywordArguments#> can be any types
that conform to the
ExpressibleByArrayLiteral
and
ExpressibleByDictionaryLiteral
protocols, respectively. The latter is inclusive of
KeyValuePairs,
which supports duplicate keys, unlike Dictionary.
Thus, using KeyValuePairs is recommended to support duplicate keywords and
positional arguments (because positional arguments are desugared as keyword
arguments with the empty string "" as the key).
If a type implements the withKeywordArguments: method, it may be dynamically
called with both positional and keyword arguments: positional arguments have
the empty string "" as the key. If a type only implements the
withArguments: method but is called with keyword arguments, a compile-time
error is emitted.
Since dynamic calls are syntactic sugar for direct calls to dynamicallyCall
methods, additional behavior of the dynamicallyCall methods is directly
forwarded. For example, if a dynamicallyCall method is marked with throws
or #discardableResult, then the corresponding sugared dynamic call will
forward that behavior.
Ambiguity resolution: most specific match
Since there are two #dynamicCallable methods, there may be multiple ways to
handle some dynamic calls. What happens if a type specifies both the
withArguments: and withKeywordArguments: methods?
We propose that the type checker resolve this ambiguity towards the tightest
match based on syntactic form of the expression. The exact rules are:
If a #dynamicCallable type implements the withArguments: method and it is
called with no keyword arguments, use the withArguments: method.
In all other cases, attempt to use the withKeywordArguments: method.
This includes the case where a #dynamicCallable type implements the
withKeywordArguments: method and it is called with at least one keyword
argument.
This also includes the case where a #dynamicCallable type implements only
the withKeywordArguments: method (not the withArguments: method) and
it is called with no keyword arguments.
If #dynamicCallable type does not implement the withKeywordArguments:
method but the call site has keyword arguments, an error is emitted.
Here are some toy illustrative examples:
#dynamicCallable
struct Callable {
func dynamicallyCall(withArguments args: [Int]) -> Int { return args.count }
}
let c1 = Callable()
c1() // desugars to `c1.dynamicallyCall(withArguments: [])`
c1(1, 2) // desugars to `c1.dynamicallyCall(withArguments: [1, 2])`
c1(a: 1, 2) // error: `Callable` does not define the 'withKeywordArguments:' method
#dynamicCallable
struct KeywordCallable {
func dynamicallyCall(withKeywordArguments args: KeyValuePairs<String, Int>) -> Int {
return args.count
}
}
let c2 = KeywordCallable()
c2() // desugars to `c2.dynamicallyCall(withKeywordArguments: [:])`
c2(1, 2) // desugars to `c2.dynamicallyCall(withKeywordArguments: ["": 1, "": 2])`
c2(a: 1, 2) // desugars to `c2.dynamicallyCall(withKeywordArguments: ["a": 1, "": 2])`
#dynamicCallable
struct BothCallable {
func dynamicallyCall(withArguments args: [Int]) -> Int { return args.count }
func dynamicallyCall(withKeywordArguments args: KeyValuePairs<String, Int>) -> Int {
return args.count
}
}
let c3 = BothCallable()
c3() // desugars to `c3.dynamicallyCall(withArguments: [])`
c3(1, 2) // desugars to `c3.dynamicallyCall(withArguments: [1, 2])`
c3(a: 1, 2) // desugars to `c3.dynamicallyCall(withKeywordArguments: ["a": 1, "": 2])`
This ambiguity resolution rule works out naturally given the behavior of the
Swift type checker, because it only resolves call expressions when the type
of the base expression is known. At that point, it knows whether the base is a
function type, metatype, or a valid #dynamicCallable type, and it knows the
syntactic form of the call.
This proposal does not require massive or invasive changes to the constraint
solver. Please look at the implementation for more details.
Example usage
Here, we sketch some example bindings to show how this could be used in
practice. Note that there are lots of design decisions that are orthogonal to
this proposal (e.g. how to handle exceptions) that we aren't going into here.
This is just to show how this feature provides an underlying facility that
language bindings authors can use to achieve their desired result. These
examples also show #dynamicMemberLookup to illustrate how they work together,
but elides other implementation details.
JavaScript supports callable objects but does not have keyword arguments.
Here is a sample JavaScript binding:
#dynamicCallable #dynamicMemberLookup
struct JSValue {
// JavaScript doesn't have keyword arguments.
#discardableResult
func dynamicallyCall(withArguments: [JSValue]) -> JSValue { ... }
// This is a `#dynamicMemberLookup` requirement.
subscript(dynamicMember member: JSValue) -> JSValue {...}
// ... other stuff ...
}
On the other hand, a common JavaScript pattern is to take a dictionary of
values as a stand-in for argument labels (called like
example({first: 1, second: 2, third: 3}) in JavaScript). A JavaScript bridge
in Swift could choose to implement keyword argument support to allow this to be
called as example(first: 1, second: 2, third: 3) from Swift code (kudos to
Ben Rimmington for this
observation).
Python does support keyword arguments. While a Python binding could implement
only the withKeywordArguments: method, it is be better to implement both the
non-keyword and keyword forms to make the non-keyword case slightly more
efficient (avoid allocating temporary storage) and to make direct calls with
positional arguments nicer (x.dynamicallyCall(withArguments: 1, 2) instead of
x.dynamicallyCall(withKeywordArguments: ["": 1, "": 2])).
Here is a sample Python binding:
#dynamicCallable #dynamicMemberLookup
struct PythonObject {
// Python supports arbitrary mixes of keyword arguments and non-keyword
// arguments.
#discardableResult
func dynamicallyCall(
withKeywordArguments: KeyValuePairs<String, PythonObject>
) -> PythonObject { ... }
// An implementation of a Python binding could choose to implement this
// method as well, avoiding allocation of a temporary array.
#discardableResult
func dynamicallyCall(withArguments: [PythonObject]) -> PythonObject { ... }
// This is a `#dynamicMemberLookup` requirement.
subscript(dynamicMember member: String) -> PythonObject {...}
// ... other stuff ...
}
Limitations
Following the precedent of SE-0195, this attribute must be placed on the
primary definition of a type, not on an extension.
This proposal does not introduce the ability to provide dynamically callable
static/class members. We don't believe this is important given the goal of
supporting dynamic languages like Python, but it could be explored if a use
case is discovered in the future. Such future work should keep in mind that
call syntax on metatypes is already meaningful, and that ambiguity would have
to be resolved somehow (e.g. through the most specific rule).
This proposal supports direct calls of values and methods, but subsets out
support for currying methods in Smalltalk family languages. This is just an
implementation limitation given the current state of currying in the Swift
compiler. Support can be added in the future if there is a specific need.
Source compatibility
This is a strictly additive proposal with no source breaking changes.
Effect on ABI stability
This is a strictly additive proposal with no ABI breaking changes.
Effect on API resilience
This has no impact on API resilience which is not already captured by other
language features.
Future directions
Dynamic member calling (for Smalltalk family languages)
In addition to supporting languages like Python and JavaScript, we would also
like to grow to support Smalltalk derived languages like Ruby and Squeak. These
languages resolve method calls using both the base name as well as the
keyword arguments at the same time. For example, consider this Ruby code:
time = Time.zone.parse(user_time)
The Time.zone reference is a member lookup, but zone.parse(user_time) is a
method call, and needs to be handled differently than a lookup of zone.parse
followed by a direct function call.
This can be handled by adding a new #dynamicMemberCallable attribute, which
acts similarly to #dynamicCallable but enables dynamic member calls (instead
of dynamic calls of self).
#dynamicMemberCallable would have the following requirements:
func dynamicallyCallMethod(named: S1, withArguments: [T5]) -> T6
func dynamicallyCallMethod(named: S2, withKeywordArguments: [S3 : T7]) -> T8
Here is a sample Ruby binding:
#dynamicMemberCallable #dynamicMemberLookup
struct RubyObject {
#discardableResult
func dynamicallyCallMethod(
named: String, withKeywordArguments: KeyValuePairs<String, RubyObject>
) -> RubyObject { ... }
// This is a `#dynamicMemberLookup` requirement.
subscript(dynamicMember member: String) -> RubyObject {...}
// ... other stuff ...
}
General callable behavior
This proposal is mainly directed at dynamic language interoperability. For this
use case, it makes sense for the dynamicallyCall method to take a
variable-sized list of arguments where each argument has the same type.
However, it may be useful to support general callable behavior (akin to
operator() in C++) where the desugared "callable" method can have a fixed
number of arguments and arguments of different types.
For example, consider something like:
struct BinaryFunction<T1, T2, U> {
func call(_ argument1: T1, _ argument1: T2) -> U { ... }
}
It is not unreasonable to look ahead to a day where sugaring such things is
supported, particularly when/if Swift gets variadic
generics.
This could allow typesafe n-ary smart function pointer types.
We feel that the approach outlined in this proposal supports this direction.
When/if a motivating use case for general callable behavior comes up, we can
simply add a new form to represent it and enhance the type checker to prefer
that during ambiguity resolution. If this is a likely direction, then it may be
better to name the attribute #callable instead of #dynamicCallable in
anticipation of that future growth.
We believe that general callable behavior and #dynamicCallable are orthogonal
features and should be evaluated separately.
Alternatives considered
Many alternatives were considered and discussed. Most of them are captured in
the "Alternatives Considered" section of
SE-0195.
Here are a few points raised in the discussion:
It was suggested that we use subscripts to represent the call
implementations instead of a function call, aligning with
#dynamicMemberLookup. We think that functions are a better fit here: the
reason #dynamicMemberLookup uses subscripts is to allow the members to be
l-values, but call results are not l-values.
It was requested that we design and implement the 'static callable' version
of this proposal in conjunction with the dynamic version proposed here. In
the author's opinion, it is important to consider static callable support as
a likely future direction to make sure that the two features sit well next
to each other and have a consistent design (something we believe this
proposal has done) but it doesn't make sense to join the two proposals. So
far, there have been no strong motivating use case presented for the static
callable version, and Swift lacks certain generics features (e.g. variadics)
that would be necessary to make static callables general. We feel that static
callable should stand alone on its own merits.

How to convert C# code that uses Shell COM to F#?

I have the following C# method:
private static bool IsLink(string shortcutFilename)
{
var pathOnly = Path.GetDirectoryName(shortcutFilename);
var filenameOnly = Path.GetFileName(shortcutFilename);
var shell = new Shell32.Shell();
var folder = shell.NameSpace(pathOnly);
var folderItem = folder.ParseName(filenameOnly);
return folderItem != null && folderItem.IsLink;
}
I have tried converting this to F# as:
let private isLink filename =
let pathOnly = Path.GetDirectoryName(filename)
let filenameOnly = Path.GetFileName(filename)
let shell = new Shell32.Shell()
let folder = shell.NameSpace(pathOnly)
let folderItem = folder.ParseName(filenameOnly)
folderItem <> null && folderItem.IsLink
It however reports an error for the let shell = new Shell32.Shell() line, saying that new cannot be used on interface types.
Have I just made a silly syntactic mistake, or is there extra work needed to access COM from F#?
I don't know enough about the F# compiler but your comments makes it obvious enough. The C# and VB.NET compilers have a fair amount of explicit support for COM built-in. Note that your statement uses the new operator on an interface type, Shell32.Shell in the interop library looks like this:
[ComImport]
[Guid("286E6F1B-7113-4355-9562-96B7E9D64C54")]
[CoClass(typeof(ShellClass))]
public interface Shell : IShellDispatch6 {}
IShellDispatch6 is the real interface type, you can also see the IShellDispatch through IShellDispatch5 interfaces. That's versioning across the past 20 years at work, COM interface definitions are immutable since changing them almost always causes an undiagnosable hard crash at runtime.
The [CoClass] attribute is the important one for this story, that's what the C# compiler goes looking for you use new on a [ComImport] interface type. Tells it to create the object by creating an instance of Shell32.ShellClass instance and obtain the Shell interface. What the F# compiler doesn't do.
ShellClass is a fake class, it is auto-generated by the type library importer. COM never exposes concrete classes, it uses a hyper-pure interface-based programming paradigm. Objects are always created by an object factory, CoCreateInstance() is the workhorse for that. Itself a convenience function, the real work is done by the universal IClassFactory interface, hyper-pure style. Every COM coclass implements its CreateInstance() method.
The type library importer makes ShellClass look like this:
[ComImport]
[TypeLibType(TypeLibTypeFlags.FCanCreate)]
[ClassInterface(ClassInterfaceType.None)]
[Guid("13709620-C279-11CE-A49E-444553540000")]
public class ShellClass : IShellDispatch6, Shell {
// Methods
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime), DispId(0x60040000)]
public virtual extern void AddToRecent([In, MarshalAs(UnmanagedType.Struct)] object varFile, [In, Optional, MarshalAs(UnmanagedType.BStr)] string bstrCategory);
// Etc, many more methods...
}
Lots of fire and movement, none of it should ever be used. The only thing that really matters is the [Guid] attribute, that provides the CLSID that CoCreateInstance() needs. It also needs the IID, the [Guid] of the interface, provided by the interface declaration.
So the workaround in F# is to create the Shell32.ShellClass object, just like the C# compiler does implicitly. While technically you can keep the reference in a ShellClass variable, you should strongly favor the interface type instead. The COM way, the pure way, it avoids this kind of problem. Ultimately it is the CLR that gets the job done, it recognizes the [ClassInterface] attribute on the ShellClass class declaration in its new operator implementation. The more explicit way in .NET is to use Type.GetTypeFromCLSID() and Activator.CreateInstance(), handy when you only have the Guid of the coclass.

F# Val without Self Identifier

Just curious why F# has:
member val Foo = ... with get, set
While omitting the self identifier (e.g. this.).
This is still an instance property. Maybe I am the only one confused when using it. But just bothered me enough to query whoever knows how the language was defined.
With this syntax, the property is almost totally auto-implemented -- all you provide is the initialization code, which essentially runs as part of the constructor.
One of the best-practice guard rails F# puts in place is that it does not let you access instance members before the instance is fully initialized. (wow, crazy idea, right?).
So you would have no use for a self-identifier in auto-props, anyways, since the only code you get to write is init code that can't touch instance members.
Per the MSDN docs (emphasis mine):
Automatically implemented properties are part of the initialization of
a type, so they must be included before any other member definitions,
just like let bindings and do bindings in a type definition. Note that
the expression that initializes an automatically implemented property
is only evaluated upon initialization, and not every time the property
is accessed. This behavior is in contrast to the behavior of an
explicitly implemented property. What this effectively means is that
the code to initialize these properties is added to the constructor of
a class.
Btw, if you try to be a smartass and use the class-level self-identifier to get around this, you'll still blow up at runtime:
type A() as this =
member val X =
this.Y + 10
with get, set
member this.Y = 42
let a = A()
System.InvalidOperationException: The initialization of an object or value resulted in an object or value being accessed recursively before it was fully initialized.
at Microsoft.FSharp.Core.LanguagePrimitives.IntrinsicFunctions.FailInit()
at FSI_0013.A.get_Y()
at FSI_0013.A..ctor()
at <StartupCode$FSI_0014>.$FSI_0014.main#()
Edit: Worth noting that in upcoming C# 6, they also now allow auto-props with initializers (more F# features stolen for C#, shocker :-P), and there is a similar restriction that you can't use the self-identifier:
class A
{
// error CS0027: Keyword 'this' is not available in the current context
public int X { get; set; } = this.Y + 10;
public int Y = 42;
public A() { }
}

Resources