Exemplo n.º 1
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);
        }
Exemplo n.º 2
0
        public static NamespaceDeclarationSyntax AddNamespaceTo(
            ICodeGenerationService service,
            NamespaceDeclarationSyntax destination,
            INamespaceSymbol @namespace,
            CodeGenerationOptions options,
            IList <bool> availableIndices,
            CancellationToken cancellationToken
            )
        {
            var declaration = GenerateNamespaceDeclaration(
                service,
                @namespace,
                options,
                cancellationToken
                );

            if (!(declaration is NamespaceDeclarationSyntax))
            {
                throw new ArgumentException(
                          CSharpWorkspaceResources.Namespace_can_not_be_added_in_this_destination
                          );
            }

            var members = Insert(
                destination.Members,
                (NamespaceDeclarationSyntax)declaration,
                options,
                availableIndices
                );

            return(destination.WithMembers(members));
        }
Exemplo n.º 3
0
        private static SyntaxTree MakeProgram(string sourceFilePath, IOKind ioKind, string methodName, string className, string namespaceName)
        {
            ParsingResult result = Parsing.ParseFromFile(sourceFilePath);

            if (!result.Success)
            {
                throw new Exception("Syntax error in source file.");
            }
            else
            {
                if (!result.ParsedAll)
                {
                    Console.WriteLine("Could not parse the whole source file, output might not work as intended.");
                }

                MethodDeclarationSyntax method = Exprs.Method(methodName, ioKind, result.SyntaxGenerators);

                if (ioKind == IOKind.Argument)
                {
                    method = method.WithParameterList(SyntaxFactory.ParseParameterList("(IEnumerable<byte> input)"));
                }

                ClassDeclarationSyntax @class = Exprs.Class(className);
                @class = @class.WithMembers(SyntaxFactory.SingletonList <MemberDeclarationSyntax>(method));

                NamespaceDeclarationSyntax @namespace = Exprs.Namespace(namespaceName);
                @namespace = @namespace.WithMembers(SyntaxFactory.SingletonList <MemberDeclarationSyntax>(@class));

                CompilationUnitSyntax cu = SyntaxFactory.CompilationUnit().AddMembers(@namespace);

                return(SyntaxFactory.SyntaxTree(cu, path: sourceFilePath));
            }
        }
        public static SourceText GeneratePrintMembersText(
            RecordDeclarationSyntax recordDeclaration,
            INamedTypeSymbol recordSymbol,
            Dictionary <SymbolClassification, List <ISymbol> > groups)
        {
            MemberDeclarationSyntax printMembersMethod = SyntaxFactory.MethodDeclaration(
                attributeLists: s_emptyAttributeList,
                modifiers: GetPrintMembersModifiers(recordSymbol),
                returnType: SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.BoolKeyword)),
                explicitInterfaceSpecifier: null,
                identifier: s_printMembersIdentifier,
                typeParameterList: null,
                parameterList: SyntaxFactory.ParameterList(
                    SyntaxFactory.SeparatedList <ParameterSyntax>(
                        new[] { SyntaxFactory.Parameter(s_emptyAttributeList, s_emptyTokenList, s_stringBuilderType, s_builderIdentifier, null) }
                        )
                    ),
                constraintClauses: s_emptyConstraintList,
                body: GenerateBody(recordDeclaration, recordSymbol, groups),
                expressionBody: null
                );

            string namespaceFullyQualifiedName = GetFullyQualifiedNameOfNamespace(recordSymbol.ContainingNamespace);

            recordDeclaration = recordDeclaration.WithMembers(new SyntaxList <MemberDeclarationSyntax>(printMembersMethod));

            if (namespaceFullyQualifiedName.Length == 0)
            {
                return(recordDeclaration.NormalizeWhitespace().GetText(Encoding.UTF8));
            }

            NamespaceDeclarationSyntax namespaceDeclaration = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.IdentifierName(namespaceFullyQualifiedName));

            return(namespaceDeclaration.WithMembers(new SyntaxList <MemberDeclarationSyntax>(recordDeclaration)).NormalizeWhitespace().GetText(Encoding.UTF8));
        }
Exemplo n.º 5
0
        public static string Generate(List <ClassMetadata> classInfo, List <UsingDirectiveSyntax> usings)
        {
            var result = string.Empty;

            foreach (ClassMetadata Class in classInfo)
            {
                NamespaceDeclarationSyntax namespaceDeclaration = NamespaceDeclaration(
                    QualifiedName(IdentifierName(Class.NameSpace), IdentifierName("NUnitTests")));

                CompilationUnitSyntax testClass = CompilationUnit()
                                                  .WithUsings(GetDefaultUsings(Class, usings))
                                                  .WithMembers(SingletonList <MemberDeclarationSyntax>(
                                                                   namespaceDeclaration
                                                                   .WithMembers(SingletonList <MemberDeclarationSyntax>(

                                                                                    ClassDeclaration(Class.Name + "NUnitTests")

                                                                                    .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword)))

                                                                                    .WithAttributeLists(
                                                                                        SingletonList(
                                                                                            AttributeList(
                                                                                                SingletonSeparatedList(
                                                                                                    Attribute(
                                                                                                        IdentifierName("TestFixture"))))))
                                                                                    .WithMembers(GetMethodsAndProperties(Class))))));

                result += testClass.NormalizeWhitespace().ToFullString();
            }

            return(result);
        }
Exemplo n.º 6
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.º 7
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.º 8
0
        public static NamespaceDeclarationSyntax InsertMember(NamespaceDeclarationSyntax namespaceDeclaration, MemberDeclarationSyntax member)
        {
            if (namespaceDeclaration == null)
            {
                throw new ArgumentNullException(nameof(namespaceDeclaration));
            }

            return(namespaceDeclaration.WithMembers(InsertMember(namespaceDeclaration.Members, member)));
        }
Exemplo n.º 9
0
        private static NamespaceDeclarationSyntax ReorderNsMembers(NamespaceDeclarationSyntax ns)
        {
            Debug.Assert(ns.Members.All(m => m is TypeDeclarationSyntax));

            var types = ns.Members.OfType <TypeDeclarationSyntax>().OrderBy(t => t.Identifier.Text).ToList();

            ns = ns.WithMembers(new SyntaxList <MemberDeclarationSyntax>(types));
            return(ns);
        }
Exemplo n.º 10
0
        public static Task <List <GeneratedTestClass> > Generate(string code)
        {
            return(Task.Run(() => {
                List <GeneratedTestClass> generatedClasses = new List <GeneratedTestClass>();

                var tree = CSharpSyntaxTree.ParseText(code);
                var syntaxRoot = tree.GetRoot();

                var mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
                var compilation = CSharpCompilation.Create("MyCompilation",
                                                           syntaxTrees: new[] { tree }, references: new[] { mscorlib });
                var model = compilation.GetSemanticModel(tree);

                var classDeclarations = syntaxRoot.DescendantNodes().OfType <ClassDeclarationSyntax>();

                foreach (var clsInfo in classDeclarations)
                {
                    string className = clsInfo.Identifier.ValueText;
                    string clsNamespace = ((NamespaceDeclarationSyntax)clsInfo.Parent).Name.ToString();

                    NamespaceDeclarationSyntax template_namespace = NamespaceDeclaration(
                        QualifiedName(
                            IdentifierName(className), IdentifierName("Test")));

                    var template_usings = GetTemplateUsing(clsNamespace);

                    var template_methods = GetTemplateMethods(clsInfo, model);
                    var template_fields = GetTemplateFields(clsInfo, model);
                    var template_members = List(template_fields.Concat(template_methods));

                    var template_classname = className + "Tests";

                    //Class declaration
                    var classTemplate =
                        CompilationUnit()
                        .WithUsings(template_usings)
                        .WithMembers(SingletonList <MemberDeclarationSyntax>(template_namespace
                                                                             .WithMembers(SingletonList <MemberDeclarationSyntax>(ClassDeclaration(template_classname)
                                                                                                                                  .WithAttributeLists(
                                                                                                                                      SingletonList(
                                                                                                                                          AttributeList(
                                                                                                                                              SingletonSeparatedList(
                                                                                                                                                  Attribute(
                                                                                                                                                      IdentifierName("TestClass"))))))
                                                                                                                                  .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword)))
                                                                                                                                  .WithMembers(template_members)))));

                    string generatedCode = classTemplate.NormalizeWhitespace().ToFullString();
                    string generatedName = template_classname + ".cs";

                    generatedClasses.Add(new GeneratedTestClass(generatedName, generatedCode));
                }

                return generatedClasses;
            }));
        }
 private TSyntax AddNullableRegions <TSyntax>(TSyntax node, CancellationToken cancellationToken)
     where TSyntax : SyntaxNode
 {
     return(node switch
     {
         CompilationUnitSyntax compilationUnit => (TSyntax)(object)compilationUnit.WithMembers(AddNullableRegions(compilationUnit.Members, cancellationToken)),
         NamespaceDeclarationSyntax ns => (TSyntax)(object)ns.WithMembers(AddNullableRegions(ns.Members, cancellationToken)),
         TypeDeclarationSyntax type => (TSyntax)(object)AddNullableRegionsAroundTypeMembers(type, cancellationToken),
         _ => node,
     });
Exemplo n.º 12
0
        public static NamespaceDeclarationSyntax WithMembers(
            this NamespaceDeclarationSyntax namespaceDeclaration,
            MemberDeclarationSyntax member)
        {
            if (namespaceDeclaration == null)
            {
                throw new ArgumentNullException(nameof(namespaceDeclaration));
            }

            return(namespaceDeclaration.WithMembers(SingletonList(member)));
        }
Exemplo n.º 13
0
        internal static NamespaceDeclarationSyntax AddMethodTo(
            NamespaceDeclarationSyntax destination,
            IMethodSymbol method,
            CodeGenerationOptions options,
            IList <bool> availableIndices)
        {
            var declaration = GenerateMethodDeclaration(method, CodeGenerationDestination.Namespace, options);
            var members     = Insert(destination.Members, declaration, options, availableIndices, after: LastMethod);

            return(destination.WithMembers(members.ToSyntaxList()));
        }
        public static MemberDeclarationSyntax RemoveMember(
            this NamespaceDeclarationSyntax declaration,
            MemberDeclarationSyntax member,
            int index)
        {
            MemberDeclarationSyntax newMember = member.RemoveSingleLineDocumentationComment();

            declaration = declaration
                          .WithMembers(declaration.Members.Replace(member, newMember));

            return(declaration
                   .RemoveNode(declaration.Members[index], MemberDeclarationRefactoring.GetRemoveOptions(newMember)));
        }
Exemplo n.º 15
0
        private static MemberDeclarationSyntax RemoveMember(
            NamespaceDeclarationSyntax namespaceDeclaration,
            MemberDeclarationSyntax member,
            int index)
        {
            MemberDeclarationSyntax newMember = RemoveSingleLineDocumentationComment(member);

            namespaceDeclaration = namespaceDeclaration
                                   .WithMembers(namespaceDeclaration.Members.Replace(member, newMember));

            return(namespaceDeclaration
                   .RemoveNode(namespaceDeclaration.Members[index], GetRemoveOptions(newMember)));
        }
Exemplo n.º 16
0
        public static NamespaceDeclarationSyntax AddNamedTypeTo(
            ICodeGenerationService service,
            NamespaceDeclarationSyntax destination,
            INamedTypeSymbol namedType,
            CodeGenerationOptions options,
            IList <bool> availableIndices)
        {
            var declaration = GenerateNamedTypeDeclaration(service, namedType, CodeGenerationDestination.Namespace, options);
            var members     = Insert(destination.Members, declaration, options, availableIndices);

            return(ConditionallyAddFormattingAnnotationTo(
                       destination.WithMembers(members),
                       members));
        }
Exemplo n.º 17
0
        private static SyntaxList <MemberDeclarationSyntax> GenerateClass(NamespaceDeclarationSyntax namespaceDeclaration, Type type, string serviceName)
        {
            var className = type.Name.TrimStart('I') + "_____UraganoClientProxy";

            //var serviceProviderProperty = SyntaxFactory.PropertyDeclaration(SyntaxFactory.ParseTypeName("IServiceProvider"), " ServiceProvider")
            //	.AddModifiers(SyntaxFactory.Token(SyntaxKind.PrivateKeyword))
            //	.AddAccessorListAccessors(
            //		SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)));

            var classDeclaration = SyntaxFactory.ClassDeclaration(className)
                                   .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
                                   .AddBaseListTypes(
                SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName("DynamicProxyAbstract")),
                SyntaxFactory.SimpleBaseType(GenerateQualifiedNameSyntax(type)))
                                   //.AddMembers(serviceProviderProperty)
                                   .AddMembers(GenerateMethods(type, className, serviceName));

            return(SyntaxFactory.SingletonList <MemberDeclarationSyntax>(namespaceDeclaration.WithMembers(SyntaxFactory.SingletonList <MemberDeclarationSyntax>(classDeclaration))));
        }
Exemplo n.º 18
0
        public static NamespaceDeclarationSyntax RemoveMember(NamespaceDeclarationSyntax namespaceDeclaration, MemberDeclarationSyntax member)
        {
            if (namespaceDeclaration == null)
            {
                throw new ArgumentNullException(nameof(namespaceDeclaration));
            }

            if (member == null)
            {
                throw new ArgumentNullException(nameof(member));
            }

            int index = namespaceDeclaration.Members.IndexOf(member);

            MemberDeclarationSyntax newMember = RemoveSingleLineDocumentationComment(member);

            namespaceDeclaration = namespaceDeclaration.WithMembers(namespaceDeclaration.Members.ReplaceAt(index, newMember));

            return(namespaceDeclaration.RemoveNode(namespaceDeclaration.Members[index], GetRemoveOptions(newMember)));
        }
        /// <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.º 20
0
        public ICompiledWelfareService CreateCompilation()
        {
            var compilationUnit = CompilationUnit()
                                  .WithUsings(List <UsingDirectiveSyntax>(usings.ToArray()));

            var classDeclaration = ClassDeclaration($"{serviceName}")
                                   .WithModifiers(
                TokenList(
                    Token(SyntaxKind.PublicKeyword)))
                                   .WithBaseList(
                BaseList(
                    SingletonSeparatedList <BaseTypeSyntax>(
                        SimpleBaseType(
                            IdentifierName($"{nameof(IWelfareService)}")))));

            classDeclaration = classDeclaration.WithMembers(SingletonList <MemberDeclarationSyntax>(GenerateWelfareRules(welfareRules)));

            namespaceDeclarationSyntax = namespaceDeclarationSyntax.WithMembers(SingletonList <MemberDeclarationSyntax>(classDeclaration));

            compilationUnit = compilationUnit.WithMembers(SingletonList <MemberDeclarationSyntax>(namespaceDeclarationSyntax));

            return(new CompiledWelfareService(compilationUnit.NormalizeWhitespace(), namespaceType));
        }
Exemplo n.º 21
0
        public override SyntaxNode VisitNamespaceDeclaration(NamespaceDeclarationSyntax node)
        {
            node = (NamespaceDeclarationSyntax)base.VisitNamespaceDeclaration(node);

            return(node.WithMembers(SortMembers(node.Members)));
        }
Exemplo n.º 22
0
        public List <GeneratedTestResult> GenerateTestsAsync(string taskInputFile, string outputDirectory)
        {
            //taskInputFile.Wait();
            string source = taskInputFile;
            var    res    = new List <GeneratedTestResult>();

            var syntaxTree            = CSharpSyntaxTree.ParseText(source);
            var compilationUnitSyntax = syntaxTree.GetCompilationUnitRoot();

            var classes = compilationUnitSyntax.DescendantNodes().OfType <ClassDeclarationSyntax>();

            foreach (var classDeclaration in classes)
            {
                var publicMethods = classDeclaration.DescendantNodes().OfType <MethodDeclarationSyntax>()
                                    .Where(x => x.Modifiers.Any(y => y.ValueText == "public"));

                var ns          = (classDeclaration.Parent as NamespaceDeclarationSyntax)?.Name.ToString();
                var className   = classDeclaration.Identifier.ValueText;
                var methodsName = new List <string>();
                foreach (var method in publicMethods)
                {
                    var name = GetMethodName(methodsName, method.Identifier.ToString(), 0);
                    methodsName.Add(name);
                }

                NamespaceDeclarationSyntax namespaceDeclarationSyntax = NamespaceDeclaration(QualifiedName(
                                                                                                 IdentifierName(ns), IdentifierName("Test")));

                CompilationUnitSyntax compilationUnit = CompilationUnit()
                                                        .WithUsings(GetUsings())
                                                        .WithMembers(SingletonList <MemberDeclarationSyntax>(namespaceDeclarationSyntax
                                                                                                             .WithMembers(SingletonList <MemberDeclarationSyntax>(ClassDeclaration(className + "Test")
                                                                                                                                                                  .WithAttributeLists(SingletonList(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("TestClass"))))))
                                                                                                                                                                  .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword)))
                                                                                                                                                                  .WithMembers(GetMethodsSyntaxList(methodsName))))));



                var outputPath = Path.Combine(outputDirectory, className + "Test.cs");

                res.Add(new GeneratedTestResult
                {
                    Result     = compilationUnit.NormalizeWhitespace().ToFullString(),
                    OutputPath = outputPath
                });
            }

            return(res);
        }
Exemplo n.º 23
0
 public static NamespaceDeclarationSyntax WithMembers(this NamespaceDeclarationSyntax syntax, params MemberDeclarationSyntax[] members)
 {
     return(syntax.WithMembers(SyntaxFactory.List(members)));
 }
Exemplo n.º 24
0
        private List <TestClassTemplate> GetTestTemplates(string sourceCode)
        {
            SyntaxProcessor          syntaxProcessor     = new SyntaxProcessor();
            SyntaxProcessResult      syntaxProcessResult = syntaxProcessor.Process(sourceCode);
            List <TestClassTemplate> result = new List <TestClassTemplate>();

            foreach (ClassInformation classInfo in syntaxProcessResult.Classes)
            {
                NamespaceDeclarationSyntax namespaceDeclaration = NamespaceDeclaration(
                    QualifiedName(
                        IdentifierName(classInfo.NamespaceName),
                        IdentifierName("Tests")));
                CompilationUnitSyntax testClass = CompilationUnit()
                                                  .WithUsings(GetTemplateUsings(classInfo))
                                                  .WithMembers(SingletonList <MemberDeclarationSyntax>(namespaceDeclaration
                                                                                                       .WithMembers(SingletonList <MemberDeclarationSyntax>(ClassDeclaration(classInfo.Name + "Tests")
                                                                                                                                                            .WithAttributeLists(
                                                                                                                                                                SingletonList(
                                                                                                                                                                    AttributeList(
                                                                                                                                                                        SingletonSeparatedList(
                                                                                                                                                                            Attribute(
                                                                                                                                                                                IdentifierName("TestClass"))))))
                                                                                                                                                            .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword)))
                                                                                                                                                            .WithMembers(GetTestMethods(classInfo.Methods))))));
                string fileName  = classInfo.Name + "Tests.cs";
                string innerText = testClass.NormalizeWhitespace().ToFullString();
                result.Add(new TestClassTemplate(fileName, innerText));
            }
            return(result);
        }
Exemplo n.º 25
0
        private List <TestClassInfo> GetTestTemplates(string sourceCode)
        {
            CodeAnalyzer         analyzer    = new CodeAnalyzer();
            List <ClassInfo>     classes     = analyzer.Parse(sourceCode);
            List <TestClassInfo> testClasses = new List <TestClassInfo>();

            foreach (ClassInfo classInfo in classes)
            {
                Console.WriteLine(classInfo.Name + " " + classInfo.Namespace);
                NamespaceDeclarationSyntax namespaceDeclaration = NamespaceDeclaration(
                    QualifiedName(
                        IdentifierName(classInfo.Namespace),
                        IdentifierName("Tests")));
                CompilationUnitSyntax testClass = CompilationUnit()
                                                  .WithUsings(GetUsings(classInfo))
                                                  .WithMembers(SingletonList <MemberDeclarationSyntax>(namespaceDeclaration
                                                                                                       .WithMembers(SingletonList <MemberDeclarationSyntax>(ClassDeclaration(classInfo.Name + "Tests")
                                                                                                                                                            .WithAttributeLists(
                                                                                                                                                                SingletonList(
                                                                                                                                                                    AttributeList(
                                                                                                                                                                        SingletonSeparatedList(
                                                                                                                                                                            Attribute(
                                                                                                                                                                                IdentifierName("TestClass"))))))
                                                                                                                                                            .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword)))
                                                                                                                                                            .WithMembers(GetTestMethods(classInfo.MethodList))))));
                string fileName  = classInfo.Name + "Tests.cs";
                string innerText = testClass.NormalizeWhitespace().ToFullString();
                testClasses.Add(new TestClassInfo(fileName, innerText));
            }
            return(testClasses);
        }
Exemplo n.º 26
0
        private SyntaxTree renameProgramClass(SyntaxTree tree)
        {
            ClassDeclarationSyntax mainClass = this.getTopLevelClasses(tree).First();
            SyntaxTree             newTree   = null;

            if (mainClass != null)
            {
                SyntaxToken newIdentifier = SyntaxFactory.Identifier(SESCriptBuilderInstance.ProgramName);
                SyntaxList <MemberDeclarationSyntax> members = mainClass.Members;
                if (members != null && members.Count() > 0)
                {
                    SyntaxList <MemberDeclarationSyntax> newMembers = new SyntaxList <MemberDeclarationSyntax>();
                    foreach (MemberDeclarationSyntax member in members)
                    {
                        MemberDeclarationSyntax newMember = member;
                        if (member.GetType() == typeof(ConstructorDeclarationSyntax))
                        {
                            ConstructorDeclarationSyntax cons = member as ConstructorDeclarationSyntax;
                            SyntaxToken identifier            = cons.Identifier;
                            if (identifier != null)
                            {
                                newMember = SyntaxFactory.ConstructorDeclaration(cons.AttributeLists, cons.Modifiers, newIdentifier, cons.ParameterList, cons.Initializer, cons.Body, cons.ExpressionBody, cons.SemicolonToken);
                            }
                        }
                        newMembers = newMembers.Add(newMember);
                    }

                    members = newMembers;
                }

                ClassDeclarationSyntax newClass = mainClass.WithIdentifier(newIdentifier).WithMembers(members);

                if (newClass != null)
                {
                    IEnumerable <NamespaceDeclarationSyntax> namespaces = tree.GetRootAsync().Result.DescendantNodes().OfType <NamespaceDeclarationSyntax>();
                    CompilationUnitSyntax newComp = null;
                    CompilationUnitSyntax oldComp = tree.GetCompilationUnitRoot();
                    SyntaxList <MemberDeclarationSyntax> newClassMembers = new SyntaxList <MemberDeclarationSyntax>();
                    newClassMembers = newClassMembers.Add(newClass);
                    if (namespaces != null && namespaces.Count() > 0)
                    {
                        NamespaceDeclarationSyntax ns = namespaces.First();
                        if (ns != null)
                        {
                            NamespaceDeclarationSyntax           newNs        = ns.WithMembers(newClassMembers);
                            SyntaxList <MemberDeclarationSyntax> newNsMembers = new SyntaxList <MemberDeclarationSyntax>();
                            newNsMembers = newNsMembers.Add(newNs);
                            newComp      = oldComp.WithMembers(newNsMembers);
                        }
                    }
                    else
                    {
                        newComp = oldComp.WithMembers(newClassMembers);
                    }

                    if (newComp != null)
                    {
                        newTree = newComp.SyntaxTree;
                    }
                }
            }
            return(newTree);
        }
Exemplo n.º 27
0
 public override SyntaxNode VisitNamespaceDeclaration(NamespaceDeclarationSyntax node)
 {
     return(node.WithMembers(ReplaceMembers(node.Members)));
 }
Exemplo n.º 28
0
        public static Task <List <TestClass> > GetTestClasses(string code)
        {
            return(Task.Run(() =>
            {
                List <TestClass> result = new List <TestClass>();

                var tree = CSharpSyntaxTree.ParseText(code);

                var mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
                var compilation = CSharpCompilation.Create("MyCompilation",
                                                           syntaxTrees: new[] { tree }, references: new[] { mscorlib });
                model = compilation.GetSemanticModel(tree);

                var root = tree.GetRoot();
                var classes = root.DescendantNodes().OfType <ClassDeclarationSyntax>();

                var attr = Attribute(IdentifierName("TestClass()"));
                var attributes = SingletonList(AttributeList(SingletonSeparatedList(attr)));

                foreach (ClassDeclarationSyntax classDeclaration in classes)
                {
                    List <MemberDeclarationSyntax> fields = new List <MemberDeclarationSyntax>();

                    var constructor = classDeclaration.Members.FirstOrDefault(m => m.Kind() == SyntaxKind.ConstructorDeclaration);
                    string className = classDeclaration.Identifier.ValueText;

                    NamespaceDeclarationSyntax testClassNamespace = NamespaceDeclaration(IdentifierName(className + "Test"));
                    string testClassName = className + "Tests";
                    var methods = GetTestMethods(classDeclaration);
                    if (methods.Count > 0)
                    {
                        if (!classDeclaration.Modifiers.Where(m => m.Kind() == SyntaxKind.StaticKeyword).Any())
                        {
                            methods = methods.Insert(0, GetClassinitializeMethod(classDeclaration, constructor as ConstructorDeclarationSyntax, fields));
                        }

                        var usings = GetTestUsingDirectives(((NamespaceDeclarationSyntax)classDeclaration.Parent).Name.ToString());

                        var newTree = CompilationUnit()
                                      .WithUsings(usings)
                                      .WithMembers(SingletonList <MemberDeclarationSyntax>(testClassNamespace
                                                                                           .WithMembers(SingletonList <MemberDeclarationSyntax>(ClassDeclaration(testClassName)
                                                                                                                                                .WithMembers(List(fields).AddRange(methods))
                                                                                                                                                .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword)))
                                                                                                                                                .WithAttributeLists(attributes))))
                                                   );

                        result.Add(new TestClass(testClassName + ".cs", newTree.NormalizeWhitespace().ToFullString()));
                    }
                }
                return result;
            }
                            ));
        }
Exemplo n.º 29
0
        // method that generates test classes for each class found in code
        public static Task <List <GeneratedTestClass> > Generate(string code)
        {
            return(Task.Run(() => {
                List <GeneratedTestClass> generatedClasses = new List <GeneratedTestClass>();

                // using Roslyn to parse/build syntax tree
                var tree = CSharpSyntaxTree.ParseText(code);
                var syntaxRoot = tree.GetRoot();

                var classDeclarations = syntaxRoot.DescendantNodes().OfType <ClassDeclarationSyntax>();

                foreach (var clsInfo in classDeclarations)
                {
                    // get class name, namespace name and public methods

                    string className = clsInfo.Identifier.ValueText;
                    string clsNamespace = ((NamespaceDeclarationSyntax)clsInfo.Parent).Name.ToString();

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

                    // use roslyn to generate test class code

                    // declare namespace, template usings and methods
                    NamespaceDeclarationSyntax template_namespace = NamespaceDeclaration(
                        QualifiedName(
                            IdentifierName(className), IdentifierName("Test")));

                    var template_usings = getTemplateUsing(clsNamespace);
                    var template_methods = getTemplateMethods(publicMethods);
                    var template_classname = className + "Tests";

                    // creating compilation unit --> transfer to code

                    var template_class = CompilationUnit()
                                         .WithUsings(template_usings)
                                         .WithMembers(SingletonList <MemberDeclarationSyntax>(template_namespace
                                                                                              .WithMembers(SingletonList <MemberDeclarationSyntax>(ClassDeclaration(template_classname)
                                                                                                                                                   .WithAttributeLists(
                                                                                                                                                       SingletonList(
                                                                                                                                                           AttributeList(
                                                                                                                                                               SingletonSeparatedList(
                                                                                                                                                                   Attribute(
                                                                                                                                                                       IdentifierName("TestClass"))))))
                                                                                                                                                   .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword)))
                                                                                                                                                   .WithMembers(template_methods)))));

                    string generatedCode = template_class.NormalizeWhitespace().ToFullString();
                    string generatedName = template_classname + ".cs";

                    generatedClasses.Add(new GeneratedTestClass(generatedName, generatedCode));
                }

                return generatedClasses;
            }));
        }
Exemplo n.º 30
0
        public IEnumerable <FileSource> GetTestTemplates()
        {
            List <FileSource> testTemplates = new List <FileSource>();

            foreach (ClassInfo classInfo in _syntaxTreeInfo.Classes)
            {
                NamespaceDeclarationSyntax namespaceDeclaration = NamespaceDeclaration(QualifiedName(
                                                                                           IdentifierName(classInfo.NamespaceName), IdentifierName("Tests")));

                CompilationUnitSyntax compilationUnit = CompilationUnit()
                                                        .WithUsings(GetUsingDirectives(classInfo))
                                                        .WithMembers(SingletonList <MemberDeclarationSyntax>(namespaceDeclaration
                                                                                                             .WithMembers(SingletonList <MemberDeclarationSyntax>(ClassDeclaration(classInfo.Name + "Tests")
                                                                                                                                                                  .WithAttributeLists(
                                                                                                                                                                      SingletonList(
                                                                                                                                                                          AttributeList(
                                                                                                                                                                              SingletonSeparatedList(
                                                                                                                                                                                  Attribute(
                                                                                                                                                                                      IdentifierName("TestClass"))))))
                                                                                                                                                                  .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword)))
                                                                                                                                                                  .WithMembers(GetClassMembers(classInfo))))));

                string fileName = $"{classInfo.Name}Tests.cs";
                byte[] fileData = Encoding.Default.GetBytes(compilationUnit.NormalizeWhitespace().ToFullString());

                testTemplates.Add(new FileSource(fileData, fileName));
            }

            return(testTemplates);
        }
Exemplo n.º 31
0
 public static NamespaceDeclarationSyntax WithSingleMember(this NamespaceDeclarationSyntax @namespace, MemberDeclarationSyntax member)
 => @namespace.WithMembers(SingletonList(member));