static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            var node              = nodeContext.Node as IfStatementSyntax;
            var semanticModel     = nodeContext.SemanticModel;
            var cancellationToken = nodeContext.CancellationToken;

            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
            {
                return(false);
            }
            ExpressionSyntax           condition, target;
            AssignmentExpressionSyntax trueAssignment, falseAssignment;

            if (!ConvertIfStatementToConditionalTernaryExpressionCodeRefactoringProvider.ParseIfStatement(node, out condition, out target, out trueAssignment, out falseAssignment))
            {
                return(false);
            }
            if (IsComplexCondition(condition) || IsComplexExpression(trueAssignment.Right) || IsComplexExpression(falseAssignment.Right))
            {
                return(false);
            }

            diagnostic = Diagnostic.Create(
                descriptor,
                node.IfKeyword.GetLocation()
                );
            return(true);
        }
Example #2
0
        public async override Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var document          = context.Document;
            var cancellationToken = context.CancellationToken;
            var span        = context.Span;
            var diagnostics = context.Diagnostics;
            var root        = await document.GetSyntaxRootAsync(cancellationToken);

            var diagnostic = diagnostics.First();
            var node       = root.FindNode(context.Span) as IfStatementSyntax;

            ExpressionSyntax           condition, target;
            AssignmentExpressionSyntax trueAssignment, falseAssignment;

            if (!ConvertIfStatementToConditionalTernaryExpressionCodeRefactoringProvider.ParseIfStatement(node, out condition, out target, out trueAssignment, out falseAssignment))
            {
                return;
            }
            var newRoot = root.ReplaceNode((SyntaxNode)node,
                                           SyntaxFactory.ExpressionStatement(
                                               SyntaxFactory.AssignmentExpression(
                                                   trueAssignment.Kind(),
                                                   trueAssignment.Left,
                                                   SyntaxFactory.ConditionalExpression(condition, trueAssignment.Right, falseAssignment.Right)
                                                   )
                                               ).WithAdditionalAnnotations(Formatter.Annotation)
                                           );

            context.RegisterCodeFix(CodeActionFactory.Create(node.Span, diagnostic.Severity, "Convert to '?:' expression", document.WithSyntaxRoot(newRoot)), diagnostic);
        }