public void ObjCRefProtocolArg()
        {
            var swiftCode =
                "import Foundation\n" +
                "@objc\n" +
                "public protocol LifeTheUniverseAnd {\n" +
                "   @objc func Everything () -> Int\n" +
                "}\n" +
                "@objc\n" +
                "internal class Liff : NSObject, LifeTheUniverseAnd {\n" +
                "   private var x: Int\n" +
                "   public init (z: Int) {\n" +
                "      x = z\n" +
                "   }\n" +
                "   @objc func Everything () -> Int {\n" +
                "       return x\n" +
                "   }\n" +
                "}\n" +
                "public func makeIt (a: Int) -> LifeTheUniverseAnd {\n" +
                "    return Liff(z: a)\n" +
                "}\n" +
                "public func setIt (a:inout LifeTheUniverseAnd) {\n" +
                "    a = Liff(z: 42)\n" +
                "}\n";

            var inst        = CSVariableDeclaration.VarLine(CSSimpleType.Var, "liff", new CSFunctionCall("TopLevelEntities.MakeIt", false, CSConstant.Val(17)));
            var morphIt     = CSFunctionCall.FunctionCallLine("TopLevelEntities.SetIt", false, new CSIdentifier("ref liff"));
            var printIt     = CSFunctionCall.ConsoleWriteLine(CSFunctionCall.Function("liff.Everything"));
            var callingCode = CSCodeBlock.Create(inst, morphIt, printIt);

            TestRunning.TestAndExecute(swiftCode, callingCode, "42\n", platform: PlatformName.macOS);
        }
        public void ObjCInvokeProp()
        {
            var swiftCode =
                "import Foundation\n" +
                "@objc\n" +
                "public protocol HandProp {\n" +
                "   @objc var whichHand:Int { get }\n" +
                "}\n" +
                "public func doWhichHand(a:HandProp) -> Int {\n" +
                "    return a.whichHand\n" +
                "}\n";
            var altClass = new CSClass(CSVisibility.Public, "MyHandsProp");

            altClass.Inheritance.Add(new CSIdentifier("NSObject"));
            altClass.Inheritance.Add(new CSIdentifier("IHandProp"));

            var whichHandProp = CSProperty.PublicGetBacking(new CSSimpleType("nint"), new CSIdentifier("WhichHand"), new CSIdentifier("42"));

            altClass.Properties.Add(whichHandProp);

            var altCtor = new CSMethod(CSVisibility.Public, CSMethodKind.None, null, altClass.Name, new CSParameterList(), new CSBaseExpression [0], true, new CSCodeBlock());

            altClass.Constructors.Add(altCtor);


            var altInst = CSVariableDeclaration.VarLine(CSSimpleType.Var, "lefty", new CSFunctionCall("MyHandsProp", true));

            var caller      = CSFunctionCall.ConsoleWriteLine(CSFunctionCall.Function("TopLevelEntities.DoWhichHand", new CSIdentifier("lefty")));
            var callingCode = CSCodeBlock.Create(altInst, caller);

            TestRunning.TestAndExecute(swiftCode, callingCode, "42\n", otherClass: altClass, platform: PlatformName.macOS);
        }
        public void ObjCInvokePropInSwift()
        {
            var swiftCode =
                "import Foundation\n" +
                "@objc\n" +
                "public protocol HandProp1 {\n" +
                "   @objc var whichHand:Int { get }\n" +
                "}\n" +
                "@objc\n" +
                "internal class HandPropImpl : NSObject, HandProp1 {\n" +
                "    @objc public var whichHand:Int {\n" +
                "        get {\n" +
                "            return 42\n" +
                "        }\n" +
                "    }\n" +
                "}\n" +
                "public func makeHandProp1 () -> HandProp1 {\n" +
                "    return HandPropImpl ()\n" +
                "}\n";

            var inst = CSVariableDeclaration.VarLine(CSSimpleType.Var, "lefty", new CSFunctionCall("TopLevelEntities.MakeHandProp1", false));

            var caller      = CSFunctionCall.ConsoleWriteLine(new CSIdentifier("lefty.WhichHand"));
            var callingCode = CSCodeBlock.Create(inst, caller);

            TestRunning.TestAndExecute(swiftCode, callingCode, "42\n", platform: PlatformName.macOS);
        }
Beispiel #4
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);
        }
Beispiel #5
0
        public void CallAVirtualInACtor(PlatformName platform)
        {
            string swiftCode =
                @"import Foundation
open class VirtInInit : NSObject {
	private var theValue:Int = 0;
	public init (value:Int) {
		super.init()
		setValue (value: value)
	}
	open func setValue (value: Int) {
		theValue = value
	}
	open func getValue () -> Int {
		return theValue;
	}
}
";
            var clDecl  = CSVariableDeclaration.VarLine(CSSimpleType.Var, "cl", new CSFunctionCall("VirtInInit", true, CSConstant.Val(5)));
            var printer = CSFunctionCall.ConsoleWriteLine(new CSFunctionCall("cl.GetValue", false));
            var setter  = CSFunctionCall.FunctionCallLine("cl.SetValue", CSConstant.Val(7));

            var callingCode = CSCodeBlock.Create(clDecl, printer, setter, printer);

            TestRunning.TestAndExecute(swiftCode, callingCode, "5\n7\n", platform: platform);
        }
        public void TestDictionary()
        {
            var swiftCode = @"
public func dictionaryTestDoesNothing () {
}";

            // var ocsty = typeof (SwiftOptional<bool>);
            // var mt = StructMarshal.Marshaler.Metatypeof (ocsty);
            // Type csty;
            // SwiftTypeRegistry.Registry.TryGetValue (mt, out csty);
            // Console.WriteLine (csty.Name);
            // Console.WriteLine (genargs.Length);
            // Console.WriteLine (genargs[1].Name);
            // Console.WriteLine (csty == ocsty);
            var ocsTypeID = new CSIdentifier("ocsty");
            var csTypeID  = new CSIdentifier("csty");
            var mtID      = new CSIdentifier("mt");

            var ocstyDecl = CSVariableDeclaration.VarLine(CSSimpleType.Var, ocsTypeID, new CSSimpleType("SwiftDictionary", false, CSSimpleType.Bool, CSSimpleType.Int).Typeof());
            var mtDecl    = CSVariableDeclaration.VarLine(CSSimpleType.Var, mtID,
                                                          new CSFunctionCall("StructMarshal.Marshaler.Metatypeof", false, ocsTypeID));
            var cstyDecl   = CSVariableDeclaration.VarLine(CSSimpleType.Type, csTypeID);
            var tryGetLine = CSFunctionCall.FunctionCallLine("SwiftTypeRegistry.Registry.TryGetValue", false,
                                                             mtID, new CSUnaryExpression(CSUnaryOperator.Out, csTypeID));
            var print1      = CSFunctionCall.ConsoleWriteLine(ocsTypeID.Dot(new CSIdentifier("Name")));
            var genargsID   = new CSIdentifier("genargs");
            var genArgsDecl = CSVariableDeclaration.VarLine(CSSimpleType.Var, genargsID, new CSFunctionCall($"{csTypeID.Name}.GetGenericArguments", false));
            var print2      = CSFunctionCall.ConsoleWriteLine(genargsID.Dot(new CSIdentifier("Length")));
            var print3      = CSFunctionCall.ConsoleWriteLine(new CSIdentifier($"{genargsID.Name} [0].Name"));
            var print4      = CSFunctionCall.ConsoleWriteLine(csTypeID == ocsTypeID);
            var callingCode = CSCodeBlock.Create(ocstyDecl, mtDecl, cstyDecl, tryGetLine, print1, genArgsDecl, print2, print3, print4);

            TestRunning.TestAndExecute(swiftCode, callingCode, "SwiftDictionary`2\n2\nBoolean\nTrue\n");
        }
        CSCodeBlock PrintTypeName(string csTypeName, bool hexEncode = false)
        {
            // string name;
            // SwiftTypeNameAttribute.TryGetSwiftName (typeof (csTypeName), out name);
            // Console.WriteLine (name.Substring (name.IndexOf ('.')));

            var nameID   = "name";
            var nameDecl = CSVariableDeclaration.VarLine(new CSSimpleType(typeof(string)), nameID);


            var tryGet = CSFunctionCall.FunctionCallLine("SwiftTypeNameAttribute.TryGetSwiftName", false,
                                                         new CSFunctionCall("typeof", false, new CSIdentifier(csTypeName)),
                                                         new CSIdentifier($"out {nameID}"));

            CSBaseExpression nameExpr = new CSFunctionCall($"{nameID}.Substring", false,
                                                           new CSFunctionCall($"{nameID}.IndexOf", false, CSConstant.Val('.')));

            if (hexEncode)
            {
                nameExpr = new CSFunctionCall("BitConverter.ToString", false,
                                              new CSFunctionCall("System.Text.Encoding.Default.GetBytes", false, nameExpr));
            }

            var printer = CSFunctionCall.ConsoleWriteLine(nameExpr);

            return(CSCodeBlock.Create(nameDecl, tryGet, printer));
        }
Beispiel #8
0
        public void TestSetRemove(string swiftType, string cstype, string val)
        {
            var variant   = swiftType;
            var swiftCode =
                $"public func makeSetTR{variant}() -> Set<{swiftType}> {{\n" +
                "    return Set()\n" +
                "}\n";


            var callingCode = new CodeElementCollection <ICodeElement> ();

            var setID   = new CSIdentifier("theSet");
            var setDecl = CSVariableDeclaration.VarLine(new CSSimpleType("SwiftSet", false, new CSSimpleType(cstype)), setID,
                                                        new CSFunctionCall($"TopLevelEntities.MakeSetTR{variant}", false));
            var valID        = new CSIdentifier("theVal");
            var valDecl      = CSVariableDeclaration.VarLine(new CSSimpleType(cstype), valID, new CSIdentifier(val));
            var containsLine = CSFunctionCall.ConsoleWriteLine(CSFunctionCall.Function("theSet.Contains", (CSIdentifier)val));

            var addLine    = CSFunctionCall.FunctionCallLine("theSet.Insert", false, valID);
            var removeLine = CSFunctionCall.FunctionCallLine("theSet.Remove", false, valID);

            callingCode.Add(setDecl);
            callingCode.Add(valDecl);
            callingCode.Add(containsLine);
            callingCode.Add(addLine);
            callingCode.Add(containsLine);
            callingCode.Add(removeLine);
            callingCode.Add(containsLine);

            TestRunning.TestAndExecute(swiftCode, callingCode, "False\nTrue\nFalse\n", testName: $"TestSetRemove{variant}");
        }
Beispiel #9
0
        void TLArrayMethodRemove(string swiftType, string csType, string csValue, string csNewValue, string output)
        {
            string swiftCode =
                $"public class FooTLAMR{swiftType} {{\n" +
                $"public init() {{ }}\n" +
                $"public func makeArray(a:{swiftType})  -> [{swiftType}]\n {{\n return [{swiftType}](repeating:a, count:2) \n}}\n" +
                $"}}";
            CodeElementCollection <ICodeElement> callingCode = new CodeElementCollection <ICodeElement> ();
            CSLine decl = CSVariableDeclaration.VarLine(new CSSimpleType("SwiftArray", false, new CSSimpleType(csType)),
                                                        new CSIdentifier("arr"),
                                                        new CSFunctionCall($"new FooTLAMR{swiftType}().MakeArray", false, new CSIdentifier(csValue)));
            CSLine    addLine = CSFunctionCall.FunctionCallLine("arr.Insert", false, CSConstant.Val(1), new CSIdentifier(csNewValue));
            CSLine    remLine = CSFunctionCall.FunctionCallLine("arr.RemoveAt", false, CSConstant.Val(1));
            CSLine    call    = CSFunctionCall.FunctionCallLine("Console.Write", false, new CSIdentifier("arr.Count"));
            CSForEach feach   = new CSForEach(new CSSimpleType(csType), "x", new CSIdentifier("arr"), null);

            feach.Body.Add(CSFunctionCall.FunctionCallLine("Console.Write", false, CSConstant.Val(" {0}"), feach.Ident));

            callingCode.Add(decl);
            callingCode.Add(addLine);
            callingCode.Add(remLine);
            callingCode.Add(call);
            callingCode.Add(feach);
            TestRunning.TestAndExecute(swiftCode, callingCode, output, testName: $"TLArrayMethodRemove{swiftType}");
        }
        public void TestExistentialContainer()
        {
            var swiftCode = @"
public protocol SomeProtocol {
	func foo ()
}
";
            // var ocsty = typeof (ISomeProtocol);
            // var mt = StructMarshal.Marshaler.ExistentialMetatypeof (ocsty);
            // Type csty;
            // SwiftTypeRegistry.Registry.TryGetValue (mt, out csty);
            // Console.WriteLine (csty.Name);
            // Console.WriteLine (csty == ocsty);
            var ocsTypeID = new CSIdentifier("ocsty");
            var csTypeID  = new CSIdentifier("csty");
            var mtID      = new CSIdentifier("mt");

            var ocstyDecl = CSVariableDeclaration.VarLine(CSSimpleType.Var, ocsTypeID, new CSSimpleType("ISomeProtocol").Typeof());
            var mtDecl    = CSVariableDeclaration.VarLine(CSSimpleType.Var, mtID,
                                                          new CSFunctionCall("StructMarshal.Marshaler.ExistentialMetatypeof", false, ocsTypeID));
            var cstyDecl   = CSVariableDeclaration.VarLine(CSSimpleType.Type, csTypeID);
            var tryGetLine = CSFunctionCall.FunctionCallLine("SwiftTypeRegistry.Registry.TryGetValue", false,
                                                             mtID, new CSUnaryExpression(CSUnaryOperator.Out, csTypeID));
            var print1      = CSFunctionCall.ConsoleWriteLine(ocsTypeID.Dot(new CSIdentifier("Name")));
            var print2      = CSFunctionCall.ConsoleWriteLine(csTypeID == ocsTypeID);
            var callingCode = CSCodeBlock.Create(ocstyDecl, mtDecl, cstyDecl, tryGetLine, print1, print2);

            TestRunning.TestAndExecute(swiftCode, callingCode, "ISomeProtocol\nTrue\n", platform: PlatformName.macOS);
        }
        void WrapSingleSubscriptGetOnly(string type, string csType, string csReplacement, string csAlt, string expected)
        {
            string swiftCode =
                TestRunningCodeGenerator.kSwiftFileWriter +
                $"public protocol MontyWSGO{type} {{ subscript(i:Int32) -> {type} {{ get }} \n  }}\n" +
                $"public class TestMontyWSGO{type} {{\npublic init() {{ }}\npublic func doIt(m:MontyWSGO{type}) {{\nvar s = \"\", t=\"\"\nprint(m[0], to:&s)\nprint(m[1], to:&t)\nwriteToFile(s+t, \"WrapSingleSubscriptGetOnly{type}\")\n}}\n}}\n";

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

            overCS.Inheritance.Add(new CSIdentifier($"IMontyWSGO{type}"));
            CSParameterList overParams = new CSParameterList();

            overParams.Add(new CSParameter(CSSimpleType.Int, "i"));
            CSCodeBlock overBody = CSCodeBlock.Create(CSReturn.ReturnLine(new CSTernary(new CSIdentifier("i") == CSConstant.Val(0),
                                                                                        new CSIdentifier(csReplacement), new CSIdentifier(csAlt), false)));
            CSProperty overProp = new CSProperty(new CSSimpleType(csType), CSMethodKind.None, CSVisibility.Public,
                                                 overBody, CSVisibility.Public, null, overParams);

            overCS.Properties.Add(overProp);

            CSLine      decl        = CSVariableDeclaration.VarLine(new CSSimpleType($"OverWSGO{type}"), "myOver", new CSFunctionCall($"OverWSGO{type}", true));
            CSLine      decl1       = CSVariableDeclaration.VarLine(new CSSimpleType($"TestMontyWSGO{type}"), "tester", new CSFunctionCall($"TestMontyWSGO{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: $"WrapSingleSubscriptGetOnly{type}", otherClass: overCS);
        }
        public void HasBuiltInTypes(string csType)
        {
            var swiftCode = $"public func doesNothing{csType}() {{\n}}\n";

            // var ocsty = typeof (csType);
            // var mt = StructMarshal.Marshaler.Metatypeof (ocsty);
            // Type csty;
            // SwiftTypeRegistry.Registry.TryGetValue(mt, out csty);
            // Console.WriteLine (csty == ocsty);

            var ocsTypeID = new CSIdentifier("ocsty");
            var csTypeID  = new CSIdentifier("csty");
            var mtID      = new CSIdentifier("mt");

            var ocstyDecl = CSVariableDeclaration.VarLine(CSSimpleType.Var, ocsTypeID, new CSSimpleType(csType).Typeof());
            var mtDecl    = CSVariableDeclaration.VarLine(CSSimpleType.Var, mtID,
                                                          new CSFunctionCall("StructMarshal.Marshaler.Metatypeof", false, ocsTypeID));
            var cstyDecl   = CSVariableDeclaration.VarLine(CSSimpleType.Type, csTypeID);
            var tryGetLine = CSFunctionCall.FunctionCallLine("SwiftTypeRegistry.Registry.TryGetValue", false,
                                                             mtID, new CSUnaryExpression(CSUnaryOperator.Out, csTypeID));
            var printer     = CSFunctionCall.ConsoleWriteLine(csTypeID == ocsTypeID);
            var callingCode = CSCodeBlock.Create(ocstyDecl, mtDecl, cstyDecl, tryGetLine, printer);

            TestRunning.TestAndExecute(swiftCode, callingCode, "True\n", testName: "HashBuiltInTypes" + csType);
        }
Beispiel #13
0
        public void ArcClassStruct()
        {
            string swiftCode =
                "public final class Foo {\npublic var _nm:String\npublic init(name:String) {\n_nm = name }\n" +
                "deinit {\nprint(_nm)\n}\n}\n" +
                "public struct Bar {\n public var a:Foo\n public init(f:Foo) {\n a = f\n}\n }\n"
            ;

            swiftCode += TestRunning.CreateSwiftConsoleRedirect();

            using (TempDirectoryFilenameProvider provider = new TempDirectoryFilenameProvider(null, true)) {
                Utils.CompileSwift(swiftCode, provider);

                string libFileName = Path.Combine(provider.DirectoryPath, "libXython.dylib");
                var    errors      = new ErrorHandling();

                ModuleInventory.FromFile(libFileName, errors);
                Utils.CheckErrors(errors);

                Utils.CompileToCSharp(provider);

                CSUsingPackages use = new CSUsingPackages("System", "System.Runtime.InteropServices", "SwiftRuntimeLibrary");

                CSNamespace ns     = new CSNamespace("Xython");
                CSFile      csfile = CSFile.Create(use, ns);

                CSIdentifier inst  = new CSIdentifier("inst");
                CSLine       newer = CSVariableDeclaration.VarLine((CSSimpleType)"Foo", inst, CSFunctionCall.Ctor("Foo",
                                                                                                                  CSFunctionCall.Function("SwiftString.FromString", CSConstant.Val("nothing"))));

                CSIdentifier inst1  = new CSIdentifier("bar");
                CSLine       newer1 = CSVariableDeclaration.VarLine((CSSimpleType)"Bar", inst1, CSFunctionCall.Ctor("Bar", inst));

                CSLine disposer  = CSFunctionCall.FunctionCallLine(inst.Name + ".Dispose", false);
                CSLine disposer1 = CSFunctionCall.FunctionCallLine(inst1.Name + ".Dispose", false);

                CSCodeBlock mainBody = CSCodeBlock.Create(newer, newer1, disposer, disposer1);

                CSMethod main = new CSMethod(CSVisibility.Public, CSMethodKind.Static, CSSimpleType.Void,
                                             (CSIdentifier)"Main", new CSParameterList(new CSParameter(CSSimpleType.CreateArray("string"), "args")),
                                             mainBody);
                CSClass mainClass = new CSClass(CSVisibility.Public, "NameNotImportant", new CSMethod [] { main });
                ns.Block.Add(mainClass);

                string csOutFilename  = provider.ProvideFileFor(provider.UniqueName(null, "CSWrap", "cs"));
                var    exeOutFilename = provider.UniquePath(null, "CSWrap", "exe");

                CodeWriter.WriteToFile(csOutFilename, csfile);

                Compiler.CSCompile(provider.DirectoryPath, Directory.GetFiles(provider.DirectoryPath, "*.cs"), exeOutFilename);

                TestRunning.CopyTestReferencesTo(provider.DirectoryPath);

                string output = Compiler.RunWithMono(exeOutFilename, provider.DirectoryPath);
                Assert.AreEqual("nothing\n", output);
            }
        }
Beispiel #14
0
        void WrapSingleGetSetSubscript0(string type, string returnVal, string csType, string csReplacement, string expected)
        {
            string      swiftCode   = $"public class MontyWSGSSub{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($"MontyWSGSSub{type}"), "monty", new CSFunctionCall($"MontyWSGSSub{type}", true));
            CSLine      invoker     = CSFunctionCall.ConsoleWriteLine((CSIdentifier)"monty[0]");
            CSCodeBlock callingCode = CSCodeBlock.Create(decl, invoker);

            TestRunning.TestAndExecute(swiftCode, callingCode, expected, $"WrapSingleGetSetSubscript0{type}");
        }
Beispiel #15
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");
        }
Beispiel #16
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}");
        }
        static CodeElementCollection <ICodeElement> CaptureSwiftOutputPostlude(string fileName)
        {
            //#if _MAC_TS_TEST_
            //            string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), fileName);
            //#else
            //NSUrl[] urls = NSFileManager.DefaultManager.GetUrls(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User);
            //string path = Path.Combine(urls[0].Path, fileName);
            //#endif

            //NSUrl[] urls = NSFileManager.DefaultManager.GetUrls(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User);
            //string path = Path.Combine(urls[0].Path, fileName);
            //if (File.Exists(path))
            //{
            //    Console.Write(File.ReadAllText(path));
            //}

            CSCodeBlock  block  = new CSCodeBlock();
            CSIdentifier pathID = new CSIdentifier("path");

            block.Add(new CSIdentifier("\n#if _MAC_TS_TEST_\n"));
            block.Add(CSVariableDeclaration.VarLine(CSSimpleType.String, pathID,
                                                    new CSFunctionCall("Path.Combine", false,
                                                                       new CSIdentifier("Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)") +
                                                                       CSConstant.Val("/Documents/"),
                                                                       CSConstant.Val(fileName))));
            block.Add(new CSIdentifier("\n#else\n"));
            CSIdentifier urlID    = new CSIdentifier("urls");
            CSLine       urlsLine = CSVariableDeclaration.VarLine(new CSSimpleType("NSUrl", true), urlID,
                                                                  new CSFunctionCall("NSFileManager.DefaultManager.GetUrls", false,
                                                                                     new CSIdentifier("NSSearchPathDirectory.DocumentDirectory"),
                                                                                     new CSIdentifier("NSSearchPathDomain.User")));

            block.Add(urlsLine);


            CSLine pathLine = CSVariableDeclaration.VarLine(CSSimpleType.String, pathID,
                                                            new CSFunctionCall("Path.Combine", false,
                                                                               new CSArray1D(urlID.Name, CSConstant.Val(0)).Dot(new CSIdentifier("Path")),
                                                                               CSConstant.Val(fileName)));

            block.Add(pathLine);
            block.Add(new CSIdentifier("\n#endif\n"));

            CSCodeBlock ifBlock = new CSCodeBlock();
            CSLine      writer  = CSFunctionCall.FunctionCallLine("Console.Write", false, new CSFunctionCall("File.ReadAllText", false, pathID));

            ifBlock.Add(writer);
            ifBlock.Add(CSFunctionCall.FunctionCallLine("File.Delete", false, pathID));
            CSIfElse iftest = new CSIfElse(new CSFunctionCall("File.Exists", false, pathID), ifBlock);

            block.Add(iftest);
            return(block);
        }
        public void WrapImplicitlyUnwrappedOptional(string swiftType, string swiftVal, string csType, string expected)
        {
            string swiftCode = $"public func returnBang{swiftType}()->{swiftType}! {{\n" +
                               $"   return {swiftVal}\n" +
                               "}";
            CSLine csopt = CSVariableDeclaration.VarLine(new CSSimpleType($"SwiftOptional<{csType}>"), "foo",
                                                         new CSFunctionCall($"TopLevelEntities.ReturnBang{swiftType}", false));
            CSLine      printer     = CSFunctionCall.ConsoleWriteLine((CSIdentifier)"foo.Value");
            CSCodeBlock callingCode = CSCodeBlock.Create(csopt, printer);

            TestRunning.TestAndExecute(swiftCode, callingCode, expected, testName: $"WrapImplicitlyUnwrappedOptional{swiftType}");
        }
        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);
        }
Beispiel #20
0
        public void NSObjectSubclassableMethodTest3()
        {
            string swiftCode =
                "import Foundation\n" +
                "@objc\n" +
                "open class Subclassable3 : NSObject {\n" +
                "   public override init () { }\n" +
                "   open var returnsTrue:Bool {\n" +
                "       get { return true\n } " +
                "   }\n" +
                "}\n" +
                "public func callIt (a: Subclassable3) -> Bool {\n" +
                "    return a.returnsTrue\n" +
                "}\n";


            var theSub = new CSClass(CSVisibility.Public, "TheSub3");
            var ctor   = new CSMethod(CSVisibility.Public, CSMethodKind.None, null, theSub.Name,
                                      new CSParameterList(), new CSBaseExpression [0], true, new CSCodeBlock());

            theSub.Constructors.Add(ctor);
            theSub.Inheritance.Add(new CSIdentifier("Subclassable3"));

            var theBody = new CSCodeBlock();

            theBody.Add(CSReturn.ReturnLine(CSConstant.Val(false)));

            LineCodeElementCollection <ICodeElement> getCode =
                new LineCodeElementCollection <ICodeElement> (
                    new ICodeElement [] {
                CSReturn.ReturnLine(CSConstant.Val(false))
            }, false, true);
            CSProperty returnsFalse = new CSProperty(CSSimpleType.Bool, CSMethodKind.Override, new CSIdentifier("ReturnsTrue"),
                                                     CSVisibility.Public, new CSCodeBlock(getCode),
                                                     CSVisibility.Public, null);

            theSub.Properties.Add(returnsFalse);


            var callingCode = new CodeElementCollection <ICodeElement> ();
            var objID       = new CSIdentifier("subTest");
            var objDecl     = CSVariableDeclaration.VarLine(CSSimpleType.Var, objID, new CSFunctionCall("TheSub3", true));
            var call        = CSFunctionCall.ConsoleWriteLine(objID.Dot((CSIdentifier)"ReturnsTrue"));
            var call2       = CSFunctionCall.ConsoleWriteLine(CSFunctionCall.Function("TopLevelEntities.CallIt", objID));

            callingCode.Add(objDecl);
            callingCode.Add(call);
            callingCode.Add(call2);

            TestRunning.TestAndExecute(swiftCode, callingCode, "False\nFalse\n", otherClass: theSub, platform: PlatformName.macOS);
        }
Beispiel #21
0
        public void UnicodeInOperatorName()
        {
            string swiftCode =
                "infix operator \x2295\x2295\n" +
                "public func \x2295\x2295 (left:Int, right: Int) -> Int {\n" +
                "    return left + right\n" +
                "}\n";
            var callingCode = new CodeElementCollection <ICodeElement> {
                CSVariableDeclaration.VarLine((CSSimpleType)"nint", "x", CSFunctionCall.Function("TopLevelEntities.InfixOperatorCirclePlusCirclePlus", CSConstant.Val(3), CSConstant.Val(4))),
                CSFunctionCall.ConsoleWriteLine((CSIdentifier)"x")
            };

            TestRunning.TestAndExecute(swiftCode, callingCode, "7\n");
        }
        void TupleProp(string type1, string type2, string cstype1, string cstype2, string val1, string val2, string expected)
        {
            string appendage = type1 + type2.Replace('(', '_').Replace(')', '_').Replace(',', '_').Replace(' ', '_');
            string swiftCode = $"public final class MontyTupleProp{appendage} {{ public init() {{ }}\n public var prop:({type1}, {type2}) {{\n return ({val1}, {val2});\n }}\n}}\n";
            CSLine cstupe    = CSVariableDeclaration.VarLine(new CSSimpleType("Tuple", false, new CSSimpleType(cstype1),
                                                                              new CSSimpleType(cstype2)),
                                                             "tupe", new CSFunctionCall($"MontyTupleProp{appendage}", true).Dot(new CSIdentifier("Prop")));

            CSLine printer = CSFunctionCall.ConsoleWriteLine((CSIdentifier)"tupe");

            CSCodeBlock callingCode = CSCodeBlock.Create(cstupe, printer);

            TestRunning.TestAndExecute(swiftCode, callingCode, expected, testName: $"TupleProp{appendage}");
        }
Beispiel #23
0
        public void BasicTest(PlatformName platform)
        {
            var swiftCode = @"
public func dateIsNotUsed () { }
";

            var clID    = new CSIdentifier("date");
            var clDecl  = CSVariableDeclaration.VarLine(CSSimpleType.Var, clID, new CSFunctionCall("SwiftDate.SwiftDate_TimeIntervalSince1970", false, CSConstant.Val(0.0)));
            var printer = CSFunctionCall.ConsoleWriteLine(new CSFunctionCall($"{clID.Name}.ToNSDate", false));

            var callingCode = CSCodeBlock.Create(clDecl, printer);

            TestRunning.TestAndExecute(swiftCode, callingCode, "1970-01-01 00:00:00 +0000\n", testName: $"BasicTest{platform}", platform: platform);
        }
Beispiel #24
0
        public void WrapVirtClassNonVirtProp()
        {
            string swiftCode =
                "open class VirtClassNVP {\n" +
                "    public init() { }\n" +
                "    public var x:Int = 17" +
                "}\n";

            var decl        = CSVariableDeclaration.VarLine(new CSSimpleType("VirtClassNVP"), "cl", new CSFunctionCall("VirtClassNVP", true));
            var printer     = CSFunctionCall.ConsoleWriteLine((CSIdentifier)"cl.X");
            var callingCode = CSCodeBlock.Create(decl, printer);

            TestRunning.TestAndExecute(swiftCode, callingCode, "17\n");
        }
Beispiel #25
0
        void TestObjectType(string type, string expectedOutput, PlatformName platform)
        {
            string source =
// no-op
                $"public func GetType{type} () {{\n" +
                "}\n";
            string testName    = $"TestObjectType{type}";
            var    mtID        = new CSIdentifier("mt");
            var    mtDecl      = CSVariableDeclaration.VarLine(CSSimpleType.Var, mtID, new CSFunctionCall("StructMarshal.Marshaler.Metatypeof", false, new CSSimpleType(type).Typeof()));
            var    printer     = CSFunctionCall.ConsoleWriteLine(mtID.Dot(new CSIdentifier("Kind")));
            var    callingCode = CSCodeBlock.Create(mtDecl, printer);

            TestRunning.TestAndExecute(source, callingCode, expectedOutput, testName: testName, platform: platform);
        }
Beispiel #26
0
        public void UnicodeInClassNameAndProperty()
        {
            string swiftCode =
                "public class cd1\x1800 {\n" +
                "   public init() { }\n" +
                "   public var v\x3004:Int = 3\n" +
                "}\n";

            var callingCode = new CodeElementCollection <ICodeElement> {
                CSVariableDeclaration.VarLine((CSSimpleType)"Cd1U1800", "cl", CSFunctionCall.Ctor("Cd1U1800")),
                CSFunctionCall.ConsoleWriteLine((CSIdentifier)"cl.VU3004")
            };

            TestRunning.TestAndExecute(swiftCode, callingCode, "3\n");
        }
        void Wrap2Tuple(string type1, string type2, string cstype1, string cstype2, string val1, string val2, string expected)
        {
            string typetype  = type1 + type2;
            string swiftCode = $"public final class MontyW2T{typetype} {{ public init() {{ }}\n public static func tupe(a:{type1}, b: {type2}) -> ({type1}, {type2})\n {{\n return (a, b);\n }}\n}}\n";

            CSLine cstupe = CSVariableDeclaration.VarLine(new CSSimpleType("Tuple", false, new CSSimpleType(cstype1),
                                                                           new CSSimpleType(cstype2)), "tupe", new CSFunctionCall($"MontyW2T{typetype}.Tupe", false,
                                                                                                                                  new CSIdentifier(val1), new CSIdentifier(val2)));

            CSLine printer = CSFunctionCall.ConsoleWriteLine((CSIdentifier)"tupe");

            CSCodeBlock callingCode = CSCodeBlock.Create(cstupe, printer);

            TestRunning.TestAndExecute(swiftCode, callingCode, expected, testName: $"Wrap2Tuple{typetype}");
        }
        public void TestAllocCount(string tag)
        {
            var swiftCode = $"public func neverUsed{tag}() {{\n}}\n";
            var ptrID     = new CSIdentifier("ptr");
            var ptrDecl   = CSVariableDeclaration.VarLine(CSSimpleType.Var, ptrID,
                                                          new CSFunctionCall("System.Runtime.InteropServices.Marshal.AllocHGlobal", false, CSConstant.Val(128)));
            var clID   = new CSIdentifier("ubp");
            var clDecl = CSVariableDeclaration.VarLine(CSSimpleType.Var, clID, new CSFunctionCall(tag, true, ptrID, CSConstant.Val(128)));

            var printer     = CSFunctionCall.ConsoleWriteLine(clID.Dot(new CSIdentifier("Count")));
            var cleanUp     = CSFunctionCall.FunctionCallLine("System.Runtime.InteropServices.Marshal.FreeHGlobal", false, ptrID);
            var callingCode = CSCodeBlock.Create(ptrDecl, clDecl, printer, cleanUp);

            TestRunning.TestAndExecute(swiftCode, callingCode, "128\n", testName: "TestAllocCount" + tag);
        }
Beispiel #29
0
        void TLArraySimple(string swiftType, string csType, string output)
        {
            string swiftCode =
                $"public func makeArrayTLAS{swiftType}()  -> [{swiftType}]\n {{\n return [{swiftType}]() \n}}\n";
            CodeElementCollection <ICodeElement> callingCode = new CodeElementCollection <ICodeElement> ();
            CSLine decl = CSVariableDeclaration.VarLine(new CSSimpleType("SwiftArray", false, new CSSimpleType(csType)),
                                                        new CSIdentifier("arr"),
                                                        new CSFunctionCall($"TopLevelEntities.MakeArrayTLAS{swiftType}", false));
            CSLine call = CSFunctionCall.FunctionCallLine("Console.Write", false, new CSIdentifier("arr.Count"));

            callingCode.Add(decl);
            callingCode.Add(call);

            TestRunning.TestAndExecute(swiftCode, callingCode, output, testName: $"MakeArrayTLAS{swiftType}");
        }
Beispiel #30
0
        public void OptionalInitFailTest()
        {
            string swiftCode =
                "open class OptionalInitFail {\n" +
                "    public init? (b: Bool) {\n" +
                "        if !b { return nil; }\n" +
                "    }\n" +
                "}\n";

            var decl        = CSVariableDeclaration.VarLine(new CSSimpleType("SwiftOptional<OptionalInitFail>"), "opt", new CSFunctionCall("OptionalInitFail.OptionalInitFailOptional", false, CSConstant.Val(false)));
            var printer     = CSFunctionCall.ConsoleWriteLine(new CSIdentifier("opt.HasValue"));
            var callingCode = CSCodeBlock.Create(decl, printer);

            TestRunning.TestAndExecute(swiftCode, callingCode, "False\n");
        }