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
Add analyzer for flagging single-use of local JsonSerializerOptions #6850
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
b885e6b
Add analyzer for flagging single-use of local JsonSerializerOptions
Jozkee 7b265fc
Add changes made by msbuild /t:pack /v:m
Jozkee af0c8df
Merge branch 'main' of https://github.com/dotnet/roslyn-analyzers int…
Jozkee 3df8c17
Amend id CA1865 -> CA1869
Jozkee 28d5f32
Address feedback
Jozkee 4c24fa0
Update rule description, message and title
Jozkee 4c2fcc6
Fix formatting and apply changes from msbuild /t:pack /v:m
Jozkee File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
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
328 changes: 328 additions & 0 deletions
328
...ore/Microsoft.NetCore.Analyzers/Performance/AvoidSingleUseOfLocalJsonSerializerOptions.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,328 @@ | ||
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. | ||
|
||
using Microsoft.CodeAnalysis.Diagnostics; | ||
using Microsoft.CodeAnalysis; | ||
using System.Collections.Immutable; | ||
using Analyzer.Utilities; | ||
using Analyzer.Utilities.Extensions; | ||
using Microsoft.CodeAnalysis.Operations; | ||
using System.Diagnostics.CodeAnalysis; | ||
using System; | ||
using System.Collections.Generic; | ||
|
||
namespace Microsoft.NetCore.Analyzers.Performance | ||
{ | ||
using static MicrosoftNetCoreAnalyzersResources; | ||
|
||
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] | ||
public sealed class AvoidSingleUseOfLocalJsonSerializerOptions : DiagnosticAnalyzer | ||
{ | ||
internal static readonly DiagnosticDescriptor s_Rule = DiagnosticDescriptorHelper.Create( | ||
id: "CA1869", | ||
title: CreateLocalizableResourceString(nameof(AvoidSingleUseOfLocalJsonSerializerOptionsTitle)), | ||
messageFormat: CreateLocalizableResourceString(nameof(AvoidSingleUseOfLocalJsonSerializerOptionsMessage)), | ||
category: DiagnosticCategory.Performance, | ||
ruleLevel: RuleLevel.IdeSuggestion, | ||
description: CreateLocalizableResourceString(nameof(AvoidSingleUseOfLocalJsonSerializerOptionsDescription)), | ||
isPortedFxCopRule: false, | ||
isDataflowRule: false); | ||
|
||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(s_Rule); | ||
|
||
public override void Initialize(AnalysisContext context) | ||
{ | ||
context.EnableConcurrentExecution(); | ||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
context.RegisterCompilationStartAction(OnCompilationStart); | ||
} | ||
|
||
private static void OnCompilationStart(CompilationStartAnalysisContext context) | ||
{ | ||
Compilation compilation = context.Compilation; | ||
|
||
compilation.TryGetOrCreateTypeByMetadataName( | ||
WellKnownTypeNames.SystemTextJsonJsonSerializerOptions, out INamedTypeSymbol? jsonSerializerOptionsSymbol); | ||
|
||
compilation.TryGetOrCreateTypeByMetadataName( | ||
WellKnownTypeNames.SystemTextJsonJsonSerializer, out INamedTypeSymbol? jsonSerializerSymbol); | ||
|
||
if (jsonSerializerOptionsSymbol is null || jsonSerializerSymbol is null) | ||
{ | ||
return; | ||
} | ||
|
||
context.RegisterOperationAction( | ||
context => | ||
{ | ||
var operation = (IObjectCreationOperation)context.Operation; | ||
|
||
INamedTypeSymbol? typeSymbol = operation.Constructor?.ContainingType; | ||
if (SymbolEqualityComparer.Default.Equals(typeSymbol, jsonSerializerOptionsSymbol)) | ||
{ | ||
if (IsCtorUsedAsArgumentForJsonSerializer(operation, jsonSerializerSymbol) || | ||
IsLocalUsedAsArgumentForJsonSerializerOnly(operation, jsonSerializerSymbol)) | ||
{ | ||
context.ReportDiagnostic(operation.CreateDiagnostic(s_Rule)); | ||
} | ||
} | ||
}, | ||
OperationKind.ObjectCreation); | ||
} | ||
|
||
private static bool IsCtorUsedAsArgumentForJsonSerializer(IObjectCreationOperation objCreationOperation, INamedTypeSymbol jsonSerializerSymbol) | ||
{ | ||
IOperation operation = WalkUpConditional(objCreationOperation); | ||
|
||
return operation.Parent is IArgumentOperation argumentOperation && | ||
IsArgumentForJsonSerializer(argumentOperation, jsonSerializerSymbol); | ||
} | ||
|
||
private static bool IsArgumentForJsonSerializer(IArgumentOperation argumentOperation, INamedTypeSymbol jsonSerializerSymbol) | ||
{ | ||
return argumentOperation.Parent is IInvocationOperation invocationOperation && | ||
SymbolEqualityComparer.Default.Equals(invocationOperation.TargetMethod.ContainingType, jsonSerializerSymbol); | ||
} | ||
|
||
private static bool IsLocalUsedAsArgumentForJsonSerializerOnly(IObjectCreationOperation objCreation, INamedTypeSymbol jsonSerializerSymbol) | ||
{ | ||
IOperation operation = WalkUpConditional(objCreation); | ||
|
||
if (!IsLocalAssignment(operation, out List<ILocalSymbol>? localSymbols)) | ||
{ | ||
return false; | ||
} | ||
|
||
IBlockOperation? localBlock = objCreation.GetFirstParentBlock(); | ||
bool isSingleUseJsonSerializerInvocation = false; | ||
|
||
foreach (IOperation descendant in localBlock.Descendants()) | ||
{ | ||
if (descendant is not ILocalReferenceOperation localRefOperation || | ||
!localSymbols.Contains(localRefOperation.Local)) | ||
{ | ||
continue; | ||
} | ||
|
||
// Avoid cases that would potentially make the local escape current block scope. | ||
if (IsArgumentOfJsonSerializer(descendant, jsonSerializerSymbol, out bool isArgumentOfInvocation)) | ||
{ | ||
// Case: used more than once i.e: not single-use. | ||
if (isSingleUseJsonSerializerInvocation) | ||
{ | ||
return false; | ||
} | ||
|
||
isSingleUseJsonSerializerInvocation = true; | ||
} | ||
|
||
// Case: passed as argument of a non-JsonSerializer method. | ||
else if (isArgumentOfInvocation) | ||
{ | ||
return false; | ||
} | ||
|
||
if (IsFieldOrPropertyAssignment(descendant)) | ||
{ | ||
return false; | ||
} | ||
|
||
// Case: deconstruction assignment. | ||
if (IsTupleForDeconstructionTargetingFieldOrProperty(descendant)) | ||
{ | ||
return false; | ||
} | ||
|
||
// Case: local goes into closure. | ||
if (IsClosureOnLambdaOrLocalFunction(descendant, localBlock!)) | ||
{ | ||
return false; | ||
} | ||
} | ||
|
||
return isSingleUseJsonSerializerInvocation; | ||
} | ||
|
||
[return: NotNullIfNotNull(nameof(operation))] | ||
private static IOperation? WalkUpConditional(IOperation? operation) | ||
{ | ||
if (operation is null) | ||
return null; | ||
|
||
while (operation.Parent is IConditionalOperation conditionalOperation) | ||
{ | ||
operation = conditionalOperation; | ||
} | ||
|
||
return operation; | ||
} | ||
|
||
private static bool IsArgumentOfJsonSerializer(IOperation operation, INamedTypeSymbol jsonSerializerSymbol, out bool isArgumentOfInvocation) | ||
{ | ||
if (operation.Parent is IArgumentOperation arg && arg.Parent is IInvocationOperation inv) | ||
{ | ||
isArgumentOfInvocation = true; | ||
return SymbolEqualityComparer.Default.Equals(inv.TargetMethod.ContainingType, jsonSerializerSymbol); | ||
} | ||
|
||
isArgumentOfInvocation = false; | ||
return false; | ||
} | ||
|
||
private static bool IsFieldOrPropertyAssignment(IOperation operation) | ||
{ | ||
IOperation? current = operation.Parent; | ||
|
||
while (current is IAssignmentOperation assignment) | ||
{ | ||
if (assignment.Target is IFieldReferenceOperation or IPropertyReferenceOperation) | ||
{ | ||
return true; | ||
} | ||
|
||
current = current.Parent; | ||
} | ||
|
||
return false; | ||
} | ||
|
||
private static bool IsTupleForDeconstructionTargetingFieldOrProperty(IOperation operation) | ||
{ | ||
IOperation? current = operation.Parent; | ||
|
||
if (current is not ITupleOperation tuple) | ||
{ | ||
return false; | ||
} | ||
|
||
Stack<int> depth = new Stack<int>(); | ||
depth.Push(tuple.Elements.IndexOf(operation)); | ||
|
||
// walk-up right-hand nested tuples. | ||
while (tuple.Parent is ITupleOperation parent) | ||
{ | ||
depth.Push(parent.Elements.IndexOf(tuple)); | ||
tuple = parent; | ||
} | ||
|
||
current = tuple.WalkUpConversion().Parent; | ||
if (current is not IDeconstructionAssignmentOperation deconstruction) | ||
{ | ||
return false; | ||
} | ||
|
||
// walk-down left-hand nested tuples and see if it targets a field or property. | ||
if (deconstruction.Target is not ITupleOperation deconstructionTarget) | ||
{ | ||
return false; | ||
} | ||
|
||
tuple = deconstructionTarget; | ||
|
||
IOperation? target = null; | ||
while (depth.Count > 0) | ||
{ | ||
int idx = depth.Pop(); | ||
target = tuple.Elements[idx]; | ||
|
||
if (target is ITupleOperation targetAsTuple) | ||
{ | ||
tuple = targetAsTuple; | ||
} | ||
else if (depth.Count > 0) | ||
{ | ||
return false; | ||
} | ||
} | ||
|
||
return target is IFieldReferenceOperation or IPropertyReferenceOperation; | ||
} | ||
|
||
private static bool IsClosureOnLambdaOrLocalFunction(IOperation operation, IBlockOperation localBlock) | ||
{ | ||
if (!operation.IsWithinLambdaOrLocalFunction(out IOperation? lambdaOrLocalFunc)) | ||
{ | ||
return false; | ||
} | ||
|
||
IBlockOperation? block = lambdaOrLocalFunc switch | ||
{ | ||
IAnonymousFunctionOperation lambda => lambda.Body, | ||
ILocalFunctionOperation localFunc => localFunc.Body, | ||
_ => throw new InvalidOperationException() | ||
}; | ||
|
||
return block != localBlock; | ||
} | ||
|
||
private static bool IsLocalAssignment(IOperation operation, [NotNullWhen(true)] out List<ILocalSymbol>? localSymbols) | ||
{ | ||
localSymbols = null; | ||
IOperation? currentOperation = operation.Parent; | ||
|
||
while (currentOperation is not null) | ||
{ | ||
// for cases like: | ||
// var options; | ||
// options = new JsonSerializerOptions(); | ||
if (currentOperation is IExpressionStatementOperation) | ||
{ | ||
IOperation? tmpOperation = operation.Parent; | ||
while (tmpOperation is IAssignmentOperation assignment) | ||
{ | ||
if (assignment.Target is IFieldReferenceOperation or IPropertyReferenceOperation) | ||
{ | ||
return false; | ||
} | ||
else if (assignment.Target is ILocalReferenceOperation localRef) | ||
{ | ||
localSymbols ??= new List<ILocalSymbol>(); | ||
localSymbols.Add(localRef.Local); | ||
} | ||
|
||
tmpOperation = assignment.Parent; | ||
} | ||
|
||
return localSymbols != null; | ||
} | ||
// For cases like: | ||
// var options = new JsonSerializerOptions(); | ||
else if (currentOperation is IVariableDeclarationOperation declaration) | ||
{ | ||
if (operation.Parent is IAssignmentOperation assignment) | ||
{ | ||
foreach (IOperation children in assignment.Children) | ||
{ | ||
if (children is IFieldReferenceOperation or IPropertyReferenceOperation) | ||
{ | ||
return false; | ||
} | ||
} | ||
} | ||
|
||
var local = GetLocalSymbolFromDeclaration(declaration); | ||
if (local != null) | ||
{ | ||
localSymbols = new List<ILocalSymbol> { local }; | ||
} | ||
|
||
return local != null; | ||
} | ||
|
||
currentOperation = currentOperation.Parent; | ||
} | ||
|
||
return false; | ||
} | ||
|
||
private static ILocalSymbol? GetLocalSymbolFromDeclaration(IVariableDeclarationOperation declaration) | ||
{ | ||
if (declaration.Declarators.Length != 1) | ||
{ | ||
return null; | ||
} | ||
|
||
IVariableDeclaratorOperation declarator = declaration.Declarators[0]; | ||
return declarator.Symbol; | ||
} | ||
} | ||
} |
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.
NIT: Lots if effort for checking if the tuple targeting field or property, did not see a test case that flags a usage with tuple, is there any case that should be flagged? isn't it better to just bail out if the option is used within an tuple?
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.
Yes, it is probably too much effort for a rare case. But it doesn't hurt to have it. I can add the missing test you are referring to.