public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var document = context.Document; var textSpan = context.Span; var cancellationToken = context.CancellationToken; var root = (SyntaxNode)await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(textSpan.Start); // Only trigger if the text span is within the 'if' keyword token of an if-else statement. if (token.Kind() != SyntaxKind.IfKeyword || !token.Span.IntersectsWith(textSpan.Start) || !token.Span.IntersectsWith(textSpan.End)) { return; } var ifStatement = token.Parent as IfStatementSyntax; if (ifStatement == null || ifStatement.Else == null) { return; } var semanticModel = (SemanticModel)await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); ReturnStatementSyntax returnStatement; if (ReturnConditionalAnalyzer.TryGetNewReturnStatement(ifStatement, semanticModel, out returnStatement)) { var action = new ConvertToConditionalCodeAction("Convert to conditional expression", (c) => Task.FromResult(ConvertToConditional(document, semanticModel, ifStatement, returnStatement, c))); context.RegisterRefactoring(action); } }
public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { Document document = context.Document; Microsoft.CodeAnalysis.Text.TextSpan textSpan = context.Span; CancellationToken cancellationToken = context.CancellationToken; SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); SyntaxToken token = root.FindToken(textSpan.Start); // Only trigger if the text span is within the 'if' keyword token of an if-else statement. if (token.Kind() != SyntaxKind.IfKeyword || !token.Span.IntersectsWith(textSpan.Start) || !token.Span.IntersectsWith(textSpan.End)) { return; } if (!(token.Parent is IfStatementSyntax ifStatement) || ifStatement.Else == null) { return; } SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); if (ReturnConditionalAnalyzer.TryGetNewReturnStatement(ifStatement, semanticModel, out ReturnStatementSyntax returnStatement)) { ConvertToConditionalCodeAction action = new ConvertToConditionalCodeAction("Convert to conditional expression", (c) => Task.FromResult(ConvertToConditional(document, semanticModel, ifStatement, returnStatement, c))); context.RegisterRefactoring(action); } }