Exemplo n.º 1
0
        public void TestAnalyzeNameSpace()
        {
            string     code1 = @"namespace Test{class TestClass { public void TestMethod( int test = 0; test = 1;){}}}";
            SyntaxTree tree1 = CSharpSyntaxTree.ParseText(code1);

            NamespaceDeclarationSyntax nsNode = tree1.GetRootAsync().Result.DescendantNodes().OfType <NamespaceDeclarationSyntax>().First();

            List <SyntaxTree> trees1 = new List <SyntaxTree> {
                tree1
            };
            Compilation comp1 = CSharpCompilation.Create("TestCompilation1", trees1);

            ScriptAnalyzer analyzer = this.createAnalyzer(comp1);

            TaggedSyntaxLibrary lib = analyzer.AnalyzeNode(nsNode);

            Assert.IsNotNull(lib, "Library defined");
            Assert.AreEqual(1, lib.TaggedSyntaxTrees.Count(), "Has one tree");

            TaggedSyntaxTree tree = lib.TaggedSyntaxTrees.First();

            CollectionAssert.Contains(tree.TaggedNodes, nsNode, "Tree contains class node");

            IEnumerable <SyntaxNode> nodes = nsNode.DescendantNodes();

            foreach (SyntaxNode node in nodes)
            {
                CollectionAssert.DoesNotContain(tree.TaggedNodes, node, "SubNode is not added to tree");
            }
        }
        //protected override void VisitInvocationExpression(InvocationExpressionSyntax node)
        //{

        //}
        public override void VisitNamespaceDeclaration(NamespaceDeclarationSyntax node)
        {
            foreach (var type in node.DescendantNodes().OfType <ClassDeclarationSyntax>())
            {
                Visit(type);
            }
        }
Exemplo n.º 3
0
    /// <summary>
    ///   Takes a namespace declaration and returns a new namespace declaration containing only
    ///   the ServiceContract interfaces, converted to an asynchronous version
    /// </summary>
    /// <param name="originalNamespace">The namespace declaration to replace</param>
    /// <returns></returns>
    private static NamespaceDeclarationSyntax ComputeNewNamespaceDeclarationNode(NamespaceDeclarationSyntax originalNamespace)
    {
      var serviceContractInterfaces =
        originalNamespace.DescendantNodes().OfType<InterfaceDeclarationSyntax>().Where(
          i => i.GetAttribute<ServiceContractAttribute>() != null);

      return originalNamespace.WithMembers(Syntax.List<MemberDeclarationSyntax>(serviceContractInterfaces.Select(ComputeNewServiceContractInterfaceNode)));
    }
Exemplo n.º 4
0
        /// <summary>
        ///   Takes a namespace declaration and returns a new namespace declaration containing only
        ///   the ServiceContract interfaces, converted to an asynchronous version
        /// </summary>
        /// <param name="originalNamespace">The namespace declaration to replace</param>
        /// <returns></returns>
        private static NamespaceDeclarationSyntax ComputeNewNamespaceDeclarationNode(NamespaceDeclarationSyntax originalNamespace)
        {
            var serviceContractInterfaces =
                originalNamespace.DescendantNodes().OfType <InterfaceDeclarationSyntax>().Where(
                    i => i.GetAttribute <ServiceContractAttribute>() != null);

            return(originalNamespace.WithMembers(Syntax.List <MemberDeclarationSyntax>(serviceContractInterfaces.Select(ComputeNewServiceContractInterfaceNode))));
        }
 internal void Initialize(NamespaceDeclarationSyntax nds)
 {
     Name = nds.Name.ToString();
     foreach (ClassDeclarationSyntax cds in nds.DescendantNodes().OfType <ClassDeclarationSyntax>())
     {
         ClassInfo ciToAdd = new ClassInfo();
         ciToAdd.Initialize(cds);
         Classes.Add(ciToAdd);
     }
 }
Exemplo n.º 6
0
        private string GetMethodName(NamespaceDeclarationSyntax node)
        {
            var methodName = node.DescendantNodes().OfType <MethodDeclarationSyntax>().FirstOrDefault()?.Identifier.ValueText;

            if (string.IsNullOrEmpty(methodName))
            {
                throw new ArgumentException(this.messageManager.GetMessage("MethodNotFoundInClass"));
            }
            return(methodName);
        }
Exemplo n.º 7
0
 public void Initialize(NamespaceDeclarationSyntax namespaceDeclaration)
 {
     Name = namespaceDeclaration.Name.ToString();
     foreach (var cds in namespaceDeclaration.DescendantNodes()
              .OfType <ClassDeclarationSyntax>())
     {
         var classInfoToAdd = new TestableClassInfo();
         classInfoToAdd.Initialize(cds);
         Classes.Add(classInfoToAdd);
     }
 }
Exemplo n.º 8
0
        public SourceNamespace(NamespaceDeclarationSyntax namespaceInfo)
        {
            this.namespaceInfo = namespaceInfo;
            this.name          = namespaceInfo.Name.ToString();

            foreach (ClassDeclarationSyntax classInfo in namespaceInfo.DescendantNodes().OfType <ClassDeclarationSyntax>())
            {
                //fork
                classes.Add(new SourceClass(classInfo));
            }
            //join
        }
Exemplo n.º 9
0
            private ClassDeclarationSyntax GetParentClass(NamespaceDeclarationSyntax namespaceDeclaration, ClassDeclarationSyntax classDeclaration)
            {
                var maybeBaseType = classDeclaration.DescendantNodes()
                                    .Where(c => c.Kind() == SyntaxKind.SimpleBaseType)
                                    .FirstOrDefault();

                if (maybeBaseType is not SimpleBaseTypeSyntax simpleBaseType)
                {
                    return(null);
                }

                var maybeParentClass = namespaceDeclaration.DescendantNodes()
                                       .OfType <ClassDeclarationSyntax>()
                                       .Where(n => n.Identifier.ValueText == maybeBaseType.ToString())
                                       .FirstOrDefault();

                return(maybeParentClass);
            }
Exemplo n.º 10
0
        private static NamespaceDeclarationSyntax AddTypeToTargetNamespace(TypeDeclarationSyntax originalTargetType, NamespaceDeclarationSyntax targetNamespace, TypeDeclarationSyntax targetType)
        {
            if (originalTargetType != null)
            {
                targetNamespace = targetNamespace.RemoveNode(originalTargetType, SyntaxRemoveOptions.KeepNoTrivia);
            }
            else
            {
                var type = targetNamespace.DescendantNodes().OfType <TypeDeclarationSyntax>().FirstOrDefault(x => x.Identifier.ValueText == targetType.Identifier.ValueText);
                if (type != null)
                {
                    targetNamespace = targetNamespace.RemoveNode(type, SyntaxRemoveOptions.KeepNoTrivia);
                }
            }

            targetNamespace = targetNamespace.AddMembers(targetType);
            return(targetNamespace);
        }
Exemplo n.º 11
0
        private void ParseNamespace(Bindings result, NamespaceDeclarationSyntax ns)
        {
            var classNode = ns.DescendantNodes()
                            .OfType <ClassDeclarationSyntax>()
                            .FirstOrDefault();

            result.Target = new Target()
            {
                ClassFullname = $"{ns.Name.GetText().ToString().Trim()}.{classNode.Identifier.Text}",
                Bindings      = new System.Collections.Generic.List <Property>(),
            };

            var method = classNode.DescendantNodes()
                         .OfType <MethodDeclarationSyntax>()
                         .FirstOrDefault(x => x.AttributeLists.Any(l => l.Attributes.Any(a => a.Name.ToString() == "Bindings")));

            this.ParseMethod(result, method);
        }
Exemplo n.º 12
0
        private static NamespaceDeclarationSyntax AddTypeParameterAliases(ClassModel classModel, HashSet <string> typeParametersEmitted, NamespaceDeclarationSyntax targetNamespace)
        {
            foreach (var parameter in classModel.Declaration.TypeParameterList?.Parameters ?? Enumerable.Empty <TypeParameterSyntax>())
            {
                var aliasedName = parameter.Identifier.ToString();
                if (targetNamespace.DescendantNodes().OfType <UsingDirectiveSyntax>().Any(node => string.Equals(node.Alias?.Name?.ToString(), aliasedName, StringComparison.OrdinalIgnoreCase)))
                {
                    continue;
                }

                if (typeParametersEmitted.Add(parameter.Identifier.ValueText))
                {
                    targetNamespace = targetNamespace.AddUsings(
                        SyntaxFactory.UsingDirective(SyntaxFactory.QualifiedName(SyntaxFactory.IdentifierName(Strings.UnitTestGenerator_AddUsingStatements_System), SyntaxFactory.IdentifierName("String")))
                        .WithAlias(SyntaxFactory.NameEquals(SyntaxFactory.IdentifierName(parameter.Identifier))));
                }
            }

            return(targetNamespace);
        }
Exemplo n.º 13
0
        private string GetEntryPoint(CompilationUnitSyntax rootnode)
        {
            string result = "";

            if (rootnode.Members.Count == 0)
            {
                throw new ApplicationException("Error parsing soure code");
            }

            if (!(rootnode.Members[0] is NamespaceDeclarationSyntax))
            {
                throw new ApplicationException("Error parsing soure code");
            }

            NamespaceDeclarationSyntax rootNameSpace = (NamespaceDeclarationSyntax)rootnode.Members[0];

            if (rootNameSpace is null)
            {
                return(result);
            }

            var entryPointMethod = rootNameSpace.DescendantNodes().OfType <MethodDeclarationSyntax>().Where(n => n.Identifier.Text.Equals("Main")).FirstOrDefault();

            if (entryPointMethod is null)
            {
                return(result);
            }

            var entryType = entryPointMethod.Ancestors().OfType <ClassDeclarationSyntax>().FirstOrDefault();

            if (entryType is null)
            {
                return(result);
            }

            IdentifierNameSyntax name = (IdentifierNameSyntax)rootNameSpace.Name;

            result = String.Concat(name.Identifier.Text, ".", entryType.Identifier.Text);

            return(result);
        }
        /// <summary>
        ///   Takes a namespace declaration and returns a new namespace declaration containing only
        ///   the ServiceContract interfaces, converted to an asynchronous version
        /// </summary>
        /// <param name="originalNamespace">The namespace declaration to replace</param>
        /// <param name="semanticModel"></param>
        /// <returns></returns>
        private static NamespaceDeclarationSyntax ComputeNewNamespaceDeclarationNode(NamespaceDeclarationSyntax originalNamespace, SemanticModel semanticModel, IBindingModelSyntaxGenerator generator)
        {
            var classDeclarations =
                originalNamespace.DescendantNodes().OfType <ClassDeclarationSyntax>();

            var newNamespaceDeclaration = originalNamespace.WithMembers(SyntaxFactory.List <MemberDeclarationSyntax>());

            foreach (var classDeclaration in classDeclarations)
            {
                var classSymbol = semanticModel.GetDeclaredSymbol(classDeclaration);

                var modelDefinition = ModelDefinition.GetModelDefinition(classSymbol);

                if (modelDefinition == null)
                {
                    continue;
                }

                var newClassDeclaration = SyntaxFactory.ClassDeclaration(classDeclaration.Identifier.Text).WithModifiers(SyntaxTokenList.Create(SyntaxFactory.Token(SyntaxKind.PartialKeyword)));

                newClassDeclaration = newClassDeclaration.AddMembers(GetProtectedFillEntityMethodDeclaration(modelDefinition));

                var toEntityMethodDeclaration = GetPublicToEntityMethodDeclaration(modelDefinition);

                if (toEntityMethodDeclaration != null)
                {
                    newClassDeclaration = newClassDeclaration.AddMembers(toEntityMethodDeclaration);
                }

                if (!modelDefinition.IsAbstract)
                {
                    newClassDeclaration = newClassDeclaration.AddMembers(
                        GetToBindingModelMethodDeclaration(modelDefinition, generator));
                }

                newNamespaceDeclaration = newNamespaceDeclaration.AddMembers(newClassDeclaration);
            }

            return(newNamespaceDeclaration);
        }
Exemplo n.º 15
0
        public static NamespaceDeclarationSyntax AppendUsing(
            this NamespaceDeclarationSyntax node,
            params string[] usingDirectives)
        {
            List <string> list = node.DescendantNodes((Func <SyntaxNode, bool>)(p => !(p is ClassDeclarationSyntax)), false).OfType <UsingDirectiveSyntax>().Select <UsingDirectiveSyntax, string>((Func <UsingDirectiveSyntax, string>)(p => p.Name.ToString())).ToList <string>();

            foreach (string usingDirective in usingDirectives)
            {
                if (usingDirective != null && !list.Contains(usingDirective))
                {
                    list.Add(usingDirective);
                }
            }
            list.Sort();
            SyntaxList <UsingDirectiveSyntax> usings = node.Usings;

            while (usings.Count > 0)
            {
                usings = usings.RemoveAt(0);
            }
            usings = usings.AddRange(list.Select <string, UsingDirectiveSyntax>((Func <string, UsingDirectiveSyntax>)(u => u.ToUsing())));
            return(node.WithUsings(usings));
        }
Exemplo n.º 16
0
        private string GetFullClassName(NamespaceDeclarationSyntax node)
        {
            var cls = node.DescendantNodes().OfType <ClassDeclarationSyntax>().FirstOrDefault();

            if (cls == null)
            {
                throw new ArgumentException(this.messageManager.GetMessage("ClassNotFoundInNamespace"));
            }
            string clsName       = cls.Identifier.ValueText;
            string namespaceName = string.Empty;

            if (node.Parent is NamespaceDeclarationSyntax)
            {
                namespaceName = String.Format("{0}.{1}",
                                              GetFullClassName((NamespaceDeclarationSyntax)node.Parent),
                                              ((IdentifierNameSyntax)node.Name).Identifier.ToString());
            }
            else
            {
                namespaceName = ((IdentifierNameSyntax)node.Name).Identifier.ToString();
            }

            return(string.Format("{0}.{1}", namespaceName, clsName));
        }
Exemplo n.º 17
0
 internal Namespace(NamespaceDeclarationSyntax namespaceDeclaration)
 {
     Name    = namespaceDeclaration.Name.ToString();
     Classes = namespaceDeclaration.DescendantNodes().OfType <ClassDeclarationSyntax>().Where(cl => cl.TypeParameterList == null).Select(cl => new Class(cl)).ToArray();
 }
 /// <summary>
 /// Gets the immediate descendants of the namespace.
 /// </summary>
 /// <param name="node">The node.</param>
 /// <returns></returns>
 internal static IEnumerable <SyntaxNode> DescendantNodesImmediate(this NamespaceDeclarationSyntax node)
 => node
 .DescendantNodes(descendIntoChildren: n => n is NamespaceDeclarationSyntax);
Exemplo n.º 19
0
 // returns all classes in a given namespace
 public List <ClassDeclarationSyntax> GetAllClasses(NamespaceDeclarationSyntax namespaceDecl)
 {
     return(namespaceDecl.DescendantNodes().OfType <ClassDeclarationSyntax>().ToList());
 }