public void SimpleProtocolProGetSetIndexer ()
		{
			var swiftCode = @"
public protocol Simplest5 {
	associatedtype Item
	subscript (index: Int) -> Item {
		get set
	}
}
public func doSetIt<T:Simplest5> (a: inout T, i: Int, v: T.Item) {
	a[i] = v
}
";
			var altClass = new CSClass (CSVisibility.Public, "Simple5Impl");
			altClass.Inheritance.Add (new CSIdentifier ("ISimplest5<SwiftString>"));

			var fieldName = new CSIdentifier ("v");
			altClass.Fields.Add (CSFieldDeclaration.FieldLine (new CSSimpleType ("SwiftString"), fieldName));
			var getBlock = CSCodeBlock.Create (CSReturn.ReturnLine (fieldName));
			var setBlock = CSCodeBlock.Create (CSAssignment.Assign (fieldName, new CSIdentifier ("value")));

			var parameters = new CSParameterList (new CSParameter (new CSSimpleType ("nint"), new CSIdentifier ("index")));
			var thingIndex = new CSProperty (new CSSimpleType ("SwiftString"), CSMethodKind.None,
				CSVisibility.Public, getBlock, CSVisibility.Public, setBlock, parameters);
			altClass.Properties.Add (thingIndex);

			var ctor = new CSMethod (CSVisibility.Public, CSMethodKind.None, null, altClass.Name, new CSParameterList (), CSCodeBlock.Create ());
			altClass.Methods.Add (ctor);
			var instID = new CSIdentifier ("inst");
			var instDecl = CSVariableDeclaration.VarLine (instID, new CSFunctionCall ("Simple5Impl", true));
			var callSetter = CSFunctionCall.FunctionCallLine ("TopLevelEntities.DoSetIt", false, instID, CSConstant.Val (3), new CSFunctionCall ("SwiftString.FromString", false, CSConstant.Val ("Got here!")));
			var printer = CSFunctionCall.ConsoleWriteLine (new CSIdentifier ($"{instID.Name}[3]"));
			var callingCode = CSCodeBlock.Create (instDecl, callSetter, printer);
			TestRunning.TestAndExecute (swiftCode, callingCode, "Got here!\n", otherClass: altClass, platform: PlatformName.macOS);
		}
Example #2
0
        public void VirtualOpenPropStruct(PlatformName platform)
        {
            string swiftCode =
                $"import Foundation\nopen class AnotherOpenVirtualClass{platform} {{\n\tpublic init () {{ }}\n\topen var OSVersion = OperatingSystemVersion (majorVersion: 1, minorVersion:2, patchVersion: 3)\n}}\n";

            // var cl = new AnotherVirtualClass ();
            // var vers = cl.OSVersion;
            // Console.WriteLine(vers);
            // vers.Major = 5;
            // cl.OSVersion = vers;
            // vers = cl.OSVersion;
            // Console.WriteLine(vers);
            var versID    = new CSIdentifier("vers");
            var clID      = new CSIdentifier("cl");
            var osverExpr = clID.Dot(new CSIdentifier("OSVersion"));
            var clDecl    = CSVariableDeclaration.VarLine(CSSimpleType.Var, clID, new CSFunctionCall($"AnotherOpenVirtualClass{platform}", true));
            var versDecl  = CSVariableDeclaration.VarLine(CSSimpleType.Var, versID, osverExpr);
            var printer   = CSFunctionCall.ConsoleWriteLine(versID);
            var setMajor  = CSAssignment.Assign(versID.Dot(new CSIdentifier("Major")), CSConstant.Val(5));
            var setOSVer  = CSAssignment.Assign(osverExpr, versID);
            var resetVer  = CSAssignment.Assign(versID, osverExpr);

            var callingCode = CSCodeBlock.Create(clDecl, versDecl, printer, setMajor, setOSVer, resetVer, printer);

            TestRunning.TestAndExecute(swiftCode, callingCode, "1.2.3\n5.2.3\n", platform: platform);
        }
        void WrapSubscriptGetSetOnly(string type, string csType, string csVal, string swiftReplacement, string expected)
        {
            string swiftCode =
                TestRunningCodeGenerator.kSwiftFileWriter +
                $"public protocol MontyWSubSGO{type} {{ subscript(i:Int32) -> {type} {{ get set }}\n  }}\n" +
                $"public class TestMontyWSubSGO{type} {{\npublic init() {{ }}\npublic func doIt(m:MontyWSubSGO{type}) {{\nvar x = m\nvar s = \"\", t = \"\"\nprint(x[0], to:&s)\nx[0] = {swiftReplacement}\nprint(x[0], to:&t)\nwriteToFile(s + t, \"WrapSubscriptGetSetOnly{type}\")\n}}\n}}\n";

            CSClass overCS = new CSClass(CSVisibility.Public, $"OverWSubSGO{type}");

            overCS.Inheritance.Add(new CSIdentifier($"IMontyWSubSGO{type}"));
            overCS.Fields.Add(new CSLine(new CSFieldDeclaration(new CSSimpleType(csType), new CSIdentifier("_x"), new CSIdentifier(csVal))));

            CSParameterList overParams = new CSParameterList();

            overParams.Add(new CSParameter(CSSimpleType.Int, "i"));
            CSCodeBlock getBody  = CSCodeBlock.Create(CSReturn.ReturnLine((CSIdentifier)"_x"));
            CSCodeBlock setBody  = CSCodeBlock.Create(CSAssignment.Assign("_x", (CSIdentifier)"value"));
            CSProperty  overProp = new CSProperty(new CSSimpleType(csType), CSMethodKind.None, CSVisibility.Public,
                                                  getBody, CSVisibility.Public, setBody, overParams);

            overCS.Properties.Add(overProp);

            CSLine      decl        = CSVariableDeclaration.VarLine(new CSSimpleType($"OverWSubSGO{type}"), "myOver", new CSFunctionCall($"OverWSubSGO{type}", true));
            CSLine      decl1       = CSVariableDeclaration.VarLine(new CSSimpleType($"TestMontyWSubSGO{type}"), "tester", new CSFunctionCall($"TestMontyWSubSGO{type}", true));
            CSLine      invoker     = CSFunctionCall.FunctionCallLine("tester.DoIt", false, new CSIdentifier("myOver"));
            CSCodeBlock callingCode = CSCodeBlock.Create(decl, decl1, invoker);

            TestRunning.TestAndExecute(swiftCode, callingCode, expected, testName: $"WrapSubscriptGetSetOnly{type}", otherClass: overCS);
        }
Example #4
0
        public void WrapSingleGetSetSubscript3()
        {
            string      swiftCode   = $"public struct FooWSGSub3 {{ public let X:Int\npublic init(i:Int) {{ X = i\n }} }}\n public class MontyWSGSub3 {{ public init() {{}}\n private var _x:FooWSGSub3 = FooWSGSub3(i:42);\npublic subscript(i:Int32) -> FooWSGSub3 {{\nget {{ return _x\n}}\nset {{ _x = newValue\n}} }} }}";
            CSLine      decl        = CSVariableDeclaration.VarLine(new CSSimpleType("MontyWSGSub3"), "monty", new CSFunctionCall("MontyWSGSub3", true));
            CSLine      invoker     = CSFunctionCall.ConsoleWriteLine((CSIdentifier)"monty[0].X");
            CSLine      setter      = CSAssignment.Assign("monty[0]", new CSFunctionCall("FooWSGSub3", true, CSConstant.Val(37L)));
            CSCodeBlock callingCode = CSCodeBlock.Create(decl, invoker, setter, invoker);

            TestRunning.TestAndExecute(swiftCode, callingCode, "42\n37\n");
        }
Example #5
0
        void WrapSingleGetSetSubscript1(string type, string returnVal, string csType, string csReplacement, string expected)
        {
            string      swiftCode   = $"public class MontyWSGSSub1{type} {{ public init() {{}}\n private var _x:{type} = {returnVal}\npublic subscript(i:Int32) -> {type} {{\nget {{ return _x\n}}\nset {{ _x = newValue\n}} }} }}";
            CSLine      decl        = CSVariableDeclaration.VarLine(new CSSimpleType($"MontyWSGSSub1{type}"), "monty", new CSFunctionCall($"MontyWSGSSub1{type}", true));
            CSLine      invoker     = CSFunctionCall.ConsoleWriteLine((CSIdentifier)"monty[0]");
            CSLine      setter      = CSAssignment.Assign("monty[0]", new CSIdentifier(csReplacement));
            CSCodeBlock callingCode = CSCodeBlock.Create(decl, invoker, setter, invoker);

            TestRunning.TestAndExecute(swiftCode, callingCode, expected, testName: $"WrapSingleGetSetSubscript1{type}");
        }
Example #6
0
        void WrapSingleGetSetProperty(string type, string returnVal, string csType, string csReplacement, string expectedOutput)
        {
            string appendage   = type.Replace('.', '_');
            var    swiftCode   = String.Format("public class Monty {{ public init() {{}}\n private var _x:{0} = {1}\npublic var val: {0} {{\nget {{ return _x\n}}\nset {{ _x = newValue\n}} }} }}", type, returnVal);
            var    decl        = CSVariableDeclaration.VarLine(new CSSimpleType("Monty"), "monty", new CSFunctionCall("Monty", true));
            var    invoker     = CSFunctionCall.ConsoleWriteLine(new CSIdentifier("monty.Val"));
            var    setter      = CSAssignment.Assign("monty.Val", new CSIdentifier(csReplacement));
            var    callingCode = CSCodeBlock.Create(decl, invoker, setter, invoker);

            TestRunning.TestAndExecute(swiftCode, callingCode, expectedOutput, testName: $"WrapSingleProperty{appendage}");
        }
        public void TestIdentityPointer(string tag)
        {
            var swiftCode = $"public func identityPointer(p: {tag}) -> {tag} {{\n return p\n }}";

            var ptrID   = new CSIdentifier("ptr");
            var ptrDecl = CSVariableDeclaration.VarLine(CSSimpleType.Var, ptrID,
                                                        new CSCastExpression(new CSSimpleType(tag), new CSFunctionCall("IntPtr", true, CSConstant.Val(0x01020304))));
            var assign      = CSAssignment.Assign(ptrID, new CSFunctionCall("TopLevelEntities.IdentityPointer", false, ptrID));
            var printer     = CSFunctionCall.ConsoleWriteLine(new CSCastExpression(CSSimpleType.IntPtr, ptrID));
            var callingCode = CSCodeBlock.Create(ptrDecl, assign, printer);

            TestRunning.TestAndExecute(swiftCode, callingCode, "16909060\n", testName: "IdentityPointer" + tag);
        }
Example #8
0
        void WrapSingleProperty(string type, string returnVal, string reassignVal, string expected)
        {
            string swiftCode = String.Format("public final class MontyWSP{2} {{ public init() {{ }}\npublic var val:{0} = {1}; }}",
                                             type, returnVal, type);

            CodeElementCollection <ICodeElement> callingCode = new CodeElementCollection <ICodeElement> {
                CSAssignment.Assign("var nothing", CSFunctionCall.Ctor($"MontyWSP{type}")),
                CSFunctionCall.ConsoleWriteLine(CSIdentifier.Create("nothing").Dot((CSIdentifier)"Val")),
                CSAssignment.Assign("nothing.Val", new CSConstant(reassignVal)),
                CSFunctionCall.ConsoleWriteLine(CSIdentifier.Create("nothing").Dot((CSIdentifier)"Val"))
            };

            TestRunning.TestAndExecute(swiftCode, callingCode, expected, testName: $"WrapSingleProperty{type}");
        }
Example #9
0
        public void WrapClassReturningClass()
        {
            string classOne  = "public final class GarbleWCRC { public init() { }\npublic func success() { var s = \"\"\n print(\"success\", to:&s)\nwriteToFile(s, \"WrapClassReturningClass\")\n  } }\n";
            string classTwo  = "public final class MontyWCRC { public init() { }\npublic func doIt() -> GarbleWCRC { return GarbleWCRC(); } }";
            string swiftCode = TestRunningCodeGenerator.kSwiftFileWriter + classOne + classTwo;

            CodeElementCollection <ICodeElement> callingCode = new CodeElementCollection <ICodeElement> ();

            callingCode.Add(CSAssignment.Assign("var monty", new CSFunctionCall("MontyWCRC", true)));
            callingCode.Add(CSAssignment.Assign("var garb", new CSFunctionCall("monty.DoIt", false)));
            callingCode.Add(CSFunctionCall.FunctionCallLine("garb.Success", false));

            TestRunning.TestAndExecute(swiftCode, callingCode, "success\n");
        }
Example #10
0
        public void TestClosureSimpleProp()
        {
            var swiftCode = @"
open class ClosureSimpleProp {
	public init () { }
	open var x: ()->() = { () in }
}
";

            var declID      = new CSIdentifier("cl");
            var decl        = CSVariableDeclaration.VarLine(CSSimpleType.Var, declID, new CSFunctionCall("ClosureSimpleProp", true));
            var setter      = CSAssignment.Assign($"{declID}.X", new CSIdentifier("() => { Console.WriteLine (\"here\"); }"));
            var execIt      = CSFunctionCall.FunctionCallLine($"{declID}.X");
            var callingCode = CSCodeBlock.Create(decl, setter, execIt);

            TestRunning.TestAndExecute(swiftCode, callingCode, "here\n", platform: PlatformName.macOS);
        }
        void MakeHandler(CSClass cl, string name, string propName)
        {
            CSSimpleType evtType = new CSSimpleType(typeof(EventArgs));
            CSProperty   prop    = CSProperty.PublicGetSet(evtType, propName);

            cl.Properties.Add(prop);
            CSParameterList pl = new CSParameterList();

            pl.Add(new CSParameter(CSSimpleType.Object, "sender"));
            pl.Add(new CSParameter(evtType, "args"));
            CSCodeBlock body = new CSCodeBlock();

            body.Add(CSAssignment.Assign(propName, CSAssignmentOperator.Assign, new CSIdentifier("args")));
            CSMethod meth = new CSMethod(CSVisibility.Public, CSMethodKind.None,
                                         CSSimpleType.Void, new CSIdentifier(name), pl, body);

            cl.Methods.Add(meth);
        }
        public void ComputedPropertyTestString()
        {
            string swiftCode   = @"private var _backingField: String = """"

public var DoubleStr: String {
    get {
        return _backingField
    }
    set {
        _backingField = newValue + newValue
    }
}
";
            var    setterCall  = CSAssignment.Assign(new CSIdentifier("TopLevelEntities").Dot(new CSIdentifier("DoubleStr")), new CSFunctionCall("SwiftString.FromString", false, CSConstant.Val("nothing")));
            var    printer     = CSFunctionCall.ConsoleWriteLine(new CSIdentifier("TopLevelEntities").Dot(new CSIdentifier("DoubleStr")));
            var    callingCode = CSCodeBlock.Create(setterCall, printer);

            TestRunning.TestAndExecute(swiftCode, callingCode, "nothingnothing\n");
        }
        public void ComputedPropertyTestInt()
        {
            string swiftCode   = @"public var X: Int = 0

public var DoubleX: Int {
    get {
        return X * 2
    }
    set {
        X = newValue / 2
    }
}
";
            var    setterCall  = CSAssignment.Assign(new CSIdentifier("TopLevelEntities").Dot(new CSIdentifier("DoubleX")), CSConstant.Val(8));
            var    printer     = CSFunctionCall.ConsoleWriteLine(new CSIdentifier("TopLevelEntities").Dot(new CSIdentifier("X")));
            var    callingCode = CSCodeBlock.Create(setterCall, printer);

            TestRunning.TestAndExecute(swiftCode, callingCode, "4\n");
        }
Example #14
0
        public void HashSimpleTest()
        {
            var swiftCode = @"public func hashNoOp () { }";

            var hashId       = new CSIdentifier("hash");
            var bytesId      = new CSIdentifier("bytes");
            var hashInit     = new CSFunctionCall("SwiftHasher", true);
            var hashDecl     = CSVariableDeclaration.VarLine(CSSimpleType.Var, hashId, hashInit);
            var bytesDecl    = CSVariableDeclaration.VarLine(CSSimpleType.Var, bytesId, new CSIdentifier("new byte[] { 0, 1, 2, 3, 4 }"));
            var hashCall     = CSFunctionCall.FunctionCallLine($"{hashId.Name}.Combine", false, bytesId);
            var finalizeCall = new CSFunctionCall($"{hashId}.FinalizeHasher", false);

            var hashValue0Id   = new CSIdentifier("hashValue0");
            var hashValue1Id   = new CSIdentifier("hashValue1");
            var hashValue0Decl = CSVariableDeclaration.VarLine(CSSimpleType.Var, hashValue0Id, finalizeCall);
            var reInitLine     = CSAssignment.Assign(hashId, hashInit);
            var hashValue1Decl = CSVariableDeclaration.VarLine(CSSimpleType.Var, hashValue1Id, finalizeCall);

            var printer = CSFunctionCall.ConsoleWriteLine(hashValue0Id == hashValue1Id);

            var callingCode = CSCodeBlock.Create(hashDecl, bytesDecl, hashCall, hashValue0Decl, reInitLine, hashCall, hashValue1Decl, printer);

            // this mess should generate:
            // var hash = new SwiftHasher ();
            // var bytes = new byte [] { 0, 1, 2, 3, 4 };
            // hash.Combine (bytes);
            // var hashValue0 = hash.Finalize0 ();
            // hash = new SwiftHasher ();
            // hash.Combine (bytes);
            // var hashValue1 = hash.Finalize0 ();
            // Console.WriteLine (hashValue0 == hashValue1);

            // this is essentially asserting that the hashvalue of the same byte array will be the same
            // when rehashed. This condition is invariant within process invocations in swift although
            // it may be different across different process invocations (in other words, Hasher seeds
            // using some process-specific value that may change run to run).


            TestRunning.TestAndExecute(swiftCode, callingCode, "True\n");
        }
        void WrapGenFieldGetSet(string cstype, string val1, string val2, string expected)
        {
            string swiftCode =
                $"public struct BarWGFGS{cstype} {{\npublic var X:Int32 = 0;\npublic init(x:Int32) {{\n X = x;\n}}\n}}\n" +
                $"public struct FooWGFGS{cstype}<T> {{\npublic var x:T\npublic init(a:T) {{\nx = a\n }}\n}}\n";

            CSSimpleType fooType = new CSSimpleType($"FooWGFGS{cstype}", false, cstype);

            CSLine fooDecl = CSVariableDeclaration.VarLine(new CSSimpleType($"FooWGFGS{cstype}", false,
                                                                            new CSSimpleType(cstype)),
                                                           "foo", new CSFunctionCall(fooType.ToString(),
                                                                                     true, new CSIdentifier(val1)));


            CSLine printer = CSFunctionCall.ConsoleWriteLine((CSIdentifier)"foo.X");

            CSLine setter = CSAssignment.Assign("foo.X", CSAssignmentOperator.Assign, new CSIdentifier(val2));

            CSCodeBlock callingCode = CSCodeBlock.Create(fooDecl, printer, setter, printer);

            TestRunning.TestAndExecute(swiftCode, callingCode, expected, testName: $"WrapGenFieldGetSet{cstype}");
        }
        void WrapSinglePropertyGetSetOnly(string type, string csType, string csVal, string swiftReplacement, string expected)
        {
            string swiftCode =
                TestRunningCodeGenerator.kSwiftFileWriter +
                $"public protocol MontyWSPGSO{type} {{ var prop : {type} {{ get set }} \n  }}\n" +
                $"public class TestMontyWSPGSO{type} {{\npublic init() {{ }}\npublic func doIt(m:MontyWSPGSO{type}) {{\nvar x = m\nvar s = \"\", t = \"\"\nprint(x.prop, to:&s)\nx.prop = {swiftReplacement}\nprint(x.prop, to:&t)\nwriteToFile(s + t, \"WrapSinglePropertyGetSetOnly{type}\")\n}}\n}}\n";

            CSClass overCS = new CSClass(CSVisibility.Public, $"OverWSPGSO{type}");

            overCS.Inheritance.Add(new CSIdentifier($"IMontyWSPGSO{type}"));
            CSProperty overProp = new CSProperty(new CSSimpleType(csType), CSMethodKind.None, new CSIdentifier("Prop"),
                                                 CSVisibility.Public, new CSCodeBlock(), CSVisibility.Public, new CSCodeBlock());

            overCS.Properties.Add(overProp);

            CSLine      decl        = CSVariableDeclaration.VarLine(new CSSimpleType($"OverWSPGSO{type}"), "myOver", new CSFunctionCall($"OverWSPGSO{type}", true));
            CSLine      decl1       = CSVariableDeclaration.VarLine(new CSSimpleType($"TestMontyWSPGSO{type}"), "tester", new CSFunctionCall($"TestMontyWSPGSO{type}", true));
            CSLine      initer      = CSAssignment.Assign("myOver.Prop", new CSIdentifier(csVal));
            CSLine      invoker     = CSFunctionCall.FunctionCallLine("tester.DoIt", false, new CSIdentifier("myOver"));
            CSCodeBlock callingCode = CSCodeBlock.Create(decl, decl1, initer, invoker);

            TestRunning.TestAndExecute(swiftCode, callingCode, expected, testName: $"WrapSinglePropertyGetSetOnly{type}", otherClass: overCS, platform: PlatformName.macOS);
        }
        public List <ICodeElement> MarshalFromLambdaReceiverToCSProp(CSProperty prop, CSType thisType, string csProxyName, CSParameterList delegateParams,
                                                                     FunctionDeclaration funcDecl, CSType methodType, bool isObjC)
        {
            bool forProtocol     = csProxyName != null;
            bool needsReturn     = funcDecl.IsGetter;
            bool returnIsGeneric = funcDecl.IsTypeSpecGeneric(funcDecl.ReturnTypeSpec);

            var entity = !returnIsGeneric?typeMapper.GetEntityForTypeSpec(funcDecl.ReturnTypeSpec) : null;

            var entityType = !returnIsGeneric?typeMapper.GetEntityTypeForTypeSpec(funcDecl.ReturnTypeSpec) : EntityType.None;

            bool returnIsStructOrEnum = needsReturn && entity != null && entity.IsStructOrEnum;
            bool returnIsClass        = needsReturn && entity != null && entity.EntityType == EntityType.Class;
            bool returnIsProtocol     = needsReturn && entity != null && entity.EntityType == EntityType.Protocol;
            bool returnIsProtocolList = needsReturn && entityType == EntityType.ProtocolList;
            bool returnIsTuple        = needsReturn && entityType == EntityType.Tuple;
            bool returnIsClosure      = needsReturn && entityType == EntityType.Closure;

            string returnCsProxyName = returnIsProtocol ?
                                       NewClassCompiler.CSProxyNameForProtocol(entity.Type.ToFullyQualifiedName(true), typeMapper) : null;

            if (returnIsProtocol && returnCsProxyName == null)
            {
                throw ErrorHelper.CreateError(ReflectorError.kCompilerReferenceBase + 22, $"Unable to find C# interface for protocol {entity.Type.ToFullyQualifiedName ()}");
            }


            var body = new List <ICodeElement> ();

            if (isObjC)
            {
                use.AddIfNotPresent("ObjCRuntime");
            }
            else
            {
                use.AddIfNotPresent(typeof(SwiftObjectRegistry));
            }


            CSIdentifier csharpCall = null;

            if (forProtocol)
            {
                csharpCall = new CSIdentifier($"SwiftObjectRegistry.Registry.InterfaceForExistentialContainer<{thisType.ToString()}> (self).{prop.Name.Name}");
            }
            else
            {
                var call = isObjC ?
                           $"ObjCRuntime.Runtime.GetNSObject<{thisType.ToString ()}> (self).{prop.Name.Name}" :
                           $"SwiftObjectRegistry.Registry.CSObjectForSwiftObject<{thisType.ToString ()}> (self).{prop.Name.Name}";

                csharpCall = new CSIdentifier(call);
            }

            if (funcDecl.IsGetter)
            {
                if (returnIsClass)
                {
                    if (isObjC)
                    {
                        body.Add(CSReturn.ReturnLine(csharpCall.Dot(new CSIdentifier("Handle"))));
                    }
                    else
                    {
                        body.Add(CSReturn.ReturnLine(csharpCall.Dot(NewClassCompiler.kSwiftObjectGetter)));
                    }
                }
                else if (returnIsStructOrEnum || returnIsTuple || returnIsGeneric)
                {
                    use.AddIfNotPresent(typeof(StructMarshal));
                    string retvalName = MarshalEngine.Uniqueify("retval", identifiersUsed);
                    var    retvalId   = new CSIdentifier(retvalName);
                    body.Add(CSFieldDeclaration.VarLine(methodType, retvalId, csharpCall));
                    if (returnIsGeneric)
                    {
                        body.Add(CSFunctionCall.FunctionCallLine("StructMarshal.Marshaler.ToSwift", false,
                                                                 methodType.Typeof(), retvalId, delegateParams [0].Name));
                    }
                    else
                    {
                        body.Add(CSFunctionCall.FunctionCallLine("StructMarshal.Marshaler.ToSwift", false,
                                                                 retvalId, delegateParams [0].Name));
                    }
                }
                else if (returnIsProtocol)
                {
                    string retvalName = MarshalEngine.Uniqueify("retval", identifiersUsed);
                    identifiersUsed.Add(retvalName);
                    var retvalId = new CSIdentifier(retvalName);
                    body.Add(CSFieldDeclaration.VarLine(methodType, retvalId, csharpCall));
                    var protocolMaker = new CSFunctionCall("SwiftExistentialContainer1", true,
                                                           new CSFunctionCall("SwiftObjectRegistry.Registry.ExistentialContainerForProtocols", false, retvalId, methodType.Typeof()));
                    body.Add(CSReturn.ReturnLine(protocolMaker));
                }
                else if (returnIsProtocolList)
                {
                    var protoTypeOf    = new List <CSBaseExpression> ();
                    var swiftProtoList = funcDecl.ReturnTypeSpec as ProtocolListTypeSpec;
                    foreach (var swiftProto in swiftProtoList.Protocols.Keys)
                    {
                        protoTypeOf.Add(typeMapper.MapType(funcDecl, swiftProto, false).ToCSType(use).Typeof());
                    }
                    var callExprs = new List <CSBaseExpression> ();
                    callExprs.Add(csharpCall);
                    callExprs.AddRange(protoTypeOf);
                    var retvalName = MarshalEngine.Uniqueify("retval", identifiersUsed);
                    identifiersUsed.Add(retvalName);
                    var retvalId = new CSIdentifier(retvalName);
                    body.Add(CSVariableDeclaration.VarLine(methodType, retvalId, new CSFunctionCall("StructMarshal.ThrowIfNotImplementsAll", false, callExprs.ToArray())));
                    var containerExprs = new List <CSBaseExpression> ();
                    containerExprs.Add(retvalId);
                    containerExprs.AddRange(protoTypeOf);

                    var returnContainerName = MarshalEngine.Uniqueify("returnContainer", identifiersUsed);
                    identifiersUsed.Add(returnContainerName);
                    var returnContainerId = new CSIdentifier(returnContainerName);
                    body.Add(CSVariableDeclaration.VarLine(CSSimpleType.Var, returnContainerId, new CSFunctionCall("SwiftObjectRegistry.Registry.ExistentialContainerForProtocols", false, containerExprs.ToArray())));
                    body.Add(CSFunctionCall.FunctionCallLine($"{returnContainerName}.CopyTo", false, new CSUnaryExpression(CSUnaryOperator.Ref, delegateParams [0].Name)));
                }
                else
                {
                    if (returnIsClosure)
                    {
                        body.Add(CSReturn.ReturnLine(MarshalEngine.BuildBlindClosureCall(csharpCall, methodType as CSSimpleType, use)));
                    }
                    else
                    {
                        body.Add(CSReturn.ReturnLine(csharpCall));
                    }
                }
            }
            else
            {
                CSBaseExpression valueExpr      = null;
                bool             valueIsGeneric = funcDecl.IsTypeSpecGeneric(funcDecl.ParameterLists [1] [0].TypeSpec);
                entity = !valueIsGeneric?typeMapper.GetEntityForTypeSpec(funcDecl.ParameterLists [1] [0].TypeSpec) : null;

                entityType = !valueIsGeneric?typeMapper.GetEntityTypeForTypeSpec(funcDecl.ParameterLists [1] [0].TypeSpec) : EntityType.None;

                var isUnusualNewValue = IsUnusualParameter(entity, delegateParams [1]);

                if (entityType == EntityType.Class || (entity != null && entity.IsObjCProtocol))
                {
                    var csParmType = delegateParams [1].CSType as CSSimpleType;
                    if (csParmType == null)
                    {
                        throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 42, "Inconceivable! The class type for a method was a CSSimpleType!");
                    }
                    use.AddIfNotPresent(typeof(SwiftObjectRegistry));
                    var fullClassName = entity.Type.ToFullyQualifiedName(true);
                    var retrievecall  = NewClassCompiler.SafeMarshalClassFromIntPtr(delegateParams [1].Name, csParmType, use, fullClassName, typeMapper, entity.IsObjCProtocol);
                    valueExpr = retrievecall;
                }
                else if (entityType == EntityType.Protocol)
                {
                    use.AddIfNotPresent(typeof(SwiftObjectRegistry));
                    var retrievecall = new CSFunctionCall($"SwiftObjectRegistry.Registry.InterfaceForExistentialContainer<{thisType.ToString ()}> (self).{prop.Name.Name}", false);
                    valueExpr = retrievecall;
                }
                else if (entityType == EntityType.Tuple || (entity != null && entity.IsStructOrEnum && !isUnusualNewValue))
                {
                    var ntb     = typeMapper.MapType(funcDecl, funcDecl.ParameterLists [1] [0].TypeSpec, false);
                    var valType = ntb.ToCSType(use);
                    if (entityType == EntityType.TrivialEnum)
                    {
                        valueExpr = new CSCastExpression(valType, new CSCastExpression(CSSimpleType.Long, delegateParams [1].Name));
                    }
                    else
                    {
                        var marshalCall = new CSFunctionCall("StructMarshal.Marshaler.ToNet", false, delegateParams [1].Name, valType.Typeof());
                        valueExpr = new CSCastExpression(valType, marshalCall);
                    }
                }
                else if (valueIsGeneric)
                {
                    // T someVal = (T)StructMarshal.Marshaler.ToNet(parm, typeof(T));
                    // someVal gets passed in
                    var depthIndex = funcDecl.GetGenericDepthAndIndex(funcDecl.ParameterLists [1] [0].TypeSpec);
                    var genRef     = new CSGenericReferenceType(depthIndex.Item1, depthIndex.Item2);
                    use.AddIfNotPresent(typeof(StructMarshal));
                    string valMarshalName = MarshalEngine.Uniqueify(delegateParams [1].Name + "Temp", identifiersUsed);
                    var    valMarshalId   = new CSIdentifier(valMarshalName);

                    var valDecl = CSVariableDeclaration.VarLine(genRef, valMarshalId,
                                                                new CSCastExpression(genRef, new CSFunctionCall("StructMarshal.Marshaler.ToNet", false,
                                                                                                                delegateParams [1].Name,
                                                                                                                genRef.Typeof())));
                    body.Add(valDecl);
                    valueExpr = valMarshalId;
                }
                else
                {
                    if (entityType == EntityType.Closure)
                    {
                        valueExpr = MarshalEngine.BuildWrappedClosureCall(delegateParams [1].Name, methodType as CSSimpleType);
                    }
                    else
                    {
                        valueExpr = delegateParams [1].Name;
                    }
                }
                body.Add(CSAssignment.Assign(csharpCall, valueExpr));
            }
            return(body);
        }
        public List <ICodeElement> MarshalFromLambdaReceiverToCSFunc(CSType thisType, string csProxyName, CSParameterList delegateParams,
                                                                     FunctionDeclaration funcDecl, CSType methodType, CSParameterList methodParams, string methodName, bool isObjC)
        {
            bool thisIsInterface = csProxyName != null;
            bool isIndexer       = funcDecl.IsSubscript;
            bool needsReturn     = methodType != null && methodType != CSSimpleType.Void;
            bool isSetter        = funcDecl.IsSubscriptSetter;
            bool returnIsGeneric = funcDecl.IsTypeSpecGeneric(funcDecl.ReturnTypeSpec);

            var entity = !returnIsGeneric?typeMapper.GetEntityForTypeSpec(funcDecl.ReturnTypeSpec) : null;

            var returnEntity = entity;
            var entityType   = !returnIsGeneric?typeMapper.GetEntityTypeForTypeSpec(funcDecl.ReturnTypeSpec) : EntityType.None;

            bool returnIsStruct   = needsReturn && entity != null && entity.IsStructOrEnum;
            bool returnIsClass    = needsReturn && entity != null && entity.EntityType == EntityType.Class;
            bool returnIsProtocol = needsReturn && ((entity != null && entity.EntityType == EntityType.Protocol) || entityType == EntityType.ProtocolList);
            bool returnIsTuple    = needsReturn && entityType == EntityType.Tuple;
            bool returnIsClosure  = needsReturn && entityType == EntityType.Closure;

            var callParams                    = new List <CSBaseExpression> ();
            var preMarshalCode                = new List <CSLine> ();
            var postMarshalCode               = new List <CSLine> ();
            CSBaseExpression valueExpr        = null;
            bool             marshalingThrows = false;


            if (isSetter)
            {
                var valueID = delegateParams [1].Name;
                valueExpr = valueID;
                var  swiftNewValue     = funcDecl.ParameterLists [1] [0];
                bool newValueIsGeneric = funcDecl.IsTypeSpecGeneric(funcDecl.PropertyType);
                entity = !newValueIsGeneric?typeMapper.GetEntityForTypeSpec(swiftNewValue.TypeSpec) : null;

                entityType = !newValueIsGeneric?typeMapper.GetEntityTypeForTypeSpec(swiftNewValue.TypeSpec) : EntityType.None;

                var isUnusualNewValue = IsUnusualParameter(entity, delegateParams [1]);

                if (entityType == EntityType.Class || entity.IsObjCProtocol)
                {
                    var csParmType = new CSSimpleType(entity.SharpNamespace + "." + entity.SharpTypeName);
                    if (csParmType == null)
                    {
                        throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 26, "Inconceivable! The class type for a subscript was NOT a CSSimpleType!");
                    }
                    use.AddIfNotPresent(typeof(SwiftObjectRegistry));

                    var fullClassName = entity.Type.ToFullyQualifiedName(true);
                    valueExpr = NewClassCompiler.SafeMarshalClassFromIntPtr(valueID, csParmType, use, fullClassName, typeMapper, entity.IsObjCProtocol);
                }
                else if (entityType == EntityType.Protocol)
                {
                    var csParmType = new CSSimpleType(entity.SharpNamespace + "." + entity.SharpTypeName);
                    if (csParmType == null)
                    {
                        throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 27, "Inconceivable! The protocol type for a subscript was NOT a CSSimpleType!");
                    }
                    use.AddIfNotPresent(typeof(StructMarshal));
                    use.AddIfNotPresent(typeof(SwiftObjectRegistry));
                    valueExpr = new CSFunctionCall($"SwiftObjectRegistry.Registry.InterfaceForExistentialContainer<{csParmType.ToString ()}>", false, valueID);
                }
                else if ((entityType == EntityType.Struct || entityType == EntityType.Enum) && !isUnusualNewValue)
                {
                    var csParmType = new CSSimpleType(entity.SharpNamespace + "." + entity.SharpTypeName);
                    if (csParmType == null)
                    {
                        throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 28, $"Inconceivable! The {entityType} type for a subscript was NOT a CSSimpleType!");
                    }
                    use.AddIfNotPresent(typeof(StructMarshal));
                    string valMarshalName = MarshalEngine.Uniqueify("val", identifiersUsed);
                    var    valMarshalId   = new CSIdentifier(valMarshalName);

                    CSLine valDecl = CSVariableDeclaration.VarLine(csParmType, valMarshalId,
                                                                   new CSCastExpression(csParmType, new CSFunctionCall("StructMarshal.Marshaler.ToNet", false, valueID,
                                                                                                                       csParmType.Typeof())));
                    preMarshalCode.Add(valDecl);
                    valueExpr = valMarshalId;
                }
                else if (entityType == EntityType.Tuple)
                {
                    var csParmType = new CSSimpleType(entity.SharpNamespace + "." + entity.SharpTypeName);
                    if (csParmType == null)
                    {
                        throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 29, "Inconceivable! The tuple type for a subscript was NOT a CSSimpleType!");
                    }
                    use.AddIfNotPresent(typeof(StructMarshal));
                    string valMarshalName = MarshalEngine.Uniqueify("val", identifiersUsed);
                    var    valMarshalId   = new CSIdentifier(valMarshalName);

                    var valDecl = CSVariableDeclaration.VarLine(csParmType, valMarshalId,
                                                                new CSCastExpression(csParmType, new CSFunctionCall("StructMarshal.Marshaler.ToNet", false, valueID,
                                                                                                                    csParmType.Typeof())));
                    preMarshalCode.Add(valDecl);
                    valueExpr = valMarshalId;
                }
                else if (newValueIsGeneric)
                {
                    var depthIndex = funcDecl.GetGenericDepthAndIndex(swiftNewValue.TypeSpec);
                    var genRef     = new CSGenericReferenceType(depthIndex.Item1, depthIndex.Item2);
                    if (genRef == null)
                    {
                        throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 30, "Inconceivable! The generic type for a parameter in a method was NOT a CSGenericReferenceType!");
                    }
                    use.AddIfNotPresent(typeof(StructMarshal));
                    string valMarshalName = MarshalEngine.Uniqueify("valTemp", identifiersUsed);
                    var    valMarshalId   = new CSIdentifier(valMarshalName);

                    var valDecl = CSVariableDeclaration.VarLine(genRef, valMarshalId,
                                                                new CSCastExpression(genRef, new CSFunctionCall("StructMarshal.Marshaler.ToNet", false,
                                                                                                                valueID, genRef.Typeof())));
                    preMarshalCode.Add(valDecl);
                    valueExpr = valMarshalId;
                }
            }

            int j = 0;
            int k = isSetter ? 1 : 0;

            for (int i = (funcDecl.HasThrows || returnIsStruct || returnIsProtocol || isSetter || returnIsGeneric) ? 2 : 1; i < delegateParams.Count; i++, j++, k++)
            {
                var  swiftParm     = funcDecl.ParameterLists [1] [k];
                bool parmIsGeneric = funcDecl.IsTypeSpecGeneric(swiftParm);
                entity = !parmIsGeneric?typeMapper.GetEntityForTypeSpec(swiftParm.TypeSpec) : null;

                entityType = !parmIsGeneric?typeMapper.GetEntityTypeForTypeSpec(swiftParm.TypeSpec) : EntityType.None;

                var isUnusualParameter = IsUnusualParameter(entity, delegateParams [i]);
                var csParm             = methodParams [j];

                if (entityType == EntityType.Class || (entity != null && entity.IsObjCProtocol))
                {
                    var csParmType = csParm.CSType as CSSimpleType;
                    if (csParmType == null)
                    {
                        throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 31, "Inconceivable! The class type for a method was NOT a CSSimpleType!");
                    }
                    use.AddIfNotPresent(typeof(SwiftObjectRegistry));

                    var fullClassName = entity.Type.ToFullyQualifiedName(true);
                    var retrievecall  = NewClassCompiler.SafeMarshalClassFromIntPtr(delegateParams [0].Name, csParmType, use, fullClassName, typeMapper, entity.IsObjCProtocol);
                    if (csParm.ParameterKind == CSParameterKind.Out || csParm.ParameterKind == CSParameterKind.Ref)
                    {
                        string id = MarshalEngine.Uniqueify(delegateParams [i].Name.Name, identifiersUsed);
                        identifiersUsed.Add(id);
                        preMarshalCode.Add(CSFieldDeclaration.FieldLine(csParmType, id, retrievecall));
                        callParams.Add(new CSIdentifier(String.Format("{0} {1}",
                                                                      csParm.ParameterKind == CSParameterKind.Out ? "out" : "ref", id)));
                        postMarshalCode.Add(CSAssignment.Assign(delegateParams [i].Name,
                                                                NewClassCompiler.SafeBackingFieldAccessor(new CSIdentifier(id), use, entity.Type.ToFullyQualifiedName(true), typeMapper)));
                    }
                    else
                    {
                        callParams.Add(retrievecall);
                    }
                }
                else if (entityType == EntityType.Protocol)
                {
                    var thePtr     = new CSIdentifier(MarshalEngine.Uniqueify("p", identifiersUsed));
                    var csParmType = csParm.CSType as CSSimpleType;
                    if (csParmType == null)
                    {
                        throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 32, "Inconceivable! The protocol type for a method was NOT a CSSimpleType!");
                    }
                    use.AddIfNotPresent(typeof(SwiftObjectRegistry));
                    string csParmProxyType = NewClassCompiler.CSProxyNameForProtocol(entity.Type.ToFullyQualifiedName(true), typeMapper);
                    if (csParmProxyType == null)
                    {
                        throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 33, $"Unable to find C# interface type for protocol {entity.Type.ToFullyQualifiedName ()}");
                    }

                    var retrievecall = new CSFunctionCall($"SwiftObjectRegistry.Registry.InterfaceForExistentialContainer<{csParmType.Name}>", false, delegateParams [i].Name);
                    if (csParm.ParameterKind == CSParameterKind.Out || csParm.ParameterKind == CSParameterKind.Ref)
                    {
                        CSIdentifier id = new CSIdentifier(MarshalEngine.Uniqueify(delegateParams [i].Name.Name, identifiersUsed));
                        identifiersUsed.Add(id.Name);
                        preMarshalCode.Add(CSFieldDeclaration.FieldLine(csParmType, id.Name, retrievecall));
                        callParams.Add(new CSIdentifier(String.Format("{0} {1}",
                                                                      csParm.ParameterKind == CSParameterKind.Out ? "out" : "ref", id)));
                        postMarshalCode.Add(CSAssignment.Assign(delegateParams [i].Name,
                                                                new CSFunctionCall("SwiftExistentialContainer1", true,
                                                                                   new CSFunctionCall("SwiftObjectRegistry.Registry.ExistentialContainerForProtocol", false, id, csParmType.Typeof()))));
                    }
                    else
                    {
                        callParams.Add(retrievecall);
                    }
                }
                else if ((entityType == EntityType.Struct || entityType == EntityType.Enum) && !isUnusualParameter)
                {
                    var csParmType = csParm.CSType as CSSimpleType;
                    if (csParmType == null)
                    {
                        throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 34, $"Inconceivable! The {entityType} type for a method was NOT a CSSimpleType!");
                    }
                    use.AddIfNotPresent(typeof(StructMarshal));
                    use.AddIfNotPresent(typeof(StructMarshal));
                    string valMarshalName = MarshalEngine.Uniqueify(delegateParams [i].Name + "Temp", identifiersUsed);
                    var    valMarshalId   = new CSIdentifier(valMarshalName);

                    var valDecl = CSVariableDeclaration.VarLine(csParmType, valMarshalId,
                                                                new CSCastExpression(csParmType, new CSFunctionCall("StructMarshal.Marshaler.ToNet", false, delegateParams [i].Name,
                                                                                                                    csParmType.Typeof())));
                    preMarshalCode.Add(valDecl);
                    callParams.Add(valMarshalId);
                }
                else if (entityType == EntityType.Tuple)
                {
                    var csParmType = csParm.CSType as CSSimpleType;
                    if (csParmType == null)
                    {
                        throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 35, "Inconceivable! The tuple type for a parameter in a method was NOT a CSSimpleType!");
                    }
                    use.AddIfNotPresent(typeof(StructMarshal));
                    string valMarshalName = MarshalEngine.Uniqueify(delegateParams [i].Name + "Temp", identifiersUsed);
                    var    valMarshalId   = new CSIdentifier(valMarshalName);

                    var valDecl = CSVariableDeclaration.VarLine(csParmType, valMarshalId,
                                                                new CSCastExpression(csParmType, new CSFunctionCall("StructMarshal.Marshaler.ToNet", false, delegateParams [i].Name,
                                                                                                                    csParmType.Typeof())));
                    preMarshalCode.Add(valDecl);
                    callParams.Add(valMarshalId);
                }
                else if (entityType == EntityType.Closure)
                {
                    // parm is a SwiftClosureRepresentation
                    // (FuncType)StructMarshal.Marshaler.MakeDelegateFromBlindClosure (arg, argTypes, returnType);
                    var argTypesId = new CSIdentifier(MarshalEngine.Uniqueify("argTypes" + delegateParams [i], identifiersUsed));
                    identifiersUsed.Add(argTypesId.Name);
                    var parmType = csParm.CSType as CSSimpleType;
                    if (parmType == null)
                    {
                        throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 44, "Inconceivable! The type for a closure should be a CSSimpleType");
                    }
                    var hasReturn      = parmType.GenericTypeName == "Func";
                    var returnType     = hasReturn ? (CSBaseExpression)parmType.GenericTypes [parmType.GenericTypes.Length - 1].Typeof() : CSConstant.Null;
                    var argTypesLength = hasReturn ? parmType.GenericTypes.Length - 1 : parmType.GenericTypes.Length;
                    var argTypes       = new CSBaseExpression [argTypesLength];
                    for (int idx = 0; idx < argTypesLength; idx++)
                    {
                        argTypes [idx] = parmType.GenericTypes [idx].Typeof();
                    }
                    var typeArr = new CSArray1DInitialized(CSSimpleType.Type, argTypes);

                    var closureExpr = new CSFunctionCall("StructMarshal.Marshaler.MakeDelegateFromBlindClosure", false, delegateParams [i].Name,
                                                         typeArr, returnType);
                    var castTo = new CSCastExpression(csParm.CSType, closureExpr);
                    callParams.Add(castTo);
                }
                else if (entityType == EntityType.ProtocolList)
                {
                    preMarshalCode.Add(CSFunctionCall.FunctionCallLine("throw new NotImplementedException", false, CSConstant.Val($"Argument {csParm.Name} is a protocol list type and can't be marshaled from a virtual method.")));
                    callParams.Add(CSConstant.Null);
                    marshalingThrows = true;
                }
                else if (parmIsGeneric)
                {
                    // parm is an IntPtr to some T
                    // to get T, we ask funcDecl for the depthIndex of T
                    // T someVal = (T)StructMarshal.Marshaler.ToNet(parm, typeof(T));
                    // someVal gets passed in
                    var genRef = csParm.CSType as CSGenericReferenceType;
                    if (genRef == null)
                    {
                        throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 36, "Inconceivable! The generic type for a parameter in a method was NOT a CSGenericReferenceType!");
                    }
                    use.AddIfNotPresent(typeof(StructMarshal));
                    string valMarshalName = MarshalEngine.Uniqueify(delegateParams [i].Name + "Temp", identifiersUsed);
                    var    valMarshalId   = new CSIdentifier(valMarshalName);

                    var valDecl = CSVariableDeclaration.VarLine(genRef, valMarshalId,
                                                                new CSCastExpression(genRef, new CSFunctionCall("StructMarshal.Marshaler.ToNet", false,
                                                                                                                delegateParams [i].Name,
                                                                                                                genRef.Typeof())));
                    preMarshalCode.Add(valDecl);
                    callParams.Add(valMarshalId);
                }
                else
                {
                    if (csParm.ParameterKind == CSParameterKind.Out || csParm.ParameterKind == CSParameterKind.Ref)
                    {
                        callParams.Add(new CSIdentifier(String.Format("{0} {1}",
                                                                      csParm.ParameterKind == CSParameterKind.Out ? "out" : "ref", delegateParams [i].Name.Name)));
                    }
                    else
                    {
                        callParams.Add(delegateParams [i].Name);
                    }
                }
            }

            var body = new CSCodeBlock();

            if (isObjC)
            {
                use.AddIfNotPresent("ObjCRuntime");
            }
            else
            {
                use.AddIfNotPresent(typeof(SwiftObjectRegistry));
            }


            CSBaseExpression invoker = null;

            if (isIndexer)
            {
                if (thisIsInterface)
                {
                    invoker = new CSIndexExpression(
                        $"SwiftObjectRegistry.Registry.InterfaceForExistentialContainer<{thisType.ToString ()}> (self)",
                        false, callParams.ToArray());
                }
                else
                {
                    var registryCall = isObjC ?
                                       $"Runtime.GetNSObject<{thisType.ToString ()}> (self)" :
                                       $"SwiftObjectRegistry.Registry.CSObjectForSwiftObject <{thisType.ToString ()}> (self)";
                    invoker = new CSIndexExpression(registryCall, false, callParams.ToArray());
                }
            }
            else
            {
                if (thisIsInterface)
                {
                    invoker = new CSFunctionCall(
                        $"SwiftObjectRegistry.Registry.InterfaceForExistentialContainer<{thisType.ToString ()}> (self).{methodName}",
                        false, callParams.ToArray());
                }
                else
                {
                    var registryCall = isObjC ?
                                       $"Runtime.GetNSObject<{thisType.ToString ()}>(self).{methodName}" :
                                       $"SwiftObjectRegistry.Registry.CSObjectForSwiftObject <{thisType.ToString ()}> (self).{methodName}";
                    invoker = new CSFunctionCall(registryCall, false, callParams.ToArray());
                }
            }

            var    tryBlock   = funcDecl.HasThrows ? new CSCodeBlock() : null;
            var    catchBlock = funcDecl.HasThrows ? new CSCodeBlock() : null;
            var    altBody    = tryBlock ?? body;
            string catchName  = MarshalEngine.Uniqueify("e", identifiersUsed);
            var    catchID    = new CSIdentifier(catchName);


            altBody.AddRange(preMarshalCode);
            if (marshalingThrows)
            {
                return(altBody);
            }

            if (funcDecl.HasThrows || needsReturn)               // function that returns or getter
            {
                if (funcDecl.HasThrows)
                {
                    use.AddIfNotPresent(typeof(SwiftError));
                    use.AddIfNotPresent(typeof(Tuple));
                    use.AddIfNotPresent(typeof(StructMarshal));
                    CSType returnTuple = null;
                    if (needsReturn)
                    {
                        returnTuple = new CSSimpleType("Tuple", false,
                                                       methodType,
                                                       new CSSimpleType(typeof(SwiftError)),
                                                       CSSimpleType.Bool);
                    }
                    else
                    {
                        returnTuple = new CSSimpleType("Tuple", false,
                                                       new CSSimpleType(typeof(SwiftError)),
                                                       CSSimpleType.Bool);
                    }


                    if (needsReturn)
                    {
                        string retvalName = MarshalEngine.Uniqueify("retval", identifiersUsed);
                        var    retvalId   = new CSIdentifier(retvalName);
                        altBody.Add(CSFieldDeclaration.VarLine(methodType, retvalId, invoker));
                        postMarshalCode.Add(CSFunctionCall.FunctionCallLine("StructMarshal.Marshaler.ToSwift", false,
                                                                            methodType.Typeof(),
                                                                            retvalId,
                                                                            delegateParams [0].Name));
                        altBody.Add(CSFunctionCall.FunctionCallLine("StructMarshal.Marshaler.SetErrorNotThrown", false,
                                                                    delegateParams [0].Name, returnTuple.Typeof()));
                    }
                    else
                    {
                        if (isSetter)
                        {
                            altBody.Add(CSAssignment.Assign(invoker, CSAssignmentOperator.Assign, valueExpr));
                        }
                        else
                        {
                            altBody.Add(new CSLine(invoker));
                        }
                        altBody.Add(CSFunctionCall.FunctionCallLine("StructMarshal.Marshaler.SetErrorNotThrown", false,
                                                                    delegateParams [0].Name, returnTuple.Typeof()));
                    }
                    string swiftError           = MarshalEngine.Uniqueify("err", identifiersUsed);
                    var    swiftErrorIdentifier = new CSIdentifier(swiftError);
                    catchBlock.Add(CSFieldDeclaration.VarLine(new CSSimpleType(typeof(SwiftError)), swiftErrorIdentifier,
                                                              new CSFunctionCall("SwiftError.FromException", false, catchID)));
                    catchBlock.Add(CSFunctionCall.FunctionCallLine("StructMarshal.Marshaler.SetErrorThrown", false,
                                                                   delegateParams [0].Name,
                                                                   swiftErrorIdentifier,
                                                                   returnTuple.Typeof()));
                }
                else
                {
                    if (returnIsClass)
                    {
                        string       retvalName = MarshalEngine.Uniqueify("retval", identifiersUsed);
                        CSIdentifier retvalId   = new CSIdentifier(retvalName);
                        altBody.Add(CSFieldDeclaration.VarLine(methodType, retvalId, invoker));
                        postMarshalCode.Add(CSReturn.ReturnLine(
                                                NewClassCompiler.SafeBackingFieldAccessor(retvalId, use, returnEntity.Type.ToFullyQualifiedName(), typeMapper)));
                    }
                    else if (returnIsProtocol)
                    {
                        string retvalName = MarshalEngine.Uniqueify("retval", identifiersUsed);
                        identifiersUsed.Add(retvalName);
                        var retvalId = new CSIdentifier(retvalName);
                        altBody.Add(CSFieldDeclaration.VarLine(methodType, retvalId, invoker));
                        var returnContainer = MarshalEngine.Uniqueify("returnContainer", identifiersUsed);
                        identifiersUsed.Add(returnContainer);
                        var returnContainerId = new CSIdentifier(returnContainer);
                        var protoGetter       = new CSFunctionCall($"SwiftObjectRegistry.Registry.ExistentialContainerForProtocols", false, retvalId, methodType.Typeof());
                        var protoDecl         = CSVariableDeclaration.VarLine(CSSimpleType.Var, returnContainerId, protoGetter);
                        var marshalBack       = CSFunctionCall.FunctionCallLine($"{returnContainer}.CopyTo", delegateParams [0].Name);
                        postMarshalCode.Add(protoDecl);
                        postMarshalCode.Add(marshalBack);
                    }
                    else if (returnIsStruct)
                    {
                        // non-blitable means that the parameter is an IntPtr and we can call the
                        // marshaler to copy into it
                        use.AddIfNotPresent(typeof(StructMarshal));
                        var marshalCall = CSFunctionCall.FunctionCallLine("StructMarshal.Marshaler.ToSwift", false,
                                                                          invoker, delegateParams [0].Name);
                        altBody.Add(marshalCall);
                    }
                    else if (returnIsTuple)
                    {
                        // non-blitable means that the parameter is an IntPtr and we can call the
                        // marshaler to copy into it
                        use.AddIfNotPresent(typeof(StructMarshal));
                        var marshalCall = CSFunctionCall.FunctionCallLine("StructMarshal.Marshaler.ToSwift", false,
                                                                          invoker, delegateParams [0].Name);
                        altBody.Add(marshalCall);
                    }
                    else if (returnIsGeneric)
                    {
                        // T retval = invoker();
                        // if (retval is ISwiftObject) {
                        //     Marshal.WriteIntPtr(delegateParams [0].Name, ((ISwiftObject)retval).SwiftObject);
                        // }
                        // else {
                        //    StructMarshal.Marshaler.ToSwift(typeof(T), retval, delegateParams[0].Name);
                        // }
                        string retvalName = MarshalEngine.Uniqueify("retval", identifiersUsed);
                        var    retvalId   = new CSIdentifier(retvalName);
                        altBody.Add(CSFieldDeclaration.VarLine(methodType, retvalId, invoker));
                        var ifClause = new CSCodeBlock();
                        ifClause.Add(CSFunctionCall.FunctionCallLine("Marshal.WriteIntPtr", false,
                                                                     delegateParams [0].Name,
                                                                     new CSParenthesisExpression(new CSCastExpression("ISwiftObject", retvalId)).Dot(NewClassCompiler.kSwiftObjectGetter)));
                        var elseClause = new CSCodeBlock();
                        elseClause.Add(CSFunctionCall.FunctionCallLine("StructMarshal.Marshaler.ToSwift", false,
                                                                       methodType.Typeof(),
                                                                       retvalId,
                                                                       delegateParams [0].Name));
                        CSBaseExpression ifExpr = new CSSimpleType("ISwiftObject").Typeof().Dot(new CSFunctionCall("IsAssignableFrom", false,
                                                                                                                   methodType.Typeof()));

                        var retTest = new CSIfElse(ifExpr, ifClause, elseClause);
                        altBody.Add(retTest);
                    }
                    else
                    {
                        if (returnIsClosure)
                        {
                            invoker = MarshalEngine.BuildBlindClosureCall(invoker, methodType as CSSimpleType, use);
                        }
                        if (postMarshalCode.Count > 0)
                        {
                            string       retvalName = MarshalEngine.Uniqueify("retval", identifiersUsed);
                            CSIdentifier retvalId   = new CSIdentifier(retvalName);
                            altBody.Add(CSFieldDeclaration.VarLine(methodType, retvalId, invoker));
                            postMarshalCode.Add(CSReturn.ReturnLine(retvalId));
                        }
                        else
                        {
                            altBody.Add(CSReturn.ReturnLine(invoker));
                        }
                    }
                }
            }
            else                 // no return or setter
            {
                if (isSetter)
                {
                    altBody.Add(CSAssignment.Assign(invoker, CSAssignmentOperator.Assign, valueExpr));
                }
                else
                {
                    altBody.Add(new CSLine(invoker));
                }
            }
            altBody.AddRange(postMarshalCode);

            if (funcDecl.HasThrows)
            {
                body.Add(new CSTryCatch(tryBlock, new CSCatch(typeof(Exception), catchName, catchBlock)));
            }
            return(body);
        }
        public static CSNamespace CreateManagedConsoleRedirect()
        {
            // Same as GetManagedConsoleRedirectCode, just different format.
            var cs = new CSNamespace();

            var console = new CSClass(CSVisibility.Public, "Console", isStatic: true);

            console.Fields.Add(CSFieldDeclaration.FieldLine(CSSimpleType.String, new CSIdentifier("filename"), isStatic: true));
            console.Properties.Add(
                new CSProperty(
                    CSSimpleType.String,
                    CSMethodKind.Static,
                    new CSIdentifier("Filename"),
                    CSVisibility.None,
                    CSCodeBlock.Create(
                        new CSIfElse(
                            new CSBinaryExpression(
                                CSBinaryOperator.Equal,
                                new CSIdentifier("filename"),
                                new CSIdentifier("null")
                                ),
                            CSCodeBlock.Create(
                                CSAssignment.Assign(
                                    new CSIdentifier("filename"),
                                    new CSBinaryExpression(
                                        CSBinaryOperator.NullCoalesce,
                                        CSFunctionCall.Function(
                                            "Environment.GetEnvironmentVariable",
                                            CSConstant.Val("LEAKTEST_STDOUT_PATH")
                                            ),
                                        new CSIdentifier("string.Empty")
                                        )
                                    )
                                )
                            ),
                        CSReturn.ReturnLine(new CSIdentifier("filename"))
                        ),
                    CSVisibility.None,
                    null
                    )
                );
            console.Methods.Add(
                new CSMethod(
                    CSVisibility.Public,
                    CSMethodKind.Static,
                    CSSimpleType.Void,
                    new CSIdentifier("write"),
                    new CSParameterList(
                        new CSParameter(CSSimpleType.String, new CSIdentifier("value"))
                        ),
                    CSCodeBlock.Create(
                        new CSIfElse(
                            new CSIdentifier("string.IsNullOrEmpty (Filename)"),
                            CSCodeBlock.Create(CSFunctionCall.FunctionCallLine("global::System.Console.Write", new CSIdentifier("value"))),
                            CSCodeBlock.Create(CSFunctionCall.FunctionCallLine("System.IO.File.AppendAllText", new CSIdentifier("Filename"), new CSIdentifier("value")))
                            )
                        )
                    )
                );
            console.Methods.Add(
                new CSMethod(
                    CSVisibility.Public,
                    CSMethodKind.Static,
                    CSSimpleType.Void,
                    new CSIdentifier("Write"),
                    new CSParameterList(
                        new CSParameter(CSSimpleType.Object, new CSIdentifier("value"))
                        ),
                    CSCodeBlock.Create(
                        CSFunctionCall.FunctionCallLine(
                            "write",
                            false,
                            new CSIdentifier("value?.ToString ()")
                            )
                        )
                    )
                );
            console.Methods.Add(
                new CSMethod(
                    CSVisibility.Public,
                    CSMethodKind.Static,
                    CSSimpleType.Void,
                    new CSIdentifier("Write"),
                    new CSParameterList(
                        new CSParameter(CSSimpleType.String, new CSIdentifier("value")),
                        new CSParameter(CSSimpleType.CreateArray("object"), new CSIdentifier("args"), CSParameterKind.Params)
                        ),
                    CSCodeBlock.Create(
                        CSFunctionCall.FunctionCallLine(
                            "write",
                            false,
                            new CSIdentifier("value == null ? string.Empty : string.Format (value, args)")
                            )
                        )
                    )
                );
            console.Methods.Add(
                new CSMethod(
                    CSVisibility.Public,
                    CSMethodKind.Static,
                    CSSimpleType.Void,
                    new CSIdentifier("WriteLine"),
                    new CSParameterList(
                        new CSParameter(CSSimpleType.Object, new CSIdentifier("value"))
                        ),
                    CSCodeBlock.Create(
                        CSFunctionCall.FunctionCallLine(
                            "write",
                            false,
                            new CSIdentifier("value?.ToString () + Environment.NewLine")
                            )
                        )
                    )
                );
            console.Methods.Add(
                new CSMethod(
                    CSVisibility.Public,
                    CSMethodKind.Static,
                    CSSimpleType.Void,
                    new CSIdentifier("WriteLine"),
                    new CSParameterList(
                        new CSParameter(CSSimpleType.String, new CSIdentifier("value")),
                        new CSParameter(CSSimpleType.CreateArray("object"), new CSIdentifier("args"), CSParameterKind.Params)
                        ),
                    CSCodeBlock.Create(
                        CSFunctionCall.FunctionCallLine(
                            "write",
                            false,
                            new CSIdentifier("(value == null ? string.Empty : string.Format (value, args)) + Environment.NewLine")
                            )
                        )
                    )
                );
            cs.Block.Add(console);
            return(cs);
        }
        public void ClassEquals()
        {
            // Note for future Steve
            // If an argument is a protocol with associated types, the calling conventions are different.
            // Typically, if a function accepts a protocol type as its argument it gets passed in as an existential
            // container.
            // It appears that if a function is generic with a protocol constraint then the argument gets
            // passed in as a pointer to the type then with the attendant metadata and protocol witness table
            // As a result, this code crashes since we're passing in the wrong type as far as I can tell.
            // This clearly needs more investigation

            // note to current or future Steve:
            // The calling conventions for this are:
            // rdi - pointer to value containing a
            // rsi - pointer to value containing b
            // rdx - metadata for type T
            // rcx - protocol witness table for T
            //
            // in pinvoke terms, this is
            // extern static void areEqualClass(IntPtr a, IntPtr b, SwiftMetatype mt, IntPtr protowitness);

            var swiftCode =
                $"public func areEqualClass<T:Equatable>(a: T, b: T) -> Bool {{\n" +
                "    return a == b\n" +
                "}\n" +
                "public protocol XXEquals {\n" +
                "    func Equals() -> Bool\n" +
                "}\n"
            ;

            var eqClass = new CSClass(CSVisibility.Public, "EqClass");
            var field   = CSVariableDeclaration.VarLine(CSSimpleType.Int, "X");

            eqClass.Fields.Add(field);
            var ctorParms = new CSParameterList();

            ctorParms.Add(new CSParameter(CSSimpleType.Int, new CSIdentifier("x")));
            var assignLine = CSAssignment.Assign("X", new CSIdentifier("x"));
            var ctor       = new CSMethod(CSVisibility.Public, CSMethodKind.None, null, new CSIdentifier("EqClass"), ctorParms,
                                          CSCodeBlock.Create(assignLine));

            eqClass.Constructors.Add(ctor);
            eqClass.Inheritance.Add(typeof(ISwiftEquatable));

            var eqParms = new CSParameterList();

            eqParms.Add(new CSParameter(new CSSimpleType("ISwiftEquatable"), new CSIdentifier("other")));
            var castLine = CSVariableDeclaration.VarLine(new CSSimpleType("EqClass"), "otherEqClass",
                                                         new CSBinaryExpression(CSBinaryOperator.As, new CSIdentifier("other"), new CSIdentifier("EqClass")));
            var nonNull    = new CSBinaryExpression(CSBinaryOperator.NotEqual, new CSIdentifier("otherEqClass"), CSConstant.Null);
            var valsEq     = new CSBinaryExpression(CSBinaryOperator.Equal, new CSIdentifier("otherEqClass.X"), new CSIdentifier("X"));
            var returnLine = CSReturn.ReturnLine(new CSBinaryExpression(CSBinaryOperator.And, nonNull, valsEq));
            var opEquals   = new CSMethod(CSVisibility.Public, CSMethodKind.None, CSSimpleType.Bool, new CSIdentifier("OpEquals"), eqParms,
                                          CSCodeBlock.Create(castLine, returnLine));

            eqClass.Methods.Add(opEquals);


            var newClass    = new CSFunctionCall("EqClass", true, CSConstant.Val(5));
            var isEqual     = new CSFunctionCall($"TopLevelEntities.AreEqualClass", false, newClass, newClass);
            var printer     = CSFunctionCall.ConsoleWriteLine(isEqual);
            var callingCode = CSCodeBlock.Create(printer);

            TestRunning.TestAndExecute(swiftCode, callingCode, "True\n", otherClass: eqClass, platform: PlatformName.macOS);
        }