Coder Social home page Coder Social logo

binding-tools-for-swift's Introduction

Xamarin Binding Tools For Swift

Welcome!

This module is the main repository for Binding Tools for Swift.

This is a set of tools that can consume a compiled Apple Swift library and generates wrappers that allow it to be surfaced as a .NET library.

Quickstart

Check out our quickstart guide to build and run the tool locally.

The packaging of BTFS is still evolving, and we expect to provide a binding project style interface to make this process easier in the future.

Caution ❗

In order to contribute to Binding-Tools-For-Swift, you will need Xcode 12 or Xcode 13!

Binding Tools for Swift is currently in the process of moving to Swift 5.5. At present, the code and tests appear to run correctly with either Swift 5.3 or Swift 5.5, however the new concurrency model (async/await/actor) is not yet supported. Continuous integration is being done with Xcode 12.

Current Status

What Binds?

  • Classes
  • Structs
  • Enums
  • Protocols without associated types
  • Top-level functions and variables
  • Generic classes, structs, and enums
  • Escaping closures
  • Support of @ObjC types
  • Protocol composition types in non-virtual methods
  • Exceptions
  • Extensions

What Doesn’t Bind Yet?

  • Protocols with associated types
  • Bound generic types with closures
  • Non-escaping closures
  • Async function/methods/properties
  • Actors

What Else Can I Expect?

  • An open class in Swift can be subclassed in C# and the subclass can be passed in to Swift. Overridden virtual methods in C# will be called when invoked from Swift.
  • A C# type implementing an interface bound to a Swift protocol can be passed in to Swift. Methods and properties in the C# interface implementation will be called when invoked from Swift.
  • At runtime, the generated code honors the Swift Automatic Reference Counting as well as .NET garbage collection.
  • When writing bindings, the code generator tries hard to generate something. If an API uses a type that’s not supported yet, that API will be flagged and skipped.

Technical Documentation

The docs directory contains a detailed walkthrough of how things work under the hood.

In particular the functional outline is a great place to start exploring.

Feedback

  • Discuss development and design on Gitter

Gitter

License

Copyright (c) .NET Foundation Contributors. All rights reserved. Licensed under the MIT License.

binding-tools-for-swift's People

Contributors

a-churchill avatar cadsit avatar chamons avatar dalexsoto avatar eilon avatar jingliancui avatar kotlarmilos avatar mandel-macaque avatar rolfbjarne avatar stephen-hawley avatar tj-devel709 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

binding-tools-for-swift's Issues

[SoM] some entry points aren't getting demangled correctly

__T021NewClassCompilerTests10aGlobalIntSifau - unsafe mutable addressor
__T0s6UInt16V14ExtensionTestsE9subscriptABSicfm - subscript materialize for set

We don't technically need either of these types for Swift-o-Matic, but we should probably still consume them correctly.

Error (Fatal): Unable to find module contents for module SwiftCAAnimationClosure. (CompilerException)

Test case: SwiftCAAnimationClosure.zip

Repro: unzip & make all TOOL_LIB=/path/to/swift-o-matic

Result:

$ make all
/Users/rolf/Downloads/swift-o-matic/swift-o-matic --verbose --retain-swift-wrappers --swift-bin-path /Users/rolf/Downloads/swift-o-matic/bin/swift/bin --swift-lib-path /Users/rolf/Downloads/swift-o-matic/bin/swift/lib/swift -o output -C SwiftCAAnimationClosure.framework -C /Users/rolf/Downloads/swift-o-matic/lib/SwiftInterop/mac/XamGlue.framework SwiftCAAnimationClosure
Aggregating swift types.
Reflecting on types from module(s): SwiftCAAnimationClosure
- Tool: /Users/rolf/Downloads/swift-o-matic/bin/swift/bin/swift
- Arguments: -xamreflect -target armv7-apple-ios8.0 -sdk /Applications/Xcode92.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS11.2.sdk
 -I /var/folders/3d/m3cj039j7yg55lj4hrmfk9nw0000gn/T/1440535e-4ccb-4713-ab4a-09edfac03770 -L /Users/rolf/Downloads/swift-o-matic/lib/swift-o-matic/../SwiftInterop/iphone/XamGlue.Framework -F /Users/rolf/test/swift-o-matic/CAAnimationClosure -F /Users/rolf/Downloads/swift-o-matic/lib/SwiftInterop/mac -L /Users/rolf/Downloads/swift-o-matic/bin/swift/lib/swift/iphoneos -o /var/folders/3d/m3cj039j7yg55lj4hrmfk9nw0000gn/T/87828693-9007-4859-af63-675aaedb06db/b7973e87-ad60-469e-84be-f04fdfd3027e.xml SwiftCAAnimationClosure
- Working Directory: /var/folders/3d/m3cj039j7yg55lj4hrmfk9nw0000gn/T/87828693-9007-4859-af63-675aaedb06db
Warning: entry __T0So11CAAnimationC05SwiftA7ClosureE10completionySbcSgfg uses an unsupported swift feature, skipping. (NotSupportedException)
Warning: entry __T0So11CAAnimationC05SwiftA7ClosureE10completionySbcSgfm uses an unsupported swift feature, skipping. (NotSupportedException)
Warning: entry __T0So11CAAnimationC05SwiftA7ClosureE10completionySbcSgfs uses an unsupported swift feature, skipping. (NotSupportedException)
Warning: entry __T0So11CAAnimationC05SwiftA7ClosureE5startyycSgfg uses an unsupported swift feature, skipping. (NotSupportedException)
Warning: entry __T0So11CAAnimationC05SwiftA7ClosureE5startyycSgfm uses an unsupported swift feature, skipping. (NotSupportedException)
Warning: entry __T0So11CAAnimationC05SwiftA7ClosureE5startyycSgfs uses an unsupported swift feature, skipping. (NotSupportedException)
Warning: entry __T0So11CAAnimationC05SwiftA7ClosureE8progressy12CoreGraphics7CGFloatVcSgfg uses an unsupported swift feature, skipping. (NotSupportedException)
Warning: entry __T0So11CAAnimationC05SwiftA7ClosureE8progressy12CoreGraphics7CGFloatVcSgfm uses an unsupported swift feature, skipping. (NotSupportedException)
Warning: entry __T0So11CAAnimationC05SwiftA7ClosureE8progressy12CoreGraphics7CGFloatVcSgfs uses an unsupported swift feature, skipping. (NotSupportedException)
Warning: entry __T0So11CAAnimationC05SwiftA7ClosureE9animatingy12CoreGraphics7CGFloatVcSgfg uses an unsupported swift feature, skipping. (NotSupportedException)
Warning: entry __T0So11CAAnimationC05SwiftA7ClosureE9animatingy12CoreGraphics7CGFloatVcSgfm uses an unsupported swift feature, skipping. (NotSupportedException)
Warning: entry __T0So11CAAnimationC05SwiftA7ClosureE9animatingy12CoreGraphics7CGFloatVcSgfs uses an unsupported swift feature, skipping. (NotSupportedException)
Warning: entry __T0So7CALayerC23SwiftCAAnimationClosureE3addySo0C0C_SSSg6forKeyySbcSg14withCompletiontF uses an unsupported swift feature, skipping. (NotSupportedException)
Error (Fatal): Unable to find module contents for module SwiftCAAnimationClosure. (CompilerException)

Source: https://github.com/honghaoz/Swift-CAAnimation-Closure

[SoM] - error: ambiguous reference to member

public class Event <T> {

  public init () {}
}

public extension Event where T == Void {

  func emit () {
  }

  func emit (on target: AnyObject) {
  }

  func emit (on targets: [AnyObject]) {
  }
}


Error (Fatal): SwiftRepro-Event-Extension0.swift:7:5: error: ambiguous reference to member 'emit()'
    this.emit();
    ^~~~
SwiftRepro.Event<()>:2:17: note: found this candidate
    public func emit()
                ^
SwiftRepro.Event<()>:3:17: note: found this candidate
    public func emit(on target: Swift.AnyObject)
                ^
SwiftRepro.Event<()>:4:17: note: found this candidate
    public func emit(on targets: [Swift.AnyObject])
                ^
SwiftRepro-Event-Extension0.swift:11:5: error: ambiguous reference to member 'emit()'
    this.emit(on: on);
    ^~~~
SwiftRepro.Event<()>:2:17: note: found this candidate
    public func emit()
                ^
SwiftRepro.Event<()>:3:17: note: found this candidate
    public func emit(on target: Swift.AnyObject)
                ^
SwiftRepro.Event<()>:4:17: note: found this candidate
    public func emit(on targets: [Swift.AnyObject])
                ^
SwiftRepro-Event-Extension0.swift:15:5: error: ambiguous reference to member 'emit()'
    this.emit(on: on.pointee);
    ^~~~
SwiftRepro.Event<()>:2:17: note: found this candidate
    public func emit()
                ^
SwiftRepro.Event<()>:3:17: note: found this candidate
    public func emit(on target: Swift.AnyObject)
                ^
SwiftRepro.Event<()>:4:17: note: found this candidate
    public func emit(on targets: [Swift.AnyObject])
                ^
 (Exception)
Error (Fatal): Failed to wrap module SwiftRepro. (CompilerException)

enum managed / native size

The managed enum size should, when possible, match the native one. E.g.

using System;
using System.Runtime.InteropServices;
using SwiftRuntimeLibrary;
using SwiftRuntimeLibrary.SwiftMarshal;
namespace XamVersions
{
    [SwiftEnumHasRawValue(typeof(long))]
    [SwiftEnumType("libXamVersions.dylib", "_T011XamVersions8SemanticOMn", 
        "_T011XamVersions8SemanticON", "")]
    public enum Semantic
    {
        Major, 
        Minor, 
        Patch, 
        Same, 
            
            Unknown
        }
}

should be public enum Semantic : long as this will help if that same type is used in C or ObjC intro with other API. If the size don't match then extra, manual code is required (and that often leads to mistakes).

The [Native] attribute (from XI/XM) can also be used when a enum is based on n[u]int (NS[U]Integer) as we have some tooling to spot those cases.

[SoM] Basic tooling update

Align with the best / current practices used by other tools. This includes

Handling Command-Line Options

  • Adopting Mono.Options for command-line parsing;
  • Add support for response files
  • Show help for options, e.g. when asked or when no argument is supplied

Unique error codes

  • Normalized (VS) Error Reporting, e.g. SOM0000 Blah, for IDE consumption and documentation;
  • Template for new errors
  • Document exist errors, i.e. minimally make them actionable

Tools

  • plist-swifty
  • tom-swifty

Let's start with the (much smaller) plist-swifty so the actions are understood with a lower volume of changes.

Errors

The goal is to have error pages like the compiler, e.g. CS0841 and have the IDE detect them and upon action open the corresponding web page.

This requires a file per error code, for the above example, something like https://raw.githubusercontent.com/dotnet/docs/master/docs/csharp/misc/cs0841.md

This is very similar to what XI/XM have today (code here) except that we have all errors in single web page. That has several drawbacks, e.g.

  • updating/merging them across branches
  • not being able to track (from the web site stats) which pages are being accessed (and the time spent on them). IDE telemetry can only answer part of this;
  • have better customer feedback (at least it we'll know the error code from the page if not mentioned);

There's a plan/RFC to fix the above issues inside XI and XM. The point is not to repeat those mistakes since we're starting from scratch here.

[SoM] init cannot convert \ do not match overloads

open class JSONKey<ValueType> {
    
    public init(_ key: String) {
    }
    
    public init(_ key: Int) {
    }
    
    public init(path indexes: Any...) {
    }
}

Error (Fatal): SwiftRepro-JSONKey.swift:14:21: error: argument names for initializer 'init(key:)' do not match those of overridden initializer 'init'
    public override init(key: Int)
                    ^
                         _ 
SwiftRepro-JSONKey.swift:18:21: error: initializer does not override a designated initializer from its superclass
    public override init(path: Array<Any>)
                    ^
SwiftRepro.JSONKey:3:12: note: potential overridden initializer 'init(path:)' here
    public init(path indexes: Any...)
           ^
SwiftRepro-JSONKey.swift:20:20: error: cannot convert value of type 'Array<Any>' to expected argument type 'Int'
        super.init(path);
                   ^~~~
SwiftRepro-JSONKey.swift:31:44: error: missing argument label 'types:' in call
    SwiftRepro_xamVtableCache[TypeCacheKey(ObjectIdentifier(t0))] 
                                           ^
                                           types: 
SwiftRepro-JSONKey.swift:37:51: error: missing argument label 'types:' in call
    return SwiftRepro_xamVtableCache[TypeCacheKey(ObjectIdentifier(t0))];
                                                  ^
                                                  types: 
SwiftRepro-JSONKey.swift:41:12: error: argument labels '(_:)' do not match any available overloads
    return xam_sub_JSONKey(key);
           ^              ~~~~~
SwiftRepro-JSONKey.swift:41:12: note: overloads for 'xam_sub_JSONKey<_>' exist with these partially matching parameter lists: (key: Int), (path: Array<Any>)
    return xam_sub_JSONKey(key);
           ^
 (Exception)

Error (Fatal): SwiftState-_RouteMappingID.swift:5:11: error: use of undeclared type '_RouteMappingID'

Test case: SwiftState.zip

Repro: unzip & make all TOOL_LIB=/path/to/swift-o-matic

Result: https://gist.github.com/rolfbjarne/a470b851bafd2302116a1a967f27c22e

Error (Bad): Object reference not set to an instance of an object (NullReferenceException)
Error (Bad): Object reference not set to an instance of an object (NullReferenceException)
Warning: Unable to find constructor for struct SwiftState.RouteChain..ctor, skipping. (CompilerException)
Warning: Unable to find constructor for struct SwiftState.Route..ctor, skipping. (CompilerException)
Error (Bad): Unable to find protocol definition for Swift.Hashable, which is a parent of SwiftState.StateType. (CompilerException)
Error (Bad): Unable to find protocol definition for Swift.Hashable, which is a parent of SwiftState.EventType. (CompilerException)
Error (Bad): In wrapping function SwiftState.==, unable to find matching top level function. (CompilerException)
Error (Bad): In wrapping function SwiftState.==, unable to find matching top level function. (CompilerException)
Error (Bad): In wrapping function SwiftState.==, unable to find matching top level function. (CompilerException)
Error (Bad): In wrapping function SwiftState.==, unable to find matching top level function. (CompilerException)
Error (Bad): In wrapping function SwiftState.==, unable to find matching top level function. (CompilerException)
Error (Bad): In wrapping function SwiftState.==, unable to find matching top level function. (CompilerException)
Error (Bad): In wrapping function SwiftState.==, unable to find matching top level function. (CompilerException)
Error (Bad): In wrapping function SwiftState.=>, unable to find matching top level function. (CompilerException)
Error (Bad): In wrapping function SwiftState.=>, unable to find matching top level function. (CompilerException)
Error (Bad): In wrapping function SwiftState.=>, unable to find matching top level function. (CompilerException)
Error (Bad): In wrapping function SwiftState.=>, unable to find matching top level function. (CompilerException)
Error (Bad): In wrapping function SwiftState.=>, unable to find matching top level function. (CompilerException)
Error (Bad): In wrapping function SwiftState.=>, unable to find matching top level function. (CompilerException)
Error (Bad): In wrapping function SwiftState.=>, unable to find matching top level function. (CompilerException)
Error (Bad): In wrapping function SwiftState.=>, unable to find matching top level function. (CompilerException)
Error (Bad): In wrapping function SwiftState.=>, unable to find matching top level function. (CompilerException)
Error (Bad): In wrapping function SwiftState.=>, unable to find matching top level function. (CompilerException)
Error (Bad): In wrapping function SwiftState.=>, unable to find matching top level function. (CompilerException)
Error (Bad): In wrapping function SwiftState.=>, unable to find matching top level function. (CompilerException)
Error (Bad): In wrapping function SwiftState.=>, unable to find matching top level function. (CompilerException)
Error (Bad): In wrapping function SwiftState.=>, unable to find matching top level function. (CompilerException)
Error (Bad): In wrapping function SwiftState.=>, unable to find matching top level function. (CompilerException)
Error (Bad): In wrapping function SwiftState.=>, unable to find matching top level function. (CompilerException)
Error (Bad): In wrapping function SwiftState.=>, unable to find matching top level function. (CompilerException)
Error (Bad): In wrapping function SwiftState.<-, unable to find matching top level function. (CompilerException)
Error (Bad): In wrapping function SwiftState.<-, unable to find matching top level function. (CompilerException)
Error (Bad): In wrapping function SwiftState.<-!, unable to find matching top level function. (CompilerException)
Error (Bad): In wrapping function SwiftState.<-!, unable to find matching top level function. (CompilerException)
Error (Fatal): SwiftState-_RouteMappingID.swift:5:11: error: use of undeclared type '_RouteMappingID'
    this: _RouteMappingID)
          ^~~~~~~~~~~~~~~
 (Exception)
Error (Fatal): Failed to wrap module SwiftState. (CompilerException)

Source: https://github.com/ReactKit/SwiftState

[SoM] Promote "module compiled with Swift X cannot be imported in Swift Y" to non-verbose

I spent too long today trying to figure why I was getting this:


Warnings and errors

Error (Fatal): Unable to find module contents for module SwiftIgPay. (CompilerException)```

Only upon adding --verbose did I get the useful part:

<unknown>:0: error: module compiled with Swift 4.2 cannot be imported in Swift 4.0.3: /var/folders/gc/7vct49652r1df_tp36ffvph00000gn/T/99dfae57-abce-4cb8-965f-880b61f48123/SwiftIgPay.swiftmodule

I believe this should be part of the error text on non-verbose, maybe a top level error itself?

[SoM] Reflection fails on assignment style properties

Compiling this code:

public var Answer: Int = 42

and then reflecting with this:

/Users/donblas/Programming/maccore/tools/tom-swifty/SwiftToolchain-v2-10030bbcb0fb2e42a26d43cea70662fb6a019b9a/build/Ninja-DebugAssert/swift-macosx-x86_64/bin/swift -xamreflect -target x86_64-apple-macosx10.9 -sdk /Applications/Xcode92.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk -F /Users/donblas/Programming/maccore/tools/tom-swifty/swiftglue/bin/Debug/mac/FinalProduct -L /Users/donblas/Programming/maccore/tools/tom-swifty/SwiftToolchain-v2-10030bbcb0fb2e42a26d43cea70662fb6a019b9a/build/Ninja-DebugAssert/swift-macosx-x86_64/lib/swift/macosx -o liboutput.xml libXython.dylib 

gives:

<unknown>:0: error: error opening input file 'libXython.dylib' (Undefined error: 0)
0  swift                    0x0000000116aca6bc llvm::sys::PrintStackTrace(llvm::raw_ostream&) + 60
1  swift                    0x0000000116acacb9 PrintStackTraceSignalHandler(void*) + 25
2  swift                    0x0000000116ac6499 llvm::sys::RunSignalHandlers() + 425
3  swift                    0x0000000116acb152 SignalHandler(int) + 354
4  libsystem_platform.dylib 0x00007fff77641f5a _sigtramp + 26
5  libsystem_platform.dylib 000000000000000000 _sigtramp + 2291916992
6  swift                    0x0000000111f41509 swift::ModuleDecl::getTopLevelDecls(llvm::SmallVectorImpl<swift::Decl*>&) const + 25
7  swift                    0x000000010f6dfc27 ReflectionPrinter::reflect() + 87
8  swift                    0x000000010f6df7b7 xamreflect_main(llvm::ArrayRef<char const*>, char const*, void*) + 9655
9  swift                    0x000000010f6bab11 main + 5681
10 libdyld.dylib            0x00007fff77333015 start + 1
11 libdyld.dylib            0x000000000000000d start + 2295123961
Stack dump:

Library:

libXython.dylib.zip

You can also find this soon in a commented out test case in ImportBindingSmokeTest (that you should comment back in when this works).

https://github.com/xamarin/maccore/pull/939

[SoM] error: use of undeclared type 'U2' UnsafeMutablePointer<Optional<U2>>

public extension Dictionary {
    func property<T>(_ name: String) -> T? {
        guard let key = name as? Key, let value = self[key] else { return nil }        
        return value as? T
    }
}
SwiftRepro-Dictionary-Extension0.swift:6:35: error: use of undeclared type 'U2'
    UnsafeMutablePointer<Optional<U2>>, this: inout Dictionary<U0, 

[SoM] SwiftRuntimeLibrary could be made friendlier with some implicit operators

SwiftAnyObject which is used to represent the AnyObject type in swift has a static converter, but it might be nice to have an implicit operator for ISwiftObject.

SwiftImplicitlyUnwrappedOptional<T> could also benefit from this.
In swift, this is used to represent the type T!.

SwiftOptional<T> could also benefit from this from C# Optional<T>.

SwiftString could use benefit to C# string.

Would also be somewhat better with explicit operators.

[SoM] IDE Integration

This includes

  • Nuget / SDK support
  • Configuration / UI
  • Redirecting error codes to web pages

[SoM] Revisit placement of swift standard libraries

Currently, we are assuming that swift standard libraries (libswiftCore.dylib, etc) are going to be put into the executable folder, but this is not what is done by Apple. Apple expects to see the libraries in the Frameworks directory instead.

This leaves us with a little bit of a problem: VS Mac right now won't accept a library in the Native References folder to put it into the Frameworks directory and when put into the Resources folder, it ends up in the executable directory.

We can continue to put them in the executable directory, but that means that there may be multiple copies of the libraries or missing references from frameworks that needs them and are looking for them in the Frameworks folder.

[SoM] Can't handle marshaling of closures which are bound into generic types

This came up as a result of the Runes library issue (721)

Given a function of this variety in swift:

public func safeCall<T, U> (f: Optional<(T)->U>, a: T) -> U? {
    if let fprime = f {
       return f(T)
    }
    return nil
}

We can't bind to it correctly.

Here's the scoop from past Steve for future Steve:
At this point we can marshal nearly every type in swift as is. There is one exception: closures.
We can’t marshal closures because swift calling conventions don’t match the rest of the world. We can match tuples, so we do a cute trick/hack where we make adapters for any closure that looks something like this:

// Given (a, b)->c
// Adapt it into (UnsafeMutablePointer<c>, UnsafeMutablePointer<(a, b)>)->()
​
func adapt<T, U, R> (@escaping f:(T, U) -> R) ->
  (UnsafeMutablePointer<R>, UnsafeMutablePointer<(T, U)>
{
  let fprime = { (retval:UnsafeMutablePointer<R>, args:UnsafeMutablePointer<T, U> in
	  let (a, b) = args.pointee
		retval.pointee = f(a, b)
	}
	return fprime
}

There’s slightly more to it, but that’s the gist of it.
The problem is what happens when a closure type is bound into a generic type that itself is an argument. (edited)
So if I have this:
Untitled
public func foo(args:SwiftOptional<(a)->b> { }
I have a problem. My wrapping code correctly turns it into something like this:
public func foo_wrapper(args:UnsafeMutablePointer<Swift.Optional<(b, a)->()>>) { }
The problem comes when it’s time to call the wrapper. We need to do something like this:

public func foo_wrapper(args:UnsafeMutablePointer<Swift.Optional<(b, a)->())>)
{
  foo(args.pointee) // fails - wrong type
}

And of course it’s the wrong type.
The problem is that there is a difference in treating a closure like a callable entity and as data.
The short is that we can’t treat wrapped closures as data.
A registry of adapted closures might work, but the whole Swift.Optional presents a problem in and of itself because Swift.Optional has specific semantic meaning in the language. Touching the value of one without proper protections will generate syntax errors, and while this could be special cased, it gets even worse when you get presented a type like Foo<Bar<Baz<Swift.Optional<(T)->U>>>>.
Ultimately, I think that the real solution is to be able to call swift methods and closures using the Swift calling conventions directly.
This will represent a number of changes, not the least of which is how pinvokes work as well as MonoNativeFunctionWrapper.

[SoM] Unable to find swiftmodule file for OtherUnit

public protocol TimeUnit {
    
    static var toTimeIntervalRatio: Double { get }
    
}

public struct Interval<Unit : TimeUnit> {
    
    public init(_ value: Double) {
    }
    
    public var timeInterval: Foundation.TimeInterval {
        return 0
    }
    
    public init(timeInterval: Foundation.TimeInterval) {
        let value = timeInterval / Unit.toTimeIntervalRatio
        self.init(value)
    }
    
}

public extension Interval {
    
    func converted<OtherUnit : TimeUnit>(to otherTimeUnit: OtherUnit.Type = OtherUnit.self) -> Interval<OtherUnit> {
        return Interval<OtherUnit>(0)
    }
}
Error (Fatal): Unable to find swiftmodule file for OtherUnit for target x86_64-apple-macosx10.12. (CompilerException)

[SoM] error: missing argument label X in call

open class AEXMLElement {
    public init(name: String) {
    }
    
    open subscript(key: String) -> AEXMLElement {
        return AEXMLElement (name: "")
    }
}
SwiftRepro-AEXMLElement.swift:19:20: error: missing argument label 'name:' in call
        super.init(name);
                   ^
                   name: 
SwiftRepro-AEXMLElement.swift:34:35: error: missing argument label 'ptr:' in call
                return fromIntPtr(xam_sub_AEXMLElement._vtable.func0!(toIntPtr(value: 
                                  ^
                                  ptr: 
 (Exception)
Error (Fatal): Failed to wrap module SwiftRepro. (CompilerException)

[SoM] escaping attribute may only be used in function parameter position

This originally used NSImage instead of NSObject but it fails just the same

import AppKit

public extension Array where Element : NSObject {

  public func gradient(_ transform: ((_ gradient: inout CAGradientLayer) -> CAGradientLayer)? = nil) -> CAGradientLayer {
    var gradient = CAGradientLayer()
    return gradient
  }
}

Error (Fatal): SwiftRepro-Array-Extension0.swift:7:40: error: @escaping attribute may only be used in function parameter position
    transform: UnsafePointer<Optional<@escaping (_: UnsafeMutablePointer<CAGradientLayer>, 
                                      ~^~~~~~~~~
                                      
SwiftRepro-Array-Extension0.swift:7:40: error: @escaping attribute may only be used in function parameter position
    transform: UnsafePointer<Optional<@escaping (_: UnsafeMutablePointer<CAGradientLayer>, 
                                      ~^~~~~~~~~
                                      
SwiftRepro-Array-Extension0.swift:7:40: error: @escaping attribute may only be used in function parameter position
    transform: UnsafePointer<Optional<@escaping (_: UnsafeMutablePointer<CAGradientLayer>, 
                                      ~^~~~~~~~~
                                      
SwiftRepro-Array-Extension0.swift:11:17: error: 'T0' is not a subtype of 'NSObject'
    return this.gradient(transform.pointee);
           ~~~~~^~~~~~~~
 (Exception)

[SoM] expected expression in list of expressions

import Foundation

open class AEXMLElement {
    public init() {
    }
    
        
    open func allDescendants(where predicate: (AEXMLElement) -> Bool) -> [AEXMLElement] {
        return []
    }
    
    open func firstDescendant(where predicate: (AEXMLElement) -> Bool) -> AEXMLElement? {
        return nil
    }
    
    open func hasDescendant(where predicate: (AEXMLElement) -> Bool) -> Bool {
        return false
    }
}


Error (Fatal): SwiftRepro-AEXMLElement.swift:34:17: error: expected expression in list of expressions
                where);
                ^
SwiftRepro-AEXMLElement.swift:62:17: error: expected expression in list of expressions
                where);
                ^
SwiftRepro-AEXMLElement.swift:90:17: error: expected expression in list of expressions
                where);
                ^
SwiftRepro-AEXMLElement.swift:26:26: error: argument names for method 'allDescendants(where0:)' do not match those of overridden method 'allDescendants(where:)'
    public override func allDescendants(where0: (AEXMLElement) 
                         ^
                                        where 
SwiftRepro-AEXMLElement.swift:54:26: error: argument names for method 'firstDescendant(where0:)' do not match those of overridden method 'firstDescendant(where:)'
    public override func firstDescendant(where0: (AEXMLElement) 
                         ^
                                         where 
SwiftRepro-AEXMLElement.swift:82:26: error: argument names for method 'hasDescendant(where0:)' do not match those of overridden method 'hasDescendant(where:)'
    public override func hasDescendant(where0: (AEXMLElement) 
                         ^
                                       where 
SwiftRepro-AEXMLElement.swift:33:19: error: cannot invoke 'swiftClosureToFunc' with no arguments
            ptr = swiftClosureToFunc(a1: 
                  ^
SwiftRepro-AEXMLElement.swift:33:19: note: overloads for 'swiftClosureToFunc' exist with these partially matching parameter lists: (a1: @escaping () -> TR), (a1: @escaping (T1) -> TR), (a1: @escaping (T1, T2) -> TR), (a1: @escaping (T1, T2, T3) -> TR), (a1: @escaping (T1, T2, T3, T4) -> TR), (a1: @escaping (T1, T2, T3, T4, T5) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7, T8) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7, T8, T9) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16) -> TR)
            ptr = swiftClosureToFunc(a1: 
                  ^
SwiftRepro-AEXMLElement.swift:46:40: error: incorrect argument label in call (have 'where0:', expected 'where:')
            return super.allDescendants(where0: where0);
                                       ^~~~~~~
                                        where
SwiftRepro-AEXMLElement.swift:61:19: error: cannot invoke 'swiftClosureToFunc' with no arguments
            ptr = swiftClosureToFunc(a1: 
                  ^
SwiftRepro-AEXMLElement.swift:61:19: note: overloads for 'swiftClosureToFunc' exist with these partially matching parameter lists: (a1: @escaping () -> TR), (a1: @escaping (T1) -> TR), (a1: @escaping (T1, T2) -> TR), (a1: @escaping (T1, T2, T3) -> TR), (a1: @escaping (T1, T2, T3, T4) -> TR), (a1: @escaping (T1, T2, T3, T4, T5) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7, T8) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7, T8, T9) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16) -> TR)
            ptr = swiftClosureToFunc(a1: 
                  ^
SwiftRepro-AEXMLElement.swift:74:41: error: incorrect argument label in call (have 'where0:', expected 'where:')
            return super.firstDescendant(where0: where0);
                                        ^~~~~~~
                                         where
SwiftRepro-AEXMLElement.swift:89:19: error: cannot invoke 'swiftClosureToFunc' with no arguments
            ptr = swiftClosureToFunc(a1: 
                  ^
SwiftRepro-AEXMLElement.swift:89:19: note: overloads for 'swiftClosureToFunc' exist with these partially matching parameter lists: (a1: @escaping () -> TR), (a1: @escaping (T1) -> TR), (a1: @escaping (T1, T2) -> TR), (a1: @escaping (T1, T2, T3) -> TR), (a1: @escaping (T1, T2, T3, T4) -> TR), (a1: @escaping (T1, T2, T3, T4, T5) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7, T8) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7, T8, T9) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15) -> TR), (a1: @escaping (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16) -> TR)
            ptr = swiftClosureToFunc(a1: 
                  ^
SwiftRepro-AEXMLElement.swift:100:39: error: incorrect argument label in call (have 'where0:', expected 'where:')
            return super.hasDescendant(where0: where0);
                                      ^~~~~~~
                                       where

[SoM] Documentation

This includes

  • Creating a branch in xamarin-docs-pr for the 1st preview
  • Setting up the structure
  • Step-by-step instructions on a happy (to be defined) project
  • Documenting limitations / known issues
  • Documenting error codes

[SoM] Unicode mapping should be more flexible

SoM has built-in unicode mapping in UnicodeMapper.cs.

This needs some refactoring.
First, the static definition should be moved to an external file
Second, the mapping is current char -> String. The .NET char holds one UTF16 code point, ideally the mapping should allow UTF32 code points rather than UTF16 since swift allows > 16 bit code points. See the definition of a swift identifier here.
Finally, there should be a command line option to allow user-selectable mappings from an input file.
Suggest -unicode-mapping:file which should be allowed multiple times and each subsequent one can override previous definitions.

File format? Why not XML.

<?xml version="1.0" encoding="utf-8"?>
    <unicodemapping version="1.0">
        <map from="" to="" />
    </unicodemapping>

Error (Bad): Unable to find interface for protocol Swift.[Comparable|Equatable] (CompilerException)

Source: [email protected]:zenangst/Versions.git

Makefile

SWIFTOMATIC=/Users/poupou/Downloads/swift-o-matic-0

SWIFT_BIN = $(SWIFTOMATIC)/bin/swift/bin
SWIFT_LIB = $(SWIFTOMATIC)/bin/swift/lib/swift/macosx/

SWIFTC = $(SWIFT_BIN)/swiftc
SWIFTARGS = -sdk `xcrun --show-sdk-path` -emit-module -emit-library

TOM_SWIFTY=$(SWIFTOMATIC)/lib/swift-o-matic/tom-swifty.exe
SWIFT_GLUE = $(SWIFTOMATIC)/lib/mac/XamGlue.framework

OUTPUT_MODULE=XamVersions
TOM_SWIFTY_OUTPUT=tsout

all:
	@rm -rf $(TOM_SWIFTY_OUTPUT)
	@mkdir $(TOM_SWIFTY_OUTPUT)
	mono --debug $(TOM_SWIFTY) --retain-swift-wrappers --swift-bin-path $(SWIFT_BIN) -o $(TOM_SWIFTY_OUTPUT) -C . $(OUTPUT_MODULE)

libXamVersions.dylib:
	$(SWIFTC) $(SWIFTARGS) -module-name $(OUTPUT_MODULE) Versions/*.swift

clean:
	@rm -rf tsout
	@rm -rf libXamVersions.dylib

With 2018-04-11 update I get

mono --debug /Users/poupou/Downloads/swift-o-matic-0/lib/swift-o-matic/tom-swifty.exe --retain-swift-wrappers --swift-bin-path /Users/poupou/Downloads/swift-o-matic-0/bin/swift/bin -o tsout -C . XamVersions
Warning: entry __T0SS11XamVersionsE11majorChangeSbSSF uses an unsupported swift feature, skipping. (NotSupportedException)
Warning: entry __T0SS11XamVersionsE11minorChangeSbSSF uses an unsupported swift feature, skipping. (NotSupportedException)
Warning: entry __T0SS11XamVersionsE11patchChangeSbSSF uses an unsupported swift feature, skipping. (NotSupportedException)
Warning: entry __T0SS11XamVersionsE15semanticCompareAA8SemanticOSSF uses an unsupported swift feature, skipping. (NotSupportedException)
Warning: entry __T0SS11XamVersionsE5majorSSfg uses an unsupported swift feature, skipping. (NotSupportedException)
Warning: entry __T0SS11XamVersionsE5minorSSfg uses an unsupported swift feature, skipping. (NotSupportedException)
Warning: entry __T0SS11XamVersionsE5patchSSfg uses an unsupported swift feature, skipping. (NotSupportedException)
Warning: entry __T0SS11XamVersionsE9newerThanSbSSF uses an unsupported swift feature, skipping. (NotSupportedException)
Warning: entry __T0SS11XamVersionsE9olderThanSbSSF uses an unsupported swift feature, skipping. (NotSupportedException)
Warning: entry __T0SS11XamVersionsE9subscriptSSSicfg uses an unsupported swift feature, skipping. (NotSupportedException)
Warning: entry __T0SS11XamVersionsE9subscriptSSs5RangeVySiGcfg uses an unsupported swift feature, skipping. (NotSupportedException)
Warning: entry __T0SS11XamVersionsE9subscripts9CharacterVSicfg uses an unsupported swift feature, skipping. (NotSupportedException)
Error (Bad): Unable to find interface for protocol Swift.Comparable (CompilerException)
Error (Bad): Unable to find interface for protocol Swift.Equatable (CompilerException)
Warning: Unable to find constructor function declaration for struct XamVersions.Version from method __T011XamVersions7VersionVACSgSScfC (CompilerException)

note: I also have this error (once) in CommandCougar

[SoM] missing argument label 'ptr`

import Foundation

open class AEXMLElement {
    public init() {
    }
    
    
    open subscript(key: String) -> AEXMLElement {
            let errorElement = AEXMLElement()
            return errorElement
    }
    }

Error (Fatal): SwiftRepro-AEXMLElement.swift:34:35: error: missing argument label 'ptr:' in call
                return fromIntPtr(xam_sub_AEXMLElement._vtable.func0!(toIntPtr(value: 
                                  ^
                                  ptr: 

[CommandCougar] Several warnings and errors

Error (Bad): Function XamCougar.xam_proxy_FlagIndexable.get_flag has an unknown return type XamCougar.Option.Flag (NotImplementedException)
Error (Bad): Skipping C# wrapping protocol XamCougar.FlagIndexable, due to a previous error. (CompilerException)

and

Error (Bad): In XamCougar.Command..ctor, closure type XamCougar.CommandEvaluation throws -> () throws, which is not supported yet. (CompilerException)
Error (Bad): Skipping C# wrapping struct XamCougar.Command, due to a previous error. (CompilerException)

leads to generated code that cannot be compiled

csc -nostdlib -noconfig -r:/Library/Frameworks/Xamarin.Mac.framework/Versions/Current/lib/mono/Xamarin.Mac//mscorlib.dll -r:/Library/Frameworks/Xamarin.Mac.framework/Versions/Current/lib/mono/Xamarin.Mac//System.dll -r:"/Users/poupou/Dropbox (Personal)/Xamarin.Mac.dll" -unsafe -lib:/Users/poupou/Downloads/swift-o-matic/lib/SwiftInterop/ -r:SwiftRuntimeLibrary.Mac.dll -lib:. tsout/*.cs -t:library -out:XamCougar.dll
Microsoft (R) Visual C# Compiler version 2.6.0.62309 (d3f6b8e7)
Copyright (C) Microsoft Corporation. All rights reserved.

tsout/OptionEvaluationXamCougar.cs(13,51): error CS0246: The type or namespace name 'IFlagIndexable' could not be found (are you missing a using directive or an assembly reference?)
tsout/OptionEvaluationXamCougar.cs(14,9): error CS0246: The type or namespace name 'ICustomStringConvertible' could not be found (are you missing a using directive or an assembly reference?)
tsout/OptionEvaluationXamCougar.cs(11,37): error CS0246: The type or namespace name 'IFlagIndexable' could not be found (are you missing a using directive or an assembly reference?)
tsout/OptionXamCougar.cs(13,41): error CS0246: The type or namespace name 'IFlagIndexable' could not be found (are you missing a using directive or an assembly reference?)
tsout/OptionXamCougar.cs(13,57): error CS0246: The type or namespace name 'ICustomStringConvertible' could not be found (are you missing a using directive or an assembly reference?)
tsout/OptionXamCougar.cs(11,37): error CS0246: The type or namespace name 'IFlagIndexable' could not be found (are you missing a using directive or an assembly reference?)
tsout/CommandEvaluationXamCougar.cs(295,10): error CS0246: The type or namespace name 'Command' could not be found (are you missing a using directive or an assembly reference?)
tsout/CommandEvaluationXamCougar.cs(314,30): error CS0246: The type or namespace name 'Command' could not be found (are you missing a using directive or an assembly reference?)
tsout/CommandEvaluationXamCougar.cs(413,16): error CS0246: The type or namespace name 'Command' could not be found (are you missing a using directive or an assembly reference?)
tsout/CommandEvaluationXamCougar.cs(15,35): error CS0246: The type or namespace name 'Command' could not be found (are you missing a using directive or an assembly reference?)
make: *** [all] Error 1

[SoM] Reflector returning exit code zero when error due to required module not being -I/-L'ed

While looking at this issue I came across a bug in the reflector.

If we have two modules, one referencing another, and don't pass the correct flags to the referred to lib in reflection, we get an error but continue on since the exit code is wrong.

/Users/donblas/Programming/maccore/tools/tom-swifty/SwiftToolchain-v2-10030bbcb0fb2e42a26d43cea70662fb6a019b9a/build/Ninja-DebugAssert/swift-macosx-x86_64/bin/swift -xamreflect -target x86_64-apple-macosx10.9 -sdk /Applications/Xcode92.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk -I ~/tmp/swift_reflect/consumer/ -L ~/tmp/swift_reflect/consumer/ -F /Users/donblas/Programming/maccore/tools/tom-swifty/swiftglue/bin/Debug/mac/FinalProduct -L /Users/donblas/Programming/maccore/tools/tom-swifty/SwiftToolchain-v2-10030bbcb0fb2e42a26d43cea70662fb6a019b9a/build/Ninja-DebugAssert/swift-macosx-x86_64/lib/swift/macosx -o liboutput_consumer.xml Consumer

<unknown>:0: error: missing required module 'Lib'
$ echo $?
0

[SoM] trivial enums aren't showing constructors, methods and properties

public enum {
    case good, bad
    public init(isGood: Bool) {
        if isGood {
            self = .good
         }
        else {
            self = .bad
        }
    }
    public func convertToString() -> String {
        if self == .good {
            return "Good"
        }
        else {
            return "Bad"
       }
    }
}

This is tricky in that the distinction between trivial and non-trivial enums has to do with whether or not the have a case with a non-integral payload.
A non-trivial enum is represented by a class that implements ISwiftEnum.
A trivial enum is represented by an enum. We also create a set of extension methods on it.
There are two options here.
The easiest path is to redefine a non-trivial enum as having either a non-trivial enum or having methods. This is not palatable because it adds overhead to all marshaling for that type which should have 0 overhead.
The other path is to put every method into the extension methods. This is possible, but the problem is that every method has to be transformed into a static extension method, which puts them through a completely different code path than either structs or classes or non-trivial enums, which all share the same code paths.

[SoM] Unable to find swiftmodule file for T for target

public extension Dictionary {
    func value<T>(forKey: String, ofType: T.Type) -> T? {
        return nil
    }
}
Error (Fatal): Unable to find swiftmodule file for T for target x86_64-apple-macosx10.12. (CompilerException)
Error (Fatal): Failed to wrap module SwiftRepro. (CompilerException)

[SoM] use of unresolved identifier

import Darwin
import IOKit.pwr_mgt
import Foundation

public struct System {

    public enum LOAD_AVG {
        case short
        case long
    }
    
    public static func loadAverage(_ type: LOAD_AVG = .long) -> [Double] {
        return []
    }
}
Error (Fatal): SwiftRepro-System-LOAD_AVG.swift:7:12: error: use of unresolved identifier 'LOAD_AVG'
    return LOAD_AVG.__derived_enum_equals(a, b);
           ^~~~~~~~
Darwin.LOAD_SCALE:1:12: note: did you mean 'LOAD_SCALE'?
public var LOAD_SCALE: Int32 { get }
           ^
Darwin.VM_LOADAVG:1:12: note: did you mean 'VM_LOADAVG'?
public var VM_LOADAVG: Int32 { get } 

From SystemKit.framework

[SoM] enums are not showing constructors

public enum TheForce {
    case do, doNot
    public init(yoda: Bool) {
        self = yoda ? .do : .doNot // there is no try
    }
}

Needs to have factory methods for constructors in the sidecar class (that holds extensions right now).

Also ensure that optional constructors work too:

		[Test]
		public void TestSimpleEnumOptionalCtor ()
		{
			string swiftCode =
				"public enum FirstOptEnumCtor {\n" +
				"    case good, bad\n" +
				"    public init?(fail: Bool) {\n" +
				"        if fail {\n" +
				"            return nil\n" +
				"        }\n" +
				"        self = FirstOptEnumCtor.good\n" +
				"    }\n" +
				"}\n";

			var varDecl = CSVariableDeclaration.VarLine (new CSSimpleType ("SwiftOptional<FirstOptEnumCtor>"), "optVal",
			                                             new CSFunctionCall ("FirstOptEnumCtor.FirstOptEnumCtorOptional", false, CSConstant.Val (true)));
			var printIt = CSFunctionCall.FunctionCallLine ("Console.WriteLine", false, new CSIdentifier ("optVal").Dot (new CSIdentifier ("HasValue")));
			var callingCode = new CodeElementCollection<ICodeElement> () {
				varDecl, printIt
			};
			TestRunning.TestAndExecute (swiftCode, callingCode, "False\n",
			                            "TestSimpleEnumOptionalCtor", "NewClassCompilerTests", "TomTestSimpleEnumOptionalCtor");
		}

[SoM] cannot convert return expression of type 'Harmonizer' (aka '(Pitch) -> PitchSet') to return type '(UnsafeMutablePointer<PitchSet>, UnsafeMutablePointer<(Pitch)>)

public struct Harmony {
    
    public static func create(_ intervals: [Float]) -> Harmonizer {
        return { firstPitch in
            let pitchSet = PitchSet()
            return intervals.reduce(pitchSet) {
                (ps, interval) -> PitchSet in
                return ps
            }
        }
    }
}


public typealias Harmonizer = ((Pitch) -> PitchSet)


public struct Pitch {
    public init() {}
}

public struct PitchSet
{
    public init() {}
}
SwiftRepro-Harmony.swift:9:20: error: cannot convert return expression of type 'Harmonizer' (aka '(Pitch) -> PitchSet') to return type '(UnsafeMutablePointer<PitchSet>, UnsafeMutablePointer<(Pitch)>) -> ()'
    return Harmony.create(intervals.pointee);
           ~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~
 (Exception)
Error (Fatal): Failed to wrap module SwiftRepro. (CompilerException)

Similar to Now https://github.com/xamarin/maccore/issues/995 and may be related

[SoM] Samples makefiles outdated

When doing a make in helloswift you get an error:

../../bin/swift/bin/swiftc -sdk `xcrun --show-sdk-path` -emit-module -emit-library -module-name HelloMod *.swift
../../swift-o-matic --retain-swift-wrappers -o . -C . HelloMod
WARNING: The following extra parameters will be ignored: 'HelloMod'
-module-name option is required.
mcs -nowarn:CS0169 -lib:../lib -r:SwiftRuntimeLibrary.Mac -lib:. *.cs -out:HelloMod.exe
Main.cs(3,7): error CS0246: The type or namespace name `HelloMod' could not be found. Are you missing an assembly reference?
Compilation failed: 1 error(s), 0 warnings
make: *** [libHello.dylib] Error 1

The fix is to update the makefile to: $(SWIFTOMATIC) --retain-swift-wrappers -o . -C . -module-name $(OUTPUT_MODULE)

The lack of -module-name happens for all samples (we need to update all the makefiles).

SOM Version

tom-swifty 0.1.0.10 (swift-epsilon: 0cd4fb873d)

[SoM] generic extension functions not demangling properly

public protocol Truthy {
	func truthy (b: Bool) -> String
}

public class CTruthy : Truthy {
	public init() { }
	public func truthy (b: Bool) -> String { return b ? "truthy" : "falsish"; }
}

extension Bool {
	public func truth<T: Truthy>(a:T) -> String {
		return a.truthy(self)
	}
}

[SoM] Empty protocols give vtable error

public protocol Food {   
}

public class HotDog : Food
{
    public init ()
    {
    }
    
    public func AddOnions () {}
}
System.Exception : /Library/Frameworks/Mono.framework/Versions/Current/bin/mcs -unsafe -define:_MAC_TS_TEST_ -nowarn:CS0169 -out:NameNotImportant.exe  /var/folders/gc/7vct49652r1df_tp36ffvph00000gn/T/c79e5cd5-a007-44e6-9a98-4a422080d18d/BunNewClassCompilerTests.cs /var/folders/gc/7vct49652r1df_tp36ffvph00000gn/T/c79e5cd5-a007-44e6-9a98-4a422080d18d/ExtensionsForSystemDotnint0NewClassCompilerTests.cs /var/folders/gc/7vct49652r1df_tp36ffvph00000gn/T/c79e5cd5-a007-44e6-9a98-4a422080d18d/HotDogNewClassCompilerTests.cs /var/folders/gc/7vct49652r1df_tp36ffvph00000gn/T/c79e5cd5-a007-44e6-9a98-4a422080d18d/IFoodNewClassCompilerTests.cs /var/folders/gc/7vct49652r1df_tp36ffvph00000gn/T/c79e5cd5-a007-44e6-9a98-4a422080d18d/NameNotImportant.cs /var/folders/gc/7vct49652r1df_tp36ffvph00000gn/T/c79e5cd5-a007-44e6-9a98-4a422080d18d/NewClassCompilerTestsEnumExtensions.cs /var/folders/gc/7vct49652r1df_tp36ffvph00000gn/T/c79e5cd5-a007-44e6-9a98-4a422080d18d/NewClassCompilerTestsEnums.cs /var/folders/gc/7vct49652r1df_tp36ffvph00000gn/T/c79e5cd5-a007-44e6-9a98-4a422080d18d/TopLevelEntitiesNewClassCompilerTests.cs -lib:/Users/donblas/Programming/swift-o-matic/maccore/tools/tom-swifty/tests/tom-swifty-test/bin/Debug/../../../../SwiftRuntimeLibrary/bin/Debug -r:SwiftRuntimeLibrary 
/var/folders/gc/7vct49652r1df_tp36ffvph00000gn/T/c79e5cd5-a007-44e6-9a98-4a422080d18d/IFoodNewClassCompilerTests.cs(16,16): error CS0246: The type or namespace name `Food_xam_vtable' could not be found. Are you missing an assembly reference?
Compilation failed: 1 error(s), 0 warnings

[SoM] error: missing argument labels

import Foundation

open class AEXMLElement {
    open var name: String
    open var value: String?
    open var attributes: [String : String]
    
    public init(name: String, value: String? = nil, attributes: [String : String] = [String : String]()) {
        self.name = name
        self.value = value
        self.attributes = attributes
    }
}
Error (Fatal): SwiftRepro-AEXMLElement.swift:20:19: error: missing argument labels 'name:value:attributes:' in call
        super.init(name, value, attributes);
                  ^
                   name: value: attributes: 
 (Exception)

[SoM] packaged samples do not build

Sebastiens-iMac:sampler poupou$ make
../../bin/swift/bin/swiftc -v -sdk `xcrun --sdk macosx --show-sdk-path` -L ../../bin/swift/lib/swift/macosx/ -emit-module -emit-library -module-name Sampler *.swift
Swift version 4.0.3-dev (LLVM 2dedb62a0b, Clang ab7472e733, Swift 1cdd481a93)
Target: x86_64-apple-macosx10.9
/Users/poupou/Downloads/swift-o-matic/bin/swift/bin/swift -frontend -c -primary-file Sampler.swift -target x86_64-apple-macosx10.9 -enable-objc-interop -sdk /Applications/Xcode92.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk -emit-module-doc-path /var/folders/4p/hr7rrbjj2w5d1ky_yrjw1s380000gn/T/Sampler-0b2f5e.swiftdoc -color-diagnostics -parse-as-library -module-name Sampler -emit-module-path /var/folders/4p/hr7rrbjj2w5d1ky_yrjw1s380000gn/T/Sampler-0b2f5e.swiftmodule -o /var/folders/4p/hr7rrbjj2w5d1ky_yrjw1s380000gn/T/Sampler-0b2f5e.o
/Users/poupou/Downloads/swift-o-matic/bin/swift/bin/swift -frontend -emit-module /var/folders/4p/hr7rrbjj2w5d1ky_yrjw1s380000gn/T/Sampler-0b2f5e.swiftmodule -parse-as-library -target x86_64-apple-macosx10.9 -enable-objc-interop -sdk /Applications/Xcode92.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk -emit-module-doc-path Sampler.swiftdoc -color-diagnostics -module-name Sampler -o Sampler.swiftmodule
/usr/bin/ld /var/folders/4p/hr7rrbjj2w5d1ky_yrjw1s380000gn/T/Sampler-0b2f5e.o -dylib -force_load /Applications/Xcode92.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/arc/libarclite_macosx.a -framework CoreFoundation -L ../../bin/swift/lib/swift/macosx/ -syslibroot /Applications/Xcode92.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk -lobjc -lSystem -arch x86_64 -L /Users/poupou/Downloads/swift-o-matic/bin/swift/lib/swift/macosx -rpath /Users/poupou/Downloads/swift-o-matic/bin/swift/lib/swift/macosx -macosx_version_min 10.9.0 -no_objc_category_merging -o libSampler.dylib
../../swift-o-matic --retain-swift-wrappers -o . -C . Sampler 
WARNING: The following extra parameters will be ignored: 'Sampler'
-module-name option is required.
mcs -nowarn:CS0169 -lib:../lib -r:SwiftRuntimeLibrary -lib:. *.cs -unsafe+ -out:Sampler.exe
Main.cs(9,4): error CS0122: `System.Number' is inaccessible due to its protection level
/Library/Frameworks/Mono.framework/Versions/5.14.0/lib/mono/4.5/mscorlib.dll (Location of the symbol related to previous error)
Main.cs(10,29): error CS0841: A local variable `n' cannot be used before it is declared
Main.cs(12,51): error CS0841: A local variable `n' cannot be used before it is declared
Main.cs(18,15): error CS0103: The name `AFinalClass' does not exist in the current context
Main.cs(20,13): error CS0103: The name `AFinalClass' does not exist in the current context
Main.cs(21,4): error CS0103: The name `AFinalClass' does not exist in the current context
Main.cs(23,8): error CS0103: The name `AFinalClass' does not exist in the current context
Main.cs(24,10): error CS0246: The type or namespace name `AFinalClass' could not be found. Are you missing an assembly reference?
Compilation failed: 8 error(s), 0 warnings
make: *** [libSampler.dylib] Error 1

I'm not sure if they should be packaged (but that's another issue) but they should work and be on CI.

RFC - Debug from Packaged Build and removal of SOM_PATH

Right now debugging tom-swifty in the sln does not "do the same thing" as launching it from a package.

I came across it while working on https://github.com/xamarin/maccore/issues/906 and it has bitten me multiple times before. You can not copy paste arbitrary command line arguments into a debug session and expect success.

Today we have a SOM_PATH "hack" I added that kinda does the same thing if you set it right but not really.

This RFC proposes the following:

  • Remove SOM_PATH and demote swift-bin-path and swift-lib-path to private options when we move to Mono.Options. Consumers should never ever need to set them. We can leave them around since I assume they are useful to @stephen-hawley else they go completely as well.
  • Modify our build to output tom-swifty.exe to copy into a "build\dist" folder.
  • Modify the rest of the build to copy components there similar to what make package already does
  • Modify make package to literally just bundle up that folder

This way we can always assume our dependent libraries are in sane relative locations and consumers can stop caring about their locations.

Thoughts?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.