|
2 | 2 |
|
3 | 3 | using System.Collections.Immutable; |
4 | 4 | using System.Composition; |
| 5 | +using System.Threading; |
5 | 6 | using System.Threading.Tasks; |
6 | 7 | using Microsoft.CodeAnalysis; |
7 | 8 | using Microsoft.CodeAnalysis.CodeActions; |
8 | 9 | using Microsoft.CodeAnalysis.CodeFixes; |
9 | 10 | using Microsoft.CodeAnalysis.CSharp; |
| 11 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
10 | 12 | using Roslynator.CodeFixes; |
11 | 13 | using Roslynator.CSharp.Refactorings; |
| 14 | +using Roslynator.CSharp.Syntax; |
| 15 | +using static Roslynator.CSharp.CSharpFactory; |
12 | 16 |
|
13 | 17 | namespace Roslynator.CSharp.CodeFixes; |
14 | 18 |
|
@@ -38,9 +42,33 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) |
38 | 42 |
|
39 | 43 | CodeAction codeAction = CodeAction.Create( |
40 | 44 | "Use 'is' operator", |
41 | | - ct => UseIsOperatorInsteadOfAsOperatorRefactoring.RefactorAsync(context.Document, node, ct), |
| 45 | + ct => RefactorAsync(context.Document, node, ct), |
42 | 46 | GetEquivalenceKey(diagnostic)); |
43 | 47 |
|
44 | 48 | context.RegisterCodeFix(codeAction, diagnostic); |
45 | 49 | } |
| 50 | + |
| 51 | + private static Task<Document> RefactorAsync( |
| 52 | + Document document, |
| 53 | + SyntaxNode node, |
| 54 | + CancellationToken cancellationToken) |
| 55 | + { |
| 56 | + NullCheckExpressionInfo nullCheck = SyntaxInfo.NullCheckExpressionInfo(node); |
| 57 | + |
| 58 | + AsExpressionInfo asExpressionInfo = SyntaxInfo.AsExpressionInfo(nullCheck.Expression); |
| 59 | + |
| 60 | + ExpressionSyntax newNode = IsExpression( |
| 61 | + asExpressionInfo.Expression, |
| 62 | + SyntaxFactory.Token(asExpressionInfo.OperatorToken.LeadingTrivia, SyntaxKind.IsKeyword, asExpressionInfo.OperatorToken.TrailingTrivia), |
| 63 | + asExpressionInfo.Type); |
| 64 | + |
| 65 | + if (nullCheck.IsCheckingNull) |
| 66 | + newNode = LogicalNotExpression(newNode.WithoutTrivia().Parenthesize()).WithTriviaFrom(newNode); |
| 67 | + |
| 68 | + newNode = newNode |
| 69 | + .Parenthesize() |
| 70 | + .WithFormatterAnnotation(); |
| 71 | + |
| 72 | + return document.ReplaceNodeAsync(node, newNode, cancellationToken); |
| 73 | + } |
46 | 74 | } |
0 commit comments