-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Add CA2026 analyzer: Prefer JsonElement.Parse over JsonDocument.Parse().RootElement #51209
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
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
ef45533
Initial plan
Copilot 5bbbec2
Add CA2026 analyzer and fixer for JsonDocument.Parse().RootElement pa…
Copilot 90c105e
Run dotnet format to clean up whitespace
Copilot b4387d1
Regenerate auto-generated documentation files for CA2026
Copilot 3629e72
Refactor analyzer based on code review feedback
Copilot a30e77b
Optimize analyzer performance and avoid lambda captures
Copilot b092256
Consolidate validation checks and add comprehensive tests
Copilot e422a6d
Merge branch 'main' into copilot/add-roslyn-analyzer-json-element
stephentoub 33b84f8
Convert test strings from verbatim to raw string literals
Copilot 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
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
78 changes: 78 additions & 0 deletions
78
...Analysis.NetAnalyzers/Microsoft.NetCore.Analyzers/Runtime/PreferJsonElementParse.Fixer.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,78 @@ | ||
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. | ||
|
||
using System.Collections.Immutable; | ||
using System.Composition; | ||
using System.Linq; | ||
using System.Threading.Tasks; | ||
using Analyzer.Utilities; | ||
using Analyzer.Utilities.Extensions; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.CodeActions; | ||
using Microsoft.CodeAnalysis.CodeFixes; | ||
using Microsoft.CodeAnalysis.Editing; | ||
using Microsoft.CodeAnalysis.Operations; | ||
|
||
namespace Microsoft.NetCore.Analyzers.Runtime | ||
{ | ||
/// <summary> | ||
/// Fixer for <see cref="PreferJsonElementParse"/>. | ||
/// </summary> | ||
[ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic), Shared] | ||
public sealed class PreferJsonElementParseFixer : CodeFixProvider | ||
{ | ||
public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } = | ||
ImmutableArray.Create(PreferJsonElementParse.RuleId); | ||
|
||
public sealed override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; | ||
|
||
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) | ||
{ | ||
Document doc = context.Document; | ||
SemanticModel model = await doc.GetRequiredSemanticModelAsync(context.CancellationToken).ConfigureAwait(false); | ||
SyntaxNode root = await doc.GetRequiredSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); | ||
|
||
if (root.FindNode(context.Span, getInnermostNodeForTie: true) is not SyntaxNode node || | ||
model.GetOperation(node, context.CancellationToken) is not IPropertyReferenceOperation propertyReference || | ||
propertyReference.Property.Name != "RootElement" || | ||
propertyReference.Instance is not IInvocationOperation invocation || | ||
invocation.TargetMethod.Name != "Parse") | ||
{ | ||
return; | ||
} | ||
|
||
string title = MicrosoftNetCoreAnalyzersResources.PreferJsonElementParseFix; | ||
context.RegisterCodeFix( | ||
CodeAction.Create( | ||
title, | ||
createChangedDocument: async ct => | ||
{ | ||
DocumentEditor editor = await DocumentEditor.CreateAsync(doc, ct).ConfigureAwait(false); | ||
SyntaxGenerator generator = editor.Generator; | ||
|
||
// Get the JsonElement type | ||
INamedTypeSymbol? jsonElementType = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemTextJsonJsonElement); | ||
if (jsonElementType == null) | ||
{ | ||
return doc; | ||
} | ||
|
||
// Create the replacement: JsonElement.Parse(...) | ||
// We need to use the same arguments that were passed to JsonDocument.Parse | ||
var arguments = invocation.Arguments.Select(arg => arg.Syntax).ToArray(); | ||
|
||
SyntaxNode memberAccess = generator.MemberAccessExpression( | ||
generator.TypeExpressionForStaticMemberAccess(jsonElementType), | ||
"Parse"); | ||
|
||
SyntaxNode replacement = generator.InvocationExpression(memberAccess, arguments); | ||
|
||
// Replace the entire property reference (JsonDocument.Parse(...).RootElement) with JsonElement.Parse(...) | ||
editor.ReplaceNode(propertyReference.Syntax, replacement.WithTriviaFrom(propertyReference.Syntax)); | ||
|
||
return editor.GetChangedDocument(); | ||
}, | ||
equivalenceKey: title), | ||
context.Diagnostics); | ||
} | ||
} | ||
} |
118 changes: 118 additions & 0 deletions
118
...t.CodeAnalysis.NetAnalyzers/Microsoft.NetCore.Analyzers/Runtime/PreferJsonElementParse.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,118 @@ | ||
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. 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.Runtime | ||
{ | ||
using static MicrosoftNetCoreAnalyzersResources; | ||
|
||
/// <summary> | ||
/// CA2026: Prefer JsonElement.Parse over JsonDocument.Parse().RootElement | ||
/// </summary> | ||
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] | ||
public sealed class PreferJsonElementParse : DiagnosticAnalyzer | ||
{ | ||
internal const string RuleId = "CA2026"; | ||
|
||
internal static readonly DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create( | ||
RuleId, | ||
CreateLocalizableResourceString(nameof(PreferJsonElementParseTitle)), | ||
CreateLocalizableResourceString(nameof(PreferJsonElementParseMessage)), | ||
DiagnosticCategory.Reliability, | ||
RuleLevel.IdeSuggestion, | ||
CreateLocalizableResourceString(nameof(PreferJsonElementParseDescription)), | ||
isPortedFxCopRule: false, | ||
isDataflowRule: false); | ||
|
||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Rule); | ||
|
||
public override void Initialize(AnalysisContext context) | ||
{ | ||
context.EnableConcurrentExecution(); | ||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
|
||
context.RegisterCompilationStartAction(context => | ||
{ | ||
// Get the JsonDocument and JsonElement types | ||
INamedTypeSymbol? jsonDocumentType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemTextJsonJsonDocument); | ||
INamedTypeSymbol? jsonElementType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemTextJsonJsonElement); | ||
|
||
if (jsonDocumentType is null || jsonElementType is null) | ||
{ | ||
return; | ||
} | ||
|
||
// Get all JsonElement.Parse overloads for matching | ||
var jsonElementParseOverloads = jsonElementType.GetMembers("Parse") | ||
.OfType<IMethodSymbol>() | ||
.Where(m => m.IsStatic) | ||
.ToImmutableArray(); | ||
|
||
// Check if JsonElement.Parse exists | ||
if (jsonElementParseOverloads.IsEmpty || | ||
!jsonDocumentType.GetMembers("Parse").Any(m => m is IMethodSymbol { IsStatic: true })) | ||
{ | ||
return; | ||
} | ||
|
||
// Get the RootElement property | ||
IPropertySymbol? rootElementProperty = jsonDocumentType.GetMembers("RootElement") | ||
.OfType<IPropertySymbol>() | ||
.FirstOrDefault(); | ||
|
||
if (rootElementProperty is null) | ||
{ | ||
return; | ||
} | ||
|
||
context.RegisterOperationAction(context => | ||
{ | ||
var propertyReference = (IPropertyReferenceOperation)context.Operation; | ||
|
||
// Check if this is accessing the RootElement property and the instance is a direct call to JsonDocument.Parse | ||
if (!SymbolEqualityComparer.Default.Equals(propertyReference.Property, rootElementProperty) || | ||
propertyReference.Instance is not IInvocationOperation invocation || | ||
!SymbolEqualityComparer.Default.Equals(invocation.TargetMethod.ContainingType, jsonDocumentType) || | ||
invocation.TargetMethod.Name != "Parse") | ||
{ | ||
return; | ||
} | ||
|
||
// Now we have the pattern: JsonDocument.Parse(...).RootElement | ||
// Check if there's a matching JsonElement.Parse overload with the same parameter types | ||
var jsonDocumentParseMethod = invocation.TargetMethod; | ||
|
||
foreach (var elementParseOverload in jsonElementParseOverloads) | ||
{ | ||
if (elementParseOverload.Parameters.Length != jsonDocumentParseMethod.Parameters.Length) | ||
{ | ||
continue; | ||
} | ||
|
||
bool parametersMatch = true; | ||
for (int i = 0; i < elementParseOverload.Parameters.Length; i++) | ||
{ | ||
if (!SymbolEqualityComparer.Default.Equals(elementParseOverload.Parameters[i].Type, jsonDocumentParseMethod.Parameters[i].Type)) | ||
{ | ||
parametersMatch = false; | ||
break; | ||
} | ||
} | ||
|
||
if (parametersMatch) | ||
{ | ||
context.ReportDiagnostic(propertyReference.CreateDiagnostic(Rule)); | ||
break; | ||
} | ||
} | ||
}, OperationKind.PropertyReference); | ||
}); | ||
} | ||
} | ||
} |
20 changes: 20 additions & 0 deletions
20
...is.NetAnalyzers/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.cs.xlf
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
20 changes: 20 additions & 0 deletions
20
...is.NetAnalyzers/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.de.xlf
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
20 changes: 20 additions & 0 deletions
20
...is.NetAnalyzers/Microsoft.NetCore.Analyzers/xlf/MicrosoftNetCoreAnalyzersResources.es.xlf
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
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.