示例#1
0
			public void TestBasicProject()
			{
				string data =
				@"<?xml version=""1.0"" encoding=""utf-8""?>
					<Project DefaultTargets=""Build"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" ToolsVersion=""4.0"">
						<PropertyGroup>
						<Configuration Condition="" '$(Configuration)' == '' "">Debug</Configuration>
							<OutputType>Library</OutputType>
							<AppDesignerFolder>Properties</AppDesignerFolder>
							<RootNamespace>TestRootNamespace</RootNamespace>
							<RestorePackages>true</RestorePackages>
						</PropertyGroup>
						<ItemGroup>
							<Compile Include=""TestClass1.cs"" />
						</ItemGroup>
					</Project>
				";
				Mock<ClassParser> classParser = new Mock<ClassParser>();
				List<CSClass> classList = new List<CSClass>();
				var testClass1 = new CSClass()
				{
					ClassName = "TestClass1",
					NamespaceName = "Test.Test1"
				};
				classList.Add(testClass1);
				classParser.Setup(i => i.ParseFile("C:\\Test\\TestClass1.cs", It.IsAny<string>(), It.IsAny<IEnumerable<CSClass>>())).Returns(classList);

				ProjectParser parser = new ProjectParser(classParser.Object);

				CSProjectFile project = parser.ParseString(data, "C:\\Test\\TestProject.csproj");
			
				Assert.AreEqual("TestRootNamespace", project.RootNamespace);
				Assert.AreEqual(1, project.ClassList.Count);
				Assert.AreEqual("Test.Test1.TestClass1", project.ClassList[0].ClassFullName);
			}
示例#2
0
			public void TestWebFormFiles()
			{
				string data =
				@"<?xml version=""1.0"" encoding=""utf-8""?>
					<Project DefaultTargets=""Build"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" ToolsVersion=""4.0"">
						<ItemGroup>
							<Compile Include=""TestClass1.aspx.cs"">
								<DependentUpon>TestClass1.aspx</DependentUpon>
							</Compile>
						</ItemGroup>
						<ItemGroup>
							<Content Include=""TestClass1.aspx"" />
							<Content Include=""TestControl.ascx"" />
							<Content Include=""TestMaster.Master"" />
						</ItemGroup>
					</Project>
				";
				Mock<ClassParser> classParser = new Mock<ClassParser>();
				List<CSClass> classList = new List<CSClass>();
				var testClass1 = new CSClass()
				{
					ClassName = "TestClass1",
					NamespaceName = "Test.Test1"
				};
				classList.Add(testClass1);
				classParser.Setup(i => i.ParseFile("C:\\Test\\TestClass1.aspx.cs", It.IsAny<string>(), It.IsAny<IEnumerable<CSClass>>())).Returns(classList);

				Mock<CSWebFormParser> webFormParser =new Mock<CSWebFormParser>();
				webFormParser.Setup(i => i.ParseFile("C:\\Test\\TestClass1.aspx"))
					.Returns(new WebFormContainer { ClassFullName = "Test.Test1.TestClass1", CodeBehindFile = "TestClass1.aspx.cs", ContainerType = EnumWebFormContainerType.WebPage });
				webFormParser.Setup(i => i.ParseFile("C:\\Test\\TestControl.ascx"))
					.Returns(new WebFormContainer { ClassFullName = "Test.Test1.TestControl", CodeBehindFile = "TestControl.ascx.cs", ContainerType = EnumWebFormContainerType.UserControl });
				webFormParser.Setup(i => i.ParseFile("C:\\Test\\TestMaster.Master"))
					.Returns(new WebFormContainer { ClassFullName = "Test.Test1.TestMaster", CodeBehindFile = "TestMaster.Master.cs", ContainerType = EnumWebFormContainerType.MasterPage });

				ProjectParser parser = new ProjectParser(classParser.Object, webFormParser.Object);

				CSProjectFile project = parser.ParseString(data, "C:\\Test\\TestProject.csproj");

				Assert.AreEqual(1, project.ClassList.Count);
				Assert.AreEqual("Test.Test1.TestClass1", project.ClassList[0].ClassFullName);

				Assert.AreEqual(3, project.WebFormContainers.Count);
				Assert.AreEqual("Test.Test1.TestClass1", project.WebFormContainers[0].ClassFullName);
				Assert.AreEqual("Test.Test1.TestControl", project.WebFormContainers[1].ClassFullName);
				Assert.AreEqual("Test.Test1.TestMaster", project.WebFormContainers[2].ClassFullName);
			}
示例#3
0
            private List <CSClass> AppendClassToList(IEnumerable <CSClass> inputClassList, CSClass classObject)
            {
                if (inputClassList == null)
                {
                    inputClassList = new List <CSClass>();
                }
                var newList       = new List <CSClass>(inputClassList ?? new CSClass[] { });
                var existingClass = inputClassList.SingleOrDefault(i => i.ClassFullName == classObject.ClassFullName);

                if (existingClass == null)
                {
                    newList.Add(classObject);
                }
                else
                {
                    existingClass.AttributeList = existingClass.AttributeList.Union(classObject.AttributeList).ToList();
                    existingClass.PropertyList  = existingClass.PropertyList.Union(classObject.PropertyList).ToList();
                    existingClass.FieldList     = existingClass.FieldList.Union(classObject.FieldList).ToList();
                }
                return(newList);
            }
示例#4
0
            public void TestRelativeDependentUponFilePath()
            {
                string data =
                    @"<?xml version=""1.0"" encoding=""utf-8""?>
					<Project DefaultTargets=""Build"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" ToolsVersion=""4.0"">
						<ItemGroup>
							<Compile Include=""TestDirectory\TestClass1.aspx.cs"">
								<DependentUpon>TestClass1.aspx</DependentUpon>
							</Compile>
							<Compile Include=""TestDirectory1\TestDirectory2\TestClass2.aspx.cs"">
								<DependentUpon>TestClass2.aspx</DependentUpon>
							</Compile>
						</ItemGroup>
						<ItemGroup>
							<Content Include=""TestDirectory\TestClass1.aspx"" />
							<Content Include=""TestDirectory1\TestDirectory2\TestClass2.aspx"" />
						</ItemGroup>
					</Project>
				"                ;
                Mock <ClassParser> classParser = new Mock <ClassParser>();
                List <CSClass>     classList   = new List <CSClass>();
                var testClass1 = new CSClass()
                {
                    ClassFullName = "Test.Test1.TestClass1"
                };
                var testClass2 = new CSClass()
                {
                    ClassFullName = "Test.Test2.TestClass2"
                };

                classList.Add(testClass1);
                classParser.Setup(i => i.ParseFile("C:\\Test\\TestDirectory\\TestClass1.aspx.cs", It.IsAny <string>(), It.IsAny <IEnumerable <CSClass> >()))
                .Returns((string filePath, string projectPath, IEnumerable <CSClass> inputClassList) => AppendClassToList(inputClassList, testClass1));
                classParser.Setup(i => i.ParseFile("C:\\Test\\TestDirectory1\\TestDirectory2\\TestClass2.aspx.cs", It.IsAny <string>(), It.IsAny <IEnumerable <CSClass> >()))
                .Returns((string filePath, string projectPath, IEnumerable <CSClass> inputClassList) => AppendClassToList(inputClassList, testClass2));

                Mock <CSWebFormParser> webFormParser = new Mock <CSWebFormParser>();

                webFormParser.Setup(i => i.ParseFile("C:\\Test\\TestDirectory\\TestClass1.aspx"))
                .Returns(new WebFormContainer {
                    ClassFullName = "Test.Test1.TestClass1", CodeBehindFile = "TestClass1.aspx.cs", ContainerType = EnumWebFormContainerType.WebPage
                });
                webFormParser.Setup(i => i.ParseFile("C:\\Test\\TestDirectory1\\TestDirectory2\\TestClass2.aspx"))
                .Returns(new WebFormContainer {
                    ClassFullName = "Test.Test2.TestClass2", CodeBehindFile = "TestClass2.aspx.cs", ContainerType = EnumWebFormContainerType.WebPage
                });

                ProjectParser parser = new ProjectParser(classParser.Object, webFormParser.Object);

                CSProjectFile project = parser.ParseString(data, "C:\\Test\\TestProject.csproj");

                Assert.AreEqual(2, project.ClassList.Count);

                Assert.AreEqual("Test.Test1.TestClass1", project.ClassList[0].ClassFullName);
                Assert.AreEqual("Test.Test2.TestClass2", project.ClassList[1].ClassFullName);

                Assert.AreEqual(2, project.ClassFileDependencyList.Count);
                Assert.AreEqual("Test.Test1.TestClass1", project.ClassFileDependencyList[0].ClassFullName);
                Assert.AreEqual("TestDirectory\\TestClass1.aspx", project.ClassFileDependencyList[0].DependentUponFile);
                Assert.AreEqual("Test.Test2.TestClass2", project.ClassFileDependencyList[1].ClassFullName);
                Assert.AreEqual("TestDirectory1\\TestDirectory2\\TestClass2.aspx", project.ClassFileDependencyList[1].DependentUponFile);

                Assert.AreEqual(2, project.WebFormContainers.Count);

                Assert.AreEqual("Test.Test1.TestClass1", project.WebFormContainers[0].ClassFullName);
                Assert.AreEqual("TestClass1.aspx.cs", project.WebFormContainers[0].CodeBehindFile);
                Assert.AreEqual(EnumWebFormContainerType.WebPage, project.WebFormContainers[0].ContainerType);

                Assert.AreEqual("Test.Test2.TestClass2", project.WebFormContainers[1].ClassFullName);
                Assert.AreEqual("TestClass2.aspx.cs", project.WebFormContainers[1].CodeBehindFile);
                Assert.AreEqual(EnumWebFormContainerType.WebPage, project.WebFormContainers[1].ContainerType);
            }
 public void Add(string filePath, CSClass csvClass)
 {
     fileDict.Add(filePath, csvClass);
 }
示例#6
0
			private List<CSClass> AppendClassToList(IEnumerable<CSClass> inputClassList, CSClass classObject)
			{
				if (inputClassList == null)
				{
					inputClassList = new List<CSClass>();
				}
				var newList = new List<CSClass>(inputClassList ?? new CSClass[] { });
				var existingClass = inputClassList.SingleOrDefault(i => i.ClassFullName == classObject.ClassFullName);
				if (existingClass == null)
				{
					newList.Add(classObject);
				}
				else
				{
					existingClass.AttributeList = existingClass.AttributeList.Union(classObject.AttributeList).ToList();
					existingClass.PropertyList = existingClass.PropertyList.Union(classObject.PropertyList).ToList();
					existingClass.FieldList = existingClass.FieldList.Union(classObject.FieldList).ToList();
				}
				return newList;
			}
 public CSVariableDeclaration.VariableDeclarator Translate(VariableDeclarator value, CSClass csClassRef)
 {
     return(new CSVariableDeclaration.VariableDeclarator
     {
         id = (CSIdentifier)Translate(value.Id, csClassRef),
         type = "dynamic"
     });
 }
        /// <summary>
        /// Read assemblies to list members
        /// </summary>
        public void Read()
        {
            foreach (ProjectInfo projectInfo in ProjectInfos)
            {
                if (!projectInfo.BuildConfigurations.ContainsKey(BuildConfiguration))
                {
                    // TODO Logs warn
                    continue;
                }

                BuildConfiguration config = projectInfo.BuildConfigurations[BuildConfiguration];

                if (string.IsNullOrWhiteSpace(config.OutputPath))
                {
                    // TODO Logs warn
                    continue;
                }

                // Read assembly
                Assembly assembly = Assembly.LoadFile(Path.GetFullPath(config.OutputPath)); // Set full path in BuildConfiguration object

                // Create doc object
                XmlDoc doc = default;

                if (!string.IsNullOrWhiteSpace(config.DocumentationFilePath))
                {
                    doc = XmlDocDeserializer.Deserialize(config.DocumentationFilePath);
                }

                // Create assembly object
                CSAssembly csAssembly = new CSAssembly(assembly);
                CSMembers.Add(csAssembly);

                // Run through all the types
                foreach (TypeInfo type in assembly.DefinedTypes)
                {
                    // Get the namespace object from the list of members
                    CSNamespace csNamespace = CSMembers.Namespaces.FirstOrDefault(n => n.Name == type.Namespace);

                    // If the namespace object does not exist, create it
                    if (csNamespace == null)
                    {
                        csNamespace = new CSNamespace(type.Namespace);
                        CSMembers.Add(csNamespace);
                    }

                    // Create type object
                    CSType csType = default;
                    if (type.IsClass)
                    {
                        // TODO Create class object
                        csType = new CSClass(csAssembly, csNamespace, type);
                    }

                    // Create type object
                    if (type.IsInterface)
                    {
                        // TODO Create interface object
                        csType = new CSInterface(csAssembly, csNamespace, type);
                    }

                    // Create type object
                    if (type.IsEnum)
                    {
                        // TODO Create enumeration object
                        csType = new CSEnumeration(csAssembly, csNamespace, type);
                    }

                    // Read doc to get type summary
                    csType.Summary = doc?.Members.FirstOrDefault(m => m.Name == csType.XmlFullName)?.Summary.Value;

                    csAssembly.Types.Add(csType);
                    csNamespace.Types.Add(csType);
                    CSMembers.Add(csType);
                }
            }
        }
        public static Tuple <CSNamespace, CSUsingPackages> CreateTestClass(CodeElementCollection <ICodeElement> callingCode, string testName,
                                                                           string expectedOutput, string nameSpace, string testClassName, CSClass otherClass, string skipReason, PlatformName platform)
        {
            var use = GetTestClassUsings(nameSpace);

            // [TomSkip(skipReason)]
            // public class TomTesttestName : ITomTest
            // {
            //    public testClassName() { }
            //    public string TestName { get { return testName; } }
            //    public string ExpectedOutput { get { return expectedOuput; } }
            //    public void Run() {
            //       callingCode;
            //    }
            // }
            // otherClass

            CSNamespace ns = new CSNamespace(nameSpace);

            if (otherClass != null)
            {
                ns.Block.Add(otherClass);
            }

            CSCodeBlock body = new CSCodeBlock(callingCode);

            body.Add(CaptureSwiftOutputPostlude(testName));

            CSMethod run = new CSMethod(CSVisibility.Public, CSMethodKind.None, CSSimpleType.Void, new CSIdentifier("Run"),
                                        new CSParameterList(), body);
            CSClass testClass = new CSClass(CSVisibility.Public, new CSIdentifier($"TomTest{testName}"), new CSMethod [] { run });

            testClass.Inheritance.Add(new CSIdentifier("ITomTest"));
            testClass.Properties.Add(MakeGetOnlyStringProp("TestName", testName));
            testClass.Properties.Add(MakeGetOnlyStringProp("ExpectedOutput", expectedOutput));
            ns.Block.Add(testClass);
            if (skipReason != null)
            {
                CSArgumentList al = new CSArgumentList();
                al.Add(CSConstant.Val(skipReason));
                CSAttribute attr = new CSAttribute("TomSkip", al);
                attr.AttachBefore(testClass);
            }
            return(new Tuple <CSNamespace, CSUsingPackages> (ns, use));
        }
示例#10
0
		public void UpdateExistingClass()
		{
			var existingClass1 = new CSClass()
			{
				ClassName = "TestClassLeaveAlone",
				NamespaceName = "Test.Namespace",
				PropertyList = new List<CSProperty>() 
				{
					new CSProperty {  TypeName = "int", PropertyName = "TestProperty1" },
					new CSProperty {  TypeName = "int", PropertyName = "TestProperty2" }
				},
				FieldList = new List<CSField>()
				{
					new CSField {  TypeName = "int", FieldName = "TestField1" },
					new CSField {  TypeName = "int", FieldName = "TestField2" }
				}
			};
			var existingClass2 = new CSClass()
			{
				ClassName = "TestClassUpdate",
				NamespaceName = "Test.Namespace",
				PropertyList = new List<CSProperty>() 
				{
					new CSProperty {  TypeName = "int", PropertyName = "TestProperty1" },
					new CSProperty {  TypeName = "int", PropertyName = "TestProperty2" }
				},
				FieldList = new List<CSField>()
				{
					new CSField {  TypeName = "int", FieldName = "TestField1" },
					new CSField {  TypeName = "int", FieldName = "TestField2" }
				}
			};
			List<CSClass> existingClassList = new List<CSClass>() { existingClass1, existingClass2 };
			string data =
			@"
				using System;

				namespace Test.Namespace
				{
					public class TestClassUpdate
					{
						public int TestProperty3 { get; set; }
						public int TestProperty4 { get; set; }

						public int TestField3;
						public int TestField4;
					}
					public class TestClassNew
					{
						public int TestProperty1 { get; set; }
						public int TestProperty2 { get; set; }

						public int TestField1;
						public int TestField2;
					}
				}
			";
			ClassParser parser = new ClassParser();
			var newClassList = parser.ParseString(data, "TestFile.cs", "C:\\Test", existingClassList);

			Assert.AreEqual(3, newClassList.Count);

			var testClassLeaveAlone = newClassList[0];
			Assert.AreEqual("Test.Namespace.TestClassLeaveAlone", testClassLeaveAlone.ClassFullName);
			Assert.AreEqual(2, testClassLeaveAlone.PropertyList.Count);
			Assert.AreEqual("TestProperty1", testClassLeaveAlone.PropertyList[0].PropertyName);
			Assert.AreEqual("TestProperty2", testClassLeaveAlone.PropertyList[1].PropertyName);
			Assert.AreEqual(2, testClassLeaveAlone.FieldList.Count);
			Assert.AreEqual("TestField1", testClassLeaveAlone.FieldList[0].FieldName);
			Assert.AreEqual("TestField2", testClassLeaveAlone.FieldList[1].FieldName);

			var testClassUpdate = newClassList[1];
			Assert.AreEqual("Test.Namespace.TestClassUpdate", testClassUpdate.ClassFullName);
			Assert.AreEqual(4, testClassUpdate.PropertyList.Count);
			Assert.AreEqual("TestProperty1", testClassUpdate.PropertyList[0].PropertyName);
			Assert.AreEqual("TestProperty2", testClassUpdate.PropertyList[1].PropertyName);
			Assert.AreEqual("TestProperty3", testClassUpdate.PropertyList[2].PropertyName);
			Assert.AreEqual("TestProperty4", testClassUpdate.PropertyList[3].PropertyName);
			Assert.AreEqual(4, testClassUpdate.FieldList.Count);
			Assert.AreEqual("TestField1", testClassUpdate.FieldList[0].FieldName);
			Assert.AreEqual("TestField2", testClassUpdate.FieldList[1].FieldName);
			Assert.AreEqual("TestField3", testClassUpdate.FieldList[2].FieldName);
			Assert.AreEqual("TestField4", testClassUpdate.FieldList[3].FieldName);

			var testClassNew = newClassList[2];
			Assert.AreEqual("Test.Namespace.TestClassNew", testClassNew.ClassFullName);
			Assert.AreEqual(2, testClassNew.PropertyList.Count);
			Assert.AreEqual("TestProperty1", testClassNew.PropertyList[0].PropertyName);
			Assert.AreEqual("TestProperty2", testClassNew.PropertyList[1].PropertyName);
			Assert.AreEqual(2, testClassNew.FieldList.Count);
			Assert.AreEqual("TestField1", testClassNew.FieldList[0].FieldName);
			Assert.AreEqual("TestField2", testClassNew.FieldList[1].FieldName);
		}
示例#11
0
		public void TestClassMerge()
		{
			var targetClass = new CSClass()
			{
				ClassName = "TestClass",
				NamespaceName = "Test.Namespace",
				AttributeList = new List<CSAttribute>()
				{
					new CSAttribute { TypeName = "TestAttribute1" },
					new CSAttribute 
					{ 
						TypeName = "TestAttribute2", ArgumentList = new List<CSAttribute.CSAttributeArgument>() 
						{ 
							new CSAttribute.CSAttributeArgument
							{
								ArgumentName = "TestArgumentName",
								ArguementValue = "TestArgumentValue"
							}
						}
					}
				},
				PropertyList = new List<CSProperty>() 
				{
					new CSProperty {  TypeName = "int", PropertyName = "TestProperty1" },
					new CSProperty {  TypeName = "int", PropertyName = "TestProperty2" }
				},
				FieldList = new List<CSField>()
				{
					new CSField {  TypeName = "int", FieldName = "TestField1" },
					new CSField {  TypeName = "int", FieldName = "TestField2" }
				}
			};
			var newClass = new CSClass()
			{
				ClassName = "TestClass",
				NamespaceName = "Test.Namespace",
				AttributeList = new List<CSAttribute>()
				{
					new CSAttribute { TypeName = "TestAttribute3" }
				},
				PropertyList = new List<CSProperty>() 
				{
					new CSProperty {  TypeName = "int", PropertyName = "TestProperty3" },
				},
				FieldList = new List<CSField>()
				{
					new CSField {  TypeName = "int", FieldName = "TestField3" },
				}
			};
			var wrongClass = new CSClass()
			{
				ClassName = "TestClass2",
				NamespaceName = "Test.Namespace",
				PropertyList = new List<CSProperty>() 
				{
					new CSProperty {  TypeName = "int", PropertyName = "TestProperty1" },
					new CSProperty {  TypeName = "int", PropertyName = "TestProperty2" }
				},
				FieldList = new List<CSField>()
				{
					new CSField {  TypeName = "int", FieldName = "TestField1" },
					new CSField {  TypeName = "int", FieldName = "TestField2" }
				}
			};

			Assert.Throws(typeof(ArgumentException), delegate { targetClass.Merge(wrongClass); });

			targetClass.Merge(newClass);
			Assert.AreEqual("Test.Namespace.TestClass", targetClass.ClassFullName);

			Assert.AreEqual(3, targetClass.AttributeList.Count);
			Assert.AreEqual("TestAttribute1", targetClass.AttributeList[0].TypeFullName);
			Assert.AreEqual(0, targetClass.AttributeList[0].ArgumentList.Count);
			Assert.AreEqual("TestAttribute2", targetClass.AttributeList[1].TypeFullName);
			Assert.AreEqual(1, targetClass.AttributeList[1].ArgumentList.Count);
			Assert.AreEqual("TestArgumentName", targetClass.AttributeList[1].ArgumentList[0].ArgumentName);
			Assert.AreEqual("TestArgumentValue", targetClass.AttributeList[1].ArgumentList[0].ArguementValue);
			Assert.AreEqual("TestAttribute3", targetClass.AttributeList[2].TypeFullName);
			Assert.AreEqual(0, targetClass.AttributeList[2].ArgumentList.Count);

			Assert.AreEqual(3, targetClass.PropertyList.Count);
			Assert.AreEqual("TestProperty1", targetClass.PropertyList[0].PropertyName);
			Assert.AreEqual("TestProperty2", targetClass.PropertyList[1].PropertyName);
			Assert.AreEqual("TestProperty3", targetClass.PropertyList[2].PropertyName);

			Assert.AreEqual(3, targetClass.FieldList.Count);
			Assert.AreEqual("TestField1", targetClass.FieldList[0].FieldName);
			Assert.AreEqual("TestField2", targetClass.FieldList[1].FieldName);
			Assert.AreEqual("TestField3", targetClass.FieldList[2].FieldName);
		}
            public void BasicTargetClassTest()
            {
                CSClass csClass = new CSClass()
                {
                    ClassFullName = "Test.Target.TargetClassName",
                    AttributeList = new List <CSAttribute>()
                    {
                        new CSAttribute
                        {
                            TypeFullName = typeof(UIClientPageAttribute).FullName,
                            ArgumentList = new List <CSAttribute.CSAttributeArgument>()
                            {
                                new CSAttribute.CSAttributeArgument {
                                    ArgumentName = "sourceClassFullName", ArguementValue = "Test.Test1.SourceClassFullNameValue"
                                }                                                                                                                                                                   //,
                                //new CSAttribute.CSAttributeArgument { ArgumentName = "ExpectedUrl", ArguementValue = "SourceClassFullName.aspx" }
                            }
                        }
                    },
                    FileRelativePathList = new List <string>()
                    {
                        "TargetClassName.aspx.designer.cs",
                        "TargetClassName.aspx.cs"
                    },
                    PropertyList = new List <CSProperty>()
                    {
                        new CSProperty()
                        {
                            TypeFullName    = typeof(WatiN.Core.Link).FullName,
                            PropertyName    = "TestLink",
                            ProtectionLevel = EnumProtectionLevel.Public,
                            AttributeList   = new List <CSAttribute>()
                            {
                                new CSAttribute()
                                {
                                    TypeFullName = typeof(UIClientPropertyAttribute).FullName,
                                    ArgumentList = new List <CSAttribute.CSAttributeArgument>()
                                    {
                                        new CSAttribute.CSAttributeArgument()
                                        {
                                            ArgumentName = "sourceFieldTypeFullName", ArguementValue = typeof(System.Web.UI.WebControls.HyperLink).FullName
                                        },
                                        new CSAttribute.CSAttributeArgument()
                                        {
                                            ArgumentName = "sourceFieldName", ArguementValue = "TestLink"
                                        }
                                    }
                                }
                            }
                        },
                        new CSProperty()
                        {
                            TypeFullName    = typeof(WatiN.Core.TextField).FullName,
                            PropertyName    = "TestTextBox",
                            ProtectionLevel = EnumProtectionLevel.Public,
                            AttributeList   = new List <CSAttribute>()
                            {
                                new CSAttribute()
                                {
                                    TypeFullName = typeof(UIClientPropertyAttribute).FullName,
                                    ArgumentList = new List <CSAttribute.CSAttributeArgument>()
                                    {
                                        new CSAttribute.CSAttributeArgument()
                                        {
                                            ArgumentName = "sourceFieldTypeFullName", ArguementValue = typeof(System.Web.UI.WebControls.TextBox).FullName
                                        },
                                        new CSAttribute.CSAttributeArgument()
                                        {
                                            ArgumentName = "sourceFieldName", ArguementValue = "TestTextBox"
                                        }
                                    }
                                }
                            }
                        },
                    }
                };
                var targetClassManager = new TargetClassManager();
                var targetClass        = targetClassManager.TryLoadTargetClass(csClass);

                Assert.IsNotNull(targetClass);
                Assert.AreEqual("Test.Test1.SourceClassFullNameValue", targetClass.SourceClassFullName);
                Assert.AreEqual("Test.Target.TargetClassName", targetClass.TargetClassFullName);
                Assert.AreEqual(2, targetClass.TargetFieldList.Count);
                TestValidators.ValidateTargetField(targetField: targetClass.TargetFieldList[0],
                                                   isDirty: false,
                                                   sourceClassFullName: "System.Web.UI.WebControls.HyperLink",
                                                   sourceFieldName: "TestLink",
                                                   targetControlType: EnumTargetControlType.Link,
                                                   targetFieldName: "TestLink");
                TestValidators.ValidateTargetField(targetField: targetClass.TargetFieldList[1],
                                                   isDirty: false,
                                                   sourceClassFullName: "System.Web.UI.WebControls.TextBox",
                                                   sourceFieldName: "TestTextBox",
                                                   targetControlType: EnumTargetControlType.TextBox,
                                                   targetFieldName: "TestTextBox");
                //Assert.AreEqual("SourceClassFullName.aspx", targetClass.ExpectedUrl);
            }
示例#13
0
        static void WriteStyles(int counterIndex, List <string> tokens, DOMStyle[] styles, CSMethod constructor, CSClass @class)
        {
            for (int i = 0; i < styles.Length; i++)
            {
                tokens.Clear();
                var style = styles[i];

                ParseGUILayoutTokens(style, tokens);

                var buildMethod = new CSMethod(Scope.Private, "Style", "BuildStyle" + ++counterIndex);
                @class.AddMethod(buildMethod);

                if (tokens.Count > 0)
                {
                    if (!string.IsNullOrEmpty(style.name))
                    {
                        constructor.AddBodyLine(string.Format("SetClassStyle(\"{0}\", {1}());", style.name, buildMethod.name));
                    }
                    if (!string.IsNullOrEmpty(style.elementType))
                    {
                        constructor.AddBodyLine(string.Format("SetClassStyle(typeof({0}), {1}());", style.elementType, buildMethod.name));
                    }
                }

                buildMethod.AddBodyLine("var s = new Style();");
                for (int j = 0; j < tokens.Count; j++)
                {
                    buildMethod.AddBodyLine(tokens[j] + ";");
                }
                buildMethod.AddBodyLine("return s;");
            }
        }
        public void ClassLess()
        {
            // Note for future Steve
            // If an argument is a protocol with associated types, the calling conventions are different.
            // Typically, if a function accepts a protocol type as its argument it gets passed in as an existential
            // container.
            // It appears that if a function is generic with a protocol constraint then the argument gets
            // passed in as a pointer to the type then with the attendant metadata and protocol witness table
            // As a result, this code crashes since we're passing in the wrong type as far as I can tell.
            // This clearly needs more investigation

            var swiftCode =
                $"public func isLessClass<T:Comparable>(a: T, b: T) -> Bool {{\n" +
                "    return a < b\n" +
                "}\n";

            var lessClass = new CSClass(CSVisibility.Public, "LessClass");

            lessClass.Inheritance.Add(new CSIdentifier("ISwiftComparable"));
            var field = CSVariableDeclaration.VarLine(CSSimpleType.Int, "X");

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

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

            lessClass.Constructors.Add(ctor);


            var eqParms = new CSParameterList();

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

            lessClass.Methods.Add(opEquals);


            var lessParms = new CSParameterList();

            lessParms.Add(new CSParameter(new CSSimpleType("ISwiftComparable"), new CSIdentifier("other")));
            var lessCastLine = CSVariableDeclaration.VarLine(new CSSimpleType("LessClass"), "otherLessClass",
                                                             new CSBinaryExpression(CSBinaryOperator.As, new CSIdentifier("other"), new CSIdentifier("LessClass")));

            nonNull    = new CSBinaryExpression(CSBinaryOperator.NotEqual, new CSIdentifier("otherLessClass"), CSConstant.Null);
            valsEq     = new CSBinaryExpression(CSBinaryOperator.Less, new CSIdentifier("otherLessClass.X"), new CSIdentifier("X"));
            returnLine = CSReturn.ReturnLine(new CSBinaryExpression(CSBinaryOperator.And, nonNull, valsEq));
            var opLess = new CSMethod(CSVisibility.Public, CSMethodKind.None, CSSimpleType.Bool, new CSIdentifier("OpLess"), lessParms,
                                      CSCodeBlock.Create(lessCastLine, returnLine));

            lessClass.Methods.Add(opLess);


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

            TestRunning.TestAndExecute(swiftCode, callingCode, "False\n", otherClass: lessClass, platform: PlatformName.macOS);
        }
示例#15
0
        public void TestClassMerge()
        {
            var targetClass = new CSClass()
            {
                ClassName     = "TestClass",
                NamespaceName = "Test.Namespace",
                AttributeList = new List <CSAttribute>()
                {
                    new CSAttribute {
                        TypeName = "TestAttribute1"
                    },
                    new CSAttribute
                    {
                        TypeName = "TestAttribute2", ArgumentList = new List <CSAttribute.CSAttributeArgument>()
                        {
                            new CSAttribute.CSAttributeArgument
                            {
                                ArgumentName   = "TestArgumentName",
                                ArguementValue = "TestArgumentValue"
                            }
                        }
                    }
                },
                PropertyList = new List <CSProperty>()
                {
                    new CSProperty {
                        TypeName = "int", PropertyName = "TestProperty1"
                    },
                    new CSProperty {
                        TypeName = "int", PropertyName = "TestProperty2"
                    }
                },
                FieldList = new List <CSField>()
                {
                    new CSField {
                        TypeName = "int", FieldName = "TestField1"
                    },
                    new CSField {
                        TypeName = "int", FieldName = "TestField2"
                    }
                }
            };
            var newClass = new CSClass()
            {
                ClassName     = "TestClass",
                NamespaceName = "Test.Namespace",
                AttributeList = new List <CSAttribute>()
                {
                    new CSAttribute {
                        TypeName = "TestAttribute3"
                    }
                },
                PropertyList = new List <CSProperty>()
                {
                    new CSProperty {
                        TypeName = "int", PropertyName = "TestProperty3"
                    },
                },
                FieldList = new List <CSField>()
                {
                    new CSField {
                        TypeName = "int", FieldName = "TestField3"
                    },
                }
            };
            var wrongClass = new CSClass()
            {
                ClassName     = "TestClass2",
                NamespaceName = "Test.Namespace",
                PropertyList  = new List <CSProperty>()
                {
                    new CSProperty {
                        TypeName = "int", PropertyName = "TestProperty1"
                    },
                    new CSProperty {
                        TypeName = "int", PropertyName = "TestProperty2"
                    }
                },
                FieldList = new List <CSField>()
                {
                    new CSField {
                        TypeName = "int", FieldName = "TestField1"
                    },
                    new CSField {
                        TypeName = "int", FieldName = "TestField2"
                    }
                }
            };

            Assert.Throws(typeof(ArgumentException), delegate { targetClass.Merge(wrongClass); });

            targetClass.Merge(newClass);
            Assert.AreEqual("Test.Namespace.TestClass", targetClass.ClassFullName);

            Assert.AreEqual(3, targetClass.AttributeList.Count);
            Assert.AreEqual("TestAttribute1", targetClass.AttributeList[0].TypeFullName);
            Assert.AreEqual(0, targetClass.AttributeList[0].ArgumentList.Count);
            Assert.AreEqual("TestAttribute2", targetClass.AttributeList[1].TypeFullName);
            Assert.AreEqual(1, targetClass.AttributeList[1].ArgumentList.Count);
            Assert.AreEqual("TestArgumentName", targetClass.AttributeList[1].ArgumentList[0].ArgumentName);
            Assert.AreEqual("TestArgumentValue", targetClass.AttributeList[1].ArgumentList[0].ArguementValue);
            Assert.AreEqual("TestAttribute3", targetClass.AttributeList[2].TypeFullName);
            Assert.AreEqual(0, targetClass.AttributeList[2].ArgumentList.Count);

            Assert.AreEqual(3, targetClass.PropertyList.Count);
            Assert.AreEqual("TestProperty1", targetClass.PropertyList[0].PropertyName);
            Assert.AreEqual("TestProperty2", targetClass.PropertyList[1].PropertyName);
            Assert.AreEqual("TestProperty3", targetClass.PropertyList[2].PropertyName);

            Assert.AreEqual(3, targetClass.FieldList.Count);
            Assert.AreEqual("TestField1", targetClass.FieldList[0].FieldName);
            Assert.AreEqual("TestField2", targetClass.FieldList[1].FieldName);
            Assert.AreEqual("TestField3", targetClass.FieldList[2].FieldName);
        }
示例#16
0
        public void UpdateExistingClass()
        {
            var existingClass1 = new CSClass()
            {
                ClassName     = "TestClassLeaveAlone",
                NamespaceName = "Test.Namespace",
                PropertyList  = new List <CSProperty>()
                {
                    new CSProperty {
                        TypeName = "int", PropertyName = "TestProperty1"
                    },
                    new CSProperty {
                        TypeName = "int", PropertyName = "TestProperty2"
                    }
                },
                FieldList = new List <CSField>()
                {
                    new CSField {
                        TypeName = "int", FieldName = "TestField1"
                    },
                    new CSField {
                        TypeName = "int", FieldName = "TestField2"
                    }
                }
            };
            var existingClass2 = new CSClass()
            {
                ClassName     = "TestClassUpdate",
                NamespaceName = "Test.Namespace",
                PropertyList  = new List <CSProperty>()
                {
                    new CSProperty {
                        TypeName = "int", PropertyName = "TestProperty1"
                    },
                    new CSProperty {
                        TypeName = "int", PropertyName = "TestProperty2"
                    }
                },
                FieldList = new List <CSField>()
                {
                    new CSField {
                        TypeName = "int", FieldName = "TestField1"
                    },
                    new CSField {
                        TypeName = "int", FieldName = "TestField2"
                    }
                }
            };
            List <CSClass> existingClassList = new List <CSClass>()
            {
                existingClass1, existingClass2
            };
            string data =
                @"
				using System;

				namespace Test.Namespace
				{
					public class TestClassUpdate
					{
						public int TestProperty3 { get; set; }
						public int TestProperty4 { get; set; }

						public int TestField3;
						public int TestField4;
					}
					public class TestClassNew
					{
						public int TestProperty1 { get; set; }
						public int TestProperty2 { get; set; }

						public int TestField1;
						public int TestField2;
					}
				}
			"            ;
            ClassParser parser       = new ClassParser();
            var         newClassList = parser.ParseString(data, "TestFile.cs", "C:\\Test", existingClassList);

            Assert.AreEqual(3, newClassList.Count);

            var testClassLeaveAlone = newClassList[0];

            Assert.AreEqual("Test.Namespace.TestClassLeaveAlone", testClassLeaveAlone.ClassFullName);
            Assert.AreEqual(2, testClassLeaveAlone.PropertyList.Count);
            Assert.AreEqual("TestProperty1", testClassLeaveAlone.PropertyList[0].PropertyName);
            Assert.AreEqual("TestProperty2", testClassLeaveAlone.PropertyList[1].PropertyName);
            Assert.AreEqual(2, testClassLeaveAlone.FieldList.Count);
            Assert.AreEqual("TestField1", testClassLeaveAlone.FieldList[0].FieldName);
            Assert.AreEqual("TestField2", testClassLeaveAlone.FieldList[1].FieldName);

            var testClassUpdate = newClassList[1];

            Assert.AreEqual("Test.Namespace.TestClassUpdate", testClassUpdate.ClassFullName);
            Assert.AreEqual(4, testClassUpdate.PropertyList.Count);
            Assert.AreEqual("TestProperty1", testClassUpdate.PropertyList[0].PropertyName);
            Assert.AreEqual("TestProperty2", testClassUpdate.PropertyList[1].PropertyName);
            Assert.AreEqual("TestProperty3", testClassUpdate.PropertyList[2].PropertyName);
            Assert.AreEqual("TestProperty4", testClassUpdate.PropertyList[3].PropertyName);
            Assert.AreEqual(4, testClassUpdate.FieldList.Count);
            Assert.AreEqual("TestField1", testClassUpdate.FieldList[0].FieldName);
            Assert.AreEqual("TestField2", testClassUpdate.FieldList[1].FieldName);
            Assert.AreEqual("TestField3", testClassUpdate.FieldList[2].FieldName);
            Assert.AreEqual("TestField4", testClassUpdate.FieldList[3].FieldName);

            var testClassNew = newClassList[2];

            Assert.AreEqual("Test.Namespace.TestClassNew", testClassNew.ClassFullName);
            Assert.AreEqual(2, testClassNew.PropertyList.Count);
            Assert.AreEqual("TestProperty1", testClassNew.PropertyList[0].PropertyName);
            Assert.AreEqual("TestProperty2", testClassNew.PropertyList[1].PropertyName);
            Assert.AreEqual(2, testClassNew.FieldList.Count);
            Assert.AreEqual("TestField1", testClassNew.FieldList[0].FieldName);
            Assert.AreEqual("TestField2", testClassNew.FieldList[1].FieldName);
        }
        public static void TestAndExecute(string swiftCode, CodeElementCollection <ICodeElement> callingCode,
                                          string expectedOutput,
                                          string testName                  = null,
                                          CSClass otherClass               = null, string skipReason = null,
                                          string iosExpectedOutput         = null,
                                          PlatformName platform            = PlatformName.None,
                                          UnicodeMapper unicodeMapper      = null, int expectedErrorCount = 0,
                                          Action <string> postCompileCheck = null,
                                          string[] expectedOutputContains  = null)
        {
            SetInvokingTestNameIfUnset(ref testName, out string nameSpace);
            string testClassName = "TomTest" + testName;

            using (var provider = new DisposableTempDirectory()) {
                var compiler = Utils.CompileSwift(swiftCode, provider, nameSpace);

                var libName           = $"lib{nameSpace}.dylib";
                var tempDirectoryPath = Path.Combine(provider.DirectoryPath, "BuildDir");
                Directory.CreateDirectory(tempDirectoryPath);
                File.Copy(Path.Combine(compiler.DirectoryPath, libName), Path.Combine(tempDirectoryPath, libName));

                Utils.CompileToCSharp(provider, tempDirectoryPath, nameSpace, unicodeMapper: unicodeMapper, expectedErrorCount: expectedErrorCount);
                if (postCompileCheck != null)
                {
                    postCompileCheck(tempDirectoryPath);
                }

                Tuple <CSNamespace, CSUsingPackages> testClassParts = TestRunningCodeGenerator.CreateTestClass(callingCode, testName, iosExpectedOutput ?? expectedOutput, nameSpace,
                                                                                                               testClassName, otherClass, skipReason, platform);

                var thisTestPath = Path.Combine(Compiler.kSwiftDeviceTestRoot, nameSpace);
                Directory.CreateDirectory(thisTestPath);

                var thisTestPathSwift = Path.Combine(thisTestPath, "swiftsrc");
                Directory.CreateDirectory(thisTestPathSwift);

                var swiftPrefix = string.Empty;
                var swiftSuffix = string.Empty;
                var csPrefix    = string.Empty;
                var csSuffix    = string.Empty;
                var nameSuffix  = string.Empty;
                switch (platform)
                {
                case PlatformName.macOS:
                    swiftPrefix = "#if os(OSX)\n";
                    swiftSuffix = "#endif\n";
                    csPrefix    = "#if __MACOS__\n";
                    csSuffix    = "\n#endif\n";
                    nameSuffix  = "_macOS";
                    break;

                case PlatformName.iOS:
                    swiftPrefix = "#if os(iOS)\n";
                    swiftSuffix = "#endif\n";
                    csPrefix    = "#if __IOS__\n";
                    csSuffix    = "\n#endif\n";
                    nameSuffix  = "_iOS";
                    break;

                case PlatformName.tvOS:
                    swiftPrefix = "#if os(tvOS)\n";
                    swiftSuffix = "#endif\n";
                    csPrefix    = "#if __TVOS__\n";
                    csSuffix    = "\n#endif\n";
                    nameSuffix  = "_tvOS";
                    break;

                case PlatformName.watchOS:
                    swiftPrefix = "#if os(watchOS)\n";
                    swiftSuffix = "#endif\n";
                    csPrefix    = "#if __WATCHOS__\n";
                    csSuffix    = "\n#endif\n";
                    nameSuffix  = "_watchOS";
                    break;

                case PlatformName.None:
                    break;

                default:
                    throw new NotImplementedException(platform.ToString());
                }

                File.WriteAllText(Path.Combine(thisTestPathSwift, $"{testClassName}{testName}{nameSuffix}.swift"), swiftPrefix + swiftCode + swiftSuffix);

                CSFile csTestFile     = CSFile.Create(testClassParts.Item2, testClassParts.Item1);
                var    csTestFilePath = Path.Combine(thisTestPath, $"{testClassName}{testName}{nameSuffix}.cs");
                // Write out the file without csPrefix/csSuffix
                CodeWriter.WriteToFile(csTestFilePath, csTestFile);
                if (!string.IsNullOrEmpty(csPrefix) || !string.IsNullOrEmpty(csSuffix))
                {
                    // Read the C# code, and prepend/append the csPrefix/csSuffix blobs, then save the modified contents again.
                    File.WriteAllText(csTestFilePath, csPrefix + File.ReadAllText(csTestFilePath) + csSuffix);
                }

                var csFile = TestRunningCodeGenerator.GenerateTestEntry(callingCode, testName, nameSpace, platform, otherClass);
                csFile.Namespaces.Add(CreateManagedConsoleRedirect());
                CodeWriter.WriteToFile(Path.Combine(tempDirectoryPath, "NameNotImportant.cs"), csFile);

                var sourceFiles     = Directory.GetFiles(tempDirectoryPath, "*.cs");
                var objcRuntimePath = Path.Combine(tempDirectoryPath, "ObjCRuntime");
                if (Directory.Exists(objcRuntimePath))
                {
                    sourceFiles = sourceFiles.And(Directory.GetFiles(objcRuntimePath, "*.cs"));
                }

                var compilerWarnings = Compiler.CSCompile(tempDirectoryPath, sourceFiles, "NameNotImportant.exe", platform: platform);

                if (compilerWarnings.Contains("warning"))
                {
                    FailOnBadWarnings(compilerWarnings);
                }

                CopyTestReferencesTo(tempDirectoryPath, platform);

                var output = Execute(tempDirectoryPath, "NameNotImportant.exe", platform);
                if (expectedOutput != null)
                {
                    Assert.AreEqual(expectedOutput, output);
                }
                else
                {
                    foreach (var s in expectedOutputContains)
                    {
                        Assert.IsTrue(output.Contains(s), $"Expected to find string {s} in {output}");
                    }
                }
            }
        }
        static CSFile GeneratePInvokesFromTypes(TypeAggregator types, PlatformName platform, string framework)
        {
            var fileName  = Path.GetFileNameWithoutExtension(framework);             // /path/XamGlue.framework -> XamGlue
            var dylibFile = Path.Combine(framework, fileName);
            var funcs     = TLFunctionsForFile(dylibFile, platform);

            var ns  = new CSNamespace("SwiftRuntimeLibrary.SwiftMarshal");
            var use = new CSUsingPackages();

            use.And(new CSUsing("System.Runtime.InteropServices"))
            .And(new CSUsing("System"))
            .And(new CSUsing("System.Collections.Generic"))
            .And(new CSUsing("SwiftRuntimeLibrary"));

            var csFile  = new CSFile(use, new CSNamespace [] { ns });
            var csClass = new CSClass(CSVisibility.Internal, $"{fileName}Metadata");

            new CSComment(kRobotText).AttachBefore(use);

            CSConditionalCompilation.If(PlatformToCSCondition(platform)).AttachBefore(use);
            CSConditionalCompilation.Endif.AttachAfter(ns);
            ns.Block.Add(csClass);

            var typeOntoPinvoke = new List <KeyValuePair <CSBaseExpression, CSBaseExpression> > ();

            var typesToProcess = new List <TypeDefinition> ();

            typesToProcess.AddRange(types.PublicEnums);
            typesToProcess.AddRange(types.PublicStructs);

            // pre-sort by function name
            typesToProcess.Sort((type1, type2) => String.CompareOrdinal(FuncIDForTypeDefinition(type1), FuncIDForTypeDefinition(type2)));

            foreach (var type in typesToProcess)
            {
                if (type.HasGenericParameters)
                {
                    continue;
                }
                var moduleName = type.Namespace;
                var name       = type.Name;
                if (TypeAggregator.FilterModuleAndName(platform, moduleName, ref name))
                {
                    var pinvoke = PInvokeForType(type, funcs);
                    if (pinvoke != null)
                    {
                        csClass.Methods.Add(pinvoke);
                        use.AddIfNotPresent(type.Namespace);
                        var typeOf   = new CSSimpleType(type.FullName).Typeof();
                        var funcName = pinvoke.Name;
                        typeOntoPinvoke.Add(new KeyValuePair <CSBaseExpression, CSBaseExpression> (typeOf, funcName));
                    }
                }
            }

            var initializers = typeOntoPinvoke.Select(typeAndFunc => new CSInitializer(new CSBaseExpression [] { typeAndFunc.Key, typeAndFunc.Value }, false));
            var bindingExpr  = new CSInitializedType(new CSFunctionCall("Dictionary<Type, Func<SwiftMetatype>>", true), new CSInitializer(initializers, true));
            var bindingDecl  = new CSFieldDeclaration(new CSSimpleType("Dictionary<Type, Func<SwiftMetatype>>"), "ObjCBindingSwiftMetatypes", bindingExpr, CSVisibility.Internal, true);

            csClass.Fields.Add(new CSLine(bindingDecl));

            use.Sort((package1, package2) => String.CompareOrdinal(package1.Package, package2.Package));

            return(csFile);
        }
        public static CSFile GenerateTestEntry(CodeElementCollection <ICodeElement> callingCode, string testName, string nameSpace, PlatformName platform, CSClass otherClass = null)
        {
            var use = GetTestEntryPointUsings(nameSpace, platform);

            var ns = new CSNamespace(nameSpace);

            if (otherClass != null)
            {
                ns.Block.Add(otherClass);
            }

            var mainBody = new CSCodeBlock(callingCode);

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

            AddSupportingCode(mainClass, platform);

            ns.Block.Add(mainClass);

            return(CSFile.Create(use, ns));
        }
        public CSStatement Translate(Statement value, CSClass csClassRef, bool functionNested = false)
        {
            if (value is ExpressionStatement)
            {
                var statementExpression = (ExpressionStatement)value;
                return(new CSExpressionStatement(Translate(statementExpression.Expression, csClassRef)));
            }
            else if (value is ReturnStatement)
            {
                var statementReturn = (ReturnStatement)value;
                return(new CSReturnStatement(Translate(statementReturn.Argument, csClassRef)));
            }
            else if (value is IfStatement)
            {
                var statementIf = (IfStatement)value;
                IEnumerable <CSStatement> consequent = Translate(GetBlockStatement(statementIf.Consequent), csClassRef);
                CSExpression test = Translate(statementIf.Test, csClassRef);
                IEnumerable <CSStatement> alternate = null;
                if (statementIf.Alternate != null)
                {
                    alternate = Translate(GetBlockStatement(statementIf.Alternate), csClassRef);
                }
                return(new CSIfStatement
                {
                    alternate = alternate,
                    consequent = consequent,
                    test = test
                });
            }
            else if (value is WhileStatement)
            {
                var statementWhile             = (WhileStatement)value;
                IEnumerable <CSStatement> body = Translate(GetBlockStatement(statementWhile.Body), csClassRef);
                CSExpression test = Translate(statementWhile.Test, csClassRef);
                return(new CSWhileStatement
                {
                    body = body,
                    @do = false,
                    test = test
                });
            }
            else if (value is ForStatement)
            {
                var statementFor = (ForStatement)value;
                var body         = Translate(GetBlockStatement(statementFor.Body), csClassRef);
                var init         = Translate(statementFor.Init, csClassRef);
                var test         = Translate(statementFor.Test, csClassRef);
                var update       = Translate(statementFor.Update, csClassRef);
                return(new CSForStatement
                {
                    body = body,
                    init = init,
                    test = test,
                    update = update
                });
            }
            else if (value is DoWhileStatement)
            {
                var statementDoWhile           = (DoWhileStatement)value;
                IEnumerable <CSStatement> body = Translate(GetBlockStatement(statementDoWhile.Body), csClassRef);
                CSExpression test = Translate(statementDoWhile.Test, csClassRef);
                return(new CSWhileStatement
                {
                    body = body,
                    @do = true,
                    test = test
                });
            }
            else if (value is EmptyStatement)
            {
                return(new CSEmptyStatement(true));
            }
            else if (value is VariableDeclaration)
            {
                var statementVariableDeclaration = (VariableDeclaration)value;
                var varDeclTrans = statementVariableDeclaration.Declarations.ToList().ConvertAll(v => new CSVariableDeclaration.VariableDeclarator
                {
                    id = new CSIdentifier {
                        name = v.Id.Name
                    },
                    type = "object"
                });

                var init = Translate(statementVariableDeclaration.Declarations.Last().Init, csClassRef);

                if (functionNested)
                {
                    return new CSVariableDeclaration
                           {
                               setTo = init,
                               value = varDeclTrans
                           }
                }
                ;
                else
                {
                    csClassRef.declarables.Add(new CSStaticVariable
                    {
                        value = statementVariableDeclaration.Declarations.ToList().ConvertAll(v => Translate(v, csClassRef)),
                        setTo = init
                    });

                    return(new CSEmptyStatement(false));
                }
            }
            else if (value is ForInStatement)
            {
                var           statementForIn = (ForInStatement)value;
                string        left           = null;
                ForInLeftType type           = ForInLeftType.String;
                if (statementForIn.Left is VariableDeclaration)
                {
                    left = "\"" + ((VariableDeclaration)statementForIn.Left).Declarations.First().Id.Name + "\"";
                }
                else if (statementForIn.Right is Expression)
                {
                    type = ForInLeftType.OutString;
                    left = "out " + Translate((Expression)statementForIn.Left, csClassRef).GenerateCS();
                }
                var right = Translate(statementForIn.Right, csClassRef);
                var body  = GetBlockStatement(statementForIn.Body).ConvertAll(v => Translate(v, csClassRef));
                IfNeccessaryGenerateTemplateFunction(csClassRef, new TemplateObj
                {
                    name       = "ForIn",
                    parameters = new List <CSFunction.Parameter>
                    {
                        new CSFunction.Parameter("left", type == ForInLeftType.String ? "string" : "out string"),
                        new CSFunction.Parameter("right", "object"),
                        new CSFunction.Parameter("body", "Action<string>")
                    },
                    returnType   = "void",
                    templateText = type == ForInLeftType.String ? "for (var {left:raw} in {right})\\n{body}({left:raw})" : "for ({left}.v in {right})\\n{body}({left}.v)",
                });
                return(new CSExpressionStatement(
                           new CSCallExpression
                {
                    callee = new CSMemberExpression
                    {
                        @object = new CSIdentifier {
                            name = "Program"
                        },
                        property = "ForIn"
                    },
                    arguments = new CSExpression[] { new CSLiteral(left), right, new CSFunction {
                                                         blocks = body, parameters = new List <CSFunction.Parameter> {
                                                             new CSFunction.Parameter(left.Split(' ').Last().Replace("\"", ""), "string")
                                                         }
                                                     } }
                }));
            }
            throw new NotImplementedException();
        }
        public static CSNamespace CreateManagedConsoleRedirect()
        {
            // Same as GetManagedConsoleRedirectCode, just different format.
            var cs = new CSNamespace();

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

            console.Fields.Add(CSFieldDeclaration.FieldLine(CSSimpleType.String, new CSIdentifier("filename"), isStatic: true));
            console.Properties.Add(
                new CSProperty(
                    CSSimpleType.String,
                    CSMethodKind.Static,
                    new CSIdentifier("Filename"),
                    CSVisibility.None,
                    CSCodeBlock.Create(
                        new CSIfElse(
                            new CSBinaryExpression(
                                CSBinaryOperator.Equal,
                                new CSIdentifier("filename"),
                                new CSIdentifier("null")
                                ),
                            CSCodeBlock.Create(
                                CSAssignment.Assign(
                                    new CSIdentifier("filename"),
                                    new CSBinaryExpression(
                                        CSBinaryOperator.NullCoalesce,
                                        CSFunctionCall.Function(
                                            "Environment.GetEnvironmentVariable",
                                            CSConstant.Val("LEAKTEST_STDOUT_PATH")
                                            ),
                                        new CSIdentifier("string.Empty")
                                        )
                                    )
                                )
                            ),
                        CSReturn.ReturnLine(new CSIdentifier("filename"))
                        ),
                    CSVisibility.None,
                    null
                    )
                );
            console.Methods.Add(
                new CSMethod(
                    CSVisibility.Public,
                    CSMethodKind.Static,
                    CSSimpleType.Void,
                    new CSIdentifier("write"),
                    new CSParameterList(
                        new CSParameter(CSSimpleType.String, new CSIdentifier("value"))
                        ),
                    CSCodeBlock.Create(
                        new CSIfElse(
                            new CSIdentifier("string.IsNullOrEmpty (Filename)"),
                            CSCodeBlock.Create(CSFunctionCall.FunctionCallLine("global::System.Console.Write", new CSIdentifier("value"))),
                            CSCodeBlock.Create(CSFunctionCall.FunctionCallLine("System.IO.File.AppendAllText", new CSIdentifier("Filename"), new CSIdentifier("value")))
                            )
                        )
                    )
                );
            console.Methods.Add(
                new CSMethod(
                    CSVisibility.Public,
                    CSMethodKind.Static,
                    CSSimpleType.Void,
                    new CSIdentifier("Write"),
                    new CSParameterList(
                        new CSParameter(CSSimpleType.Object, new CSIdentifier("value"))
                        ),
                    CSCodeBlock.Create(
                        CSFunctionCall.FunctionCallLine(
                            "write",
                            false,
                            new CSIdentifier("value?.ToString ()")
                            )
                        )
                    )
                );
            console.Methods.Add(
                new CSMethod(
                    CSVisibility.Public,
                    CSMethodKind.Static,
                    CSSimpleType.Void,
                    new CSIdentifier("Write"),
                    new CSParameterList(
                        new CSParameter(CSSimpleType.String, new CSIdentifier("value")),
                        new CSParameter(CSSimpleType.CreateArray("object"), new CSIdentifier("args"), CSParameterKind.Params)
                        ),
                    CSCodeBlock.Create(
                        CSFunctionCall.FunctionCallLine(
                            "write",
                            false,
                            new CSIdentifier("value == null ? string.Empty : string.Format (value, args)")
                            )
                        )
                    )
                );
            console.Methods.Add(
                new CSMethod(
                    CSVisibility.Public,
                    CSMethodKind.Static,
                    CSSimpleType.Void,
                    new CSIdentifier("WriteLine"),
                    new CSParameterList(
                        new CSParameter(CSSimpleType.Object, new CSIdentifier("value"))
                        ),
                    CSCodeBlock.Create(
                        CSFunctionCall.FunctionCallLine(
                            "write",
                            false,
                            new CSIdentifier("value?.ToString () + Environment.NewLine")
                            )
                        )
                    )
                );
            console.Methods.Add(
                new CSMethod(
                    CSVisibility.Public,
                    CSMethodKind.Static,
                    CSSimpleType.Void,
                    new CSIdentifier("WriteLine"),
                    new CSParameterList(
                        new CSParameter(CSSimpleType.String, new CSIdentifier("value")),
                        new CSParameter(CSSimpleType.CreateArray("object"), new CSIdentifier("args"), CSParameterKind.Params)
                        ),
                    CSCodeBlock.Create(
                        CSFunctionCall.FunctionCallLine(
                            "write",
                            false,
                            new CSIdentifier("(value == null ? string.Empty : string.Format (value, args)) + Environment.NewLine")
                            )
                        )
                    )
                );
            cs.Block.Add(console);
            return(cs);
        }
示例#22
0
			public void TestRelativeDependentUponFilePath()
			{
				string data =
				@"<?xml version=""1.0"" encoding=""utf-8""?>
					<Project DefaultTargets=""Build"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" ToolsVersion=""4.0"">
						<ItemGroup>
							<Compile Include=""TestDirectory\TestClass1.aspx.cs"">
								<DependentUpon>TestClass1.aspx</DependentUpon>
							</Compile>
							<Compile Include=""TestDirectory1\TestDirectory2\TestClass2.aspx.cs"">
								<DependentUpon>TestClass2.aspx</DependentUpon>
							</Compile>
						</ItemGroup>
						<ItemGroup>
							<Content Include=""TestDirectory\TestClass1.aspx"" />
							<Content Include=""TestDirectory1\TestDirectory2\TestClass2.aspx"" />
						</ItemGroup>
					</Project>
				";
				Mock<ClassParser> classParser = new Mock<ClassParser>();
				List<CSClass> classList = new List<CSClass>();
				var testClass1 = new CSClass()
				{
					ClassFullName = "Test.Test1.TestClass1"
				};
				var testClass2 = new CSClass()
				{
					ClassFullName = "Test.Test2.TestClass2"
				};
				classList.Add(testClass1);
				classParser.Setup(i => i.ParseFile("C:\\Test\\TestDirectory\\TestClass1.aspx.cs", It.IsAny<string>(), It.IsAny<IEnumerable<CSClass>>()))
							.Returns((string filePath, string projectPath, IEnumerable<CSClass> inputClassList) => AppendClassToList(inputClassList, testClass1));
				classParser.Setup(i => i.ParseFile("C:\\Test\\TestDirectory1\\TestDirectory2\\TestClass2.aspx.cs", It.IsAny<string>(), It.IsAny<IEnumerable<CSClass>>()))
							.Returns((string filePath, string projectPath, IEnumerable<CSClass> inputClassList) => AppendClassToList(inputClassList, testClass2));

				Mock<CSWebFormParser> webFormParser = new Mock<CSWebFormParser>();
				webFormParser.Setup(i => i.ParseFile("C:\\Test\\TestDirectory\\TestClass1.aspx"))
							.Returns(new WebFormContainer { ClassFullName = "Test.Test1.TestClass1", CodeBehindFile = "TestClass1.aspx.cs", ContainerType = EnumWebFormContainerType.WebPage });
				webFormParser.Setup(i => i.ParseFile("C:\\Test\\TestDirectory1\\TestDirectory2\\TestClass2.aspx"))
							.Returns(new WebFormContainer { ClassFullName = "Test.Test2.TestClass2", CodeBehindFile = "TestClass2.aspx.cs", ContainerType = EnumWebFormContainerType.WebPage });

				ProjectParser parser = new ProjectParser(classParser.Object, webFormParser.Object);

				CSProjectFile project = parser.ParseString(data, "C:\\Test\\TestProject.csproj");

				Assert.AreEqual(2, project.ClassList.Count);

				Assert.AreEqual("Test.Test1.TestClass1", project.ClassList[0].ClassFullName);
				Assert.AreEqual("Test.Test2.TestClass2", project.ClassList[1].ClassFullName);

				Assert.AreEqual(2, project.ClassFileDependencyList.Count);
				Assert.AreEqual("Test.Test1.TestClass1", project.ClassFileDependencyList[0].ClassFullName);
				Assert.AreEqual("TestDirectory\\TestClass1.aspx", project.ClassFileDependencyList[0].DependentUponFile);
				Assert.AreEqual("Test.Test2.TestClass2", project.ClassFileDependencyList[1].ClassFullName);
				Assert.AreEqual("TestDirectory1\\TestDirectory2\\TestClass2.aspx", project.ClassFileDependencyList[1].DependentUponFile);

				Assert.AreEqual(2, project.WebFormContainers.Count);

				Assert.AreEqual("Test.Test1.TestClass1", project.WebFormContainers[0].ClassFullName);
				Assert.AreEqual("TestClass1.aspx.cs", project.WebFormContainers[0].CodeBehindFile);
				Assert.AreEqual(EnumWebFormContainerType.WebPage, project.WebFormContainers[0].ContainerType);

				Assert.AreEqual("Test.Test2.TestClass2", project.WebFormContainers[1].ClassFullName);
				Assert.AreEqual("TestClass2.aspx.cs", project.WebFormContainers[1].CodeBehindFile);
				Assert.AreEqual(EnumWebFormContainerType.WebPage, project.WebFormContainers[1].ContainerType);
			}
 static void AddXISpecificInitializationCode(CSClass cl)
 {
     // I'm not sure anything needs to be done.
 }
 public GenerateCSClass()
 {
     InitializeComponent();
     CSClass = new CSClass();
 }
示例#25
0
 public static bool IsTargetClass(CSClass csClass)
 {
     return(csClass.AttributeList.Any(i => i.TypeName == typeof(UIClientPageAttribute).Name && i.TypeNamespace == typeof(UIClientPageAttribute).Namespace));
 }