Exemple #1
0
        public static Span HasValidCopyright(this CompilationUnitSyntax node)
        {
            if (node == null)
            {
                return(null);
            }

            Error error = Test.CodeCompliance.Query.HasValidCopyright(node.GetLeadingTrivia(), DateTime.Now.Year).Information.FirstOrDefault() as Error;

            if (error != null)
            {
                return(error.Location.Line.ToSpan(node.GetLeadingTrivia().ToString()));
            }

            return(null);
        }
Exemple #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));
        }
Exemple #3
0
        public override void VisitCompilationUnit(CompilationUnitSyntax compilationUnit)
        {
            foreach (var m in compilationUnit.ChildNodes())
            {
                Cx.Try(m, null, () => ((CSharpSyntaxNode)m).Accept(this));
            }

            ExtractGlobalStatements(compilationUnit);

            // Gather comments:
            foreach (var trivia in compilationUnit.DescendantTrivia(compilationUnit.Span, descendIntoTrivia: true))
            {
                CommentPopulator.ExtractComment(Cx, trivia);
            }

            foreach (var trivia in compilationUnit.GetLeadingTrivia())
            {
                CommentPopulator.ExtractComment(Cx, trivia);
            }

            foreach (var trivia in compilationUnit.GetTrailingTrivia())
            {
                CommentPopulator.ExtractComment(Cx, trivia);
            }
        }
Exemple #4
0
        private static CompilationUnitSyntax RemoveLeadingTrivia(CompilationUnitSyntax root)
        {
            if (root.HasLeadingTrivia)
            {
                return(root.ReplaceTrivia(root.GetLeadingTrivia(), (trivia, syntaxTrivia) => default(SyntaxTrivia)));
            }

            return(root);
        }
        public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node)
        {
            string leadingComment = node.GetLeadingTrivia().ToFullString();

            if (leadingComment.StartsWith(CommentText) || leadingComment.Contains("<auto-generated>"))
            {
                return(node);
            }
            else
            {
                return(node.WithLeadingTrivia(Comment));
            }
        }
Exemple #6
0
        public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node)
        {
            if (node.Usings.Count > 0)
            {
                var newUsingDirectives = new SyntaxList <UsingDirectiveSyntax>();
                var nodesToKeep        = node.Usings.Where(directive => directive.Name.ToString() != Constants.Proto.USING_STATEMENT).ToArray();
                newUsingDirectives = newUsingDirectives.AddRange(nodesToKeep);
                var leadTriv = node.GetLeadingTrivia();
                node = node.WithUsings(newUsingDirectives);
                node = node.WithLeadingTrivia(leadTriv);
            }

            return(base.VisitCompilationUnit(node));
        }
        public static CompilationUnitSyntax AddUsings(CompilationUnitSyntax node, Options options)
        {
            // Remember leading trivia (e.g. license header comments) so we can restore
            // it later. For some reason, manipulating the usings can remove it.
            var comment = node.GetLeadingTrivia();
            var treeWithTriviaTrimmed = node.WithoutLeadingTrivia();

            // add any usings that were required when visiting the tree
            var usingsToRemove = treeWithTriviaTrimmed.Usings.FindByName(u => u.Name, "Rhino.Mocks");
            var usingsToAdd    = CreateUsing("NSubstitute");
            var treeWithUsings = AddUsingsToCompilationUnit(treeWithTriviaTrimmed, usingsToRemove, usingsToAdd);

            // restore the leading trivia to the new syntax tree.
            var treeWithTriviaRestored = treeWithUsings.WithLeadingTrivia(comment);

            return(treeWithTriviaRestored);
        }
Exemple #8
0
        public static async Task <Document> RefactorAsync(
            Document document,
            CompilationUnitSyntax compilationUnit,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            CompilationUnitSyntax newNode = compilationUnit
                                            .WithLeadingTrivia(
                compilationUnit
                .GetLeadingTrivia()
                .Insert(0, CSharpFactory.NewLine())
                .Insert(0, HeaderTrivia));

            root = root.ReplaceNode(compilationUnit, newNode);

            return(document.WithSyntaxRoot(root));
        }
        public static CompilationUnitSyntax AddUsings(CompilationUnitSyntax node, RequiredUsings requiredUsings, Options options)
        {
            // Remember leading trivia (e.g. license header comments) so we can restore
            // it later. For some reason, manipulating the usings can remove it.
            var comment = node.GetLeadingTrivia();
            var treeWithTriviaTrimmed = options.ConvertAssert
                ? node.RemoveNUnitUsing().WithoutLeadingTrivia()
                : node.WithoutLeadingTrivia();

            // add any usings that were required when visiting the tree
            var additionalUsings = GenerateAdditionalUsings(node.Usings, requiredUsings, options).ToArray();
            var treeWithUsings   = AddUsingsToCompilationUnit(treeWithTriviaTrimmed, additionalUsings);

            // restore the leading trivia to the new syntax tree.
            var treeWithTriviaRestored = treeWithUsings.WithLeadingTrivia(comment);

            return(treeWithTriviaRestored);
        }
Exemple #10
0
        private static void Analyze(SyntaxNodeAnalysisContext context)
        {
            CompilationUnitSyntax node = (CompilationUnitSyntax)context.Node;

            if (Helper.IsGeneratedCode(context) || Helper.IsAssemblyInfo(context) || Helper.HasAutoGeneratedComment(node))
            {
                return;
            }

            if (node.FindToken(0).IsKind(SyntaxKind.EndOfFileToken))
            {
                return;
            }

            var first = node.GetLeadingTrivia();

            if (!first.Any())
            {
                CreateDiagnostic(context, node.GetLocation());
                return;
            }

            SyntaxTrivia copyrightSyntax = first[0];

            if (first[0].IsKind(SyntaxKind.RegionDirectiveTrivia))
            {
                if (first.Count < 2 || !first[1].IsKind(SyntaxKind.SingleLineCommentTrivia))
                {
                    CreateDiagnostic(context, context.Node.GetLocation());
                    return;
                }
                copyrightSyntax = first[1];
            }

            bool isCorrectStatement = CheckCopyrightStatement(context, copyrightSyntax);

            if (!isCorrectStatement)
            {
                CreateDiagnostic(context, copyrightSyntax.GetLocation());
                return;
            }
        }
        public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node)
        {
            node = base.VisitCompilationUnit(node) as CompilationUnitSyntax;

            List <ExternAliasDirectiveSyntax> addExterns = new List <ExternAliasDirectiveSyntax>();
            List <UsingDirectiveSyntax>       addUsings  = new List <UsingDirectiveSyntax>();
            List <MemberDeclarationSyntax>    addMembers = new List <MemberDeclarationSyntax>();

            addExterns.AddRange(node.Externs);
            foreach (var us in node.Usings)
            {
                if (us.Name.ToString().IndexOf(m_RootNs) == 0)
                {
                }
                else
                {
                    addUsings.Add(us);
                }
            }
            foreach (var member in node.Members)
            {
                var ns = member as NamespaceDeclarationSyntax;
                if (null != ns)
                {
                    if (ns.Name.ToString().IndexOf(m_RootNs) == 0)
                    {
                        ExtractMembersRecursively(addExterns, addUsings, addMembers, ns);
                    }
                    else
                    {
                        addMembers.Add(member);
                    }
                }
                else
                {
                    addMembers.Add(member);
                }
            }
            var newNode = SyntaxFactory.CompilationUnit(SyntaxFactory.List <ExternAliasDirectiveSyntax>(addExterns), SyntaxFactory.List <UsingDirectiveSyntax>(addUsings), node.AttributeLists, SyntaxFactory.List <MemberDeclarationSyntax>(addMembers));

            return(newNode.WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia()).WithEndOfFileToken(node.EndOfFileToken));
        }
Exemple #12
0
        public static bool CanRefactor(CompilationUnitSyntax compilationUnit)
        {
            foreach (SyntaxTrivia trivia in compilationUnit.GetLeadingTrivia())
            {
                switch (trivia.Kind())
                {
                case SyntaxKind.WhitespaceTrivia:
                case SyntaxKind.EndOfLineTrivia:
                    continue;

                case SyntaxKind.SingleLineCommentTrivia:
                    return(!string.Equals(trivia.ToString(), Header, StringComparison.Ordinal));

                default:
                    return(true);
                }
            }

            return(true);
        }
Exemple #13
0
        /// <summary>
        /// Checks for the presence of an "autogenerated" comment in the starting trivia for a file
        /// The compiler generates a version of the AssemblyInfo.cs file for certain projects (not named AssemblyInfo.cs), and this is how to pick it up
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        public static bool HasAutoGeneratedComment(CompilationUnitSyntax node)
        {
            if (node.FindToken(0).IsKind(SyntaxKind.EndOfFileToken))
            {
                return(false);
            }

            var first = node.GetLeadingTrivia();

            if (first.Count == 0)
            {
                return(false);
            }

            string possibleHeader = first.ToFullString();


            bool isAutogenerated = possibleHeader.Contains(@"<autogenerated />") || possibleHeader.Contains("<auto-generated");

            return(isAutogenerated);
        }
Exemple #14
0
        public override void VisitCompilationUnit(CompilationUnitSyntax compilationUnit)
        {
            foreach (var m in compilationUnit.ChildNodes())
            {
                cx.Try(m, null, () => ((CSharpSyntaxNode)m).Accept(this));
            }

            // Gather comments:
            foreach (SyntaxTrivia trivia in compilationUnit.DescendantTrivia(compilationUnit.Span))
            {
                CommentLine.Extract(cx, trivia);
            }

            foreach (var trivia in compilationUnit.GetLeadingTrivia())
            {
                CommentLine.Extract(cx, trivia);
            }

            foreach (var trivia in compilationUnit.GetTrailingTrivia())
            {
                CommentLine.Extract(cx, trivia);
            }
        }
Exemple #15
0
        public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node)
        {
            string comment = string.Format(
                "//-----------------------------------------------------------------------\n" +
                "// <copyright file=\"{0}\" company=\"{1}\">\n" +
                "// {2}\n" +
                "// </copyright>\n" +
                "//-----------------------------------------------------------------------\n" +
                "\n",
                Path.GetFileName(node.SyntaxTree.FilePath),
                this.settings.CompanyName,
                this.settings.Copyright.Replace("\n", "\n// "));

            // TODO: figure out how to do this properly.
            comment = comment.Replace("\n", Environment.NewLine);

            SyntaxTriviaList commentTrivia = Syntax.ParseLeadingTrivia(comment);
            var preservedTrivia = node.GetLeadingTrivia().SkipWhile(x =>
                x.Kind == SyntaxKind.SingleLineCommentTrivia ||
                x.Kind == SyntaxKind.EndOfLineTrivia);

            return node.WithLeadingTrivia(commentTrivia.Concat(preservedTrivia));
        }
        /// <summary>
        /// Adds a using statement to the compilation if necessary.
        /// </summary>
        /// <param name="compilation">The compilation unit to add the using to.</param>
        /// <param name="name">The name of the using to add.</param>
        /// <returns>The updated compilation unit with the new using.</returns>
        public static CompilationUnitSyntax AddUsingIfMissing(CompilationUnitSyntax compilation, NameSyntax name)
        {
            // TODO improve string comparison (replace)
            var stringName = name.ToString();

            if (compilation.DescendantNodes().OfType <UsingDirectiveSyntax>().Any(u => Equals(u.Name.ToString(), stringName)))
            {
                return(compilation);
            }

            // TODO ensure order?
            if (!compilation.ContainsDirectives || compilation.Usings.Count > 0)
            {
                return(compilation.AddUsings(SyntaxFactory.UsingDirective(name)));
            }

            // Roslyn bug: AddUsings adds the using before preprocessor settings (aka #define), which is incorrect (compiler error).
            return(compilation.WithoutLeadingTrivia().AddUsings(SyntaxFactory.UsingDirective(name).WithLeadingTrivia(compilation.GetLeadingTrivia())));
        }