internal void Initialize(ClassDeclarationSyntax cds)
        {
            Name = cds.Identifier.ToString();
            foreach (var mds in cds.DescendantNodes().OfType <MethodDeclarationSyntax>())
            {
                SyntaxToken publicToken = mds.ChildTokens().ToList().Find(token => token.ValueText == "public");
                if (publicToken == default(SyntaxToken))
                {
                    continue;
                }

                BaseMethodInfo miToAdd = new BaseMethodInfo();
                miToAdd.Initialize(mds);
                Methods.Add(miToAdd);
            }

            foreach (var ctor in cds.DescendantNodes().OfType <ConstructorDeclarationSyntax>())
            {
                SyntaxToken publicToken = cds.ChildTokens().ToList().Find(token => token.ValueText == "public");
                if (publicToken == default(SyntaxToken))
                {
                    continue;
                }

                BaseMethodInfo miToAdd = new BaseMethodInfo();
                miToAdd.Initialize(ctor);
                Constructors.Add(miToAdd);
            }
        }
        public static IEnumerable <EntryPoint> GetPublicEntryPoints(this ClassDeclarationSyntax c)
        {
            List <EntryPoint> entryPoints = new List <EntryPoint>();

            foreach (var m in c.DescendantNodes()
                     .OfType <MethodDeclarationSyntax>()
                     .Where(m => m.Modifiers.Any(mod => mod.Text.Equals("public"))))
            {
                entryPoints.Add(new EntryPoint(m));
            }
            foreach (var m in c.DescendantNodes()
                     .OfType <ConstructorDeclarationSyntax>()
                     .Where(m => m.Modifiers.Any(mod => mod.Text.Equals("public"))))
            {
                entryPoints.Add(new EntryPoint(m));
            }
            foreach (var m in c.DescendantNodes()
                     .OfType <PropertyDeclarationSyntax>()
                     .Where(m => m.Modifiers.Any(mod => mod.Text.Equals("public"))))
            {
                foreach (var a in m.AccessorList.Accessors)
                {
                    entryPoints.Add(new EntryPoint(a, m.Type.ToString(), m.Identifier.Text));
                }
            }
            return(entryPoints);
        }
        public static ClassDeclarationSyntax AddProperty(this ClassDeclarationSyntax currentClass,
                                                         string name, INamedTypeSymbol type)
        {
            if (currentClass.DescendantNodes().OfType <PropertyDeclarationSyntax>()
                .Any(p => p.Identifier.Text == name))
            {
                // class already has the specified property
                return(currentClass);
            }
            if (currentClass.DescendantNodes().OfType <PropertyDeclarationSyntax>().Count() > 128)
            {
                throw new Exception("Class already has too many properties");
            }
            var typeSentax  = SyntaxFactory.ParseTypeName(type.Name);
            var newProperty = SyntaxFactory.PropertyDeclaration(typeSentax, name)
                              .WithModifiers(
                SyntaxFactory.TokenList(
                    SyntaxFactory.Token(SyntaxKind.PublicKeyword)))
                              .WithAccessorList(
                SyntaxFactory.AccessorList(
                    SyntaxFactory.List(
                        new[]
            {
                SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)),
                SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
                .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))
            })));

            return(currentClass.AddMembers(newProperty));
        }
Esempio n. 4
0
        private void GenerateOrdinaryClass(ClassDeclarationSyntax classDeclaration, SemanticModel semanticModel, string outputPath)
        {
            INamedTypeSymbol typeInfo   = semanticModel.GetDeclaredSymbol(classDeclaration);
            var fullyQualifiedNameParts = SyntaxTreeHelper.GetFullyQualifiedNameParts(typeInfo);
            var genericTypeParameters   = typeInfo.TypeParameters;
            var typeReferences          = new HashSet <string>();

            var propertyDeclarations = classDeclaration.DescendantNodes().OfType <PropertyDeclarationSyntax>();
            var generatedProperties  = GetProperties(semanticModel, typeReferences, propertyDeclarations, false);

            var fieldsDeclarations = classDeclaration.DescendantNodes().OfType <FieldDeclarationSyntax>();
            var generatedFields    = GetFields(semanticModel, typeReferences, fieldsDeclarations);

            var constructorDeclarations = classDeclaration.DescendantNodes().OfType <ConstructorDeclarationSyntax>();
            var generatedConstructors   = GetConstructors(semanticModel, typeReferences, constructorDeclarations);

            var methodDeclarations = classDeclaration.DescendantNodes().OfType <MethodDeclarationSyntax>();
            var generatedMethods   = GetMethods(semanticModel, typeReferences, methodDeclarations);

            var classSourceCode = TypeBuilder.BuildType(semanticModel,
                                                        fullyQualifiedNameParts, genericTypeParameters,
                                                        typeInfo.BaseType,
                                                        typeInfo.AllInterfaces,
                                                        generatedConstructors,
                                                        generatedFields,
                                                        generatedProperties,
                                                        generatedMethods);

            WriteToOutputIfPathPresent(outputPath, fullyQualifiedNameParts, classSourceCode.MainPart);
        }
Esempio n. 5
0
        private ClassDeclarationSyntax TranslateClass(ClassDeclarationSyntax classDeclaration)
        {
            for (int i = 0; i < classDeclaration.AttributeLists.Count; i++)
            {
                var attributeList = classDeclaration.AttributeLists.ToList()[i];
                AttributeListSyntax newAttributeList = AttributeTranslator.TranslateClassAttributeList(attributeList);
                classDeclaration = classDeclaration.ReplaceNode(attributeList, newAttributeList);
            }

            classDeclaration = AddClassAnnotationIfNotPresent(classDeclaration);
            classDeclaration = AddPublicModifierIfNotPresent(classDeclaration);

            //methods
            List <MethodDeclarationSyntax> methods = classDeclaration.DescendantNodes().OfType <MethodDeclarationSyntax>().ToList();

            for (int i = 0; i < classDeclaration.DescendantNodes().OfType <MethodDeclarationSyntax>().Count(); i++)
            {
                methods[i] = classDeclaration.DescendantNodes().OfType <MethodDeclarationSyntax>().ToList()[i];
                var methodDeclaration = methods[i];
                if (IsTranslatable(methodDeclaration))
                {
                    MethodDeclarationSyntax translatedMethod = TranslateMethod(methods[i]);
                    classDeclaration = classDeclaration.ReplaceNode(methods[i], translatedMethod);
                }
                else
                {
                    classDeclaration = classDeclaration.ReplaceNode(methods[i], Comment(methodDeclaration));
                    classDeclaration = classDeclaration.RemoveNode(classDeclaration.DescendantNodes().OfType <MethodDeclarationSyntax>().ToList()[i], SyntaxRemoveOptions.KeepExteriorTrivia);
                    i--;
                }
            }
            return(classDeclaration);
        }
Esempio n. 6
0
        public void TestGetSyntaxNodesFromIdentifierObjectCreation()
        {
            string code1 = "public class TestCLass{public void Main(){ClassA test = new ClassA(0);}} public class ClassA{ public ClassA(){} public ClassA(int param){}}";

            SyntaxTree tree1 = CSharpSyntaxTree.ParseText(code1);
            ObjectCreationExpressionSyntax node1 = tree1.GetRootAsync().Result.DescendantNodesAndSelf().OfType <ObjectCreationExpressionSyntax>().First();
            ClassDeclarationSyntax         node2 = tree1.GetRootAsync().Result.DescendantNodesAndSelf().OfType <ClassDeclarationSyntax>().Last();
            ConstructorDeclarationSyntax   node3 = node2.DescendantNodes().OfType <ConstructorDeclarationSyntax>().First();
            ConstructorDeclarationSyntax   node4 = node2.DescendantNodes().OfType <ConstructorDeclarationSyntax>().Last();
            IdentifierNameSyntax           node5 = node1.DescendantNodes().OfType <IdentifierNameSyntax>().Last();

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

            ScriptAnalyzerSymbolHelper   sHelper = new ScriptAnalyzerSymbolHelper(new Compilation[] { comp1 });
            ScriptAnalyzerResourceHelper rHelper = new ScriptAnalyzerResourceHelper(sHelper);

            List <SyntaxNode> result = rHelper.GetSyntaxNodes(node5);

            Assert.IsNotNull(result, "Returns a list");
            Assert.AreEqual(1, result.Count(), "List has one node");
            CollectionAssert.Contains(result, node2, "Node is class");
        }
Esempio n. 7
0
        public void Symbol_IsInterfaceImplementationOrMemberOverride()
        {
            var method = baseClassDeclaration.DescendantNodes().OfType <MethodDeclarationSyntax>()
                         .First(m => m.Identifier.ValueText == "Method1");
            var symbol = semanticModel.GetDeclaredSymbol(method);

            symbol.GetInterfaceMember().Should().BeNull();
            symbol.GetOverriddenMember().Should().BeNull();

            var property = derivedClassDeclaration2.DescendantNodes().OfType <PropertyDeclarationSyntax>()
                           .First(m => m.Identifier.ValueText == "Property");

            symbol = semanticModel.GetDeclaredSymbol(property);

            symbol.GetOverriddenMember().Should().NotBeNull();

            property = derivedClassDeclaration2.DescendantNodes().OfType <PropertyDeclarationSyntax>()
                       .First(m => m.Identifier.ValueText == "Property2");
            symbol = semanticModel.GetDeclaredSymbol(property);

            symbol.GetInterfaceMember().Should().NotBeNull();

            method = derivedClassDeclaration2.DescendantNodes().OfType <MethodDeclarationSyntax>()
                     .First(m => m.Identifier.ValueText == "Method3");
            symbol = semanticModel.GetDeclaredSymbol(method);

            symbol.GetInterfaceMember().Should().NotBeNull();
        }
        public static int GetCount(ClassDeclarationSyntax classNode)
        {
            int methodDeclarations = classNode
                                     .DescendantNodes()
                                     .Count(x => x is MethodDeclarationSyntax || x is ConstructorDeclarationSyntax)
            ;

            int methodInvocations = classNode
                                    .DescendantNodes()
                                    .Count(x => x is InvocationExpressionSyntax || x is ObjectCreationExpressionSyntax)
            ;

            return(methodDeclarations + methodInvocations);
        }
Esempio n. 9
0
        public void Symbol_IsPublicApi()
        {
            var method = baseClassDeclaration.DescendantNodes().OfType <MethodDeclarationSyntax>()
                         .First(m => m.Identifier.ValueText == "Method1");
            var symbol = semanticModel.GetDeclaredSymbol(method);

            SymbolHelper.IsPubliclyAccessible(symbol).Should().BeTrue();

            method = baseClassDeclaration.DescendantNodes().OfType <MethodDeclarationSyntax>()
                     .First(m => m.Identifier.ValueText == "Method2");
            symbol = semanticModel.GetDeclaredSymbol(method);

            symbol.IsPubliclyAccessible().Should().BeTrue();

            var property = baseClassDeclaration.DescendantNodes().OfType <PropertyDeclarationSyntax>()
                           .First(m => m.Identifier.ValueText == "Property");

            symbol = semanticModel.GetDeclaredSymbol(property);

            symbol.IsPubliclyAccessible().Should().BeTrue();

            property = interfaceDeclaration.DescendantNodes().OfType <PropertyDeclarationSyntax>()
                       .First(m => m.Identifier.ValueText == "Property2");
            symbol = semanticModel.GetDeclaredSymbol(property);

            symbol.IsPubliclyAccessible().Should().BeTrue();

            property = derivedClassDeclaration1.DescendantNodes().OfType <PropertyDeclarationSyntax>()
                       .First(m => m.Identifier.ValueText == "Property");
            symbol = semanticModel.GetDeclaredSymbol(property);

            symbol.IsPubliclyAccessible().Should().BeFalse();
        }
Esempio n. 10
0
        static public Func <SyntaxNode, Scope, SyntaxNode> AddInitializers(StatementSyntax initializer)
        {
            return((node, scope) =>
            {
                ClassDeclarationSyntax decl = (ClassDeclarationSyntax)node;

                var found = false;
                var result = decl.ReplaceNodes(decl
                                               .DescendantNodes()
                                               .OfType <ConstructorDeclarationSyntax>(), (oldConstuctor, newConstuctor) =>
                {
                    found = true;
                    return newConstuctor.WithBody(SyntaxFactory.Block().
                                                  WithStatements(SyntaxFactory.List(
                                                                     newConstuctor.Body.Statements.Union(
                                                                         new[] { initializer }))));
                });

                if (!found)
                {
                    result = result.WithMembers(SyntaxFactory.List(
                                                    result.Members.Union(
                                                        new MemberDeclarationSyntax[] {
                        SyntaxFactory.ConstructorDeclaration(decl.Identifier.ToString()).
                        WithBody(SyntaxFactory.Block().
                                 WithStatements(SyntaxFactory.List(new[] {
                            initializer
                        })))
                    })));
                }

                return result;
            });
        }
Esempio n. 11
0
        private void AssertGeneratedFileDesc(GeneratedFileDescription fileDesc, string fileName,
                                             string namespaceName, string className, string[] methodNames)
        {
            Assert.True(fileDesc.Name == fileName);

            SyntaxNode root = CSharpSyntaxTree.ParseText(fileDesc.Text).GetRoot();

            ClassDeclarationSyntax[] classes = root.DescendantNodes().OfType <ClassDeclarationSyntax>().ToArray();

            Assert.True(classes.Length == 1);

            ClassDeclarationSyntax clazz = classes[0];

            Assert.True(clazz.Identifier.ValueText == className);
            Assert.True((clazz.Parent as NamespaceDeclarationSyntax)?.Name?.ToString() == namespaceName);

            MethodDeclarationSyntax[] methods = clazz.DescendantNodes().OfType <MethodDeclarationSyntax>().ToArray();

            Assert.True(methods.Length == methodNames.Length);

            foreach (MethodDeclarationSyntax method in methods)
            {
                Assert.Contains(method.Identifier.ValueText, methodNames);

                Assert.True(method.AttributeLists.Count == 1);
                Assert.True(method.AttributeLists.First().Attributes.First().Name.ToString() == "Fact");
            }
        }
Esempio n. 12
0
        private void AnalyzeDacDeclaration(SyntaxNodeAnalysisContext syntaxContext, PXContext pxContext)
        {
            ClassDeclarationSyntax classDeclaration = (ClassDeclarationSyntax)syntaxContext.Node;
            INamedTypeSymbol       typeSymbol       =
                syntaxContext.SemanticModel.GetDeclaredSymbol(classDeclaration, syntaxContext.CancellationToken);

            if (typeSymbol != null && typeSymbol.IsDacOrExtension(pxContext))
            {
                IEnumerable <INamedTypeSymbol> whiteList = GetWhitelist(pxContext);

                foreach (SyntaxNode node in classDeclaration.DescendantNodes(
                             n => !(n is ClassDeclarationSyntax) || IsDacOrExtension(n, pxContext, syntaxContext.SemanticModel, syntaxContext.CancellationToken)))
                {
                    syntaxContext.CancellationToken.ThrowIfCancellationRequested();

                    if (node is MethodDeclarationSyntax method)
                    {
                        AnalyzeMethodDeclarationInDac(method, syntaxContext, pxContext);
                    }
                    else if (node is PropertyDeclarationSyntax property)
                    {
                        AnalyzeMethodInvocationInDacProperty(property, whiteList, syntaxContext, pxContext);
                    }
                }
            }
        }
Esempio n. 13
0
        private CompilationUnitSyntax GenerateTestClassFile(ClassDeclarationSyntax classDeclaration)
        {
            var methods = classDeclaration.DescendantNodes().OfType <MethodDeclarationSyntax>()
                          .Where(x => x.Modifiers.Any(y => y.ValueText == "public"));
            string        ns           = (classDeclaration.Parent as NamespaceDeclarationSyntax)?.Name.ToString();
            List <string> methodsNames = new List <string>();

            foreach (MethodDeclarationSyntax method in methods)
            {
                string tempMethodName = GetMethodName(methodsNames, method.Identifier.ToString(), 0);
                methodsNames.Add(tempMethodName);
            }
            CompilationUnitSyntax result = CompilationUnit();

            result = result.WithUsings(GenerateUsingDirective());
            string className = classDeclaration.Identifier.ValueText;
            ClassDeclarationSyntax testClassDeclaration = ClassDeclaration(className + "Test");
            var classAttribute      = Attribute(IdentifierName("TestClass"));
            var classAttributesList = SingletonList(AttributeList(SingletonSeparatedList(classAttribute)));

            testClassDeclaration = testClassDeclaration.WithAttributeLists(classAttributesList);
            testClassDeclaration = testClassDeclaration.WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword)));
            testClassDeclaration = testClassDeclaration.WithMembers(GenerateMethodsList(methodsNames));
            SyntaxList <MemberDeclarationSyntax> classes = SingletonList <MemberDeclarationSyntax>(testClassDeclaration);
            NamespaceDeclarationSyntax           namespaceDeclaration =
                NamespaceDeclaration(QualifiedName(IdentifierName(ns), IdentifierName("Test")));

            namespaceDeclaration = namespaceDeclaration.WithMembers(classes);
            result = result.WithMembers(SingletonList <MemberDeclarationSyntax>(namespaceDeclaration));
            return(result);
        }
            ClassDeclarationSyntax Remove(ClassDeclarationSyntax classNode)
            {
                var thises   = classNode.DescendantNodes().OfType <ThisExpressionSyntax>();
                var newItems = new Dictionary <MemberAccessExpressionSyntax, SyntaxNode>();

                foreach (var thisItem in thises)
                {
                    if (thisItem.Parent is MemberAccessExpressionSyntax thisItemAsMemberAccessException)
                    {
                        var newAccess = GetMemberAccessWithoutThis(thisItemAsMemberAccessException);

                        if (newAccess != null)
                        {
                            newItems.Add(thisItemAsMemberAccessException, newAccess);
                        }
                    }
                }

                if (newItems.Any())
                {
                    classNode = classNode.ReplaceNodes(newItems.Keys, (node1, node2) => newItems[node1]);
                }

                return(classNode);
            }
Esempio n. 15
0
        public SyntaxNode GenerateTestsForClass(ClassDeclarationSyntax classDeclaration)
        {
            if (!(classDeclaration.Parent is NamespaceDeclarationSyntax))
            {
                return(null);
            }

            string     sourceClassNamespace = (classDeclaration.Parent as NamespaceDeclarationSyntax).Name.ToString();
            SyntaxNode result = CompilationUnit()
                                .WithUsings(
                List <UsingDirectiveSyntax>(
                    new UsingDirectiveSyntax[] {
                UsingDirective(
                    IdentifierName("System")),
                UsingDirective(
                    IdentifierName("Microsoft.VisualStudio.TestTools.UnitTesting")),
                UsingDirective(
                    IdentifierName(sourceClassNamespace))
            }))
                                .WithMembers(
                SingletonList <MemberDeclarationSyntax>(
                    NamespaceDeclaration(
                        QualifiedName(
                            IdentifierName(sourceClassNamespace),
                            IdentifierName("Test")))));

            result = GenerateClassNode(result, classDeclaration);
            result = GenerateTestMethods(result, classDeclaration.DescendantNodes().OfType <MethodDeclarationSyntax>());
            return(result.NormalizeWhitespace());
        }
Esempio n. 16
0
        public void TestAnalyzeClass()
        {
            string     code1 = @"class TestClass { public void TestMethod( int test = 0; test = 1;){}}";
            SyntaxTree tree1 = CSharpSyntaxTree.ParseText(code1);

            ClassDeclarationSyntax classNode = tree1.GetRootAsync().Result.DescendantNodes().OfType <ClassDeclarationSyntax>().First();

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

            ScriptAnalyzer analyzer = this.createAnalyzer(comp1);

            TaggedSyntaxLibrary lib = analyzer.AnalyzeNode(classNode);

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

            TaggedSyntaxTree tree = lib.TaggedSyntaxTrees.First();

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

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

            foreach (SyntaxNode node in nodes)
            {
                CollectionAssert.DoesNotContain(tree.TaggedNodes, node, "SubNode is not added to tree");
            }
        }
Esempio n. 17
0
        private static IEnumerable <ParameterMetadata> GetClassDependencies(ClassDeclarationSyntax Class)
        {
            var constructors = Class.DescendantNodes()
                               .OfType <ConstructorDeclarationSyntax>()
                               .Where(method => method.Modifiers
                                      .Any(modifier => modifier.ToString() == "public"));

            foreach (var constructor in constructors)
            {
                var dependencies = constructor.ParameterList.Parameters.Where(param =>
                                                                              param.Type.GetTypeName()
                                                                              .StartsWith("I"));

                if (!dependencies.Count().Equals(0))
                {
                    return(dependencies.Select(param => new ParameterMetadata()
                    {
                        Name = param.Identifier.Value.ToString(),
                        Type = param.Type
                    }));
                }
            }

            // no dependencies were found

            return(null);
        }
Esempio n. 18
0
            static ClassDeclarationSyntax ReplaceAddProperties(TableModel tableModel, ClassDeclarationSyntax newClass)
            {
                var columnsDict = tableModel.Columns.ToDictionary(c => c.Name);

                var replacements = new Dictionary <PropertyDeclarationSyntax, PropertyDeclarationSyntax>();

                foreach (var oldProperty in newClass.DescendantNodes()
                         .OfType <PropertyDeclarationSyntax>()
                         .Where(p => columnsDict.ContainsKey(p.Identifier.ValueText)))
                {
                    var columnModel = columnsDict[oldProperty.Identifier.ValueText];

                    columnsDict.Remove(oldProperty.Identifier.ValueText);

                    var newProperty = GenerateColumnProperty(columnModel)
                                      .WithAttributeLists(oldProperty.AttributeLists);

                    replacements.Add(oldProperty, newProperty);
                }

                newClass = newClass.ReplaceNodes(replacements.Keys, (o, _) => replacements[o]);

                if (columnsDict.Count > 0)
                {
                    newClass = newClass.AddMembers(tableModel
                                                   .Columns
                                                   .Where(c => columnsDict.ContainsKey(c.Name))
                                                   .Select(GenerateColumnProperty)
                                                   .Cast <MemberDeclarationSyntax>()
                                                   .ToArray());
                }

                return(newClass);
            }
Esempio n. 19
0
        private IEnumerable <AnalysisResult> AnalyzeClassDeclaration(
            ClassDeclarationSyntax syntax)
        {
            var result = new List <AnalysisResult>();

            // Retrieve all class properties
            var properties =
                syntax.DescendantNodes().OfType <PropertyDeclarationSyntax>();

            // Append all properties display/display name attributes
            foreach (var prop in properties)
            {
                var displays =
                    prop.AttributeLists.SelectMany(p => p.Attributes)
                    .Select(AnalyzeAttribute)
                    .Where(r => r != null)
                    .ToArray();

                if (displays.Length > 0)
                {
                    // Append any display/display attribute
                    result.AddRange(displays);
                    continue;
                }

                // Append direct property name
                result.Add(new AnalysisResult(prop.Identifier.ValueText,
                                              CreateSource(prop)));
            }

            // Done
            return(result);
        }
Esempio n. 20
0
 private static List <AttributeSyntax> FindTestCaseSourceAttributes(ClassDeclarationSyntax node)
 {
     return(node.DescendantNodes()
            .OfType <AttributeSyntax>()
            .Where(attr => attr.Name.ToString() == "TestCaseSource")
            .ToList());
 }
Esempio n. 21
0
        public JavaClass Translate(ClassDeclarationSyntax declarationNode, CSharpSyntaxVisitor <IStmt> statementTranslator)
        {
            var symbol = semanticModel.GetDeclaredSymbol(declarationNode);

            if (symbol == null)
            {
                throw new Exception("Cannot build semantic information for class type");
            }
            var descendantNodes = declarationNode.DescendantNodes().ToArray();
            var methods         = descendantNodes.OfType <MethodDeclarationSyntax>()
                                  .Select(method => TranslatorHelper.TranslateMethod(semanticModel, method, statementTranslator)).ToArray();
            var ctors  = descendantNodes.OfType <ConstructorDeclarationSyntax>().Select(ctor => TranslateCtor(ctor, statementTranslator)).ToArray();
            var fields = TranslatorHelper.GetFields(declarationNode)
                         .Select(node => TranslatorHelper.TranslateField(semanticModel, node, statementTranslator));
            var props = TranslatorHelper.GetProperties(declarationNode)
                        .Select(node => TranslatorHelper.TranslateProp(semanticModel, node, statementTranslator));
            var className = declarationNode.Identifier.ToString();

            return(new JavaClass
            {
                Name = className,
                Methods = ctors.Concat <IMethod>(methods).ToArray(),
                Fields = props.Concat(fields).ToArray(),
                TypeSymbol = symbol,
                DeclaredAccessibility = symbol.DeclaredAccessibility,
                IsAbstract = symbol.IsAbstract
            });
        }
Esempio n. 22
0
        public static IReadOnlyDictionary <string, ExpressionSyntax> Fields(this ClassDeclarationSyntax claz)
        {
            var fields = new Dictionary <string, ExpressionSyntax>();

            if (claz == null)
            {
                return(fields);
            }

            var variables = claz.DescendantNodes <VariableDeclaratorSyntax>()
                            .Where(x => x.Initializer != null &&
                                   x.Parent is VariableDeclarationSyntax parent &&
                                   !parent.Type.ToString().Contains("[]") &&
                                   x.Ancestors <FieldDeclarationSyntax>().Any());

            foreach (VariableDeclaratorSyntax variable in variables)
            {
                var identifierText = variable.Identifier.Text;
                if (!fields.ContainsKey(identifierText))
                {
                    fields.Add(identifierText, variable.Initializer.Value);
                }
            }

            return(fields);
        }
Esempio n. 23
0
 protected override TypeSyntax GetTypeOfMemberDeclarationOrDefault(ClassDeclarationSyntax @class, string memberName)
 {
     return(@class
            .DescendantNodes <PropertyDeclarationSyntax>()
            .FirstOrDefault(pds => pds.Identifier.Text == memberName)
            ?.Type);
 }
Esempio n. 24
0
        /// <summary>
        /// 從程式碼讀出 class 的結構
        /// </summary>
        public static CsSchema.Class AnalysisClass(string programText)
        {
            CsSchema.Class           csClass      = new CsSchema.Class();
            List <CsSchema.Property> csProperties = new List <CsSchema.Property>();
            SyntaxTree             tree           = CSharpSyntaxTree.ParseText(programText);
            CompilationUnitSyntax  root           = tree.GetRoot() as CompilationUnitSyntax;
            ClassDeclarationSyntax classSyntax    =
                root.DescendantNodes().OfType <ClassDeclarationSyntax>().Single();
            IEnumerable <PropertyDeclarationSyntax> propertiesSyntax =
                classSyntax.DescendantNodes().OfType <PropertyDeclarationSyntax>();

            foreach (var propertySyntax in propertiesSyntax)
            {
                PredefinedTypeSyntax typeSyntax =
                    propertySyntax.DescendantNodes().OfType <PredefinedTypeSyntax>().Single();
                SyntaxToken type     = typeSyntax.Keyword;
                SyntaxToken property = propertySyntax.Identifier;
                csProperties.Add(new CsSchema.Property()
                {
                    Name     = property.Text,
                    TypeName = type.Text
                });
            }
            csClass.Name       = classSyntax.Identifier.Text;
            csClass.Properties = csProperties.ToArray();
            return(csClass);
        }
        private static IEnumerable <ObjectCreationExpressionSyntax> GetObjectCreations(SyntaxNodeAnalysisContext context, ClassDeclarationSyntax classDeclaration, PropertyDeclarationSyntax propertyDeclarationSyntax, IPropertySymbol propertySymbol)
        {
            var objectCreations = classDeclaration.DescendantNodes()
                                  .OfType <AssignmentExpressionSyntax>()
                                  .Where(a => context.SemanticModel.GetSymbolInfo(a.Left).Symbol.Equals(propertySymbol) && a.Right is ObjectCreationExpressionSyntax)
                                  .Select(a => a.Right as ObjectCreationExpressionSyntax).ToList();

            var arrowExpressionClause = propertyDeclarationSyntax.DescendantNodes()
                                        .OfType <ArrowExpressionClauseSyntax>()
                                        .SingleOrDefault(a => a.Expression is ObjectCreationExpressionSyntax)
                                        ?.Expression as ObjectCreationExpressionSyntax;

            if (arrowExpressionClause != null)
            {
                objectCreations.Add(arrowExpressionClause);
            }

            var getAcessorDeclararion = propertyDeclarationSyntax.DescendantNodes()
                                        .OfType <AccessorDeclarationSyntax>()
                                        .SingleOrDefault(a => a.IsKind(SyntaxKind.GetAccessorDeclaration));

            if (getAcessorDeclararion != null)
            {
                objectCreations.AddRange(getAcessorDeclararion.DescendantNodes()
                                         .OfType <ObjectCreationExpressionSyntax>());
            }

            return(objectCreations);
        }
Esempio n. 26
0
        private static SyntaxList <MemberDeclarationSyntax> GetTemplateMethods(ClassDeclarationSyntax clsInfo, SemanticModel model)
        {
            List <MemberDeclarationSyntax> classMethods = new List <MemberDeclarationSyntax>();

            string templateAttribute = "Test";

            //add setUp
            var constructor = (ConstructorDeclarationSyntax)clsInfo.ChildNodes().FirstOrDefault(n => n.Kind() == SyntaxKind.ConstructorDeclaration);

            if (constructor != null)
            {
                if (!clsInfo.Modifiers.Where(m => m.Kind().Equals(SyntaxKind.StaticKeyword)).Any())
                {
                    var constructorMethod = AddSetUpMethod(clsInfo, model, constructor);
                    classMethods.Add(constructorMethod);
                }
            }

            var publicMethods = clsInfo.DescendantNodes().OfType <MethodDeclarationSyntax>().Where(
                method => method.Modifiers.Any(modifier => modifier.ValueText == "public"));

            foreach (var method in publicMethods)
            {
                if (method != null)
                {
                    string classname  = char.ToLower(clsInfo.Identifier.ValueText[0]) + clsInfo.Identifier.ValueText.Substring(1);
                    var    testMethod = AddMethod(classname, model, method, method.Identifier.ValueText + "Test", templateAttribute);
                    classMethods.Add(testMethod);
                }
            }

            return(List(classMethods));
        }
Esempio n. 27
0
        private List <MethodDescription> GetMethodWithParameter(ClassDeclarationSyntax classSyntax, SemanticModel model, string parameterType, string attributeType = null)
        {
            var filter = classSyntax.DescendantNodes()
                         .OfType <MethodDeclarationSyntax>()
                         .Where(m => m.ParameterList.Parameters.Count == 1 && !m.Modifiers.Any(x => x.ValueText == "private"));

            if (attributeType != null)
            {
                filter = filter.Where(m => m.AttributeLists.Any(a => a.Attributes.Any(x => x.Name.ToString() == attributeType)));
            }

            var result = filter.Select(method => new
            {
                Name       = method.Identifier.ValueText,
                ReturnType = model.GetTypeInfo(method.ReturnType).Type as INamedTypeSymbol,
                Parameter  = model.GetDeclaredSymbol(method.ParameterList.Parameters.FirstOrDefault()),
                Attributes = method.AttributeLists.SelectMany(a => a.Attributes.Select(ax => new AttributeDescriptor
                {
                    Name   = ax.Name.ToString(),
                    Values = (ax?.ArgumentList?.Arguments.Select(x => x.Expression.ToFullString()) ?? Enumerable.Empty <string>()).ToList()
                }))
            }).Where(x => x.Parameter.Type.BaseType?.Name == parameterType || x.Parameter.Type.BaseType?.BaseType?.Name == parameterType || x.Parameter.Type.Name == parameterType)
                         .Select(c => new MethodDescription
            {
                MethodName                = c.Name,
                ParameterType             = c.Parameter.Type.Name,
                ReturnType                = c.ReturnType.Name,
                ReturnTypeGenericArgument = c.ReturnType.TypeArguments.FirstOrDefault()?.ToString(),
                Attributes                = c.Attributes.ToList()
                                            // TODO write recursive base type check
            }).ToList();

            return(result);
        }
Esempio n. 28
0
        public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            var attributeRemover = new AttributeRemover(node.AttributeLists, "TestFixture");

            if (attributeRemover.IsHavingAttribute)
            {
                if (!node.Modifiers.Any(m => m.IsKind(SyntaxKind.PublicKeyword)))
                {
                    var publicKeyword = SyntaxFactory.Token(SyntaxKind.PublicKeyword)
                                        .WithTrailingTrivia(SyntaxTriviaList.Create(SyntaxFactory.Space));
                    node = node.WithModifiers(node.Modifiers.Add(publicKeyword));
                }

                node = node.WithAttributeLists(attributeRemover.Remove());
            }

            if (node.DescendantNodes().Any(n => n is MethodDeclarationSyntax m &&
                                           m.AttributeLists.Contains("TearDown")))
            {
                node = node.AddBaseListTypes(
                    SyntaxFactory.SimpleBaseType(
                        SyntaxFactory.IdentifierName("IDisposable")).WithoutTrivia());
                node = node.WithIdentifier(node.Identifier.WithoutTrivia());
            }

            return(base.VisitClassDeclaration(node));
        }
        public void GetTemplateTest()
        {
            testClassTemplate = templateGenerator.GetTemplate(sourceCode);
            Assert.IsNotNull(testClassTemplate);
            generatedRoot = CSharpSyntaxTree.ParseText(testClassTemplate.InnerText).GetRoot();
            List <ClassDeclarationSyntax> generatedClasses = new List <ClassDeclarationSyntax>(generatedRoot.DescendantNodes().OfType <ClassDeclarationSyntax>());
            List <ClassDeclarationSyntax> sourceClasses    = new List <ClassDeclarationSyntax>(sourceRoot.DescendantNodes().OfType <ClassDeclarationSyntax>());

            Assert.AreEqual(sourceClasses.Count, generatedClasses.Count);

            for (int i = 0; i < sourceClasses.Count; i++)
            {
                ClassDeclarationSyntax sourceClass    = sourceClasses[i];
                ClassDeclarationSyntax generatedClass = generatedClasses[i];

                List <MethodDeclarationSyntax> sourceMethods = new List <MethodDeclarationSyntax>(
                    sourceClass.DescendantNodes().OfType <MethodDeclarationSyntax>()
                    .Where(method => method.Modifiers.
                           Any(modifer => modifer.ToString() == "public")));
                List <MethodDeclarationSyntax> generatedMethods = new List <MethodDeclarationSyntax>(
                    generatedClass.DescendantNodes().OfType <MethodDeclarationSyntax>()
                    .Where(method => method.Modifiers.
                           Any(modifer => modifer.ToString() == "public")));
                Assert.AreEqual(sourceMethods.Count, generatedMethods.Count);

                for (int j = 0; j < sourceMethods.Count; j++)
                {
                    MethodDeclarationSyntax sourceMethod    = sourceMethods[j];
                    MethodDeclarationSyntax generatedMethod = generatedMethods[j];
                    Assert.IsTrue(generatedMethod.Identifier.ToString().Contains(sourceMethod.Identifier.ToString()));
                }
            }
        }
Esempio n. 30
0
        public static SyntaxNode InsertPropInTopOfClass(SyntaxNode rootNode, string className, PropertyDeclarationSyntax property)
        {
            ClassDeclarationSyntax classNode = rootNode
                                               .DescendantNodes()
                                               .OfType <ClassDeclarationSyntax>()
                                               .FirstOrDefault(n => n.Identifier.ValueText == className);
            PropertyDeclarationSyntax firstProp = classNode
                                                  .DescendantNodes()
                                                  .OfType <PropertyDeclarationSyntax>()
                                                  .FirstOrDefault();

            // Если в классе есть свойство, новое добавляется перед ним
            if (firstProp != null)
            {
                rootNode = rootNode.InsertNodesBefore(
                    firstProp,
                    new List <PropertyDeclarationSyntax>()
                {
                    property.WithTrailingTrivia(property.GetTrailingTrivia())
                });
            }

            else
            {
                rootNode = rootNode.ReplaceNode(
                    classNode,
                    classNode.WithMembers(List(
                                              new List <MemberDeclarationSyntax>()
                {
                    property
                })));
            }

            return(rootNode);
        }