コード例 #1
0
        private void AnalyzeIfStatement(SyntaxNodeAnalysisContext context)
        {
            if (GeneratedCodeAnalyzer?.IsGeneratedCode(context) == true)
            {
                return;
            }

            if (context.Node.Parent?.IsKind(SyntaxKind.ElseClause) == true)
            {
                return;
            }

            var ifStatement = (IfStatementSyntax)context.Node;

            if (ifStatement.Else != null)
            {
                var result = new IfElseAnalysisResult(ifStatement);

                if (result.AddBraces)
                {
                    context.ReportDiagnostic(
                        DiagnosticDescriptors.AddBracesToIfElse,
                        ifStatement.GetLocation());
                }

                if (result.RemoveBraces)
                {
                    context.ReportDiagnostic(
                        DiagnosticDescriptors.RemoveBracesFromIfElse,
                        ifStatement.GetLocation());

                    RemoveBracesFromIfElseFadeOut(context, ifStatement);
                }
            }

            MergeIfStatementWithNestedIfStatementAnalyzer.Analyze(context, ifStatement);

            SimplifyIfStatementToReturnStatementAnalyzer.Analyze(context);

            if (SimplifyIfElseStatementRefactoring.CanRefactor(ifStatement, context.SemanticModel, context.CancellationToken) &&
                !ifStatement.SpanContainsDirectives())
            {
                context.ReportDiagnostic(
                    DiagnosticDescriptors.SimplifyIfElseStatement,
                    ifStatement.GetLocation());
            }
        }
        public static Task <Document> RefactorAsync(
            Document document,
            IfStatementSyntax ifStatement,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            IfStatementSyntax nestedIf = MergeIfStatementWithNestedIfStatementAnalyzer.GetNestedIfStatement(ifStatement);

            ExpressionSyntax left  = ifStatement.Condition.Parenthesize();
            ExpressionSyntax right = nestedIf.Condition;

            if (!right.IsKind(SyntaxKind.LogicalAndExpression))
            {
                right = right.Parenthesize();
            }

            BinaryExpressionSyntax newCondition = CSharpFactory.LogicalAndExpression(left, right);

            IfStatementSyntax newNode = GetNewIfStatement(ifStatement, nestedIf)
                                        .WithCondition(newCondition)
                                        .WithFormatterAnnotation();

            return(document.ReplaceNodeAsync(ifStatement, newNode, cancellationToken));
        }