Ejemplo n.º 1
0
        string CompileWithInvokingCode(CSFile cs, CSLine invoker, string nameSpace)
        {
            CSNamespace ns       = new CSNamespace(nameSpace);
            CSCodeBlock mainBody = CSCodeBlock.Create(invoker);
            CSMethod    main     = new CSMethod(CSVisibility.Public, CSMethodKind.Static, CSSimpleType.Void,
                                                new CSIdentifier("Main"), new CSParameterList(new CSParameter(new CSSimpleType("string", true), "args")),
                                                mainBody);
            CSClass cl = new CSClass(CSVisibility.Public, "NameNotImportant", new CSMethod [] { main });

            ns.Block.Add(cl);

            cs.Namespaces.Add(ns);

            using (DisposableTempFile csOut = new DisposableTempFile(null, null, "cs", true)) {
                CodeWriter.WriteToFile(csOut.Filename, cs);

                using (Stream csExeStm = Compiler.CompileUsing(null, XCodeCompiler.CSharpExe, csOut.Filename,
                                                               $"-lib:{kSwiftRuntimeMacOutputDirectory} -r:{kSwiftRuntimeLibraryMac}")) {
                    using (DisposableTempFile csExe = new DisposableTempFile(null, null, "exe", true)) {
                        csExeStm.CopyTo(csExe.Stream);
                        csExe.Stream.Close();
                        string output = Compiler.RunWithMono(csExe.Filename);
                        return(output);
                    }
                }
            }
        }
        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}");
        }
 protected override string GenerateVariableGetFunctionReturnContainerType(string type)
 {
     return(CSLine.Single("EnumerableLookupSet<?LABEL_TYPE, ?TYPE>",
                          "LABEL_TYPE", GetLabelTypeConcept().GetStoreTypeName(),
                          "TYPE", type
                          ));
 }
 public override string GetStringToTypeExpression(string string_expression)
 {
     return(CSLine.Single("?STRING_EXPRESSION.Parse?TYPE()",
                          "STRING_EXPRESSION", string_expression,
                          "TYPE", GetTypeName().StyleAsFunctionName()
                          ));
 }
Ejemplo n.º 6
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 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());
        }
Ejemplo n.º 8
0
 public string GetContextToTypeExpression(string context_expression)
 {
     return(CSLine.Single("?TYPE.DOMify(?CONTEXT_EXPRESSION)",
                          "TYPE", GetTypeName(),
                          "CONTEXT_EXPRESSION", context_expression
                          ));
 }
        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}");
        }
Ejemplo n.º 10
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}");
        }
Ejemplo n.º 11
0
        void WrapMultiTuple(string type, int count, string appendage, string expected, int nothing, params string [] values)
        {
            StringBuilder sbargs = new StringBuilder();
            StringBuilder sbtype = new StringBuilder();
            StringBuilder sbret  = new StringBuilder();

            for (int i = 0; i < count; i++)
            {
                if (i > 0)
                {
                    sbargs.Append(", ");
                    sbtype.Append(", ");
                    sbret.Append(", ");
                }
                sbargs.Append(String.Format("a{0}: {1}", i, type));
                sbtype.Append(type);
                sbret.Append(String.Format("a{0}", i));
            }

            string swiftCode =
                $"public final class MontyWMT{appendage} {{ public init() {{ }}\n public static func tupe({sbargs.ToString ()}) -> ({sbtype.ToString ()})\n {{\n return ({sbret.ToString ()});\n }}\n}}\n";

            CSBaseExpression [] args = values.Select(str => (CSBaseExpression) new CSIdentifier(str)).ToArray();

            CSLine cstupe = CSVariableDeclaration.VarLine(new CSSimpleType("var"), "tupe",
                                                          new CSFunctionCall($"MontyWMT{appendage}.Tupe", false, args));

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

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

            TestRunning.TestAndExecute(swiftCode, callingCode, expected, testName: $"WrapMultiTuple{appendage}");
        }
Ejemplo n.º 12
0
 public override string GetStringToTypeExpression(string string_expression)
 {
     return(CSLine.Single("new ?TYPE(?STRING_EXPRESSION)",
                          "TYPE", GetTypeName(),
                          "STRING_EXPRESSION", string_expression
                          ));
 }
 public DOMEVariableType_Multiple_Primitive_List(DOMEVariableTypeConcept t) : base(t)
 {
     get_type_name = new OperationCache <string>("get_type_name", delegate() {
         return(CSLine.Single("List<?INNER_TYPE>",
                              "INNER_TYPE", GetTypeConcept().GetStoreTypeName()
                              ));
     });
 }
Ejemplo n.º 14
0
 public DOMEVariableType_Multiple_RuleDefinition_NoParent_List(DOMEClass p, DOMEVariableTypeConcept t) : base(p, t)
 {
     get_type_name = new OperationCache <string>("get_type_name", delegate() {
         return(CSLine.Single("List<?INNER_TYPE>",
                              "INNER_TYPE", GetTypeConcept().GetStoreTypeName()
                              ));
     });
 }
Ejemplo n.º 15
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}");
        }
Ejemplo n.º 16
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);
            }
        }
 public DOMEVariableType_Single_RuleDefinition_AutoParent(DOMEClass p, DOMEVariableTypeConcept t) : base(p, t)
 {
     get_type_name = new OperationCache <string>("get_type_name", delegate() {
         return(CSLine.Single("HoldingSingle<?PARENT_TYPE, ?INNER_TYPE>",
                              "PARENT_TYPE", GetParentType().GetTypeName(),
                              "INNER_TYPE", GetTypeConcept().GetStoreTypeName()
                              ));
     });
 }
Ejemplo n.º 18
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");
        }
        public DOMEVariableType_Multiple_RuleDefinition_NoParent_LabeledItemSet(DOMEClass p, DOMEVariableTypeConcept t, DOMEVariableTypeConcept l) : base(p, t)
        {
            label_type_concept = l;

            get_type_name = new OperationCache <string>("get_type_name", delegate() {
                return(CSLine.Single("LabeledItemSet<?LABEL_TYPE, ?INNER_TYPE>",
                                     "LABEL_TYPE", GetLabelTypeConcept().GetStoreTypeName(),
                                     "INNER_TYPE", GetTypeConcept().GetStoreTypeName()
                                     ));
            });
        }
Ejemplo n.º 20
0
        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}");
        }
Ejemplo n.º 22
0
        private void BuildRenderCSLine(RenderTreeBuilder builder, CSLine csLine)
        {
            builder.OpenElement(Next(), "span");
            builder.AddAttribute(Next(), "class", _themeRazorKeywordClass);
            string lineType = GetLineType(csLine.LineType);

            builder.AddContent(Next(), "@" + lineType);
            builder.CloseElement();

            builder.OpenElement(Next(), "span");
            //builder.AddAttribute(Next(), "class", _textClass);
            builder.AddContent(Next(), csLine.Line);
            builder.CloseElement();
        }
Ejemplo n.º 23
0
        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}");
        }
Ejemplo n.º 24
0
        public void TopLevelFunctionHomonym()
        {
            var swiftCode =
                "public func same(a:Int) -> Int { return a }\n" +
                "public func same(b:Int) -> Int { return b }\n" +
                "public func same(b:Int) -> Bool { return true }\n";

            var         call        = new CSFunctionCall("TopLevelEntities.Same_a_nint", false, CSConstant.Val(14));
            var         call1       = new CSFunctionCall("TopLevelEntities.Same_b_bool", false, CSConstant.Val(14));
            CSLine      printer     = CSFunctionCall.ConsoleWriteLine(call);
            CSLine      printer1    = CSFunctionCall.ConsoleWriteLine(call1);
            CSCodeBlock callingCode = CSCodeBlock.Create(printer, printer1);

            TestRunning.TestAndExecute(swiftCode, callingCode, "14\nTrue\n");
        }
Ejemplo n.º 25
0
        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}");
        }
Ejemplo n.º 26
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}");
        }
Ejemplo n.º 27
0
        public void TestConstructorClassHomonym()
        {
            var swiftCode =
                "public class FooClassCtor {\n" +
                "   public var x:Int\n" +
                "   public init(a:Int) { x = a\n }\n" +
                "   public init(b:Int) { x = b + b\n }\n" +
                "}\n";
            var         call        = new CSFunctionCall("FooClassCtor.FooClassCtor_a", false, CSConstant.Val(14));
            var         call1       = new CSFunctionCall("FooClassCtor.FooClassCtor_b", false, CSConstant.Val(14));
            CSLine      printer     = CSFunctionCall.ConsoleWriteLine(call.Dot(new CSIdentifier("X")));
            CSLine      printer1    = CSFunctionCall.ConsoleWriteLine(call1.Dot(new CSIdentifier("X")));
            CSCodeBlock callingCode = CSCodeBlock.Create(printer, printer1);

            TestRunning.TestAndExecute(swiftCode, callingCode, "14\n28\n");
        }
Ejemplo n.º 28
0
        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}");
        }
Ejemplo n.º 29
0
        public void TestGenericConstructorClassHomonym()
        {
            var swiftCode =
                "public class FooGeneric<T> {\n" +
                "   public var x:Int\n" +
                "   public var t:T\n" +
                "   public init(a:Int, c:T) { x = a\n t = c\n}\n" +
                "   public init(b:Int, c:T) { x = b + b\n t = c\n}\n" +
                "}\n";
            var         call        = new CSFunctionCall("FooGeneric<bool>.FooGeneric_a_c", false, CSConstant.Val(14), CSConstant.Val(true));
            var         call1       = new CSFunctionCall("FooGeneric<bool>.FooGeneric_b_c", false, CSConstant.Val(14), CSConstant.Val(true));
            CSLine      printer     = CSFunctionCall.ConsoleWriteLine(call.Dot(new CSIdentifier("X")));
            CSLine      printer1    = CSFunctionCall.ConsoleWriteLine(call1.Dot(new CSIdentifier("X")));
            CSCodeBlock callingCode = CSCodeBlock.Create(printer, printer1);

            TestRunning.TestAndExecute(swiftCode, callingCode, "14\n28\n");
        }
Ejemplo n.º 30
0
        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");
        }