Exemplo n.º 1
0
        public void Methods()
        {
            string source = @"
                public class MyClass {
                    private void Method1() {
                    }

                    protected void Method2() {
                    }
                }
            ";

            // Getting the AST node
            CSharpSyntaxTree tree = ASTExtractor.Extract(source);

            SyntaxNode             node = new NodeLocator(tree).LocateFirst(typeof(ClassDeclarationSyntax));
            ClassDeclarationSyntax classDeclarationNode = node as ClassDeclarationSyntax;

            // Creating the walker
            var astWalker = MockedClassASTWalker.Create(classDeclarationNode);

            // Getting the translation unit
            astWalker.Walk();

            // Checking
            Assert.IsNotNull(astWalker.ClassDeclaration);

            // Checking members
            Assert.IsNotNull(astWalker.ClassDeclaration.MethodDeclarations);
            Assert.IsTrue(astWalker.ClassDeclaration.MethodDeclarations.Count() > 0);
            Assert.AreEqual(2, astWalker.ClassDeclaration.MethodDeclarations.Count());

            Assert.IsInstanceOfType(astWalker.ClassDeclaration.MethodDeclarations.ElementAt(0), typeof(MethodDeclarationTranslationUnit));
            Assert.IsInstanceOfType(astWalker.ClassDeclaration.MethodDeclarations.ElementAt(1), typeof(MethodDeclarationTranslationUnit));
        }
Exemplo n.º 2
0
        private static void Test(string source)
        {
            // Getting the AST node
            CSharpSyntaxTree tree = ASTExtractor.Extract(source);

            SyntaxNode node = new NodeLocator(tree).LocateFirst(typeof(EnumDeclarationSyntax));
            var        enumDeclarationNode = node as EnumDeclarationSyntax;

            // Creating the walker
            var astWalker = MockedEnumASTWalker.Create(enumDeclarationNode);

            // Getting the translation unit
            astWalker.Walk();

            // Checking
            Assert.IsNotNull(astWalker.EnumDeclaration);

            // Checking signatures
            Assert.IsNotNull(astWalker.EnumDeclaration.Members);
            Assert.IsTrue(astWalker.EnumDeclaration.Members.Count() > 0);
            Assert.AreEqual(3, astWalker.EnumDeclaration.Members.Count());

            Assert.IsInstanceOfType(astWalker.EnumDeclaration.Members.ElementAt(0), typeof(EnumMemberTranslationUnit));
            Assert.IsInstanceOfType(astWalker.EnumDeclaration.Members.ElementAt(1), typeof(EnumMemberTranslationUnit));
            Assert.IsInstanceOfType(astWalker.EnumDeclaration.Members.ElementAt(2), typeof(EnumMemberTranslationUnit));
        }
        public void IsCompatibleVersion_ReturnsTrueFalse(int majorVersion, bool expectedResult)
        {
            var version = new Version(majorVersion, 0);
            var result  = NodeLocator.IsCompatibleVersion(version);

            result.Should().Be(expectedResult);
        }
Exemplo n.º 4
0
        public void TypeFullNameRenderingSemanticModel()
        {
            var tree = CSharpSyntaxTree.ParseText(@"
            using System;
            public class MyClass : IDisposable {
                public void Dispose() { }
            }
            ");

            var node = new NodeLocator(tree).LocateLast(typeof(ClassDeclarationSyntax));

            Assert.IsNotNull(node, string.Format("Node of type `{0}` should be found!",
                                                 typeof(ClassDeclarationSyntax).Name));

            // Loading MSCoreLib
            var compilation = CSharpCompilation.Create("TestAssembly")
                              .AddReferences(
                MetadataReference.CreateFromFile(
                    typeof(object).Assembly.Location))
                              .AddSyntaxTrees(tree);
            var semanticModel = compilation.GetSemanticModel(tree);

            ClassDeclarationSyntax classDeclarationNode = node as ClassDeclarationSyntax;
            BaseTypeSyntax         baseTypeNode         = classDeclarationNode.BaseList.Types.FirstOrDefault();

            TestRetrieveTypeName(baseTypeNode, null, "IDisposable");
            TestRetrieveTypeName(baseTypeNode, semanticModel, "IDisposable");
            TestRetrieveTypeFullName(baseTypeNode, null, "IDisposable");
            TestRetrieveTypeFullName(baseTypeNode, semanticModel, "System.IDisposable");
        }
Exemplo n.º 5
0
        public void LocateElementWithId()
        {
            var x       = Element.Create("span", "x");
            var locator = NodeLocator.FromNode(x);

            Assert.Equal(x.Id, locator.StartingId);
        }
Exemplo n.º 6
0
        public void MethodName()
        {
            string[] methodExpectedNames = new string[]
            {
                TestSuite.Class11.Value["Method1Name"],
                TestSuite.Class11.Value["Method2Name"],
                TestSuite.Class11.Value["Method3Name"],
                TestSuite.Class11.Value["Method4Name"],
                TestSuite.Class11.Value["Method5Name"],
                TestSuite.Class11.Value["Method6Name"],
                TestSuite.Class11.Value["Method7Name"],
            };
            IEnumerable <KeyValuePair <SyntaxNode, string> > items =
                new NodeLocator(Class11SyntaxTree).LocateAll(typeof(MethodDeclarationSyntax))
                .Select((node, k) => new KeyValuePair <SyntaxNode, string>(node, methodExpectedNames[k]));

            foreach (KeyValuePair <SyntaxNode, string> item in items)
            {
                Assert.IsNotNull(item.Key, string.Format("Node of type `{0}` should be found!",
                                                         typeof(MethodDeclarationSyntax).Name));

                MethodDeclarationSyntax methodDeclarationNode = item.Key as MethodDeclarationSyntax;

                TestRetrieveMethodName(methodDeclarationNode, item.Value);
            }
        }
Exemplo n.º 7
0
        public void DetectVoidType()
        {
            var tree = CSharpSyntaxTree.ParseText(@"
            using System;
            public class MyClass {
                public void Method1() { }
                public int Method2() { }
            }
            ");

            // First method
            var node = new NodeLocator(tree).LocateFirst(typeof(MethodDeclarationSyntax));

            Assert.IsNotNull(node, string.Format("Node of type `{0}` should be found!",
                                                 typeof(MethodDeclarationSyntax).Name));

            var methodDeclarationNode = node as MethodDeclarationSyntax;
            var helper = new MethodDeclaration(methodDeclarationNode).ReturnType;

            Assert.IsTrue(helper.IsVoid, "Expected void type!");

            // Second method
            node = new NodeLocator(tree).LocateLast(typeof(MethodDeclarationSyntax));
            Assert.IsNotNull(node, string.Format("Node of type `{0}` should be found!",
                                                 typeof(MethodDeclarationSyntax).Name));

            methodDeclarationNode = node as MethodDeclarationSyntax;
            helper = new MethodDeclaration(methodDeclarationNode).ReturnType;

            Assert.IsFalse(helper.IsVoid, "Void type not expected!");
        }
Exemplo n.º 8
0
        /// <summary>
        /// Finds the <see cref="T:MemcachedNode"/> which is responsible for the specified item
        /// </summary>
        /// <param name="itemKey"></param>
        /// <returns></returns>
        private MemcachedNode LocateNode(string itemKey)
        {
            serverAccessLock.AcquireReaderLock(Timeout.Infinite);

            try
            {
                MemcachedNode node = NodeLocator.Locate(itemKey);
                if (node == null)
                {
                    return(null);
                }

                if (node.IsAlive)
                {
                    return(node);
                }

                MarkAsDead(node);

                return(LocateNode(itemKey));
            }
            finally
            {
                serverAccessLock.ReleaseLock();
            }
        }
Exemplo n.º 9
0
        public void MethodParametersAreOfCorrectType()
        {
            var source = @"
                class Class1 {
                    public void Method1(int param1) { }
                    public void Method2(int param1, string param2) { }
                    public void Method3(int param1, string param2, object param3) { }
                    public void Method4(int param1, string param2, object param3, bool param4) { }
                }
            ";

            var syntaxTree    = CSharpSyntaxTree.ParseText(source);
            var semanticModel = CSharpCompilation.Create("Class").AddReferences(
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location)).AddSyntaxTrees(
                syntaxTree).GetSemanticModel(syntaxTree);

            IEnumerable <SyntaxNode> nodes = new NodeLocator(syntaxTree).LocateAll(
                typeof(MethodDeclarationSyntax));

            foreach (SyntaxNode node in nodes)
            {
                Assert.IsNotNull(node, string.Format("Node of type `{0}` should be found!",
                                                     typeof(MethodDeclarationSyntax).Name));
                MethodDeclarationSyntax methodDeclarationNode = node as MethodDeclarationSyntax;

                MethodDeclaration methodDeclaration = new MethodDeclaration(methodDeclarationNode);

                foreach (var param in methodDeclaration.Parameters)
                {
                    Assert.IsNotNull(param, "Parameter should not be null!");
                    Assert.IsInstanceOfType(param, typeof(Parameter), "Wrong parameter type!");
                }
            }
        }
Exemplo n.º 10
0
        public void MethodWithVariableDeclarations()
        {
            string source = @"
                public void Method() {
                    string var1;
                    int var2;
                }
            ";

            // Getting the AST node
            CSharpSyntaxTree tree = ASTExtractor.Extract(source);

            SyntaxNode node = new NodeLocator(tree).LocateLast(typeof(MethodDeclarationSyntax));
            MethodDeclarationSyntax methodDeclarationNode = node as MethodDeclarationSyntax;

            // Creating the walker
            var astWalker = MockedMethodASTWalker.Create(methodDeclarationNode);

            // Getting the translation unit
            astWalker.Walk();

            // Checking
            Assert.IsNotNull(astWalker.MethodDeclaration);

            // Checking members
            Assert.IsNotNull(astWalker.MethodDeclaration.Statements);
            Assert.IsTrue(astWalker.MethodDeclaration.Statements.Count() > 0);
            Assert.AreEqual(2, astWalker.MethodDeclaration.Statements.Count());

            Assert.IsInstanceOfType(astWalker.MethodDeclaration.Statements.ElementAt(0), typeof(StatementTranslationUnit));
            Assert.IsInstanceOfType(astWalker.MethodDeclaration.Statements.ElementAt(1), typeof(StatementTranslationUnit));
        }
Exemplo n.º 11
0
        public void EmptyMethodWithNoParameters()
        {
            string source = @"
                public void Method() { }
            ";

            // Getting the AST node
            CSharpSyntaxTree tree = ASTExtractor.Extract(source);

            SyntaxNode node = new NodeLocator(tree).LocateLast(typeof(MethodDeclarationSyntax));
            MethodDeclarationSyntax methodDeclarationNode = node as MethodDeclarationSyntax;

            // Creating the walker
            var astWalker = MockedMethodASTWalker.Create(methodDeclarationNode);

            // Getting the translation unit
            astWalker.Walk();

            // Checking
            Assert.IsNotNull(astWalker.MethodDeclaration);

            // Checking members
            Assert.IsNotNull(astWalker.MethodDeclaration.Arguments);
            Assert.AreEqual(0, astWalker.MethodDeclaration.Arguments.Count());
        }
Exemplo n.º 12
0
        public void EmptyMethodWith3Parameters()
        {
            string source = @"
                public void Method(string param1, int param2, bool param3) { }
            ";

            // Getting the AST node
            CSharpSyntaxTree tree = ASTExtractor.Extract(source);

            SyntaxNode node = new NodeLocator(tree).LocateLast(typeof(MethodDeclarationSyntax));
            MethodDeclarationSyntax methodDeclarationNode = node as MethodDeclarationSyntax;

            // Creating the walker
            var astWalker = MockedMethodASTWalker.Create(methodDeclarationNode);

            // Getting the translation unit
            astWalker.Walk();

            // Checking
            Assert.IsNotNull(astWalker.MethodDeclaration);

            // Checking members
            Assert.IsNotNull(astWalker.MethodDeclaration.Arguments);
            Assert.IsTrue(astWalker.MethodDeclaration.Arguments.Count() > 0);
            Assert.AreEqual(3, astWalker.MethodDeclaration.Arguments.Count());

            Assert.IsInstanceOfType(astWalker.MethodDeclaration.Arguments.ElementAt(0), typeof(ArgumentDefinitionTranslationUnit));
            Assert.IsInstanceOfType(astWalker.MethodDeclaration.Arguments.ElementAt(1), typeof(ArgumentDefinitionTranslationUnit));
            Assert.IsInstanceOfType(astWalker.MethodDeclaration.Arguments.ElementAt(2), typeof(ArgumentDefinitionTranslationUnit));
        }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            IList<TestNode> nodeList = new List<TestNode>();

            nodeList.Add(new TestNode("abcd-123456"));
            //nodeList.Add(new TestNode("abcd-123478"));
            nodeList.Add(new TestNode("abcd-123490"));
            nodeList.Add(new TestNode("abcd-123401"));

            INodeLocator<TestNode> locator = new NodeLocator<TestNode>();

            locator.Initialize(nodeList);

            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(locator.Locate("abc" + i).Indentity);
            }

            Random rnd = new Random();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 1000; i++)
            {
                sb.Append(rnd.Next(100000, 9999999));
            }

            Console.WriteLine(BitConverter.ToInt32(new FNV1a().ComputeHash(System.Text.Encoding.ASCII.GetBytes(sb.ToString())),0));
            //Console.WriteLine(BitConverter.ToInt32(new FNV1a().ComputeHash(System.Text.Encoding.ASCII.GetBytes(sb.ToString())), 4));

            Console.ReadLine();
        }
Exemplo n.º 14
0
        public void WalkASTDeep()
        {
            string source = @"
                namespace MyNamespaceA {
                    public class MyClassA { }
                    public class MyClassB { }

                    namespace MyNamespaceB {
                        public class MyClassC { }
                        public class MyClassD { }
                    }
                }
            ";

            int traversedClassesCount = 0;

            // Getting the AST node
            CSharpSyntaxTree tree = ASTExtractor.Extract(source);
            var node = new NodeLocator(tree).LocateLast(typeof(CompilationUnitSyntax)) as CSharpSyntaxNode;

            // Calling the walker
            var astWalker = new MultiPurposeASTWalker(node,
                                                      syntaxNode => syntaxNode as ClassDeclarationSyntax != null,
                                                      delegate
            {
                traversedClassesCount++;
            },
                                                      false);

            astWalker.Start();

            // Checking
            Assert.AreEqual(4, traversedClassesCount, "Expected walker to deep traverse AST!");
        }
Exemplo n.º 15
0
        public void Properties()
        {
            string source = @"
                public interface MyInterface {
                    int Property1 { get; set; }
                    string Property2 { get; set; }
                }
            ";

            // Getting the AST node
            CSharpSyntaxTree tree = ASTExtractor.Extract(source);

            SyntaxNode node = new NodeLocator(tree).LocateFirst(typeof(InterfaceDeclarationSyntax));
            InterfaceDeclarationSyntax interfaceDeclarationNode = node as InterfaceDeclarationSyntax;

            // Creating the walker
            var astWalker = MockedInterfaceASTWalker.Create(interfaceDeclarationNode);

            // Getting the translation unit
            astWalker.Walk();

            // Checking
            Assert.IsNotNull(astWalker.InterfaceDeclaration);

            // Checking signatures
            Assert.IsNotNull(astWalker.InterfaceDeclaration.Signatures);
            Assert.IsTrue(astWalker.InterfaceDeclaration.Signatures.Count() > 0);
            Assert.AreEqual(2, astWalker.InterfaceDeclaration.Signatures.Count());

            Assert.IsInstanceOfType(astWalker.InterfaceDeclaration.Signatures.ElementAt(0), typeof(MethodSignatureDeclarationTranslationUnit));
            Assert.IsInstanceOfType(astWalker.InterfaceDeclaration.Signatures.ElementAt(1), typeof(MethodSignatureDeclarationTranslationUnit));
        }
Exemplo n.º 16
0
        public void ScriptNamespaceRetrievedOnInterfacePropertyType()
        {
            var tree = CSharpSyntaxTree.ParseText(@"
            namespace Namespace1 {
                [ScriptNamespace(""OverridenNamespace"")]
                public class Class1 { }
                public interface Interface1 {
                    Class1 MyProperty { get; set; }
                }
            }
            ");

            // Loading MSCoreLib
            var semanticModel = (CSharpCompilation.Create("TestAssembly")
                                 .AddReferences(
                                     MetadataReference.CreateFromFile(
                                         typeof(object).Assembly.Location))
                                 .AddSyntaxTrees(tree).AddScriptNamespaceReference().GetSemanticModel(tree));

            var node = new NodeLocator(tree).LocateFirst(typeof(PropertyDeclarationSyntax));

            Assert.IsNotNull(node);

            var propertyDeclarationNode = node as PropertyDeclarationSyntax;

            Assert.IsNotNull(propertyDeclarationNode);

            var typeReference = new PropertyDeclaration(propertyDeclarationNode, semanticModel).Type;

            Assert.AreEqual("OverridenNamespace.Class1", typeReference.FullName, "ScriptNamespace overriden namespace not detected!");
        }
Exemplo n.º 17
0
        public void EmptyMethodWith2Parameters()
        {
            string source = @"
                class Class1 {
                    public Class1(string param1, int param2) { }
                }
            ";

            // Getting the AST node
            CSharpSyntaxTree tree = ASTExtractor.Extract(source);

            SyntaxNode node = new NodeLocator(tree).LocateLast(typeof(ConstructorDeclarationSyntax));
            ConstructorDeclarationSyntax constructorDeclarationNode = node as ConstructorDeclarationSyntax;

            // Creating the walker
            var astWalker = MockedConstructorASTWalker.Create(constructorDeclarationNode);

            // Getting the translation unit
            astWalker.Walk();

            // Checking
            Assert.IsNotNull(astWalker.ConstructorDeclaration);

            // Checking members
            Assert.IsNotNull(astWalker.ConstructorDeclaration.Arguments);
            Assert.IsTrue(astWalker.ConstructorDeclaration.Arguments.Count() > 0);
            Assert.AreEqual(2, astWalker.ConstructorDeclaration.Arguments.Count());

            Assert.IsInstanceOfType(astWalker.ConstructorDeclaration.Arguments.ElementAt(0), typeof(ArgumentDefinitionTranslationUnit));
            Assert.IsInstanceOfType(astWalker.ConstructorDeclaration.Arguments.ElementAt(1), typeof(ArgumentDefinitionTranslationUnit));
        }
Exemplo n.º 18
0
        public void SimpleClass()
        {
            var node = (@"
                namespace Root.MyNamespace1 {
                    public class MyClass {
                    }
                }
            ").ExtractASTRoot();

            var namespaces = new NodeLocator(node).LocateAll(typeof(NamespaceDeclarationSyntax), true);

            Assert.AreEqual(1, namespaces.Count(), "Expecting only one namespace at root level");

            var @namespace    = namespaces.First() as NamespaceDeclarationSyntax;
            var namespaceName = @namespace.Name.ToString();

            Assert.AreEqual("Root.MyNamespace1", namespaceName, "Wrong namespace name");

            var classes = new NodeLocator(@namespace).LocateAll(typeof(ClassDeclarationSyntax), true);

            Assert.AreEqual(1, classes.Count(), "Expecting only one class in namespace");

            var @class    = classes.First() as ClassDeclarationSyntax;
            var className = @class.Identifier.Text;

            Assert.AreEqual("MyClass", className, "Wrong class name");
        }
Exemplo n.º 19
0
        public void OneClass()
        {
            string source = @"
                public class Class1 {
                }
            ";

            // Getting the AST node
            CSharpSyntaxTree tree = ASTExtractor.Extract(source);

            SyntaxNode            node        = new NodeLocator(tree).LocateLast(typeof(CompilationUnitSyntax));
            CompilationUnitSyntax programNode = node as CompilationUnitSyntax;

            // Creating the walker
            var astWalker = MockedProgramASTWalker.Create(programNode);

            // Getting the translation unit
            astWalker.Walk();

            // Checking
            Assert.IsNotNull(astWalker.Program);

            // Checking members
            Assert.IsNotNull(astWalker.Program.Content);
            Assert.IsTrue(astWalker.Program.Content.Count() > 0);
            Assert.AreEqual(1, astWalker.Program.Content.Count());

            Assert.IsInstanceOfType(astWalker.Program.Content.ElementAt(0), typeof(ClassDeclarationTranslationUnit));
        }
Exemplo n.º 20
0
        public void UsingDirectivesAreTransplantedAtRootLevel()
        {
            var source = @"
            namespace Namespace1 {
                namespace Namespace11 {
                    public class Class111 { }
                }
                namespace Namespace12 {
                    public class Class121 { }
                }
            }

            namespace OriginalNamespace {
                using Namespace1.Namespace11;
                using Namespace1.Namespace12;

                [ScriptNamespace(""NewNamespace"")]
                public class Class1 { }
            }
            ";

            var tree = CSharpSyntaxTree.ParseText(source) as CSharpSyntaxTree;

            // Loading MSCoreLib
            var compilation = CSharpCompilation.Create("TestAssembly")
                              .AddReferences(
                MetadataReference.CreateFromFile(
                    typeof(object).Assembly.Location))
                              .AddSyntaxTrees(tree).AddScriptNamespaceReference();

            // Transform
            new ScriptNamespaceBasedASTTransformer().Transform(ref tree, ref compilation);

            // Test
            var oldNamespaceSyntaxNodes = new NodeLocator(tree).LocateAll(typeof(NamespaceDeclarationSyntax),
                                                                          node => node as NamespaceDeclarationSyntax != null &&
                                                                          new NamespaceDeclaration(node as NamespaceDeclarationSyntax).Name == "OriginalNamespace");
            // TODO: The next line cannot happen because at the moment the transformer leaves the ld namespace if
            //       using directives are present inside, later we might think about removing using directives if
            //       a namespace contains only using directivess parte of the cleanup process
            //Assert.AreEqual(0, oldNamespaceSyntaxNodes.Count(), "Old namespace should not be present");

            var usingSyntaxNodes = new NodeLocator(tree).LocateAll(typeof(UsingDirectiveSyntax));

            Assert.IsTrue(usingSyntaxNodes.Count() >= 2, "Original using directives should still be in the transformed AST");

            var inRootUsingSyntaxNodes = new NodeLocator(tree).LocateAll(typeof(UsingDirectiveSyntax), node => node.IsInRoot());

            Assert.IsTrue(inRootUsingSyntaxNodes.Count() >= 2, "Original using directives should have been transplanted into root");

            var directive1Nodes = new NodeLocator(tree).LocateAll(typeof(UsingDirectiveSyntax),
                                                                  node => node.IsInRoot() && new UsingDirective(node as UsingDirectiveSyntax).Value == "Namespace1.Namespace11");

            Assert.AreEqual(1, directive1Nodes.Count(), "Existing using directive should have been transplanted into root");

            var directive2Nodes = new NodeLocator(tree).LocateAll(typeof(UsingDirectiveSyntax),
                                                                  node => node.IsInRoot() && new UsingDirective(node as UsingDirectiveSyntax).Value == "Namespace1.Namespace12");

            Assert.AreEqual(1, directive2Nodes.Count(), "Existing using directive should have been transplanted into root");
        }
Exemplo n.º 21
0
        public void OriginalOverridenNamespacesAreAddedAsUsingDirectivesAtRootLevel()
        {
            var source = @"
            namespace OriginalNamespace {
                [ScriptNamespace(""NewNamespace"")]
                public class Class1 { }
            }
            ";

            var tree = CSharpSyntaxTree.ParseText(source) as CSharpSyntaxTree;

            // Loading MSCoreLib
            var compilation = CSharpCompilation.Create("TestAssembly")
                              .AddReferences(
                MetadataReference.CreateFromFile(
                    typeof(object).Assembly.Location))
                              .AddSyntaxTrees(tree).AddScriptNamespaceReference();

            // Transform
            new ScriptNamespaceBasedASTTransformer().Transform(ref tree, ref compilation);

            // Test
            var directiveNodes = new NodeLocator(tree).LocateAll(typeof(UsingDirectiveSyntax),
                                                                 node => node.IsInRoot() && new UsingDirective(node as UsingDirectiveSyntax).Value == "OriginalNamespace");

            Assert.AreEqual(1, directiveNodes.Count(), "Original namespace should have been transplanted into root as using directive");
        }
Exemplo n.º 22
0
        public void ScriptNamespaceRetrievedOnClassMethodArgumentType()
        {
            var tree = CSharpSyntaxTree.ParseText(@"
            namespace Namespace1 {
                [ScriptNamespace(""OverridenNamespace"")]
                public class Class1 { }
                public class Class2 {
                    public void MyMethod(Class1 parameter) { }
                }
            }
            ");

            // Loading MSCoreLib
            var semanticModel = (CSharpCompilation.Create("TestAssembly")
                                 .AddReferences(
                                     MetadataReference.CreateFromFile(
                                         typeof(object).Assembly.Location))
                                 .AddSyntaxTrees(tree).AddScriptNamespaceReference().GetSemanticModel(tree));

            var node = new NodeLocator(tree).LocateFirst(typeof(MethodDeclarationSyntax));

            Assert.IsNotNull(node);

            var methodDeclarationNode = node as MethodDeclarationSyntax;

            Assert.IsNotNull(methodDeclarationNode);

            var parameters = new MethodDeclaration(methodDeclarationNode, semanticModel).Parameters;

            Assert.AreEqual(1, parameters.Count(), "1 argument expected");
            var typeReference = parameters.ElementAt(0).Type;

            Assert.AreEqual("OverridenNamespace.Class1", typeReference.FullName, "ScriptNamespace overriden namespace not detected!");
        }
Exemplo n.º 23
0
        private static void TestScriptNamespaceOnParameter(string source, bool withSemanticModel, string expectedFullName)
        {
            var tree = CSharpSyntaxTree.ParseText(source);

            // Loading MSCoreLib
            var semanticModel = withSemanticModel
                ? (CSharpCompilation.Create("TestAssembly")
                   .AddReferences(
                       MetadataReference.CreateFromFile(
                           typeof(object).Assembly.Location))
                   .AddSyntaxTrees(tree).AddScriptNamespaceReference().GetSemanticModel(tree))
                : null;

            var node = new NodeLocator(tree).LocateFirst(typeof(MethodDeclarationSyntax));

            Assert.IsNotNull(node);

            var methodDeclarationNode = node as MethodDeclarationSyntax;

            Assert.IsNotNull(methodDeclarationNode);

            var translationUnitFactory = new MethodDefinitionTranslationUnitFactory(methodDeclarationNode, semanticModel, true).Create();

            Assert.IsNotNull(translationUnitFactory, "Translation unit expected to be created!");

            var methodTranslationUnit = (translationUnitFactory as MethodDefinitionTranslationUnit);

            Assert.IsNotNull(methodTranslationUnit, $"Expecting a translation unit of type {typeof(MethodDefinitionTranslationUnit).Name}!");

            var translationUnit = MockedMethodDefinitionTranslationUnit.Create(methodTranslationUnit);

            Assert.IsNotNull(translationUnit.Arguments);
            Assert.AreEqual(1, translationUnit.Arguments.Count(), "Expecting 1 argument!");

            var argumentTranslationUnit = translationUnit.Arguments.ElementAt(0) as ArgumentDefinitionTranslationUnit;

            Assert.IsNotNull(argumentTranslationUnit, $"Expected argument to be of type {typeof(ArgumentDefinitionTranslationUnit).Name}");

            var mockedArgumentTranslationUnit = MockedArgumentDefinitionTranslationUnit.Create(argumentTranslationUnit);

            Assert.IsNotNull(mockedArgumentTranslationUnit.VariableDeclaration);

            var variableDeclarationTranslationUnit = mockedArgumentTranslationUnit.VariableDeclaration as VariableDeclarationTranslationUnit;

            Assert.IsNotNull(variableDeclarationTranslationUnit);

            var mockedVariableDeclarationTranslationUnit = MockedVariableDeclarationTranslationUnit.Create(variableDeclarationTranslationUnit);

            Assert.IsNotNull(mockedVariableDeclarationTranslationUnit.Type, "Expecting a type!");

            var typeIdentifierTranslationUnit = mockedVariableDeclarationTranslationUnit.Type as TypeIdentifierTranslationUnit;

            Assert.IsNotNull(typeIdentifierTranslationUnit, $"Expected argument to be of type {typeof(TypeIdentifierTranslationUnit).Name}");

            var typeFullName = typeIdentifierTranslationUnit.Translate();

            Assert.AreEqual(expectedFullName, typeFullName, "Expected ScriptNamespace overriden type to be used!");
        }
Exemplo n.º 24
0
        private static void TestWhenASTIsChangedThenNoEmptyNamespacesAreLeftOver(bool withCompilation = false)
        {
            var source = @"
            namespace OriginalNamespace {
                [ScriptNamespace(""NewNamespace"")]
                public class Class1 { }

                [ScriptNamespace(""NewNamespace"")]
                public class Class2 { }

                [ScriptNamespace(""NewNamespace1"")]
                public class Class3 { }

                [ScriptNamespace(""NewNamespace1"")]
                public class Class4 { }
            }
            ";

            var tree = CSharpSyntaxTree.ParseText(source) as CSharpSyntaxTree;

            // Loading MSCoreLib
            var compilation = withCompilation
                ? CSharpCompilation.Create("TestAssembly")
                              .AddReferences(
                MetadataReference.CreateFromFile(
                    typeof(object).Assembly.Location))
                              .AddSyntaxTrees(tree).AddScriptNamespaceReference()
                : null;

            // Transform
            if (withCompilation)
            {
                new ScriptNamespaceBasedASTTransformer().Transform(ref tree, ref compilation);
            }
            else
            {
                new ScriptNamespaceBasedASTTransformer().Transform(ref tree);
            }

            // Test
            var oldNamespaceSyntaxNodes = new NodeLocator(tree).LocateAll(typeof(NamespaceDeclarationSyntax),
                                                                          node => node as NamespaceDeclarationSyntax != null &&
                                                                          new NamespaceDeclaration(node as NamespaceDeclarationSyntax).Name == "OriginalNamespace");

            Assert.AreEqual(0, oldNamespaceSyntaxNodes.Count(), "Old namespace should not be present");

            var namespaceSyntaxNodes = new NodeLocator(tree).LocateAll(typeof(NamespaceDeclarationSyntax));

            Assert.IsTrue(namespaceSyntaxNodes.Count() > 0, "Namespaces expected");

            foreach (var namespaceNode in namespaceSyntaxNodes)
            {
                Assert.IsFalse((namespaceNode as NamespaceDeclarationSyntax).IsNamespaceEmpty(), "No empty namespace expected");
            }
        }
Exemplo n.º 25
0
        private static void DetermineLastElseAndTest(SyntaxTree syntaxTree, bool expectedElse)
        {
            SyntaxNode node = new NodeLocator(syntaxTree).LocateFirst(typeof(IfStatementSyntax));

            Assert.IsNotNull(node, string.Format("Node of type `{0}` should be found!",
                                                 typeof(IfStatementSyntax).Name));

            IfStatementSyntax conditionalNode = node as IfStatementSyntax;

            TestDeterminedLastElseClause(conditionalNode, expectedElse);
        }
Exemplo n.º 26
0
        public void ClassNameFromClassWithInterface()
        {
            SyntaxNode node = new NodeLocator(Class3SyntaxTree).LocateLast(typeof(ClassDeclarationSyntax));

            Assert.IsNotNull(node, string.Format("Node of type `{0}` should be found!",
                                                 typeof(ClassDeclarationSyntax).Name));

            ClassDeclarationSyntax classDeclarationNode = node as ClassDeclarationSyntax;

            TestRetrieveClassName(classDeclarationNode, TestSuite.Class3.Value["ClassName"]);
        }
Exemplo n.º 27
0
        public void InterfaceNameFromClassWithInheritance()
        {
            SyntaxNode node = new NodeLocator(Class2SyntaxTree).LocateLast(typeof(ClassDeclarationSyntax));

            Assert.IsNotNull(node, string.Format("Node of type `{0}` should be found!",
                                                 typeof(ClassDeclarationSyntax).Name));

            ClassDeclarationSyntax classDeclarationNode = node as ClassDeclarationSyntax;

            TestRetrieveInterfacesName(classDeclarationNode, Class2SemanticModel, null);
        }
Exemplo n.º 28
0
        public void BaseClassNameFromClass()
        {
            SyntaxNode node = new NodeLocator(Class1SyntaxTree).LocateLast(typeof(ClassDeclarationSyntax));

            Assert.IsNotNull(node, string.Format("Node of type `{0}` should be found!",
                                                 typeof(ClassDeclarationSyntax).Name));

            ClassDeclarationSyntax classDeclarationNode = node as ClassDeclarationSyntax;

            TestRetrieveBaseClassName(classDeclarationNode, Class1SemanticModel, null);
        }
Exemplo n.º 29
0
        private static void RetrieveNumberOfBodiesAndTest(SyntaxTree syntaxTree, int expectedNumberOfBodies)
        {
            SyntaxNode node = new NodeLocator(syntaxTree).LocateFirst(typeof(IfStatementSyntax));

            Assert.IsNotNull(node, string.Format("Node of type `{0}` should be found!",
                                                 typeof(IfStatementSyntax).Name));

            IfStatementSyntax conditionalNode = node as IfStatementSyntax;

            TestRetrievedNumberOfBodies(conditionalNode, expectedNumberOfBodies);
        }
Exemplo n.º 30
0
        private static void TestWhenScriptNamespaceAttributeProvidedThenClassPlacedInDifferentNamespace(bool withCompilation = false)
        {
            var source = @"
            namespace OriginalNamespace {
                [ScriptNamespace(""NewNamespace"")]
                public class MyClass { }
            }
            ";

            var tree = CSharpSyntaxTree.ParseText(source) as CSharpSyntaxTree;

            // Loading MSCoreLib
            var compilation = withCompilation
                ? CSharpCompilation.Create("TestAssembly")
                              .AddReferences(
                MetadataReference.CreateFromFile(
                    typeof(object).Assembly.Location))
                              .AddSyntaxTrees(tree).AddScriptNamespaceReference()
                : null;

            // Transform
            if (withCompilation)
            {
                new ScriptNamespaceBasedASTTransformer().Transform(ref tree, ref compilation);
            }
            else
            {
                new ScriptNamespaceBasedASTTransformer().Transform(ref tree);
            }

            // Test
            var namespaceSyntaxNode = new NodeLocator(tree).LocateFirst(typeof(NamespaceDeclarationSyntax));

            Assert.IsNotNull(namespaceSyntaxNode, "A namespace was expected");
            var namespaceDeclarationNode = namespaceSyntaxNode as NamespaceDeclarationSyntax;

            Assert.IsNotNull(namespaceDeclarationNode);
            var namespaceHelper = new NamespaceDeclaration(namespaceDeclarationNode);

            Assert.AreEqual("NewNamespace", namespaceHelper.Name, "The name of the namespace should have changed");

            var classSyntaxNode = new NodeLocator(tree).LocateFirst(typeof(ClassDeclarationSyntax));

            Assert.IsNotNull(classSyntaxNode, "A class was expected");
            var classDeclarationNode = classSyntaxNode as ClassDeclarationSyntax;

            Assert.IsNotNull(namespaceDeclarationNode);
            var classHelper = new ClassDeclaration(classDeclarationNode);

            Assert.AreEqual("MyClass", classHelper.Name, "The name of the class should be the same");

            Assert.IsTrue(classSyntaxNode.IsChildOf(namespaceDeclarationNode), "Class expected to be child of namespace");
        }
Exemplo n.º 31
0
        public void InterfaceTypeNameFromBaseList()
        {
            SyntaxNode node = new NodeLocator(Class3SyntaxTree).LocateLast(typeof(ClassDeclarationSyntax));

            Assert.IsNotNull(node, string.Format("Node of type `{0}` should be found!",
                                                 typeof(ClassDeclarationSyntax).Name));

            ClassDeclarationSyntax classDeclarationNode = node as ClassDeclarationSyntax;
            BaseTypeSyntax         baseTypeNode         = classDeclarationNode.BaseList.Types.FirstOrDefault();

            TestRetrieveTypeName(baseTypeNode, TestSuite.Class3.Value["Interface1Name"]);
        }