-
-
Notifications
You must be signed in to change notification settings - Fork 295
Add RCS9012: Call IsKind instead of comparing Kind #1820
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
josefpihrt
wants to merge
6
commits into
main
Choose a base branch
from
feature/rcs9012-use-iskind
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
a8093df
Add RCS9012 to prefer IsKind over Kind comparison.
a9c8e53
Fix RCS9012 test formatting and harden code fix.
8af8a45
Extend RCS9012 to SyntaxToken and SyntaxTrivia Kind().
a50eb81
Fix ChangeLog link to point at PR #1820.
f361980
Merge branch 'main' into feature/rcs9012-use-iskind
c5dd8ca
Merge branch 'main' into feature/rcs9012-use-iskind
josefpihrt File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
117 changes: 117 additions & 0 deletions
117
...odeAnalysis.Analyzers.CodeFixes/CSharp/UseIsKindInsteadOfKindComparisonCodeFixProvider.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,117 @@ | ||
| // Copyright (c) .NET Foundation and Contributors. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. | ||
|
|
||
| using System.Collections.Immutable; | ||
| using System.Composition; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CodeActions; | ||
| using Microsoft.CodeAnalysis.CodeFixes; | ||
| using Microsoft.CodeAnalysis.CSharp; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
| using Roslynator.CSharp; | ||
| using Roslynator.CSharp.Syntax; | ||
| using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; | ||
| using static Roslynator.CSharp.CSharpFactory; | ||
|
|
||
| namespace Roslynator.CodeAnalysis.CSharp; | ||
|
|
||
| [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(UseIsKindInsteadOfKindComparisonCodeFixProvider))] | ||
| [Shared] | ||
| public sealed class UseIsKindInsteadOfKindComparisonCodeFixProvider : BaseCodeFixProvider | ||
| { | ||
| public override ImmutableArray<string> FixableDiagnosticIds | ||
| { | ||
| get { return ImmutableArray.Create(CodeAnalysisDiagnosticIdentifiers.UseIsKindInsteadOfKindComparison); } | ||
| } | ||
|
|
||
| public override async Task RegisterCodeFixesAsync(CodeFixContext context) | ||
| { | ||
| SyntaxNode root = await context.GetSyntaxRootAsync().ConfigureAwait(false); | ||
|
|
||
| if (!TryFindFirstAncestorOrSelf(root, context.Span, out ExpressionSyntax expression)) | ||
| return; | ||
|
|
||
| Document document = context.Document; | ||
| Diagnostic diagnostic = context.Diagnostics[0]; | ||
|
|
||
| CodeAction codeAction = CodeAction.Create( | ||
| "Call 'IsKind' instead of comparing 'Kind'", | ||
| ct => RefactorAsync(document, expression, ct), | ||
| GetEquivalenceKey(diagnostic)); | ||
|
|
||
| context.RegisterCodeFix(codeAction, diagnostic); | ||
| } | ||
|
|
||
| private static async Task<Document> RefactorAsync( | ||
| Document document, | ||
| ExpressionSyntax expression, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); | ||
|
|
||
| expression = expression.WalkUpParentheses(); | ||
|
|
||
| ExpressionSyntax newExpression; | ||
|
|
||
| if (expression.IsKind(SyntaxKind.LogicalOrExpression)) | ||
| { | ||
| var logicalOr = (BinaryExpressionSyntax)expression; | ||
|
|
||
| ImmutableArray<IsKindExpressionInfo>.Builder builder = ImmutableArray.CreateBuilder<IsKindExpressionInfo>(); | ||
|
|
||
| foreach (ExpressionSyntax operand in SyntaxInfo.BinaryExpressionInfo(logicalOr).AsChain()) | ||
| { | ||
| IsKindExpressionInfo info = IsKindExpressionInfo.Create( | ||
| operand, | ||
| semanticModel, | ||
| cancellationToken: cancellationToken); | ||
|
|
||
| if (!info.Success) | ||
| return document; | ||
|
|
||
| builder.Add(info); | ||
| } | ||
|
|
||
| if (builder.Count == 0) | ||
| return document; | ||
|
|
||
| newExpression = CreateIsKindExpression(builder[0]); | ||
|
josefpihrt marked this conversation as resolved.
|
||
|
|
||
| for (int i = 1; i < builder.Count; i++) | ||
| newExpression = LogicalOrExpression(newExpression, CreateIsKindExpression(builder[i])); | ||
| } | ||
| else | ||
| { | ||
| IsKindExpressionInfo info = IsKindExpressionInfo.Create( | ||
| expression, | ||
| semanticModel, | ||
| cancellationToken: cancellationToken); | ||
|
|
||
| if (!info.Success) | ||
| return document; | ||
|
|
||
| newExpression = CreateIsKindExpression(info); | ||
| } | ||
|
|
||
| newExpression = newExpression | ||
| .WithTriviaFrom(expression) | ||
| .WithFormatterAnnotation(); | ||
|
|
||
| return await document.ReplaceNodeAsync(expression, newExpression, cancellationToken).ConfigureAwait(false); | ||
| } | ||
|
|
||
| private static ExpressionSyntax CreateIsKindExpression(IsKindExpressionInfo info) | ||
| { | ||
| InvocationExpressionSyntax invocation = SimpleMemberInvocationExpression( | ||
| info.Expression.WithoutTrivia(), | ||
| IdentifierName("IsKind"), | ||
| Argument(info.KindExpression.WithoutTrivia())); | ||
|
|
||
| return info.Style switch | ||
| { | ||
| IsKindExpressionStyle.NotKind or IsKindExpressionStyle.NotKindConditional => LogicalNotExpression(invocation), | ||
| _ => invocation, | ||
| }; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
175 changes: 175 additions & 0 deletions
175
src/CodeAnalysis.Analyzers/CSharp/UseIsKindInsteadOfKindComparisonAnalyzer.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,175 @@ | ||
| // Copyright (c) .NET Foundation and Contributors. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. | ||
|
|
||
| using System.Collections.Immutable; | ||
| using System.Threading; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CSharp; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
| using Microsoft.CodeAnalysis.Diagnostics; | ||
| using Roslynator.CSharp; | ||
| using Roslynator.CSharp.Syntax; | ||
|
|
||
| namespace Roslynator.CodeAnalysis.CSharp; | ||
|
|
||
| [DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
| public sealed class UseIsKindInsteadOfKindComparisonAnalyzer : BaseDiagnosticAnalyzer | ||
| { | ||
| private static ImmutableArray<DiagnosticDescriptor> _supportedDiagnostics; | ||
|
|
||
| public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics | ||
| { | ||
| get | ||
| { | ||
| if (_supportedDiagnostics.IsDefault) | ||
| Immutable.InterlockedInitialize(ref _supportedDiagnostics, CodeAnalysisDiagnosticRules.UseIsKindInsteadOfKindComparison); | ||
|
|
||
| return _supportedDiagnostics; | ||
| } | ||
| } | ||
|
|
||
| public override void Initialize(AnalysisContext context) | ||
| { | ||
| base.Initialize(context); | ||
|
|
||
| context.RegisterSyntaxNodeAction(f => AnalyzeBinaryExpression(f), SyntaxKind.EqualsExpression, SyntaxKind.NotEqualsExpression); | ||
|
josefpihrt marked this conversation as resolved.
|
||
| } | ||
|
|
||
| private static void AnalyzeBinaryExpression(SyntaxNodeAnalysisContext context) | ||
| { | ||
| var binaryExpression = (BinaryExpressionSyntax)context.Node; | ||
|
|
||
| if (binaryExpression.ContainsDiagnostics) | ||
| return; | ||
|
|
||
| ExpressionSyntax outermost = GetOutermostLogicalOrOrSelf(binaryExpression); | ||
|
|
||
| if (outermost.IsKind(SyntaxKind.LogicalOrExpression)) | ||
| { | ||
| var logicalOr = (BinaryExpressionSyntax)outermost; | ||
|
|
||
| if (!TryGetKindComparisonChain( | ||
| logicalOr, | ||
| context.SemanticModel, | ||
| context.CancellationToken, | ||
| out ImmutableArray<IsKindExpressionInfo> infos)) | ||
| { | ||
| AnalyzeSingleComparison(context, binaryExpression); | ||
| return; | ||
| } | ||
|
|
||
| if (!binaryExpression.Equals(infos[0].IsKindExpression)) | ||
| return; | ||
|
|
||
| DiagnosticHelpers.ReportDiagnostic( | ||
| context, | ||
| CodeAnalysisDiagnosticRules.UseIsKindInsteadOfKindComparison, | ||
| logicalOr); | ||
| } | ||
| else | ||
| { | ||
| AnalyzeSingleComparison(context, binaryExpression); | ||
| } | ||
| } | ||
|
|
||
| private static void AnalyzeSingleComparison(SyntaxNodeAnalysisContext context, BinaryExpressionSyntax binaryExpression) | ||
| { | ||
| IsKindExpressionInfo info = IsKindExpressionInfo.Create( | ||
| binaryExpression, | ||
| context.SemanticModel, | ||
| cancellationToken: context.CancellationToken); | ||
|
|
||
| if (!info.Success) | ||
| return; | ||
|
|
||
| if (!IsKindComparisonStyle(info.Style)) | ||
| return; | ||
|
|
||
| if (!IsConstantSyntaxKind(info.KindExpression, context.SemanticModel, context.CancellationToken)) | ||
| return; | ||
|
|
||
| DiagnosticHelpers.ReportDiagnostic( | ||
| context, | ||
| CodeAnalysisDiagnosticRules.UseIsKindInsteadOfKindComparison, | ||
| info.IsKindExpression); | ||
| } | ||
|
|
||
| private static bool TryGetKindComparisonChain( | ||
| BinaryExpressionSyntax logicalOr, | ||
| SemanticModel semanticModel, | ||
| CancellationToken cancellationToken, | ||
| out ImmutableArray<IsKindExpressionInfo> infos) | ||
| { | ||
| infos = default; | ||
|
|
||
| BinaryExpressionInfo binaryExpressionInfo = SyntaxInfo.BinaryExpressionInfo(logicalOr); | ||
|
|
||
| if (!binaryExpressionInfo.Success) | ||
| return false; | ||
|
|
||
| ImmutableArray<IsKindExpressionInfo>.Builder builder = ImmutableArray.CreateBuilder<IsKindExpressionInfo>(); | ||
| ExpressionSyntax commonExpression = null; | ||
|
|
||
| foreach (ExpressionSyntax expression in binaryExpressionInfo.AsChain()) | ||
| { | ||
| IsKindExpressionInfo info = IsKindExpressionInfo.Create( | ||
| expression, | ||
| semanticModel, | ||
| cancellationToken: cancellationToken); | ||
|
|
||
| if (!info.Success) | ||
| return false; | ||
|
|
||
| if (info.Style is not (IsKindExpressionStyle.Kind or IsKindExpressionStyle.KindConditional)) | ||
| return false; | ||
|
|
||
| if (!IsConstantSyntaxKind(info.KindExpression, semanticModel, cancellationToken)) | ||
| return false; | ||
|
|
||
| if (commonExpression is null) | ||
| { | ||
| commonExpression = info.Expression; | ||
| } | ||
| else if (!CSharpFactory.AreEquivalent(commonExpression, info.Expression)) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| builder.Add(info); | ||
| } | ||
|
|
||
| if (builder.Count < 2) | ||
| return false; | ||
|
|
||
| infos = builder.ToImmutable(); | ||
| return true; | ||
| } | ||
|
|
||
| private static ExpressionSyntax GetOutermostLogicalOrOrSelf(ExpressionSyntax expression) | ||
| { | ||
| expression = expression.WalkUpParentheses(); | ||
|
|
||
| while (expression.Parent.IsKind(SyntaxKind.LogicalOrExpression)) | ||
| expression = ((ExpressionSyntax)expression.Parent).WalkUpParentheses(); | ||
|
|
||
| return expression; | ||
| } | ||
|
|
||
| private static bool IsKindComparisonStyle(IsKindExpressionStyle style) | ||
| { | ||
| return style is IsKindExpressionStyle.Kind | ||
| or IsKindExpressionStyle.KindConditional | ||
| or IsKindExpressionStyle.NotKind | ||
| or IsKindExpressionStyle.NotKindConditional; | ||
| } | ||
|
|
||
| private static bool IsConstantSyntaxKind( | ||
| ExpressionSyntax expression, | ||
| SemanticModel semanticModel, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| Optional<object> optionalConstantValue = semanticModel.GetConstantValue(expression, cancellationToken); | ||
|
|
||
| return optionalConstantValue.HasValue | ||
| && optionalConstantValue.Value is ushort; | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.