protected override async Task FixOneAsync(
            Document document, Diagnostic diagnostic,
            SyntaxEditor editor, CancellationToken cancellationToken)
        {
            var syntaxFacts = document.GetLanguageService <ISyntaxFactsService>();
            var ifStatement = (TIfStatementSyntax)diagnostic.AdditionalLocations[0].FindNode(cancellationToken);

            var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            var ifOperation = (IConditionalOperation)semanticModel.GetOperation(ifStatement);

            if (!UseConditionalExpressionForReturnHelpers.TryMatchPattern(
                    syntaxFacts, ifOperation,
                    out var trueReturn, out var falseReturn))
            {
                return;
            }

            var conditionalExpression = await CreateConditionalExpressionAsync(
                document, ifOperation, trueReturn, falseReturn,
                trueReturn.ReturnedValue, falseReturn.ReturnedValue,
                IsRef(trueReturn), cancellationToken).ConfigureAwait(false);

            var returnStatement = trueReturn.Kind == OperationKind.YieldReturn
                ? (TStatementSyntax)editor.Generator.YieldReturnStatement(conditionalExpression)
                : (TStatementSyntax)editor.Generator.ReturnStatement(conditionalExpression);

            returnStatement = returnStatement.WithTriviaFrom(ifStatement);

            editor.ReplaceNode(
                ifStatement,
                this.WrapWithBlockIfAppropriate(ifStatement, returnStatement));

            // if the if-statement had no 'else' clause, then we were using the following statement
            // as the 'false' statement.  If so, remove it explicitly.
            if (ifOperation.WhenFalse == null)
            {
                editor.RemoveNode(falseReturn.Syntax, GetRemoveOptions(syntaxFacts, falseReturn.Syntax));
            }
        }
Beispiel #2
0
 protected override bool TryMatchPattern(IConditionalOperation ifOperation)
 => UseConditionalExpressionForReturnHelpers.TryMatchPattern(
     GetSyntaxFactsService(), ifOperation, out _, out _);