-
Notifications
You must be signed in to change notification settings - Fork 468
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
Detection of PLINQ nops analyzer #4126
Open
Mrnikbobjeff
wants to merge
23
commits into
dotnet:main
Choose a base branch
from
Mrnikbobjeff:feature/DetectPLINQNops
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 17 commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
2cec04e
Initial commit
14be941
Fixes for unit test and naming, adapted usage to other analyzers
2be0e72
Git mistake
e94d6e3
Git mistake
07cc042
Merge branch 'feature/DetectPLINQNops' of https://github.com/Mrnikbob…
f903c05
Preemptively adapt formatting thanks to feedback in other branch. Als…
54305c4
More formatting and minor refactoring
38136bf
Merge branch 'master' of https://github.com/dotnet/roslyn-analyzers i…
578e280
Renaming
96e5ecc
Review feedback, migrated to IOperation analyzer, cleaned up code eve…
8aa8336
Null weirdness
a5f1d88
Update DetectPLINQNops.Fixer.cs
Mrnikbobjeff bf94941
Apply suggestions from code review
Mrnikbobjeff e6ba27f
First review round
Mrnikbobjeff 3ef0abf
Merge branch 'feature/DetectPLINQNops' of https://github.com/Mrnikbob…
Mrnikbobjeff f7b4108
Review round 2
Mrnikbobjeff 90bee4b
Final cleanup
Mrnikbobjeff 4daf9fa
VB Test, fixed bug ocurring on vb code, removed unused test
Mrnikbobjeff b68ee84
Formatting
Mrnikbobjeff 52ca208
Review, docs
Mrnikbobjeff 80f27dc
Review
Mrnikbobjeff b50ae2a
Message change
Mrnikbobjeff d317bd8
Category, Id, doc gen
Mrnikbobjeff 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
68 changes: 68 additions & 0 deletions
68
src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Usage/DetectPLINQNops.Fixer.cs
This file contains 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,68 @@ | ||
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. | ||
|
||
using System; | ||
using System.Collections.Immutable; | ||
using System.Composition; | ||
using System.Linq; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
using Analyzer.Utilities; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.CodeFixes; | ||
using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
using Microsoft.NetCore.Analyzers; | ||
using Microsoft.NetCore.Analyzers.Usage; | ||
|
||
namespace Microsoft.NetCore.CSharp.Analyzers.Usage | ||
{ | ||
[ExportCodeFixProvider(LanguageNames.CSharp, Name = DetectPLINQNopsAnalyzer.RuleId), Shared] | ||
public sealed class DetectPLINQNopsFixer : CodeFixProvider | ||
{ | ||
private static readonly string[] removableEnds = new string[] { "ToList", "ToArray", "AsParallel" }; | ||
|
||
public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(DetectPLINQNopsAnalyzer.RuleId); | ||
|
||
public sealed override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; | ||
|
||
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) | ||
{ | ||
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); | ||
|
||
var node = root.FindNode(context.Span); | ||
if (node is not InvocationExpressionSyntax declaration) | ||
{ | ||
return; | ||
} | ||
|
||
context.RegisterCodeFix( | ||
new AsParallelCodeAction( | ||
title: MicrosoftNetCoreAnalyzersResources.RemoveRedundantCall, | ||
createChangedSolution: c => RemoveAsParallelCall(context.Document, declaration, c), | ||
equivalenceKey: MicrosoftNetCoreAnalyzersResources.RemoveRedundantCall), | ||
Mrnikbobjeff marked this conversation as resolved.
Show resolved
Hide resolved
|
||
context.Diagnostics); | ||
} | ||
|
||
private static async Task<Solution> RemoveAsParallelCall(Document document, InvocationExpressionSyntax invocationExpression, CancellationToken cancellationToken) | ||
{ | ||
var originalSolution = document.Project.Solution; | ||
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); | ||
ExpressionSyntax possibleInvocation = invocationExpression; | ||
|
||
do | ||
{ | ||
var newExpression = ((MemberAccessExpressionSyntax)((InvocationExpressionSyntax)possibleInvocation).Expression)!.Expression; | ||
possibleInvocation = newExpression; | ||
} while (possibleInvocation is InvocationExpressionSyntax nestedInvocation && nestedInvocation.Expression is MemberAccessExpressionSyntax member && removableEnds.Contains(member.Name.Identifier.ValueText)); | ||
|
||
return originalSolution.WithDocumentSyntaxRoot(document.Id, root.ReplaceNode(invocationExpression, possibleInvocation)); | ||
} | ||
|
||
private class AsParallelCodeAction : SolutionChangeAction | ||
{ | ||
public AsParallelCodeAction(string title, Func<CancellationToken, Task<Solution>> createChangedSolution, string equivalenceKey) | ||
: base(title, createChangedSolution, equivalenceKey) | ||
Mrnikbobjeff marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
} | ||
} | ||
} | ||
} |
This file contains 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 |
---|---|---|
@@ -1 +1,5 @@ | ||
; Please do not edit this file manually, it should only be updated through code fix application. | ||
### New Rules | ||
Mrnikbobjeff marked this conversation as resolved.
Show resolved
Hide resolved
|
||
Rule ID | Category | Severity | Notes | ||
--------|----------|----------|------- | ||
CA2250 | Usage | Info | DetectPLINQNopsAnalyzer, [Documentation](https://docs.microsoft.com/visualstudio/code-quality/ca2250) |
This file contains 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
99 changes: 99 additions & 0 deletions
99
src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Usage/DetectPLINQNopsAnalyzer.cs
This file contains 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,99 @@ | ||
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. | ||
|
||
using System.Collections.Immutable; | ||
using System.Linq; | ||
using Analyzer.Utilities; | ||
using Analyzer.Utilities.Extensions; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.Diagnostics; | ||
using Microsoft.CodeAnalysis.Operations; | ||
|
||
namespace Microsoft.NetCore.Analyzers.Usage | ||
{ | ||
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] | ||
public sealed class DetectPLINQNopsAnalyzer : DiagnosticAnalyzer | ||
{ | ||
internal const string RuleId = "CA2250"; | ||
internal static readonly LocalizableString localizableTitle = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.DetectPLINQNopsTitle), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); | ||
|
||
private static readonly LocalizableString s_localizableMessageDefault = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.DetectPLINQNopsMessage), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); | ||
private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.DetectPLINQNopsDescription), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); | ||
|
||
internal static readonly DiagnosticDescriptor DefaultRule = DiagnosticDescriptorHelper.Create(RuleId, | ||
localizableTitle, | ||
s_localizableMessageDefault, | ||
DiagnosticCategory.Usage, | ||
RuleLevel.IdeSuggestion, | ||
description: s_localizableDescription, | ||
isPortedFxCopRule: false, | ||
isDataflowRule: false); | ||
|
||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(DefaultRule); | ||
|
||
public override void Initialize(AnalysisContext context) | ||
{ | ||
context.EnableConcurrentExecution(); | ||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
context.RegisterCompilationStartAction(ctx => | ||
{ | ||
if (!ctx.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemLinqParallelEnumerable, out var parallelEnumerable)) | ||
{ | ||
return; | ||
} | ||
|
||
var asParallelSymbols = parallelEnumerable.GetMembers("AsParallel").ToImmutableHashSet(); | ||
var collectionSymbols = parallelEnumerable.GetMembers("ToArray").Concat(parallelEnumerable.GetMembers("ToList")).ToImmutableHashSet(); | ||
|
||
ctx.RegisterOperationAction(x => AnalyzeOperation(x, asParallelSymbols, collectionSymbols), OperationKind.Invocation); | ||
}); | ||
} | ||
|
||
public static bool ParentIsForEachStatement(IInvocationOperation operation) => operation.Parent is IForEachLoopOperation || operation.Parent?.Parent is IForEachLoopOperation; | ||
|
||
public static bool TryGetParentIsToArrayOrToList(IInvocationOperation operation, ImmutableHashSet<ISymbol> collectionSymbols, out IInvocationOperation parentInvocation) | ||
{ | ||
parentInvocation = operation; | ||
if (operation.Parent?.Parent is not IInvocationOperation invocation) | ||
{ | ||
return false; | ||
} | ||
if (collectionSymbols.Contains(invocation.TargetMethod.OriginalDefinition)) | ||
{ | ||
parentInvocation = invocation; | ||
return true; | ||
} | ||
|
||
return false; | ||
Mrnikbobjeff marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
private static void AnalyzeOperation(OperationAnalysisContext context, ImmutableHashSet<ISymbol> asParallelSymbols, ImmutableHashSet<ISymbol> collectionSymbols) | ||
{ | ||
var invocation = (IInvocationOperation)context.Operation; | ||
var reducedMethod = invocation.TargetMethod.OriginalDefinition; | ||
if (reducedMethod is null) | ||
{ | ||
return; | ||
} | ||
|
||
if (!asParallelSymbols.Contains(reducedMethod)) | ||
{ | ||
return; | ||
} | ||
|
||
IInvocationOperation? diagnosticInvocation = null; | ||
if (!ParentIsForEachStatement(invocation)) | ||
{ | ||
if (!TryGetParentIsToArrayOrToList(invocation, collectionSymbols, out var parentInvocation) || !ParentIsForEachStatement(parentInvocation)) | ||
{ | ||
return; | ||
} | ||
|
||
diagnosticInvocation = parentInvocation; | ||
Mrnikbobjeff marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
diagnosticInvocation ??= invocation; | ||
var diagnostic = diagnosticInvocation.CreateDiagnostic(DefaultRule, diagnosticInvocation.Syntax); | ||
Mrnikbobjeff marked this conversation as resolved.
Show resolved
Hide resolved
|
||
context.ReportDiagnostic(diagnostic); | ||
} | ||
} | ||
} |
This file contains 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 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 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 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 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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Not sure we do want to reuse this message or create a new specific one.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I have no idea, I'll adapt this to whatever is decided. It seemed to accurately reflect what the code fix does so I just chose that