Exemple #1
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 SimpleEnumPostfixOpTest()
        {
            var swiftCode  = @"
public enum CompassPoints1 {
	case North, East, South, West
}
postfix operator ^+^
public postfix func ^+^(val: CompassPoints1) -> CompassPoints1 {
	switch val {
	case .North: return .East
	case .East: return .South
	case .South: return .West
	case .West: return .North
	}
}
";
            var leftID     = new CSIdentifier("left");
            var leftDecl   = CSVariableDeclaration.VarLine(CSSimpleType.Var, leftID, new CSIdentifier("CompassPoints1.North"));
            var resultID   = new CSIdentifier("result");
            var resultDecl = CSVariableDeclaration.VarLine(CSSimpleType.Var, resultID, new CSFunctionCall("TopLevelEntities.PostfixOperatorHatPlusHat", false, leftID));
            var printer    = CSFunctionCall.ConsoleWriteLine(resultID);

            var callingCode = new CodeElementCollection <ICodeElement> {
                leftDecl, resultDecl, printer
            };

            TestRunning.TestAndExecute(swiftCode, callingCode, "East\n");
        }
        public void SuperSimpleEnumTest()
        {
            var swiftCode  = @"
import Foundation

@objc
public enum CompassPoints2 : Int {
    case North = 0, East, South, West
}

prefix operator ^*^
public prefix func ^*^(val: CompassPoints2) -> CompassPoints2 {
    switch val {
    case .North: return .South
    case .East: return .West
    case .South: return .North
    case .West: return .East
    }
}";
            var leftID     = new CSIdentifier("left");
            var leftDecl   = CSVariableDeclaration.VarLine(CSSimpleType.Var, leftID, new CSIdentifier("CompassPoints2.North"));
            var resultID   = new CSIdentifier("result");
            var resultDecl = CSVariableDeclaration.VarLine(CSSimpleType.Var, resultID, new CSFunctionCall("TopLevelEntities.PrefixOperatorHatStarHat", false, leftID));
            var printer    = CSFunctionCall.ConsoleWriteLine(resultID);

            var callingCode = new CodeElementCollection <ICodeElement> {
                leftDecl, resultDecl, printer
            };

            TestRunning.TestAndExecute(swiftCode, callingCode, "South\n");
        }
		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);
		}
        public void TestCharacterConstructors()
        {
            var swiftCode = @"public func Echo (c: Character) -> Character { return c; }";

            var           callingCode = new CodeElementCollection <ICodeElement> ();
            StringBuilder expected    = new StringBuilder();

            foreach (string c in TestCases)
            {
                CSIdentifier testIdentifier = (CSIdentifier)$@"""{c}""";

                var ctorCall     = CSFunctionCall.Ctor("SwiftCharacter", testIdentifier);
                var fromCall     = CSFunctionCall.Function("SwiftCharacter.FromCharacter", testIdentifier);
                var implicitCall = new CSCastExpression((CSSimpleType)"SwiftCharacter", testIdentifier);

                foreach (var call in new CSBaseExpression [] { ctorCall, fromCall, implicitCall })
                {
                    CSLine print = CSFunctionCall.FunctionLine("Console.Write", CSFunctionCall.Function("TopLevelEntities.Echo", call));
                    callingCode.Add(print);
                    expected.Append(c);
                }
            }

            TestRunning.TestAndExecute(swiftCode, callingCode, expected.ToString());
        }
        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 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 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");
        }
        public void CGFloatVirtual(PlatformName platform)
        {
            var swiftCode = @"
import Foundation
import CoreGraphics

open class ItsACGFloat {
    open var value:CGFloat = 0
    public init (with: CGFloat) {
        value = with
    }
    open func getValue () -> CGFloat {
        return value
    }
}
";

            var cgfID   = new CSIdentifier("cgf");
            var cgfDecl = CSVariableDeclaration.VarLine(CSSimpleType.Var, cgfID, new CSFunctionCall("ItsACGFloat", true,
                                                                                                    new CSCastExpression(new CSSimpleType("nfloat"), CSConstant.Val(42.5))));
            var printer     = CSFunctionCall.ConsoleWriteLine(new CSFunctionCall("cgf.GetValue", false));
            var callingCode = CSCodeBlock.Create(cgfDecl, printer);

            TestRunning.TestAndExecute(swiftCode, callingCode, "42.5\n", platform: platform);
        }
        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);
        }
        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);
        }
        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");
        }
Exemple #13
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);
        }
        public void CanGetProtocolConformanceDesc()
        {
            // var nomDesc = SwiftProtocolTypeAttribute.DescriptorForType (typeof (IIteratorProtocol<>));
            // var witTable = SwiftCore.ConformsToSwiftProtocol (StructMarshal.Marshaler.Metatypeof (typeof (SwiftIteratorProtocolProxy<nint>)),
            //                                          nomDesc);
            // Console.WriteLine (confDesc != IntPtr.Zero);

            var swiftCode  = @"
public func canGetProtocolConfDesc () {
}
";
            var nomDescID  = new CSIdentifier("nomDesc");
            var witTableID = new CSIdentifier("witTable");

            var nomDecl = CSVariableDeclaration.VarLine(CSSimpleType.Var, nomDescID,
                                                        new CSFunctionCall("SwiftProtocolTypeAttribute.DescriptorForType", false, new CSSimpleType("IIteratorProtocol<>").Typeof()));

            var metaTypeCall = new CSFunctionCall("StructMarshal.Marshaler.Metatypeof", false, new CSSimpleType("SwiftIteratorProtocolProxy<nint>").Typeof());
            var confDescDecl = CSVariableDeclaration.VarLine(CSSimpleType.Var, witTableID,
                                                             new CSFunctionCall("SwiftCore.ConformsToSwiftProtocol", false, metaTypeCall, nomDescID));
            var printer = CSFunctionCall.ConsoleWriteLine(witTableID.Dot(new CSIdentifier("Handle")) != new CSIdentifier("IntPtr.Zero"));

            var callingCode = CSCodeBlock.Create(nomDecl, confDescDecl, printer);

            TestRunning.TestAndExecute(swiftCode, callingCode, "True\n");
        }
        public void EnumInlineInfixOperator()
        {
            var swiftCode  = @"
infix operator ^*=*^
public enum CompassPoints3 {
	case North, East, South, West

	public static func ^*=*^(left: CompassPoints3, right: CompassPoints3) -> Bool {
		return left == right
	}
}
";
            var leftID     = new CSIdentifier("left");
            var leftDecl   = CSVariableDeclaration.VarLine(CSSimpleType.Var, leftID, new CSIdentifier("CompassPoints3.North"));
            var rightID    = new CSIdentifier("right");
            var rightDecl  = CSVariableDeclaration.VarLine(CSSimpleType.Var, rightID, new CSIdentifier("CompassPoints3.East"));
            var resultID   = new CSIdentifier("result");
            var resultDecl = CSVariableDeclaration.VarLine(CSSimpleType.Var, resultID, new CSFunctionCall("CompassPoints3Extensions.InfixOperatorHatStarEqualsStarHat", false, leftID, rightID));
            var printer    = CSFunctionCall.ConsoleWriteLine(resultID);

            var callingCode = new CodeElementCollection <ICodeElement> {
                leftDecl, rightDecl, resultDecl, printer
            };

            TestRunning.TestAndExecute(swiftCode, callingCode, "False\n");
        }
Exemple #16
0
        public void TestMultiOverride(PlatformName platform)
        {
            var swiftCode   = @"
open class FirstClass {
	public init () { }
	open func firstFunc () -> Int {
	    return 42
	}
}

open class SecondClass : FirstClass {
	public override init () { }

	open func secondFunc () -> Int {
	    return 17
	}
}
";
            var declID      = new CSIdentifier("cl");
            var decl        = CSVariableDeclaration.VarLine(CSSimpleType.Var, declID, new CSFunctionCall("SecondClass", true));
            var printer     = CSFunctionCall.ConsoleWriteLine(new CSFunctionCall($"{declID.Name}.FirstFunc", false));
            var callingCode = CSCodeBlock.Create(decl, printer);

            TestRunning.TestAndExecute(swiftCode, callingCode, "42\n", "TestMultiOverride", platform: platform);
        }
        public void EnumInlinePrefixOperator()
        {
            var swiftCode  = @"
prefix operator ^+-+^
public enum CompassPoints4 {
	case North, East, South, West

	public static prefix func ^+-+^ (item: CompassPoints4) -> CompassPoints4 {
		switch item {
		case .North: return .West
		case .East: return .North
		case .South: return .East
		case .West: return .South
		}
	}
}
";
            var itemID     = new CSIdentifier("item");
            var itemDecl   = CSVariableDeclaration.VarLine(CSSimpleType.Var, itemID, new CSIdentifier("CompassPoints4.North"));
            var resultID   = new CSIdentifier("result");
            var resultDecl = CSVariableDeclaration.VarLine(CSSimpleType.Var, resultID, new CSFunctionCall("CompassPoints4Extensions.PrefixOperatorHatPlusMinusPlusHat", false, itemID));
            var printer    = CSFunctionCall.ConsoleWriteLine(resultID);

            var callingCode = new CodeElementCollection <ICodeElement> {
                itemDecl, resultDecl, printer
            };

            TestRunning.TestAndExecute(swiftCode, callingCode, "West\n");
        }
        public void TestUnwrappedOptional()
        {
            string swiftCode =
                "public class FooAny {\n" +
                "    public init() { }\n" +
                "}\n" +
                "public class AnyBang {\n" +
                "    public var x: AnyObject!\n" +
                "    public init (ix: AnyObject!) {\n" +
                "        x = ix\n" +
                "    }\n" +
                "}\n";

            var fooAnyID   = new CSIdentifier("fooAny");
            var fooAnyDecl = CSVariableDeclaration.VarLine(new CSSimpleType("FooAny"), fooAnyID,
                                                           new CSFunctionCall("FooAny", true));

            var anyObjID   = new CSIdentifier("anyObj");
            var anyObjDecl = CSVariableDeclaration.VarLine(new CSSimpleType("SwiftAnyObject"), anyObjID, new CSFunctionCall("SwiftAnyObject.FromISwiftObject", false, fooAnyID));

            var anyBangID   = new CSIdentifier("anyBang");
            var anyBangDecl = CSVariableDeclaration.VarLine(new CSSimpleType("AnyBang"), anyBangID,
                                                            new CSFunctionCall("AnyBang", true,
                                                                               new CSFunctionCall("SwiftOptional<SwiftAnyObject>", true, anyObjID)));

            var printer = CSFunctionCall.ConsoleWriteLine(CSConstant.Val("success."));

            var callingCode = CSCodeBlock.Create(fooAnyDecl, anyObjDecl, anyBangDecl, printer);

            TestRunning.TestAndExecute(swiftCode, callingCode, "success.\n");
        }
		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 StructInfixOpTest()
        {
            var swiftCode = @"
public struct IntRep {
    public init (with: Int32) {
		val = with
	}
    public var val:Int32 = 0
}

infix operator %^^% : AdditionPrecedence
public func %^^% (left:IntRep, right: IntRep) -> IntRep {
    return IntRep (with: left.val + right.val)
}
";

            var leftID     = new CSIdentifier("left");
            var leftDecl   = CSVariableDeclaration.VarLine(CSSimpleType.Var, leftID, new CSFunctionCall("IntRep", true, CSConstant.Val(3)));
            var rightID    = new CSIdentifier("right");
            var rightDecl  = CSVariableDeclaration.VarLine(CSSimpleType.Var, rightID, new CSFunctionCall("IntRep", true, CSConstant.Val(4)));
            var resultID   = new CSIdentifier("result");
            var resultDecl = CSVariableDeclaration.VarLine(CSSimpleType.Var, resultID, new CSFunctionCall("TopLevelEntities.InfixOperatorPercentHatHatPercent", false, leftID, rightID));
            var printer    = CSFunctionCall.ConsoleWriteLine(resultID.Dot(new CSIdentifier("Val")));

            var callingCode = new CodeElementCollection <ICodeElement> {
                leftDecl, rightDecl, resultDecl, printer
            };

            TestRunning.TestAndExecute(swiftCode, callingCode, "7\n");
        }
		public void SimpleProtocolProGetIndexer ()
		{
			var swiftCode = @"
public protocol Simplest4 {
	associatedtype Item
	subscript (index: Int) -> Item {
		get
	}
}
public func doGetIt<T:Simplest4> (a: T, i: Int) -> T.Item {
	return a[i]
}
";
			var altClass = new CSClass (CSVisibility.Public, "Simple4Impl");
			altClass.Inheritance.Add (new CSIdentifier ("ISimplest4<SwiftString>"));

			var getBlock = CSCodeBlock.Create (CSReturn.ReturnLine (new CSFunctionCall ("SwiftString.FromString", false, CSConstant.Val ("Got here!"))));
			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, null, 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 ("Simple4Impl", true));
			var resultID = new CSIdentifier ("result");
			var resultDecl = CSVariableDeclaration.VarLine (resultID, new CSFunctionCall ("TopLevelEntities.DoGetIt<Simple4Impl, SwiftString>", false, instID, CSConstant.Val (3)));
			var printer = CSFunctionCall.ConsoleWriteLine (resultID);
			var callingCode = CSCodeBlock.Create (instDecl, resultDecl, printer);
			TestRunning.TestAndExecute (swiftCode, callingCode, "Got here!\n", otherClass: altClass, platform: PlatformName.macOS);
		}
        public void StructPostfixOpTest()
        {
            var swiftCode = @"
public struct IntRep2 {
    public init (with: Int32) {
		val = with
	}
    public var val:Int32 = 0
}

prefix operator %--% 
public prefix func %--% (left:IntRep2) -> IntRep2 {
    return IntRep2 (with: left.val - 1)
}
";

            var leftID     = new CSIdentifier("left");
            var leftDecl   = CSVariableDeclaration.VarLine(CSSimpleType.Var, leftID, new CSFunctionCall("IntRep2", true, CSConstant.Val(3)));
            var resultID   = new CSIdentifier("result");
            var resultDecl = CSVariableDeclaration.VarLine(CSSimpleType.Var, resultID, new CSFunctionCall("TopLevelEntities.PrefixOperatorPercentMinusMinusPercent", false, leftID));
            var printer    = CSFunctionCall.ConsoleWriteLine(resultID.Dot(new CSIdentifier("Val")));

            var callingCode = new CodeElementCollection <ICodeElement> {
                leftDecl, resultDecl, printer
            };

            TestRunning.TestAndExecute(swiftCode, callingCode, "2\n");
        }
        public void TestCharacterCreation()
        {
            var           swiftCode   = @"
public class CharacterHolder
{
    public var C: Character;
    public init (c: Character) {C = c }
}";
            var           callingCode = new CodeElementCollection <ICodeElement> ();
            StringBuilder expected    = new StringBuilder();

            foreach (string c in TestCases)
            {
                CSIdentifier testIdentifier = (CSIdentifier)$@"""{c}""";

                Action <ICSExpression> testCharacter = creation => {
                    CSCodeBlock block = new CSCodeBlock();
                    block.Add(CSVariableDeclaration.VarLine((CSSimpleType)"SwiftCharacter", (CSIdentifier)"Char", creation));

                    block.Add(CSVariableDeclaration.VarLine((CSSimpleType)"CharacterHolder", (CSIdentifier)"Foo", CSFunctionCall.Ctor("CharacterHolder", (CSIdentifier)"Char")));
                    block.Add(CSFunctionCall.FunctionLine("Console.Write", (CSIdentifier)"(string)Foo.C"));

                    expected.Append(c);

                    callingCode.Add(block);
                };

                testCharacter(CSFunctionCall.Function("SwiftCharacter.FromCharacter", (testIdentifier)));
                testCharacter(new CSCastExpression((CSSimpleType)"SwiftCharacter", testIdentifier));
            }

            TestRunning.TestAndExecute(swiftCode, callingCode, expected.ToString());
        }
        public void ClassInlinePostfixOperator()
        {
            var swiftCode = @"
postfix operator ^*--*^

public class NumRep1 {
    public init (a: Int) {
        val = a
    }
    public var val: Int
    public static postfix func ^*--*^(val: NumRep1) -> NumRep1 {
        return NumRep1 (a: -val.val)
    }
}";

            var leftID     = new CSIdentifier("left");
            var leftDecl   = CSVariableDeclaration.VarLine(CSSimpleType.Var, leftID, new CSFunctionCall("NumRep1", true, CSConstant.Val(4)));
            var resultID   = new CSIdentifier("result");
            var resultDecl = CSVariableDeclaration.VarLine(CSSimpleType.Var, resultID, new CSFunctionCall("NumRep1.PostfixOperatorHatStarMinusMinusStarHat", false, leftID));
            var printer    = CSFunctionCall.ConsoleWriteLine(resultID.Dot(new CSIdentifier("Val")));

            var callingCode = new CodeElementCollection <ICodeElement> {
                leftDecl, resultDecl, printer
            };

            TestRunning.TestAndExecute(swiftCode, callingCode, "-4\n");
        }
Exemple #25
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);
        }
        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);
        }
Exemple #28
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);
        }
Exemple #29
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);
        }
Exemple #30
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}");
        }