Skip to content

Add RequestDelegate analyzer #44048

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 1 commit into from
Sep 27, 2022
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
Original file line number Diff line number Diff line change
Expand Up @@ -124,4 +124,13 @@ internal static class DiagnosticDescriptors
DiagnosticSeverity.Info,
isEnabledByDefault: true,
helpLinkUri: "https://aka.ms/aspnet/analyzers");

internal static readonly DiagnosticDescriptor DoNotReturnValueFromRequestDelegate = new(
"ASP0016",
"Do not return a value from RequestDelegate",
"The method used to create a RequestDelegate returns Task<{0}>. RequestDelegate discards this value. If this isn't intended then don't return a value or change the method signature to not match RequestDelegate.",
"Usage",
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
helpLinkUri: "https://aka.ms/aspnet/analyzers");
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
// 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.CodeAnalysis;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;

namespace Microsoft.AspNetCore.Analyzers.Http;

[DiagnosticAnalyzer(LanguageNames.CSharp)]
public partial class RequestDelegateReturnTypeAnalyzer : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(DiagnosticDescriptors.DoNotReturnValueFromRequestDelegate);

public override void Initialize(AnalysisContext context)
{
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.EnableConcurrentExecution();
context.RegisterCompilationStartAction(context =>
{
var compilation = context.Compilation;

if (!WellKnownTypes.TryCreate(compilation, out var wellKnownTypes))
{
return;
}
context.RegisterOperationAction(context =>
{
var methodReference = (IMethodReferenceOperation)context.Operation;
if (methodReference.Parent is { } parent &&
parent.Kind == OperationKind.DelegateCreation &&
SymbolEqualityComparer.Default.Equals(parent.Type, wellKnownTypes.RequestDelegate))
{
// Inspect return type of method signature for Task<T>.
var returnType = methodReference.Method.ReturnType;

if (SymbolEqualityComparer.Default.Equals(returnType.OriginalDefinition, wellKnownTypes.TaskOfT))
{
AddDiagnosticWarning(context, methodReference.Syntax.GetLocation(), returnType);
}
}
}, OperationKind.MethodReference);
context.RegisterOperationAction(context =>
{
var anonymousFunction = (IAnonymousFunctionOperation)context.Operation;
if (anonymousFunction.Parent is { } parent &&
parent.Kind == OperationKind.DelegateCreation &&
SymbolEqualityComparer.Default.Equals(parent.Type, wellKnownTypes.RequestDelegate))
{
// Inspect contents of anonymous function and search for return statements.
// Return statement of Task<T> means a value was returned.
foreach (var item in anonymousFunction.Body.Descendants())
{
if (item is IReturnOperation returnOperation &&
returnOperation.ReturnedValue is { } returnedValue)
{
var resolvedOperation = WalkDownConversion(returnedValue);
var returnType = resolvedOperation.Type;

if (SymbolEqualityComparer.Default.Equals(returnType.OriginalDefinition, wellKnownTypes.TaskOfT))
{
AddDiagnosticWarning(context, anonymousFunction.Syntax.GetLocation(), returnType);
return;
}
}
}
}
}, OperationKind.AnonymousFunction);
});
}

private static void AddDiagnosticWarning(OperationAnalysisContext context, Location location, ITypeSymbol returnType)
{
context.ReportDiagnostic(Diagnostic.Create(
DiagnosticDescriptors.DoNotReturnValueFromRequestDelegate,
location,
((INamedTypeSymbol)returnType).TypeArguments[0].ToString()));
}

private static IOperation WalkDownConversion(IOperation operation)
{
while (operation is IConversionOperation conversionOperation)
{
operation = conversionOperation.Operand;
}

return operation;
}

internal sealed class WellKnownTypes
{
public static bool TryCreate(Compilation compilation, [NotNullWhen(returnValue: true)] out WellKnownTypes? wellKnownTypes)
{
wellKnownTypes = default;

const string RequestDelegate = "Microsoft.AspNetCore.Http.RequestDelegate";
if (compilation.GetTypeByMetadataName(RequestDelegate) is not { } requestDelegate)
{
return false;
}

const string TaskOfT = "System.Threading.Tasks.Task`1";
if (compilation.GetTypeByMetadataName(TaskOfT) is not { } taskOfT)
{
return false;
}

wellKnownTypes = new()
{
RequestDelegate = requestDelegate,
TaskOfT = taskOfT
};

return true;
}

public INamedTypeSymbol RequestDelegate { get; private init; }
public INamedTypeSymbol TaskOfT { get; private init; }
}
}
Loading