-
Notifications
You must be signed in to change notification settings - Fork 10.5k
Add an analyzer that warns about non-literal sequence numbers #35805
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
6 commits
Select commit
Hold shift + click to select a range
cd3228b
Added analyzer that warns about non-literal sequence numbers
MackinnonBuck 0d380f5
Update DisallowNonLiteralSequenceNumbersTest.cs
MackinnonBuck 3e419a2
PR feedback
MackinnonBuck dbc3634
Merge branch 'main' into t-mbuck/sequence-number-analyzer
MackinnonBuck b02a0c4
Update DiagnosticDescriptors.cs
MackinnonBuck 03f7408
PR feedback
MackinnonBuck 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
38 changes: 0 additions & 38 deletions
38
src/Framework/Analyzer/src/DelegateEndpoints/DiagnosticDescriptors.cs
This file was deleted.
Oops, something went wrong.
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,46 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using Microsoft.CodeAnalysis; | ||
|
|
||
| namespace Microsoft.AspNetCore.Analyzers; | ||
|
|
||
| [System.Diagnostics.CodeAnalysis.SuppressMessage("MicrosoftCodeAnalysisReleaseTracking", "RS2008:Enable analyzer release tracking")] | ||
| internal static class DiagnosticDescriptors | ||
| { | ||
| internal static readonly DiagnosticDescriptor DoNotUseModelBindingAttributesOnDelegateEndpointParameters = new( | ||
| "ASP0003", | ||
| "Do not use model binding attributes with Map handlers", | ||
| "{0} should not be specified for a {1} Delegate parameter", | ||
| "Usage", | ||
| DiagnosticSeverity.Warning, | ||
| isEnabledByDefault: true, | ||
| helpLinkUri: "https://aka.ms/aspnet/analyzers"); | ||
|
|
||
| internal static readonly DiagnosticDescriptor DoNotReturnActionResultsFromMapActions = new( | ||
| "ASP0004", | ||
| "Do not use action results with Map actions", | ||
| "IActionResult instances should not be returned from a {0} Delegate parameter. Consider returning an equivalent result from Microsoft.AspNetCore.Http.Results.", | ||
| "Usage", | ||
| DiagnosticSeverity.Warning, | ||
| isEnabledByDefault: true, | ||
| helpLinkUri: "https://aka.ms/aspnet/analyzers"); | ||
|
|
||
| internal static readonly DiagnosticDescriptor DetectMisplacedLambdaAttribute = new( | ||
| "ASP0005", | ||
| "Do not place attribute on route handlers", | ||
| "'{0}' should be placed on the endpoint delegate to be effective", | ||
| "Usage", | ||
| DiagnosticSeverity.Warning, | ||
| isEnabledByDefault: true, | ||
| helpLinkUri: "https://aka.ms/aspnet/analyzers"); | ||
|
|
||
| internal static readonly DiagnosticDescriptor DoNotUseNonLiteralSequenceNumbers = new( | ||
| "ASP0006", | ||
| "Do not use non-literal sequence numbers", | ||
| "'{0}' should not be used as a sequence number. Instead, use an integer literal representing source code order.", | ||
| "Usage", | ||
| DiagnosticSeverity.Warning, | ||
| isEnabledByDefault: true, | ||
| helpLinkUri: "https://aka.ms/aspnet/analyzers"); | ||
| } |
60 changes: 60 additions & 0 deletions
60
src/Framework/Analyzer/src/RenderTreeBuilder/RenderTreeBuilderAnalyzer.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,60 @@ | ||
| // 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.Diagnostics; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CSharp; | ||
| using Microsoft.CodeAnalysis.Diagnostics; | ||
| using Microsoft.CodeAnalysis.Operations; | ||
|
|
||
| namespace Microsoft.AspNetCore.Analyzers.RenderTreeBuilder; | ||
|
|
||
| [DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
| public partial class RenderTreeBuilderAnalyzer : DiagnosticAnalyzer | ||
| { | ||
| public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(new[] | ||
| { | ||
| DiagnosticDescriptors.DoNotUseNonLiteralSequenceNumbers, | ||
| }); | ||
|
|
||
| public override void Initialize(AnalysisContext context) | ||
| { | ||
| context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
| context.EnableConcurrentExecution(); | ||
| context.RegisterCompilationStartAction(compilationStartAnalysisContext => | ||
| { | ||
| var compilation = compilationStartAnalysisContext.Compilation; | ||
|
|
||
| if (!WellKnownTypes.TryCreate(compilation, out var wellKnownTypes)) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| compilationStartAnalysisContext.RegisterOperationAction(operationAnalysisContext => | ||
| { | ||
| var invocation = (IInvocationOperation)operationAnalysisContext.Operation; | ||
|
|
||
| if (!IsRenderTreeBuilderMethodWithSequenceParameter(wellKnownTypes, invocation.TargetMethod)) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| var sequenceArgument = invocation.Arguments[0]; | ||
|
|
||
| if (!sequenceArgument.Value.Syntax.IsKind(SyntaxKind.NumericLiteralExpression)) | ||
| { | ||
| operationAnalysisContext.ReportDiagnostic(Diagnostic.Create( | ||
| DiagnosticDescriptors.DoNotUseNonLiteralSequenceNumbers, | ||
| sequenceArgument.Syntax.GetLocation(), | ||
| sequenceArgument.Syntax.ToString())); | ||
| } | ||
| }, OperationKind.Invocation); | ||
| }); | ||
| } | ||
|
|
||
| private static bool IsRenderTreeBuilderMethodWithSequenceParameter(WellKnownTypes wellKnownTypes, IMethodSymbol targetMethod) | ||
| => SymbolEqualityComparer.Default.Equals(wellKnownTypes.RenderTreeBuilder, targetMethod.ContainingType) | ||
| && targetMethod.Parameters.Length != 0 | ||
| && targetMethod.Parameters[0].Name == "sequence"; | ||
| } |
30 changes: 30 additions & 0 deletions
30
src/Framework/Analyzer/src/RenderTreeBuilder/WellKnownTypes.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,30 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.Diagnostics.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis; | ||
|
|
||
| namespace Microsoft.AspNetCore.Analyzers.RenderTreeBuilder; | ||
|
|
||
| internal sealed class WellKnownTypes | ||
| { | ||
| public static bool TryCreate(Compilation compilation, [NotNullWhen(returnValue: true)] out WellKnownTypes? wellKnownTypes) | ||
| { | ||
| wellKnownTypes = default; | ||
|
|
||
| const string RenderTreeBuilder = "Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder"; | ||
| if (compilation.GetTypeByMetadataName(RenderTreeBuilder) is not { } renderTreeBuilder) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| wellKnownTypes = new() | ||
| { | ||
| RenderTreeBuilder = renderTreeBuilder | ||
| }; | ||
|
|
||
| return true; | ||
| } | ||
|
|
||
| public INamedTypeSymbol RenderTreeBuilder { get; private init; } | ||
| } |
92 changes: 92 additions & 0 deletions
92
src/Framework/Analyzer/test/Components/DisallowNonLiteralSequenceNumbersTest.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.Globalization; | ||
| using Microsoft.AspNetCore.Analyzer.Testing; | ||
|
|
||
| namespace Microsoft.AspNetCore.Analyzers.RenderTreeBuilder; | ||
|
|
||
| public class DisallowNonLiteralSequenceNumbersTest | ||
| { | ||
| private TestDiagnosticAnalyzerRunner Runner { get; } = new(new RenderTreeBuilderAnalyzer()); | ||
|
|
||
| [Fact] | ||
| public async Task RenderTreeBuilderInvocationWithNumericLiteralArgument_Works() | ||
| { | ||
| // Arrange | ||
| var source = @" | ||
| using Microsoft.AspNetCore.Components.Rendering; | ||
| var renderTreeBuilder = new RenderTreeBuilder(); | ||
| renderTreeBuilder.OpenElement(0, ""div""); | ||
| renderTreeBuilder.CloseElement(); | ||
| "; | ||
| // Act | ||
| var diagnostics = await Runner.GetDiagnosticsAsync(source); | ||
|
|
||
| // Assert | ||
| Assert.Empty(diagnostics); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task RenderTreeBuilderInvocationWithNonConstantArgument_ProducesDiagnostics() | ||
| { | ||
| // Arrange | ||
| var source = TestSource.Read(@" | ||
| using Microsoft.AspNetCore.Components.Rendering; | ||
| var renderTreeBuilder = new RenderTreeBuilder(); | ||
| var i = 0; | ||
| renderTreeBuilder.OpenRegion(/*MM*/i); | ||
| renderTreeBuilder.CloseRegion(); | ||
| "); | ||
| // Act | ||
| var diagnostics = await Runner.GetDiagnosticsAsync(source.Source); | ||
|
|
||
| // Assert | ||
| var diagnostic = Assert.Single(diagnostics); | ||
| Assert.Same(DiagnosticDescriptors.DoNotUseNonLiteralSequenceNumbers, diagnostic.Descriptor); | ||
| AnalyzerAssert.DiagnosticLocation(source.DefaultMarkerLocation, diagnostic.Location); | ||
| Assert.StartsWith("'i' should not be used as a sequence number.", diagnostic.GetMessage(CultureInfo.InvariantCulture)); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task RenderTreeBuilderInvocationWithConstantArgument_ProducesDiagnostics() | ||
| { | ||
| // Arrange | ||
| var source = TestSource.Read(@" | ||
| using Microsoft.AspNetCore.Components.Rendering; | ||
| var renderTreeBuilder = new RenderTreeBuilder(); | ||
| const int i = 0; | ||
| renderTreeBuilder.OpenRegion(/*MM*/i); | ||
| renderTreeBuilder.CloseRegion(); | ||
| "); | ||
| // Act | ||
| var diagnostics = await Runner.GetDiagnosticsAsync(source.Source); | ||
|
|
||
| // Assert | ||
| var diagnostic = Assert.Single(diagnostics); | ||
| Assert.Same(DiagnosticDescriptors.DoNotUseNonLiteralSequenceNumbers, diagnostic.Descriptor); | ||
| AnalyzerAssert.DiagnosticLocation(source.DefaultMarkerLocation, diagnostic.Location); | ||
| Assert.StartsWith("'i' should not be used as a sequence number.", diagnostic.GetMessage(CultureInfo.InvariantCulture)); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task RenderTreeBuilderInvocationWithInvocationArgument_ProducesDiagnostics() | ||
| { | ||
| // Arrange | ||
| var source = TestSource.Read(@" | ||
| using Microsoft.AspNetCore.Components.Rendering; | ||
| var renderTreeBuilder = new RenderTreeBuilder(); | ||
| renderTreeBuilder.OpenElement(/*MM*/ComputeSequenceNumber(0), ""div""); | ||
| renderTreeBuilder.CloseElement(); | ||
| static int ComputeSequenceNumber(int i) => i + 1; | ||
| "); | ||
| // Act | ||
| var diagnostics = await Runner.GetDiagnosticsAsync(source.Source); | ||
|
|
||
| // Assert | ||
| var diagnostic = Assert.Single(diagnostics); | ||
| Assert.Same(DiagnosticDescriptors.DoNotUseNonLiteralSequenceNumbers, diagnostic.Descriptor); | ||
| AnalyzerAssert.DiagnosticLocation(source.DefaultMarkerLocation, diagnostic.Location); | ||
| Assert.StartsWith("'ComputeSequenceNumber(0)' should not be used as a sequence number.", diagnostic.GetMessage(CultureInfo.InvariantCulture)); | ||
| } | ||
| } | ||
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.