Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

This file was deleted.

46 changes: 46 additions & 0 deletions src/Framework/Analyzer/src/DiagnosticDescriptors.cs
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");
}
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 src/Framework/Analyzer/src/RenderTreeBuilder/WellKnownTypes.cs
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; }
}
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));
}
}