Ejemplo n.º 1
0
        private static bool CheckTrivia(ElseClauseSyntax elseClause, IfStatementSyntax ifStatement)
        {
            TextSpan elseSpan = elseClause.Span;
            TextSpan ifSpan   = ifStatement.Span;

            TextSpan span  = TextSpan.FromBounds(elseSpan.Start, ifSpan.Start);
            TextSpan span2 = TextSpan.FromBounds(ifSpan.End, elseSpan.End);

            foreach (SyntaxTrivia trivia in elseClause.DescendantTrivia())
            {
                TextSpan triviaSpan = trivia.Span;

                if (span.Contains(triviaSpan))
                {
                    if (!trivia.IsWhitespaceOrEndOfLineTrivia())
                    {
                        return(false);
                    }
                }
                else if (span2.Contains(triviaSpan))
                {
                    if (!trivia.IsWhitespaceOrEndOfLineTrivia())
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
        public static void Analyze(SyntaxNodeAnalysisContext context, ElseClauseSyntax elseClause)
        {
            StatementSyntax statement = elseClause.Statement;

            if (statement?.IsKind(SyntaxKind.Block) == true)
            {
                var block = (BlockSyntax)statement;

                if (!block.Statements.Any() &&
                    elseClause
                    .DescendantTrivia(elseClause.Span)
                    .All(f => f.IsWhitespaceOrEndOfLineTrivia()))
                {
                    context.ReportDiagnostic(DiagnosticDescriptors.RemoveEmptyElseClause, elseClause);
                }
            }
        }