-
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 all 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
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
75 changes: 75 additions & 0 deletions
75
src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Performance/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,75 @@ | ||
// 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; | ||
using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
using Microsoft.NetCore.Analyzers; | ||
using Microsoft.NetCore.Analyzers.Performance; | ||
|
||
namespace Microsoft.NetCore.CSharp.Analyzers.Performance | ||
{ | ||
[ExportCodeFixProvider(LanguageNames.CSharp, Name = DetectPLINQNopsAnalyzer.RuleId), Shared] | ||
public sealed class DetectPLINQNopsFixer : CodeFixProvider | ||
{ | ||
private static readonly string[] s_removableEnds = new string[] { "ToList", "ToArray", "AsParallel", "ToDictionary", "ToHashSet" }; | ||
|
||
private static readonly string[] s_requiredAppendableEnds = new string[] { "ToDictionary", "ToHashSet" }; | ||
|
||
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)), | ||
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 = ((possibleInvocation as InvocationExpressionSyntax)!.Expression as MemberAccessExpressionSyntax)!.Expression; | ||
possibleInvocation = newExpression; | ||
} while (possibleInvocation is InvocationExpressionSyntax nestedInvocation && nestedInvocation.Expression is MemberAccessExpressionSyntax member && s_removableEnds.Contains(member.Name.Identifier.ValueText)); | ||
|
||
if (invocationExpression.Expression is MemberAccessExpressionSyntax directMember && s_requiredAppendableEnds.Contains(directMember.Name.Identifier.ValueText)) | ||
{ | ||
possibleInvocation = SyntaxFactory.InvocationExpression(SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, possibleInvocation, directMember.Name), invocationExpression.ArgumentList); | ||
} | ||
|
||
return originalSolution.WithDocumentSyntaxRoot(document.Id, root.ReplaceNode(invocationExpression, possibleInvocation)); | ||
} | ||
|
||
private class AsParallelCodeAction : SolutionChangeAction | ||
{ | ||
public AsParallelCodeAction(string title, Func<CancellationToken, Task<Solution>> createChangedSolution) | ||
: base(title, createChangedSolution, title) | ||
{ | ||
} | ||
} | ||
} | ||
} |
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 | ||
--------|----------|----------|------- | ||
CA1839 | Performance | Warning | 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
126 changes: 126 additions & 0 deletions
126
src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/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,126 @@ | ||
// 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.Diagnostics.CodeAnalysis; | ||
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.Performance | ||
{ | ||
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] | ||
public sealed class DetectPLINQNopsAnalyzer : DiagnosticAnalyzer | ||
{ | ||
internal const string RuleId = "CA1839"; | ||
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.Performance, | ||
RuleLevel.BuildWarning, | ||
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) || !ctx.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemLinqEnumerable, out var linqEnumerable)) | ||
{ | ||
return; | ||
} | ||
|
||
var asParallelSymbols = parallelEnumerable.GetMembers("AsParallel").ToImmutableHashSet(); | ||
var collectionSymbols = parallelEnumerable.GetMembers("ToArray") | ||
.Concat(parallelEnumerable.GetMembers("ToList")) | ||
.Concat(parallelEnumerable.GetMembers("ToDictionary")) | ||
.Concat(linqEnumerable.GetMembers("ToHashSet")) | ||
.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; | ||
|
||
private static bool FindFirstInvocationParent(IOperation operation, [NotNullWhen(true)] out IInvocationOperation? invocationOperation) | ||
{ | ||
invocationOperation = null; | ||
do | ||
{ | ||
operation = operation.Parent; | ||
if (operation is IInvocationOperation invocation) | ||
{ | ||
invocationOperation = invocation; | ||
return true; | ||
} | ||
|
||
if (operation is ILocalFunctionOperation or IAnonymousFunctionOperation) | ||
return false; | ||
} while (operation != null); | ||
|
||
return false; | ||
} | ||
|
||
public static bool TryGetParentIsToCollection(IInvocationOperation operation, ImmutableHashSet<ISymbol> collectionSymbols, out IInvocationOperation parentInvocation) | ||
{ | ||
parentInvocation = operation; | ||
var hasParentInvocation = FindFirstInvocationParent(operation, out var invocationParent); | ||
if (!hasParentInvocation) | ||
{ | ||
return false; | ||
} | ||
|
||
var targetMethod = (invocationParent!.TargetMethod.ReducedFrom ?? invocationParent.TargetMethod).OriginalDefinition; | ||
if (collectionSymbols.Contains(targetMethod)) | ||
{ | ||
parentInvocation = invocationParent; | ||
return true; | ||
} | ||
|
||
return false; | ||
} | ||
|
||
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) || asParallelSymbols.Contains(reducedMethod.ReducedFrom))) | ||
{ | ||
return; | ||
} | ||
|
||
IInvocationOperation? diagnosticInvocation = null; | ||
if (!ParentIsForEachStatement(invocation)) | ||
{ | ||
if (!TryGetParentIsToCollection(invocation, collectionSymbols, out var parentInvocation) || !ParentIsForEachStatement(parentInvocation)) | ||
{ | ||
return; | ||
} | ||
|
||
diagnosticInvocation = parentInvocation; | ||
} | ||
|
||
diagnosticInvocation ??= invocation; | ||
var diagnostic = diagnosticInvocation.CreateDiagnostic(DefaultRule); | ||
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
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.
After merging the current master into your branch, you will need to re-run msbuild pack.
The documentation links have moved from VS docs to .NET docs.
In current master you'll see these links are from .NET docs (while your branch is still on the old VS docs links).