-
Notifications
You must be signed in to change notification settings - Fork 10.4k
Add analyzer for detecting mismatched endpoint parameter optionality #36154
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
5 commits
Select commit
Hold shift + click to select a range
3b1a92b
Add analyzer for detecting mismatched endpoint parameter optionality
captainsafia 1ab519c
Address feedback from code review
captainsafia 3927aae
Factor out CodeFixes and Analyzers to separate assemblies
captainsafia 6d083a0
Address more feedback from review
captainsafia fa7c51d
Address code checks
captainsafia 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
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
139 changes: 139 additions & 0 deletions
139
src/Framework/AspNetCoreAnalyzers/src/Analyzers/DetectMismatchedParameterOptionality.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,139 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System; | ||
using System.Linq; | ||
using System.Collections.Generic; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
using Microsoft.CodeAnalysis.Diagnostics; | ||
using Microsoft.CodeAnalysis.Operations; | ||
|
||
namespace Microsoft.AspNetCore.Analyzers.DelegateEndpoints; | ||
|
||
public partial class DelegateEndpointAnalyzer : DiagnosticAnalyzer | ||
{ | ||
internal const string DetectMismatchedParameterOptionalityRuleId = "ASP0006"; | ||
|
||
private static void DetectMismatchedParameterOptionality( | ||
in OperationAnalysisContext context, | ||
IInvocationOperation invocation, | ||
IMethodSymbol methodSymbol) | ||
{ | ||
if (invocation.Arguments.Length < 2) | ||
{ | ||
return; | ||
} | ||
|
||
var value = invocation.Arguments[1].Value; | ||
if (value.ConstantValue is not { HasValue: true } constant || | ||
constant.Value is not string routeTemplate) | ||
{ | ||
return; | ||
} | ||
|
||
var allDeclarations = methodSymbol.GetAllMethodSymbolsOfPartialParts(); | ||
foreach (var method in allDeclarations) | ||
{ | ||
var parametersInArguments = method.Parameters; | ||
var enumerator = new RouteTokenEnumerator(routeTemplate); | ||
|
||
while (enumerator.MoveNext()) | ||
{ | ||
foreach (var parameter in parametersInArguments) | ||
{ | ||
var paramName = parameter.Name; | ||
// If this is not the methpd parameter associated with the route | ||
// parameter then continue looking for it in the list | ||
if (!enumerator.CurrentName.Equals(paramName.AsSpan(), StringComparison.OrdinalIgnoreCase)) | ||
{ | ||
continue; | ||
} | ||
var argumentIsOptional = parameter.IsOptional || parameter.NullableAnnotation != NullableAnnotation.NotAnnotated; | ||
var location = parameter.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax().GetLocation(); | ||
var routeParamIsOptional = enumerator.CurrentQualifiers.IndexOf('?') > -1; | ||
|
||
if (!argumentIsOptional && routeParamIsOptional) | ||
{ | ||
context.ReportDiagnostic(Diagnostic.Create( | ||
DiagnosticDescriptors.DetectMismatchedParameterOptionality, | ||
location, | ||
paramName)); | ||
} | ||
} | ||
} | ||
} | ||
} | ||
|
||
internal ref struct RouteTokenEnumerator | ||
{ | ||
private ReadOnlySpan<char> _routeTemplate; | ||
|
||
public RouteTokenEnumerator(string routeTemplateString) | ||
{ | ||
_routeTemplate = routeTemplateString.AsSpan(); | ||
CurrentName = default; | ||
CurrentQualifiers = default; | ||
} | ||
|
||
public ReadOnlySpan<char> CurrentName { get; private set; } | ||
public ReadOnlySpan<char> CurrentQualifiers { get; private set; } | ||
|
||
public bool MoveNext() | ||
{ | ||
if (_routeTemplate.IsEmpty) | ||
{ | ||
return false; | ||
} | ||
|
||
findStartBrace: | ||
var startIndex = _routeTemplate.IndexOf('{'); | ||
if (startIndex == -1) | ||
{ | ||
return false; | ||
} | ||
|
||
if (startIndex < _routeTemplate.Length - 1 && _routeTemplate[startIndex + 1] == '{') | ||
{ | ||
// Escaped sequence | ||
_routeTemplate = _routeTemplate.Slice(startIndex + 1); | ||
goto findStartBrace; | ||
} | ||
|
||
var tokenStart = startIndex + 1; | ||
|
||
findEndBrace: | ||
var endIndex = IndexOf(_routeTemplate, tokenStart, '}'); | ||
if (endIndex == -1) | ||
{ | ||
return false; | ||
} | ||
if (endIndex < _routeTemplate.Length - 1 && _routeTemplate[endIndex + 1] == '}') | ||
{ | ||
tokenStart = endIndex + 2; | ||
goto findEndBrace; | ||
} | ||
|
||
var token = _routeTemplate.Slice(startIndex + 1, endIndex - startIndex - 1); | ||
var qualifier = token.IndexOfAny(new[] { ':', '=', '?' }); | ||
CurrentName = qualifier == -1 ? token : token.Slice(0, qualifier); | ||
CurrentQualifiers = qualifier == -1 ? null : token.Slice(qualifier); | ||
|
||
_routeTemplate = _routeTemplate.Slice(endIndex + 1); | ||
return true; | ||
} | ||
} | ||
|
||
private static int IndexOf(ReadOnlySpan<char> span, int startIndex, char c) | ||
{ | ||
for (var i = startIndex; i < span.Length; i++) | ||
{ | ||
if (span[i] == c) | ||
{ | ||
return i; | ||
} | ||
} | ||
|
||
return -1; | ||
} | ||
} |
File renamed without changes.
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
File renamed without changes.
File renamed without changes.
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
File renamed without changes.
57 changes: 57 additions & 0 deletions
57
src/Framework/AspNetCoreAnalyzers/src/CodeFixes/DetectMismatchedParameterOptionalityFixer.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,57 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System.Linq; | ||
using System.Threading; | ||
using System.Collections.Immutable; | ||
using System.Threading.Tasks; | ||
using Microsoft.AspNetCore.Analyzers.DelegateEndpoints; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.CSharp; | ||
using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
using Microsoft.CodeAnalysis.CodeFixes; | ||
using Microsoft.CodeAnalysis.CodeActions; | ||
using Microsoft.CodeAnalysis.Editing; | ||
|
||
namespace Microsoft.AspNetCore.Analyzers.DelegateEndpoints.Fixers; | ||
|
||
public class DetectMismatchedParameterOptionalityFixer : CodeFixProvider | ||
{ | ||
public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(DiagnosticDescriptors.DetectMismatchedParameterOptionality.Id); | ||
|
||
public sealed override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; | ||
|
||
public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) | ||
{ | ||
foreach (var diagnostic in context.Diagnostics) | ||
{ | ||
context.RegisterCodeFix( | ||
CodeAction.Create("Fix mismatched route parameter and argument optionality", | ||
cancellationToken => FixMismatchedParameterOptionality(diagnostic, context.Document, cancellationToken), | ||
equivalenceKey: DiagnosticDescriptors.DetectMismatchedParameterOptionality.Id), | ||
diagnostic); | ||
} | ||
|
||
return Task.CompletedTask; | ||
} | ||
|
||
private static async Task<Document> FixMismatchedParameterOptionality(Diagnostic diagnostic, Document document, CancellationToken cancellationToken) | ||
{ | ||
DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken); | ||
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); | ||
|
||
if (root == null) | ||
{ | ||
return document; | ||
} | ||
|
||
var param = root.FindNode(diagnostic.Location.SourceSpan); | ||
if (param is ParameterSyntax { Type: { } parameterType } parameterSyntax) | ||
{ | ||
var newParam = parameterSyntax.WithType(SyntaxFactory.NullableType(parameterType)); | ||
editor.ReplaceNode(parameterSyntax, newParam); | ||
} | ||
|
||
return editor.GetChangedDocument(); | ||
} | ||
} |
17 changes: 17 additions & 0 deletions
17
src/Framework/AspNetCoreAnalyzers/src/CodeFixes/Microsoft.AspNetCore.App.CodeFixes.csproj
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,17 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
<PropertyGroup> | ||
<Description>CSharp CodeFixes for ASP.NET Core.</Description> | ||
<IsShippingPackage>false</IsShippingPackage> | ||
<AddPublicApiAnalyzers>false</AddPublicApiAnalyzers> | ||
<TargetFramework>netstandard2.0</TargetFramework> | ||
<IncludeBuildOutput>false</IncludeBuildOutput> | ||
<Nullable>Enable</Nullable> | ||
<RootNamespace>Microsoft.AspNetCore.Analyzers</RootNamespace> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<Reference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" PrivateAssets="All" /> | ||
<ProjectReference Include="..\Analyzers\Microsoft.AspNetCore.App.Analyzers.csproj" /> | ||
</ItemGroup> | ||
|
||
</Project> |
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
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.