Ejemplo n.º 1
0
        public async Task <string> GenerateStubs(string testProjectPath)
        {
            MSBuildWorkspace workspace      = MSBuildWorkspace.Create();
            Project          currentProject = await workspace.OpenProjectAsync(testProjectPath);

            if (currentProject == null)
            {
                throw new ArgumentException("Could not open the project located at " + testProjectPath);
            }

            List <Project> projectsToStub = GetListOfProjectsToStub(workspace, currentProject);

            if (!projectsToStub.Any())
            {
                return(string.Empty);
            }

            CompilationUnitSyntax cu = SF.CompilationUnit();
            var usings = new HashSet <UsingDirectiveSyntax>(new UsingDirectiveEqualityComparer());

            usings.Add(ToUsingDirective(" System"));
            usings.Add(ToUsingDirective(" System.Runtime.CompilerServices"));
            usings.Add(ToUsingDirective(" Etg.SimpleStubs"));

            foreach (Project project in projectsToStub)
            {
                var res = await _projectStubber.StubProject(project, cu);

                cu = res.CompilationUnit;
                usings.UnionWith(res.Usings);
            }

            cu = cu.AddUsings(usings.ToArray());
            return(Formatter.Format(cu, workspace).ToString());
        }
Ejemplo n.º 2
0
        public static CompilationUnitSyntax AddUsings(this CompilationUnitSyntax compilationUnit, bool keepSingleLineCommentsOnTop, params UsingDirectiveSyntax[] usings)
        {
            if (compilationUnit == null)
            {
                throw new ArgumentNullException(nameof(compilationUnit));
            }

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

            if (keepSingleLineCommentsOnTop &&
                usings.Length > 0 &&
                !compilationUnit.Usings.Any())
            {
                SyntaxTriviaList leadingTrivia = compilationUnit.GetLeadingTrivia();

                SyntaxTrivia[] topTrivia = GetTopSingleLineComments(leadingTrivia).ToArray();

                if (topTrivia.Length > 0)
                {
                    compilationUnit = compilationUnit.WithoutLeadingTrivia();

                    usings[0] = usings[0].WithLeadingTrivia(topTrivia);

                    usings[usings.Length - 1] = usings[usings.Length - 1].WithTrailingTrivia(leadingTrivia.Skip(topTrivia.Length));
                }
            }

            return(compilationUnit.AddUsings(usings));
        }
Ejemplo n.º 3
0
 private static void AddUsings(ref CompilationUnitSyntax cu, IEnumerable <UsingDirectiveSyntax> uds)
 {
     foreach (var ud in uds)
     {
         cu = cu.AddUsings(ud);
     }
 }
        internal static CompilationUnitSyntax WithUsingSystem(this CompilationUnitSyntax syntaxRoot)
        {
            var @namespace = syntaxRoot.Members.FirstOrDefault() as NamespaceDeclarationSyntax;

            if (@namespace == null)
            {
                if (syntaxRoot.Usings.HasUsingSystem())
                {
                    return(syntaxRoot);
                }

                return(syntaxRoot.Usings.Any()
                           ? syntaxRoot.InsertNodesBefore(syntaxRoot.Usings.First(), new[] { UsingSystem })
                           : syntaxRoot.AddUsings(UsingSystem));
            }

            if (@namespace.Usings.HasUsingSystem() || syntaxRoot.Usings.HasUsingSystem())
            {
                return(syntaxRoot);
            }

            if (@namespace.Usings.Any())
            {
                return(syntaxRoot.ReplaceNode(@namespace, @namespace.InsertNodesBefore(@namespace.Usings.First(), new[] { UsingSystem })));
            }

            if (syntaxRoot.Usings.Any())
            {
                return(syntaxRoot.InsertNodesBefore(syntaxRoot.Usings.First(), new[] { UsingSystem }));
            }

            return(syntaxRoot.ReplaceNode(@namespace, @namespace.AddUsings(UsingSystem)));
        }
Ejemplo n.º 5
0
        public static CompilationUnitSyntax AddUsing(this CompilationUnitSyntax root, string @namespace, string targetNamespace)
        {
            var usings        = root.DescendantNodes(n => true).OfType <UsingDirectiveSyntax>();
            var lastUsing     = usings.LastOrDefault();
            var namespaceDecl = !string.IsNullOrWhiteSpace(targetNamespace) ? root.GetNamespaceDeclaration(targetNamespace) : null;

            if (namespaceDecl == null || lastUsing == null || !lastUsing.Ancestors().OfType <NamespaceDeclarationSyntax>().Any())
            {
                root = root.AddUsings(CreateUsing(@namespace));
                return(root);
            }

            var nsTTokens = targetNamespace.Split('.');
            var nsTokens  = @namespace.Split('.');
            var i         = 0;

            while (i < nsTokens.Length && i < nsTTokens.Length && nsTTokens[i] == nsTokens[i])
            {
                i++;
            }
            nsTokens = nsTokens.Skip(i).ToArray();
            if (nsTokens.Length == 0)
            {
                return(root);
            }

            @namespace = nsTokens.Join(".");
            var newNamespaceDecl = namespaceDecl.AddUsings(CreateUsing(@namespace));

            root = root.ReplaceNode(namespaceDecl, newNamespaceDecl);
            return(root);
        }
Ejemplo n.º 6
0
        CompilationUnitSyntax Generate(CompilationUnitSyntax code, WaylandProtocol protocol)
        {
            code = code.AddUsings(UsingDirective(IdentifierName("System")))
                   .AddUsings(UsingDirective(IdentifierName("System.Collections.Generic")))
                   .AddUsings(UsingDirective(IdentifierName("System.Linq")))
                   .AddUsings(UsingDirective(IdentifierName("System.Text")))
                   .AddUsings(UsingDirective(IdentifierName("NWayland.Protocols.Wayland")))
                   .AddUsings(UsingDirective(IdentifierName("NWayland.Interop")))
                   .AddUsings(UsingDirective(IdentifierName("System.Threading.Tasks")));


            var ns = NamespaceDeclaration(ProtocolNamespaceSyntax(protocol.Name));

            foreach (var iface in protocol.Interfaces)
            {
                var cl = ClassDeclaration(Pascalize(iface.Name))
                         .WithModifiers(new SyntaxTokenList(
                                            Token(SyntaxKind.PublicKeyword),
                                            Token(SyntaxKind.SealedKeyword),
                                            Token(SyntaxKind.UnsafeKeyword),
                                            Token(SyntaxKind.PartialKeyword)))
                         .AddBaseListTypes(
                    SimpleBaseType(SyntaxFactory.ParseTypeName("NWayland.Protocols.Wayland.WlProxy")));
                cl = WithSummary(cl, iface.Description);
                cl = WithSignature(cl, iface);
                cl = WithRequests(cl, protocol, iface);
                cl = WithEvents(cl, protocol, iface);
                cl = WithEnums(cl, protocol, iface);
                cl = WithFactory(cl, iface)
                     .AddMembers(DeclareConstant("string", "InterfaceName", MakeLiteralExpression(iface.Name)))
                     .AddMembers(DeclareConstant("int", "InterfaceVersion", MakeLiteralExpression(iface.Version)));


                if (iface.Name != "wl_display")
                {
                    var ctor = ConstructorDeclaration(cl.Identifier)
                               .AddModifiers(Token(SyntaxKind.PublicKeyword))
                               .WithParameterList(ParameterList(
                                                      SeparatedList(new[]
                    {
                        Parameter(Identifier("handle")).WithType(ParseTypeName("IntPtr")),
                        Parameter(Identifier("version")).WithType(ParseTypeName("int")),
                        Parameter(Identifier("display"))
                        .WithType(ParseTypeName("NWayland.Protocols.Wayland.WlDisplay")),
                    }))).WithBody(Block())
                               .WithInitializer(ConstructorInitializer(SyntaxKind.BaseConstructorInitializer,
                                                                       ArgumentList(SeparatedList(new[]
                    {
                        Argument(IdentifierName("handle")),
                        Argument(IdentifierName("version")),
                        Argument(IdentifierName("display"))
                    }))));
                    cl = cl.AddMembers(ctor);
                }

                ns = ns.AddMembers(cl);
            }

            return(code.AddMembers(ns));
        }
Ejemplo n.º 7
0
        public async Task <string> GenerateStubs(string testProjectPath)
        {
            MSBuildWorkspace workspace      = MSBuildWorkspace.Create();
            Project          currentProject = await workspace.OpenProjectAsync(testProjectPath);

            if (currentProject == null)
            {
                throw new ArgumentException("Could not open the project located at " + testProjectPath);
            }

            CompilationUnitSyntax cu = SF.CompilationUnit();
            var usings = new HashSet <string>();

            usings.Add("System");
            usings.Add("System.Runtime.CompilerServices");
            usings.Add("Etg.SimpleStubs");
            foreach (ProjectReference projectRef in currentProject.ProjectReferences)
            {
                Project project = workspace.CurrentSolution.GetProject(projectRef.ProjectId);
                if (_config.IgnoredProjects.Contains(project.Name))
                {
                    continue;
                }

                var res = await _projectStubber.StubProject(project, cu);

                cu = res.CompilationUnit;
                usings.UnionWith(res.Usings);
            }

            cu = cu.AddUsings(usings.Select(@using => SF.UsingDirective(SF.IdentifierName(@using))).ToArray());
            return(Formatter.Format(cu, workspace).ToString());
        }
Ejemplo n.º 8
0
        private async Task <Document> MakeViewModelAsync(Document document,
                                                         ClassDeclarationSyntax classDeclaration, CancellationToken cancellationToken)
        {
            // Get the name of the model class
            var modelClassName = classDeclaration.Identifier.Text;
            // The name of the ViewModel class
            var viewModelClassName = $"{modelClassName}ViewModel";
            // Only for demo purposes, pluralizing an object is done by
            // simply adding the "s" letter. Consider proper algorithms
            string newImplementation = $@"class {viewModelClassName} : INotifyPropertyChanged
{{
public event PropertyChangedEventHandler PropertyChanged;
// Raise a property change notification
protected virtual void OnPropertyChanged(string propname)
{{
  PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propname));
}}
private ObservableCollection<{modelClassName}> _{modelClassName}s;
public ObservableCollection<{modelClassName}> {modelClassName}s
{{
  get {{ return _{modelClassName}s; }}
  set
  {{
    _{modelClassName}s = value;
    OnPropertyChanged(nameof({modelClassName}s));
  }}
}}
public {viewModelClassName}() {{
// Implement your logic to load a collection of items
}}
}}
";
            var    newClassNode      = SyntaxFactory.ParseSyntaxTree(newImplementation).
                                       GetRoot().DescendantNodes().
                                       OfType <ClassDeclarationSyntax>().
                                       FirstOrDefault().
                                       WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation);
            // Retrieve the parent namespace declaration
            var parentNamespace = (NamespaceDeclarationSyntax)classDeclaration.Parent;
            //Add the new class to the namespace
            var newParentNamespace =
                parentNamespace.AddMembers(newClassNode).NormalizeWhitespace();
            var root = await document.GetSyntaxRootAsync(cancellationToken);

            CompilationUnitSyntax newRoot = (CompilationUnitSyntax)root;

            newRoot = newRoot.
                      ReplaceNode(parentNamespace, newParentNamespace).NormalizeWhitespace();
            newRoot = newRoot.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.
                                                                     QualifiedName(SyntaxFactory.IdentifierName("System"),
                                                                                   SyntaxFactory.IdentifierName("Collections.ObjectModel"))),
                                        SyntaxFactory.UsingDirective(SyntaxFactory.
                                                                     QualifiedName(SyntaxFactory.IdentifierName("System"),
                                                                                   SyntaxFactory.IdentifierName("ComponentModel"))));
            // Generate a new document based on the new SyntaxNode
            var newDocument = document.WithSyntaxRoot(newRoot);

            // Return the new document
            return(newDocument);
        }
Ejemplo n.º 9
0
        public static CompilationUnitSyntax AddUsingDirectives(CompilationUnitSyntax root, List <string> usingStatements)
        {
            if (usingStatements != null)
            {
                List <string> usingStatementsCopy = new List <string>(usingStatements);
                for (int i = 0; i < usingStatements.Count; i++)
                {
                    foreach (UsingDirectiveSyntax usingSyntax in root.Usings)
                    {
                        if (string.Equals(usingStatements[i], usingSyntax.Name.ToFullString(), StringComparison.CurrentCultureIgnoreCase))
                        {
                            usingStatementsCopy.Remove(usingStatements[i]);
                        }
                    }
                }

                foreach (string usingStatement in usingStatementsCopy)
                {
                    root = root.AddUsings(
                        SyntaxFactory
                        .UsingDirective(SyntaxFactory.IdentifierName(usingStatement))
                        .NormalizeWhitespace()
                        .WithTrailingTrivia(SyntaxFactory.Whitespace("\n"))
                        );
                }
            }

            return(root);
        }
        private CompilationUnitSyntax ImportNeededNamespace(CompilationUnitSyntax root, SemanticModel semanticModel, MemberAccessExpressionSyntax callerMethod)
        {
            var symbolInfo   = semanticModel.GetSymbolInfo(callerMethod.Name);
            var methodSymbol = symbolInfo.Symbol as IMethodSymbol;

            if (methodSymbol == null)
            {
                return(root);
            }

            var namespaceDisplayString = methodSymbol.ContainingNamespace.ToDisplayString();

            var hasNamespaceImported = root
                                       .DescendantNodes()
                                       .OfType <UsingDirectiveSyntax>()
                                       .Select(s => s.DescendantNodes().OfType <IdentifierNameSyntax>())
                                       .Select(s => TransformIdentifierNameSyntaxIntoNamespace(s))
                                       .Any(p => p == namespaceDisplayString);

            if (!hasNamespaceImported)
            {
                var namespaceQualifiedName = GenerateNamespaceQualifiedName(namespaceDisplayString.Split('.'));
                root = root.AddUsings(SyntaxFactory.UsingDirective(namespaceQualifiedName));
            }
            return(root);
        }
Ejemplo n.º 11
0
        public static void CreateUnit(string unitName, Func <string, NamespaceDeclarationSyntax> nsFactory, string filePathFactory,
                                      params string[] usings)
        {
            unitName = NamingConventions.Normalize(unitName);

            CompilationUnitSyntax cu = SyntaxFactory.CompilationUnit();

            cu = cu.AddUsings(usings.OrderBy(s => s)
                              .Select(u => SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(u)))
                              .ToArray());

            var cw = new AdhocWorkspace();

            cw.Options.WithChangedOption(CSharpFormattingOptions.IndentBlock, true);
            SyntaxNode formattedNode = Formatter.Format(cu.AddMembers(nsFactory(unitName)), cw, cw.Options);

            var           file = new FileInfo(filePathFactory);
            DirectoryInfo dir  = file.Directory;

            if (!dir !.Exists)
            {
                dir.Create();
            }

            using FileStream fileStream = file.Exists ? file.Open(FileMode.Truncate) : file.Create();
            using var sw = new StreamWriter(fileStream);
            formattedNode.WriteTo(sw);
        }
Ejemplo n.º 12
0
        public List <OutputFileInfo> GenerateTestClasses(string text)
        {
            List <OutputFileInfo> outputs = new List <OutputFileInfo>();

            SyntaxNode root = CSharpSyntaxTree.ParseText(text).GetRoot();
            IEnumerable <ClassDeclarationSyntax> classes = root.DescendantNodes().OfType <ClassDeclarationSyntax>();

            foreach (ClassDeclarationSyntax cl in classes)
            {
                ClassDeclarationSyntax   testClass = CreateTestClass(cl.Identifier.Text);
                IEnumerable <SyntaxNode> methods   = cl.DescendantNodes()
                                                     .OfType <MethodDeclarationSyntax>()
                                                     .Where(method => method.Modifiers.Any(SyntaxKind.PublicKeyword));
                foreach (SyntaxNode method in methods)
                {
                    testClass = testClass.AddMembers(CreateTestMethod((method as MethodDeclarationSyntax).Identifier.ValueText));
                }
                CompilationUnitSyntax      syntaxFactory = SyntaxFactory.CompilationUnit();
                NamespaceDeclarationSyntax @namespace    = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName("CodeGenerationSample")).NormalizeWhitespace();
                @namespace    = @namespace.AddMembers(testClass);
                syntaxFactory = syntaxFactory.AddUsings(usingDirectives()).AddMembers(@namespace);
                string         code = syntaxFactory.NormalizeWhitespace().ToFullString();
                OutputFileInfo info = new OutputFileInfo(testClass.Identifier.ValueText + ".cs", code);
                outputs.Add(info);
            }


            return(outputs);
        }
Ejemplo n.º 13
0
 public static CompilationUnitSyntax AddUsingIfNotExist(this CompilationUnitSyntax node, string name)
 {
     if (node.Usings.Any(u => u.Name.ToString() == name))
     {
         return(node);
     }
     return(node.AddUsings(UsingDirective(IdentifierName(name))));
 }
Ejemplo n.º 14
0
        private async Task <Document> CreateDataRowConstructor(Document document, TypeDeclarationSyntax typeDeclaration, CancellationToken ct)
        {
            // attributes;
            var attributes = new SyntaxList <AttributeListSyntax>();

            // Modifiers;
            const string publicText     = "public ";
            var          publicModifier = SyntaxFactory.Identifier(SyntaxTriviaList.Empty, SyntaxKind.PublicKeyword, publicText, publicText, SyntaxTriviaList.Empty);
            var          modifiers      = new SyntaxTokenList(publicModifier);

            // Identifier;
            var identifier = SyntaxFactory.Identifier(SyntaxTriviaList.Empty, SyntaxKind.PublicKeyword, typeDeclaration.Identifier.Text, typeDeclaration.Identifier.ValueText, SyntaxTriviaList.Empty) /*.WithLeadingTrivia().WithTrailingTrivia()*/;

            // ParameterList;
            var parameterName = SyntaxFactory.Identifier("row").WithTrailingTrivia().WithLeadingTrivia();
            var parameterType = SyntaxFactory.IdentifierName(typeof(DataRow).Name);
            var parameter     = SyntaxFactory.Parameter(new SyntaxList <AttributeListSyntax>(), new SyntaxTokenList(), parameterType, parameterName, null);
            var parameters    = SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(new[] { parameter }));

            // Body block
            var properties = typeDeclaration.Members.OfType <PropertyDeclarationSyntax>().ToList();
            var statements = new List <StatementSyntax>(properties.Count);

            foreach (var property in properties)
            {
                statements.Add(SyntaxFactory.ExpressionStatement(CreatePropertyAssigmentExpression(parameter, SyntaxFactory.PropertyDeclaration(property.Type, property.Identifier))));
            }

            var block = SyntaxFactory.Block(statements);

            var constructor = SyntaxFactory.ConstructorDeclaration(attributes, modifiers, identifier, parameters, null, block);

            var fpt = properties.First().GetLeadingTrivia().Where(t => t.IsKind(SyntaxKind.WhitespaceTrivia)).First();

            var newClassDexlaration = typeDeclaration.InsertNodesBefore(typeDeclaration.Members.FirstOrDefault(), new[] { constructor.WithLeadingTrivia(fpt) });

            var root = await document.GetSyntaxRootAsync(ct);

            CompilationUnitSyntax newRoot = (CompilationUnitSyntax)root.ReplaceNode(typeDeclaration, newClassDexlaration);

            bool usingFinded = false;

            foreach (var usingDirective in newRoot.Usings)
            {
                if (usingDirective.Name.ToString().Equals("System.Data"))
                {
                    usingFinded = true;
                    break;
                }
            }

            if (!usingFinded)
            {
                newRoot = newRoot.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName("System.Data")));
            }

            return(document.WithSyntaxRoot(newRoot));
        }
        internal static CompilationUnitSyntax WithUsing(this CompilationUnitSyntax root, string name)
        {
            if (!root.Usings.Any(u => u.Name.ToString() == name))
            {
                root = root.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(name)).WithAdditionalAnnotations(Formatter.Annotation));
            }

            return(root);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Format a type declaration into a string representing the contents of a file
        /// containing that single type declaration.
        /// </summary>
        /// <param name="typeDecl">
        /// The type declaration to be formatted.
        /// </param>
        /// <param name="copyrightNotice">
        /// The copyright notice to display at the top of the file, or null if there is
        /// no copyright notice.
        /// </param>
        /// <param name="usings">
        /// A list containing the names of any namespaces required by the type declaration,
        /// or null if no namespaces are required.
        /// </param>
        /// <param name="namespaceName">
        /// The name of the namespace containing the type declaration. Required.
        /// </param>
        /// <param name="summaryComment">
        /// The summary comment for the type, or null if there is no summary comment.
        /// </param>
        /// <returns>
        /// The formatted string.
        /// </returns>
        /// <remarks>
        /// The first parameter is declared as <see cref="BaseTypeDeclarationSyntax"/>
        /// because this method works for enums as well as for classes and interfaces.
        /// Classes and interfaces derive from <see cref="TypeDeclarationSyntax"/>, but
        /// enums do not: they derive from <see cref="EnumDeclarationSyntax"/>, and both
        /// those types derive from BaseTypeDeclarationSyntax.
        /// </remarks>
        internal static string Format(
            this BaseTypeDeclarationSyntax typeDecl,
            string copyrightNotice,
            List <string> usings,
            string namespaceName,
            string summaryComment)
        {
            typeDecl = AddGeneratedCodeAttribute(typeDecl);

            if (summaryComment != null)
            {
                typeDecl = typeDecl.WithLeadingTrivia(
                    SyntaxHelper.MakeDocComment(summaryComment));
            }

            NamespaceDeclarationSyntax namespaceDecl =
                SyntaxFactory.NamespaceDeclaration(
                    SyntaxFactory.IdentifierName(namespaceName))
                .AddMembers(typeDecl);

            CompilationUnitSyntax compilationUnit = SyntaxFactory.CompilationUnit()
                                                    .AddMembers(namespaceDecl);

            if (usings == null)
            {
                usings = new List <string>();
            }

            usings.Add("System.CodeDom.Compiler"); // For GeneratedCodeAttribute

            UsingDirectiveSyntax[] usingDirectives = usings
                                                     .Distinct()
                                                     .OrderBy(u => u, UsingComparer.Instance)
                                                     .Select(u => SyntaxFactory.UsingDirective(MakeQualifiedName(u)))
                                                     .ToArray();

            compilationUnit = compilationUnit.AddUsings(usingDirectives);

            if (!string.IsNullOrWhiteSpace(copyrightNotice))
            {
                compilationUnit = compilationUnit.WithLeadingTrivia(
                    SyntaxFactory.ParseLeadingTrivia(copyrightNotice));
            }

            var        workspace     = new AdhocWorkspace();
            SyntaxNode formattedNode = Formatter.Format(compilationUnit, workspace);

            var sb = new StringBuilder();

            using (var writer = new StringWriter(sb))
            {
                formattedNode.WriteTo(writer);
            }

            return(sb.ToString());
        }
Ejemplo n.º 17
0
        public CSharpSyntaxNode Convert(SourceFile sourceFile)
        {
            CompilationUnitSyntax csCompilationUnit = SyntaxFactory.CompilationUnit();

            foreach (string us in this.Context.Config.Usings)
            {
                csCompilationUnit = csCompilationUnit.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(us)));
            }

            csCompilationUnit = csCompilationUnit.AddMembers(sourceFile.MouduleDeclarations.ToCsNodes <MemberDeclarationSyntax>());
            foreach (Node import in sourceFile.ImportDeclarations)
            {
                foreach (UsingDirectiveSyntax usingSyntax in import.ToCsNode <SyntaxList <UsingDirectiveSyntax> >())
                {
                    csCompilationUnit = csCompilationUnit.AddUsings(usingSyntax);
                }
            }

            List <Node> typeAliases     = sourceFile.TypeAliases;
            List <Node> typeDefinitions = this.FilterTypes(sourceFile.TypeDefinitions);

            if (typeAliases.Count > 0 || typeDefinitions.Count > 0)
            {
                string ns = sourceFile.Document.GetPackageName();
                if (!string.IsNullOrEmpty(ns))
                {
                    NamespaceDeclarationSyntax nsSyntaxNode = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(ns));
                    nsSyntaxNode = nsSyntaxNode
                                   .AddUsings(typeAliases.ToCsNodes <UsingDirectiveSyntax>())
                                   .AddMembers(typeDefinitions.ToCsNodes <MemberDeclarationSyntax>());
                    csCompilationUnit = csCompilationUnit.AddMembers(nsSyntaxNode);
                }
                else
                {
                    csCompilationUnit = csCompilationUnit
                                        .AddUsings(typeAliases.ToCsNodes <UsingDirectiveSyntax>())
                                        .AddMembers(typeDefinitions.ToCsNodes <MemberDeclarationSyntax>());
                }
            }

            return(csCompilationUnit);
        }
Ejemplo n.º 18
0
        public static CompilationUnitSyntax CheckAndAddUsing(this CompilationUnitSyntax syntax, string usingName)
        {
            var newSyntax = syntax;

            if (newSyntax.Usings.All(u => u.Name.ToString() != usingName))
            {
                newSyntax = syntax.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName(usingName)));
            }

            return(newSyntax);
        }
Ejemplo n.º 19
0
        public async Task <string> GenerateStubs(string testProjectPath, string configuration, string platform, string visualStudioVersion)
        {
            RegisterVisualStudioInstance(visualStudioVersion);

            using (var workspace = MSBuildWorkspace.Create(new Dictionary <string, string> {
                { "Configuration", configuration },
                { "Platform", platform }
            }))
            {
                Project currentProject = await workspace.OpenProjectAsync(testProjectPath);

                if (workspace.Diagnostics.Any(d => d.Kind == WorkspaceDiagnosticKind.Failure))
                {
                    StringBuilder stringBuilder = new StringBuilder();
                    foreach (var diagnostic in workspace.Diagnostics)
                    {
                        stringBuilder.AppendLine(diagnostic.ToString());
                    }
                    Console.WriteLine("Simplestubs encountered errors when opening the workspace; Stubs will be generated only for projects that successfully opened. Errors: " + stringBuilder.ToString());
                }
                else
                {
                    Console.WriteLine("MSBuildWorkspace loaded with no errors!");
                }

                if (currentProject == null)
                {
                    throw new ArgumentException("Could not open the project located at " + testProjectPath);
                }

                List <Project> projectsToStub = GetListOfProjectsToStub(workspace, currentProject);
                if (!projectsToStub.Any())
                {
                    return(string.Empty);
                }

                CompilationUnitSyntax cu = SF.CompilationUnit();
                var usings = new HashSet <UsingDirectiveSyntax>(new UsingDirectiveEqualityComparer());
                usings.Add(ToUsingDirective(" System"));
                usings.Add(ToUsingDirective(" System.Runtime.CompilerServices"));
                usings.Add(ToUsingDirective(" Etg.SimpleStubs"));

                foreach (Project project in projectsToStub)
                {
                    var res = await _projectStubber.StubProject(project, cu);

                    cu = res.CompilationUnit;
                    usings.UnionWith(res.Usings);
                }

                cu = cu.AddUsings(usings.ToArray());
                return(Formatter.Format(cu, workspace).ToString());
            }
        }
Ejemplo n.º 20
0
 internal string GetTest()
 {
     _test = _test.AddUsings(_unit.Usings.Select(us => SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName(us))).ToArray());
     _test = _test.AddUsings(
         SyntaxFactory.UsingDirective(
             SyntaxFactory.IdentifierName("NUnit.Framework")),
         SyntaxFactory.UsingDirective(
             SyntaxFactory.IdentifierName("Moq")));
     _test = _test.AddMembers(_unit.Namespaces.Select(nm => CreateNamespace(nm)).ToArray());
     return(_test.NormalizeWhitespace().ToFullString());
 }
Ejemplo n.º 21
0
        public static CompilationUnitSyntax AddUsing(CompilationUnitSyntax syntaxRoot)
        {
            var debtAnalyzerNamespace = SyntaxFactory.IdentifierName("DebtRatchet");
            var usingDirectiveSyntax  = SyntaxFactory.UsingDirective(
                debtAnalyzerNamespace).WithUsingKeyword(SyntaxFactory.Token(SyntaxKind.UsingKeyword))
                                        .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));

            return(syntaxRoot.Usings.All(@using => (@using.Name as IdentifierNameSyntax)?.Identifier.ValueText != debtAnalyzerNamespace.Identifier.ValueText)
                                ? syntaxRoot.AddUsings(usingDirectiveSyntax)
                                : syntaxRoot);
        }
Ejemplo n.º 22
0
        private CompilationUnitSyntax UpdateUsingDirectives(CompilationUnitSyntax root)
        {
            // Add using static System.FormattableString;
            if (root?.Usings.Any(u => u.Name.ToString() == "System.FormattableString") == false)
            {
                QualifiedNameSyntax  name           = QualifiedName(IdentifierName("System"), IdentifierName("FormattableString"));
                UsingDirectiveSyntax usingStatement = UsingDirective(SyntaxFactory.Token(SyntaxKind.StaticKeyword), null, name);
                root = root.AddUsings(usingStatement);
            }

            return(root);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Adds a using directive for a given namespace to the document root only if the directive is not already present.
        /// </summary>
        /// <param name="documentRoot">The document to add the directive to.</param>
        /// <param name="namespaceName">The namespace to reference with the using directive.</param>
        /// <returns>An updated document root with the specific using directive.</returns>
        public static CompilationUnitSyntax AddUsingIfMissing(this CompilationUnitSyntax documentRoot, string namespaceName)
        {
            if (documentRoot is null)
            {
                throw new ArgumentNullException(nameof(documentRoot));
            }

            var anyUsings = documentRoot.Usings.Any(u => u.Name.ToString().Equals(namespaceName, StringComparison.Ordinal));
            var result    = anyUsings ? documentRoot : documentRoot.AddUsings(UsingDirective(ParseName(namespaceName)));

            return(result);
        }
Ejemplo n.º 24
0
 public static CompilationUnitSyntax AddSystem_Runtime_CompilerServicesSyntax(CompilationUnitSyntax root)
 {
     return(root.AddUsings(
                UsingDirective(
                    QualifiedName(
                        QualifiedName(
                            IdentifierName("System"),
                            IdentifierName("Runtime")
                            ),
                        IdentifierName("CompilerServices")
                        ))));
 }
Ejemplo n.º 25
0
        /// <summary>
        /// Adds the string specified using statement to the CompilationUnitSyntax if that using is not already present.
        /// </summary>
        /// <remarks>
        /// The using statement, if inserted, will be followed by a CR/LF.
        /// </remarks>
        /// <param name="unit">
        /// The type being extended.
        /// </param>
        /// <param name="usingString">
        /// The string statement such as "System.Diagnostics" or "Microsoft.CodeAnalysis.CSharp.Syntax".
        /// </param>
        /// <returns>
        /// The CompilationUnitSyntax in <paramref name="unit"/>.
        /// </returns>
        public static CompilationUnitSyntax AddUsingIfNotPresent(this CompilationUnitSyntax unit, String usingString)
        {
            var t = unit.ChildNodes().OfType <UsingDirectiveSyntax>().Where(u => u.Name.ToString().Equals(usingString));

            if (!t.Any())
            {
                UsingDirectiveSyntax usingDirective = SyntaxFactoryHelper.QualifiedUsing(usingString);

                // I'll never understand why WithAdditionalAnnotations(Formatter.Annotation) isn't the default. Picking
                // up the default formatting should be the default and would make developing rules much easier.
                unit = unit.AddUsings(usingDirective).WithAdditionalAnnotations(Formatter.Annotation);
            }
            return(unit);
        }
Ejemplo n.º 26
0
        public static CompilationUnitSyntax AddUsing(CompilationUnitSyntax node, string usingStatement)
        {
            var hasUsing = node.Usings.Any(a => a.Name.ToString() == usingStatement);

            if (!hasUsing)
            {
                var name     = SyntaxFactory.ParseName($" {usingStatement}");
                var usingDir = SyntaxFactory.UsingDirective(name);
                usingDir = usingDir.WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation);
                usingDir = usingDir.WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed);
                node     = node.AddUsings(usingDir);
            }
            return(node);
        }
        public IWithNamespace ImportNamespaces(List <NamespaceModel> namespaceModels = null)
        {
            namespaceModels?.ForEach(model =>
            {
                if (model.PrependWithDomainName)
                {
                    model.Name = $"{_settings.DomainName}.{model.Name}";
                }

                _syntaxFactory = _syntaxFactory.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(model.Name)));
            });

            return(this);
        }
        internal static CompilationUnitSyntax AddUsings(this CompilationUnitSyntax compilationUnit, params string[] usings)
        {
            foreach (var @using in usings)
            {
                var needsUsing = !compilationUnit.ChildNodes().OfType <UsingDirectiveSyntax>().Any(u => u.Name.ToString().Equals(@using));

                if (needsUsing)
                {
                    var usingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(@using));
                    compilationUnit = compilationUnit.AddUsings(usingDirective).WithAdditionalAnnotations(Formatter.Annotation);
                }
            }

            return(compilationUnit);
        }
Ejemplo n.º 29
0
        public string Generate()
        {
            if (string.IsNullOrEmpty(SourceJson))
            {
                throw new InvalidOperationException("Source JSON for code generation cannot be empty.");
            }

            CompilationUnitSyntax compileUnit = SyntaxFactory.CompilationUnit();

            compileUnit = compileUnit.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System")));
            compileUnit = compileUnit.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("Newtonsoft.Json")));

            ButlerNamespace bNamespace = ButlerNamespaceFactory.Create(Namespace);

            JToken jToken = JToken.Parse(SourceJson);

            if (jToken == null)
            {
                throw new InvalidOperationException("Source JSON is not valid JSON.");
            }

            ButlerClass bClass = ButlerClassFactory.Create(ClassName, ClassName, jToken);

            // Add the class to the namespace.
            bNamespace.AddClass(bClass);

            // Add created classes (dependencies) to the namespace.
            bNamespace.AddClasses(bClass.Dependencies);

            compileUnit = compileUnit.AddMembers(bNamespace.Info);
            compileUnit = compileUnit.NormalizeWhitespace();

            string code = compileUnit.ToFullString();

            return(code);
        }
Ejemplo n.º 30
0
        public static async Task <Document> RefactorAsync(
            Document document,
            NamespaceDeclarationSyntax namespaceDeclaration,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (document == null)
            {
                throw new ArgumentNullException(nameof(document));
            }

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

            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var compilationUnit = (CompilationUnitSyntax)root;

            SyntaxList <UsingDirectiveSyntax> usings = namespaceDeclaration.Usings;

            CompilationUnitSyntax newCompilationUnit = compilationUnit
                                                       .RemoveNodes(usings, SyntaxRemoveOptions.KeepUnbalancedDirectives);

            if (!compilationUnit.Usings.Any())
            {
                SyntaxTriviaList leadingTrivia = compilationUnit.GetLeadingTrivia();

                SyntaxTrivia[] topTrivia = GetTopSingleLineComments(leadingTrivia).ToArray();

                if (topTrivia.Length > 0)
                {
                    newCompilationUnit = newCompilationUnit.WithoutLeadingTrivia();

                    usings = usings.Replace(
                        usings.First(),
                        usings.First().WithLeadingTrivia(topTrivia));

                    usings = usings.Replace(
                        usings.Last(),
                        usings.Last().WithTrailingTrivia(leadingTrivia.Skip(topTrivia.Length)));
                }
            }

            newCompilationUnit = newCompilationUnit.AddUsings(usings.Select(f => f.WithFormatterAnnotation()));

            return(document.WithSyntaxRoot(newCompilationUnit));
        }