-
Notifications
You must be signed in to change notification settings - Fork 10.5k
Add analyzer and code fix to recommend against IHeaderDictionary.Add #44463
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
captainsafia
merged 30 commits into
dotnet:main
from
david-acker:add-header-dictionary-analyzer
Nov 30, 2022
Merged
Changes from all commits
Commits
Show all changes
30 commits
Select commit
Hold shift + click to select a range
1373fbe
Add IHeaderDictionary.Add analyzer and code fix
david-acker aabfef9
Change wording from "Disallow-" to "RecommendAgainst-"
david-acker eb91cd8
Change diagnostic rule ID
david-acker 16332ba
Merge branch 'main' into add-header-dictionary-analyzer
david-acker 2bf902d
Remove analyzer and code fix from AspNetCore.Analyzers project
david-acker 88625b2
Add analyzer to Framework/AspNetCoreAnalyzers
david-acker dd36127
Add code fix to Framework/AspNetCoreAnalyzers
david-acker e6190b7
Fix nullable reference type
david-acker 049bde0
Fix diagnostics in the project caused by new analyzer
david-acker 1577df7
Fix using directive insertion logic
david-acker a2331a8
Fix StringComparison warning
david-acker d9aff0a
Update src/Analyzers/Analyzers/test/Microsoft.AspNetCore.Analyzers.Te…
david-acker a7d5124
Update src/Framework/AspNetCoreAnalyzers/src/Analyzers/Http/HeaderDic…
david-acker ed6ddcf
Update src/Framework/AspNetCoreAnalyzers/src/CodeFixes/Http/HeaderDic…
david-acker faee1d0
Update src/Framework/AspNetCoreAnalyzers/src/CodeFixes/Http/HeaderDic…
david-acker 81f6715
Update src/Framework/AspNetCoreAnalyzers/src/CodeFixes/Http/HeaderDic…
david-acker c2d8519
Update code fix equivalence key referenced in tests
david-acker 8a0bc4b
Remove redundant test
david-acker 362d172
Merge analyzer and code fix tests into single test file
david-acker e3caef0
Use top-level statements
david-acker debb846
Add test cases for multiple diagnostics
david-acker 40bd514
Add comment about IDictionary.Add to diagnostic message
david-acker e2f0a12
Update diagnostic message
david-acker a216f87
Move checks before code fix registration
david-acker 1bad1a3
Pass true for getInnermostNodeForTie
david-acker 289260a
Perform symbol comparison for IHeaderDictionary
david-acker bc3ef4d
Add using directive via syntax annotation
david-acker 620275d
Add editorconfig
david-acker 117ab9e
Revert "Add editorconfig"
david-acker a57af9b
Skip test on Linux, macOS
david-acker 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
92 changes: 92 additions & 0 deletions
92
src/Framework/AspNetCoreAnalyzers/src/Analyzers/Http/HeaderDictionaryAddAnalyzer.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,92 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.Collections.Immutable; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.Diagnostics; | ||
| using Microsoft.CodeAnalysis.Operations; | ||
|
|
||
| namespace Microsoft.AspNetCore.Analyzers.Http; | ||
|
|
||
| [DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
| public sealed class HeaderDictionaryAddAnalyzer : DiagnosticAnalyzer | ||
| { | ||
| public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(DiagnosticDescriptors.DoNotUseIHeaderDictionaryAdd); | ||
|
|
||
| public override void Initialize(AnalysisContext context) | ||
| { | ||
| context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
| context.EnableConcurrentExecution(); | ||
| context.RegisterCompilationStartAction(OnCompilationStart); | ||
| } | ||
|
|
||
| private static void OnCompilationStart(CompilationStartAnalysisContext context) | ||
| { | ||
| var symbols = new HeaderDictionarySymbols(context.Compilation); | ||
|
|
||
| if (!symbols.HasRequiredSymbols) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| context.RegisterOperationAction(context => | ||
| { | ||
| var invocation = (IInvocationOperation)context.Operation; | ||
|
|
||
| if (SymbolEqualityComparer.Default.Equals(symbols.IHeaderDictionary, invocation.Instance?.Type) | ||
| && IsAddMethod(invocation.TargetMethod) | ||
| && invocation.TargetMethod.Parameters.Length == 2) | ||
| { | ||
| AddDiagnosticWarning(context, invocation.Syntax.GetLocation()); | ||
| } | ||
|
|
||
| }, OperationKind.Invocation); | ||
| } | ||
|
|
||
| private static bool IsAddMethod(IMethodSymbol method) | ||
| { | ||
| return method is | ||
| { | ||
| Name: "Add", | ||
| ContainingType: | ||
| { | ||
| Name: "IDictionary", | ||
| ContainingNamespace: | ||
| { | ||
| Name: "Generic", | ||
| ContainingNamespace: | ||
| { | ||
| Name: "Collections", | ||
| ContainingNamespace: | ||
| { | ||
| Name: "System", | ||
| ContainingNamespace: | ||
| { | ||
| IsGlobalNamespace: true | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| }; | ||
| } | ||
|
|
||
| private static void AddDiagnosticWarning(OperationAnalysisContext context, Location location) | ||
| { | ||
| context.ReportDiagnostic(Diagnostic.Create( | ||
| DiagnosticDescriptors.DoNotUseIHeaderDictionaryAdd, | ||
| location)); | ||
| } | ||
|
|
||
| private sealed class HeaderDictionarySymbols | ||
| { | ||
| public HeaderDictionarySymbols(Compilation compilation) | ||
| { | ||
| IHeaderDictionary = compilation.GetTypeByMetadataName("Microsoft.AspNetCore.Http.IHeaderDictionary"); | ||
| } | ||
|
|
||
| public bool HasRequiredSymbols => IHeaderDictionary is not null; | ||
|
|
||
| public INamedTypeSymbol IHeaderDictionary { get; } | ||
| } | ||
| } |
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
129 changes: 129 additions & 0 deletions
129
src/Framework/AspNetCoreAnalyzers/src/CodeFixes/Http/HeaderDictionaryAddFixer.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,129 @@ | ||||||||
| // Licensed to the .NET Foundation under one or more agreements. | ||||||||
| // The .NET Foundation licenses this file to you under the MIT license. | ||||||||
|
|
||||||||
| 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; | ||||||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||
| using Microsoft.CodeAnalysis.Simplification; | ||||||||
|
|
||||||||
| namespace Microsoft.AspNetCore.Analyzers.Http.Fixers; | ||||||||
|
|
||||||||
| [ExportCodeFixProvider(LanguageNames.CSharp), Shared] | ||||||||
| public sealed class HeaderDictionaryAddFixer : CodeFixProvider | ||||||||
| { | ||||||||
| public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(DiagnosticDescriptors.DoNotUseIHeaderDictionaryAdd.Id); | ||||||||
|
|
||||||||
| public sealed override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; | ||||||||
|
|
||||||||
| public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) | ||||||||
| { | ||||||||
| foreach (var diagnostic in context.Diagnostics) | ||||||||
| { | ||||||||
| context.Document.TryGetSyntaxRoot(out var root); | ||||||||
|
|
||||||||
| if (CanReplaceWithAppend(diagnostic, root, out var invocation)) | ||||||||
| { | ||||||||
| var appendTitle = "Use 'IHeaderDictionary.Append'"; | ||||||||
| context.RegisterCodeFix( | ||||||||
| CodeAction.Create(appendTitle, | ||||||||
| cancellationToken => ReplaceWithAppend(diagnostic, context.Document, invocation, cancellationToken), | ||||||||
| equivalenceKey: appendTitle), | ||||||||
| diagnostic); | ||||||||
| } | ||||||||
|
|
||||||||
| if (CanReplaceWithIndexer(diagnostic, root, out var assignment)) | ||||||||
| { | ||||||||
| var indexerTitle = "Use indexer"; | ||||||||
| context.RegisterCodeFix( | ||||||||
| CodeAction.Create(indexerTitle, | ||||||||
| cancellationToken => ReplaceWithIndexer(diagnostic, context.Document, assignment, cancellationToken), | ||||||||
| equivalenceKey: indexerTitle), | ||||||||
| diagnostic); | ||||||||
| } | ||||||||
| } | ||||||||
|
|
||||||||
| return Task.CompletedTask; | ||||||||
| } | ||||||||
|
|
||||||||
| private static async Task<Document> ReplaceWithAppend(Diagnostic diagnostic, Document document, InvocationExpressionSyntax invocation, CancellationToken cancellationToken) | ||||||||
| { | ||||||||
| var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); | ||||||||
|
|
||||||||
| var diagnosticTarget = root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true); | ||||||||
|
|
||||||||
| var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); | ||||||||
| var headerDictionaryExtensionsSymbol = model.Compilation.GetTypeByMetadataName("Microsoft.AspNetCore.Http.HeaderDictionaryExtensions"); | ||||||||
| var annotation = new SyntaxAnnotation("SymbolId", DocumentationCommentId.CreateReferenceId(headerDictionaryExtensionsSymbol)); | ||||||||
|
|
||||||||
| return document.WithSyntaxRoot( | ||||||||
| root.ReplaceNode(diagnosticTarget, invocation.WithAdditionalAnnotations(Simplifier.AddImportsAnnotation, annotation))); | ||||||||
| } | ||||||||
|
|
||||||||
| private static bool CanReplaceWithAppend(Diagnostic diagnostic, SyntaxNode root, out InvocationExpressionSyntax invocation) | ||||||||
| { | ||||||||
| invocation = null; | ||||||||
|
|
||||||||
| if (root is not CompilationUnitSyntax) | ||||||||
| { | ||||||||
| return false; | ||||||||
| } | ||||||||
|
|
||||||||
| var diagnosticTarget = root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true); | ||||||||
|
|
||||||||
| if (diagnosticTarget is InvocationExpressionSyntax { Expression: MemberAccessExpressionSyntax { Name.Identifier: { } identifierToken } } invocationExpression) | ||||||||
| { | ||||||||
| invocation = invocationExpression.ReplaceToken(identifierToken, SyntaxFactory.Identifier("Append")); | ||||||||
|
|
||||||||
| return true; | ||||||||
| } | ||||||||
|
|
||||||||
| return false; | ||||||||
| } | ||||||||
|
|
||||||||
| private static async Task<Document> ReplaceWithIndexer(Diagnostic diagnostic, Document document, AssignmentExpressionSyntax assignment, CancellationToken cancellationToken) | ||||||||
| { | ||||||||
| var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); | ||||||||
|
|
||||||||
| var diagnosticTarget = root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true); | ||||||||
|
|
||||||||
| return document.WithSyntaxRoot(root.ReplaceNode(diagnosticTarget, assignment)); | ||||||||
| } | ||||||||
|
|
||||||||
| private static bool CanReplaceWithIndexer(Diagnostic diagnostic, SyntaxNode root, out AssignmentExpressionSyntax assignment) | ||||||||
| { | ||||||||
| assignment = null; | ||||||||
|
|
||||||||
| if (root is null) | ||||||||
| { | ||||||||
| return false; | ||||||||
| } | ||||||||
|
|
||||||||
| var diagnosticTarget = root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true); | ||||||||
|
|
||||||||
| if (diagnosticTarget is InvocationExpressionSyntax | ||||||||
| { | ||||||||
| Expression: MemberAccessExpressionSyntax memberAccessExpression, | ||||||||
| ArgumentList.Arguments: { Count: 2 } arguments | ||||||||
| }) | ||||||||
| { | ||||||||
| assignment = | ||||||||
| SyntaxFactory.AssignmentExpression( | ||||||||
| SyntaxKind.SimpleAssignmentExpression, | ||||||||
| SyntaxFactory.ElementAccessExpression( | ||||||||
| memberAccessExpression.Expression, | ||||||||
| SyntaxFactory.BracketedArgumentList( | ||||||||
| SyntaxFactory.SeparatedList(new[] { arguments[0] }))), | ||||||||
| arguments[1].Expression); | ||||||||
|
|
||||||||
| return true; | ||||||||
| } | ||||||||
|
|
||||||||
| return false; | ||||||||
| } | ||||||||
| } | ||||||||
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.
Is there an issue tracking documentation for analyzers?
I see ASP0015, ASP0016, ASP0017, and ASP0018 with the same help link are not yet documented.
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.
@david-acker You can file a docs issue in the docs repo here https://github.com/dotnet/AspNetCore.Docs/issues.
If you're so inclined, you can also submit the doc for this by updating this page.