Beispiel #1
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 SimpleProtocolProGetSetAssocTestAltSyntax ()
		{
			var swiftCode = @"
public protocol Simplest3 {
	associatedtype Item
	var thing: Item { get set }
}
public func doSetProp<T> (a: inout T, b:T.Item) where T:Simplest3 {
	a.thing = b
}
";
			var altClass = new CSClass (CSVisibility.Public, "Simple3Impl");
			altClass.Inheritance.Add (new CSIdentifier ("ISimplest3<SwiftString>"));
			var thingProp = CSProperty.PublicGetSet (new CSSimpleType ("SwiftString"), "Thing");
			altClass.Properties.Add (thingProp);

			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 ("Simple3Impl", true));
			var doSetProp = CSFunctionCall.FunctionCallLine ("TopLevelEntities.DoSetProp<Simple3Impl, SwiftString>", false, instID,
				new CSFunctionCall ("SwiftString.FromString", false, CSConstant.Val ("Got here!")));
			var printer = CSFunctionCall.ConsoleWriteLine (new CSIdentifier ($"{instID.Name}.Thing"));
			var callingCode = CSCodeBlock.Create (instDecl, doSetProp, printer);
			TestRunning.TestAndExecute (swiftCode, callingCode, "Got here!\n", otherClass: altClass, platform: PlatformName.macOS);
		}
		public void SimplestProtocolPropGetAssocTest ()
		{
			var swiftCode = @"
public protocol Simplest1 {
	associatedtype Item
	var printThing: Item { get }
}
public func doPrint<T>(a:T) where T:Simplest1 {
	let _ = a.printThing
}
";
			var altClass = new CSClass (CSVisibility.Public, "Simple1Impl");
			altClass.Inheritance.Add (new CSIdentifier ("ISimplest1<SwiftString>"));
			var strID = new CSIdentifier ("theStr");
			var strDecl = CSVariableDeclaration.VarLine (strID, CSConstant.Val ("Got here!"));
			var printPart = CSFunctionCall.ConsoleWriteLine (strID);
			var returnPart = CSReturn.ReturnLine (new CSFunctionCall ("SwiftString.FromString", false, strID));
			var printBody = CSCodeBlock.Create (strDecl, printPart, returnPart);
			var speak = new CSProperty (new CSSimpleType ("SwiftString"), CSMethodKind.None, new CSIdentifier ("PrintThing"),
				CSVisibility.Public, printBody, CSVisibility.Public, null);
			altClass.Properties.Add (speak);

			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 ("Simple1Impl", true));
			var doPrint = CSFunctionCall.FunctionCallLine ("TopLevelEntities.DoPrint<Simple1Impl, SwiftString>", false, instID);
			var callingCode = CSCodeBlock.Create (instDecl, doPrint);
			TestRunning.TestAndExecute (swiftCode, callingCode, "Got here!\n", otherClass: altClass, platform: PlatformName.macOS);
		}
        public void HasTuple()
        {
            var swiftCode = @"
public func tupleTestDoesNothing () {
}";
            // var ocsty = typeof (Tuple<bool, float>)
            // 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("Tuple", false, CSSimpleType.Bool, CSSimpleType.Float).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");
        }
Beispiel #5
0
        void WrapSingleProperty(string type, string returnVal, string csType, string csReplacement, string expected)
        {
            string appendage = type.Replace('.', '_');
            string swiftCode =
                $"open class MontyWSP{appendage} {{ public init() {{}}\n open var val: {type} {{\nget {{ return {returnVal}\n}} }} }}";

            CSClass overCS = new CSClass(CSVisibility.Public, $"OverWSP{appendage}");

            overCS.Inheritance.Add(new CSIdentifier($"MontyWSP{appendage}"));
            CSCodeBlock getterBody = CSCodeBlock.Create(CSReturn.ReturnLine(new CSIdentifier(csReplacement)));

            CSProperty overProp = new CSProperty(new CSSimpleType(csType), CSMethodKind.Override, new CSIdentifier("Val"),
                                                 CSVisibility.Public, getterBody, CSVisibility.Public, null);

            overCS.Properties.Add(overProp);

            CSCodeBlock printBody = CSCodeBlock.Create(CSFunctionCall.ConsoleWriteLine(CSConstant.Val("{0}, {1}"), (CSIdentifier)"base.Val", (CSIdentifier)"Val"));
            CSMethod    printIt   = new CSMethod(CSVisibility.Public, CSMethodKind.None, CSSimpleType.Void, new CSIdentifier("PrintIt"), new CSParameterList(), printBody);

            overCS.Methods.Add(printIt);

            CSLine      decl        = CSVariableDeclaration.VarLine(new CSSimpleType($"OverWSP{appendage}"), "printer", new CSFunctionCall($"OverWSP{appendage}", true));
            CSLine      invoker     = CSFunctionCall.FunctionCallLine("printer.PrintIt", false);
            CSCodeBlock callingCode = CSCodeBlock.Create(decl, invoker);

            TestRunning.TestAndExecute(swiftCode, callingCode, expected, testName: $"WrapSingleProperty{appendage}", otherClass: overCS, platform: PlatformName.macOS);
        }
        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 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);
        }
        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));
        }
        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");
        }
Beispiel #10
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 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);
		}
Beispiel #12
0
        public void TestExtenstionGetSetSubscriptOnUInt16()
        {
            var swiftCode =
                "public extension UInt16 {\n" +
                "    subscript (index:Int) -> UInt16 {\n" +
                "        get { return self & UInt16(1 << index); }\n" +
                "        set {\n" +
                "            if newValue != 0 {\n" +
                "                self = self | (1 << index)\n" +
                "            }\n" +
                "            else {\n" +
                "                self = self & ~UInt16(1 << index)\n" +
                "            }\n" +
                "         }\n" +
                "    }\n" +
                "}\n";
            var extendIt = new CSFunctionCall("((ushort)321).GetSubscript", false, CSConstant.Val(1));
            var printer  = CSFunctionCall.ConsoleWriteLine(extendIt);
            var decl     = CSVariableDeclaration.VarLine(CSSimpleType.UShort, "ashort", CSConstant.Val((ushort)0));

            var changeIt = CSFunctionCall.FunctionCallLine("ExtensionsForSystemDotushort0.SetSubscript", false, new CSIdentifier("ref ashort"),
                                                           CSConstant.Val(1), CSConstant.Val(3));
            var printAgain  = CSFunctionCall.ConsoleWriteLine((CSIdentifier)"ashort");
            var callingCode = CSCodeBlock.Create(printer, decl, changeIt, printAgain);

            TestRunning.TestAndExecuteNoDevice(swiftCode, callingCode, "0\n8\n");
        }
Beispiel #13
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}");
        }
        public void TLDictionaryAddGet(string sKeyType, string sValType,
                                       string csKeyType, string csValType, string csKey, string csValue, string output)
        {
            string swiftCode =
                $"public func makeDictTLDAG{sKeyType}{sValType}()  -> [{sKeyType}:{sValType}]\n {{\n return [{sKeyType}:{sValType}]() \n}}\n";
            CodeElementCollection <ICodeElement> callingCode = new CodeElementCollection <ICodeElement> ();
            CSLine decl = CSVariableDeclaration.VarLine(new CSSimpleType("SwiftDictionary", false,
                                                                         new CSSimpleType(csKeyType),
                                                                         new CSSimpleType(csValType)),
                                                        new CSIdentifier("dict"),
                                                        new CSFunctionCall($"TopLevelEntities.MakeDictTLDAG{sKeyType}{sValType}", false));
            CSLine call    = CSFunctionCall.FunctionCallLine("Console.Write", false, new CSIdentifier("dict.Count"));
            CSLine addcall = CSFunctionCall.FunctionCallLine("dict.Add", false, new CSIdentifier(csKey),
                                                             new CSIdentifier(csValue));
            CSLine writeCall = CSFunctionCall.FunctionCallLine("Console.Write", false, CSConstant.Val(' '));
            CSLine getLine   = CSVariableDeclaration.VarLine(new CSSimpleType(csValType), "val",
                                                             new CSArray1D("dict", new CSIdentifier(csKey)));
            CSLine valueWrite = CSFunctionCall.FunctionCallLine("Console.Write", false, new CSIdentifier("val"));

            callingCode.Add(decl);
            callingCode.Add(call);
            callingCode.Add(addcall);
            callingCode.Add(writeCall);
            callingCode.Add(call);
            callingCode.Add(writeCall);
            callingCode.Add(getLine);
            callingCode.Add(valueWrite);
            TestRunning.TestAndExecute(swiftCode, callingCode, output, testName: $"TLDictionaryAddGet{sKeyType}{sValType}");
        }
        public void OperatorCompositionNoInvoke()
        {
            var swiftCode =
                "infix operator ∘\n" +
                "    public func ∘<T>(left: @escaping (T) -> (T), right: @escaping (T) -> (T)) -> (T) -> (T) {\n" +
                "        return { (x) in\n" +
                "            left (right(x))\n" +
                "        }\n" +
                "}\n";

            var lbody1 = new CSCodeBlock();
            var lid    = new CSIdentifier("d");

            lbody1.Add(CSReturn.ReturnLine(lid * CSConstant.Val(2.0)));
            var pl = new CSParameterList();

            pl.Add(new CSParameter(CSSimpleType.Double, lid));
            var lam1   = new CSLambda(pl, lbody1);
            var lbody2 = new CSCodeBlock();

            lbody2.Add(CSReturn.ReturnLine(lid * CSConstant.Val(3.0)));
            var lam2 = new CSLambda(pl, lbody2);

            var compFunc = CSFunctionCall.FunctionCallLine("TopLevelEntities.InfixOperatorRing", false, lam1, lam2);
            var printIt  = CSFunctionCall.ConsoleWriteLine(CSConstant.Val(12.0));

            var callingCode = new CodeElementCollection <ICodeElement> {
                compFunc, printIt
            };

            TestRunning.TestAndExecute(swiftCode, callingCode, "12\n");
        }
        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);
        }
        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);
        }
        void WrapOptionalArg(string type1, string cstype1, string val1, string expected, bool isStatic = true, string distinguisher = "")
        {
            var    typeString = type1 + distinguisher;
            string finalDecl  = (isStatic ? "final" : "");
            string statDecl   = (isStatic ? "static" : "");

            string swiftCode = TestRunningCodeGenerator.kSwiftFileWriter +
                               $"public {finalDecl} class MontyWOA{typeString} {{ public init() {{ }}\n public {statDecl} func printOpt(a:{type1}?)\n {{\n var s = \"\"\nif a != nil {{\n print(\"Optional(\\(a!))\", to:&s)\n }}\n else {{ print(\"nil\", to:&s)\n }}\nwriteToFile(s, \"WrapOptionalArg{typeString}\")\n }}\n}}\n";

            CSBaseExpression optValue = null;

            if (val1 != null)
            {
                optValue = new CSFunctionCall(String.Format("SwiftOptional<{0}>", cstype1), true, new CSIdentifier(val1));
            }
            else
            {
                optValue = new CSFunctionCall(String.Format("SwiftOptional<{0}>.None", cstype1), false);
            }

            CSLine csopt = CSVariableDeclaration.VarLine(new CSSimpleType("SwiftOptional", false, new
                                                                          CSSimpleType(cstype1)), "opt", optValue);

            CSLine printer = CSFunctionCall.FunctionCallLine((isStatic ? $"MontyWOA{typeString}.PrintOpt" : $"new MontyWOA{typeString}().PrintOpt"), false, new CSIdentifier("opt"));

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

            TestRunning.TestAndExecute(swiftCode, callingCode, expected, testName: $"WrapOptionalArg{typeString}");
        }
Beispiel #19
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);
            }
        }
        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);
        }
Beispiel #21
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");
        }
Beispiel #22
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}");
        }
        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);
        }
        public void TestProtocolTypeAttribute()
        {
            var swiftCode = @"
public protocol Useless {
	func doNothing ()
}
";
            // this will throw on fail
            // SwiftProtocolTypeAttribute.DescriptorForType (typeof (Useless));
            var getter = CSFunctionCall.FunctionCallLine("SwiftProtocolTypeAttribute.DescriptorForType", false,
                                                         new CSSimpleType("IUseless").Typeof());
            var printer     = CSFunctionCall.ConsoleWriteLine(CSConstant.Val("OK"));
            var callingCode = CSCodeBlock.Create(getter, printer);

            TestRunning.TestAndExecute(swiftCode, callingCode, "OK\n", platform: PlatformName.macOS);
        }
        public void ClosureSmokeTest()
        {
            string swiftCode =
                "public func callClosureCST(f:@escaping()->()) {\n" +
                "    f()\n" +
                "}";

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

            body.Add(CSFunctionCall.ConsoleWriteLine(CSConstant.Val("C# output")));
            CSLine invoker = CSFunctionCall.FunctionCallLine("TopLevelEntities.CallClosureCST", false,
                                                             new CSLambda(new CSParameterList(), body));

            callingCode.Add(invoker);
            TestRunning.TestAndExecute(swiftCode, callingCode, "C# output\n");
        }
Beispiel #26
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 WrapVirtualTuple(string type1, string type2, string cstype1, string cstype2, string val1, string val2, string expected)
        {
            string appendage = type1 + type2;

            string swiftCode = TestRunningCodeGenerator.kSwiftFileWriter +
                               $"public class MontyWVT{appendage} {{ public init() {{ }}\n public func tupe(a:({type1}, {type2}))\n {{\nvar s = \"\"\n print(a, to:&s)\nwriteToFile(s, \"WrapVirtualTuple{appendage}\")\n }}\n}}\n";

            CSLine cstupe = CSVariableDeclaration.VarLine(new CSSimpleType($"MontyWVT{appendage}"), "m", new CSFunctionCall($"MontyWVT{appendage}", true));

            CSLine printer = CSFunctionCall.FunctionCallLine("m.Tupe", false,
                                                             new CSFunctionCall(String.Format("Tuple<{0},{1}>", cstype1, cstype2), true, new CSIdentifier(val1),
                                                                                new CSIdentifier(val2)));

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

            TestRunning.TestAndExecute(swiftCode, callingCode, expected, $"WrapVirtualTuple{appendage}");
        }
Beispiel #28
0
        void TLExceptionSimple(string toAdd, string output)
        {
            string swiftCode = $"public enum MyErrorTLES{toAdd} : Error {{\ncase itFailed\n}}\n" +
                               $"public func throwItTLES{toAdd}(doThrow: Bool) throws -> Int\n {{\n if doThrow {{\n throw MyErrorTLES{toAdd}.itFailed\n}}\nelse {{\n return 5\n}}\n}}\n";
            CodeElementCollection <ICodeElement> callingCode = new CodeElementCollection <ICodeElement> ();
            CSCodeBlock tryBlock = new CSCodeBlock();
            CSLine      call     = CSFunctionCall.FunctionCallLine("Console.Write", false,
                                                                   new CSFunctionCall($"TopLevelEntities.ThrowItTLES{toAdd}", false, new CSIdentifier(toAdd)));

            tryBlock.Add(call);
            CSCodeBlock catchBlock = new CSCodeBlock();

            catchBlock.Add(CSFunctionCall.FunctionCallLine("Console.Write", false, CSConstant.Val("exception thrown")));
            CSTryCatch catcher = new CSTryCatch(tryBlock, typeof(SwiftException), null, catchBlock);

            callingCode.Add(catcher);
            TestRunning.TestAndExecute(swiftCode, callingCode, output, testName: $"TLExceptionSimple{toAdd}");
        }
Beispiel #29
0
        public void TestSimpleSetClosure()
        {
            var swiftCode = @"
open class SimpleSetClosure {
	public init () { }
	open func setValue (a: @escaping ()->()) {
	    a()
	}
}
";

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

            TestRunning.TestAndExecute(swiftCode, callingCode, "here\n", platform: PlatformName.macOS);
        }
        void WrapOptionalClassArg(string type1, string cstype1, string val1, string expected)
        {
            string appendage = (type1 + expected).Replace('.', '_').Replace('\n', '_').Replace(' ', '_');
            string swiftCode =
                TestRunningCodeGenerator.kSwiftFileWriter +
                $"public class FooWOCA{appendage} {{\n private var x:{type1}\n public init(a:{type1}) {{\n x = a;\n}}\n public func getX() -> {type1} {{\n return x;\n}} }}\n" +
                $"public final class MontyWOCA{appendage} {{ public init() {{ }}\n public static func printOpt(a:FooWOCA{appendage}?)\n {{\nvar s = \"\"\n if a != nil {{\n print(a!.getX(), to:&s)\n }}\n else {{ print(\"nil\", to:&s)\n }}\nwriteToFile(s, \"WrapOptionalClassArg{appendage}\")\n }}\n}}\n";

            CSLine csopt = CSVariableDeclaration.VarLine(new CSSimpleType($"SwiftOptional<FooWOCA{appendage}>"), "opt",
                                                         val1 != null ? (CSBaseExpression) new CSFunctionCall($"SwiftOptional<FooWOCA{appendage}>", true, new CSFunctionCall($"FooWOCA{appendage}", true, new CSIdentifier(val1))) :
                                                         (CSBaseExpression) new CSFunctionCall($"SwiftOptional<FooWOCA{appendage}>.None", false));

            CSLine printer = CSFunctionCall.FunctionCallLine($"MontyWOCA{appendage}.PrintOpt", false, new CSIdentifier("opt"));

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

            TestRunning.TestAndExecute(swiftCode, callingCode, expected, testName: $"WrapOptionalClassArg{appendage}");
        }