|
| 1 | +using Microsoft.CodeAnalysis; |
| 2 | +using Microsoft.CodeAnalysis.CSharp; |
| 3 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 4 | +using Microsoft.CodeAnalysis.Diagnostics; |
| 5 | +using System.Collections.Immutable; |
| 6 | + |
| 7 | +namespace BenchmarkDotNet.Analyzers.Attributes; |
| 8 | + |
| 9 | +/// <summary> |
| 10 | +/// Static counterpart to <c>SetupCleanupValidator.ValidateReturnType</c>: a method annotated with |
| 11 | +/// <c>[GlobalSetup]</c>, <c>[GlobalCleanup]</c>, <c>[IterationSetup]</c>, or <c>[IterationCleanup]</c> |
| 12 | +/// must not return an async enumerable. BenchmarkDotNet awaits awaitable returns from those methods but |
| 13 | +/// does not enumerate async enumerables, so the iterator body would silently never run. |
| 14 | +/// </summary> |
| 15 | +[DiagnosticAnalyzer(LanguageNames.CSharp)] |
| 16 | +public class SetupCleanupAsyncEnumerableAnalyzer : DiagnosticAnalyzer |
| 17 | +{ |
| 18 | + internal static readonly DiagnosticDescriptor MustNotReturnAsyncEnumerableRule = new( |
| 19 | + DiagnosticIds.Attributes_SetupCleanup_MustNotReturnAsyncEnumerable, |
| 20 | + AnalyzerHelper.GetResourceString(nameof(BenchmarkDotNetAnalyzerResources.Attributes_SetupCleanup_MustNotReturnAsyncEnumerable_Title)), |
| 21 | + AnalyzerHelper.GetResourceString(nameof(BenchmarkDotNetAnalyzerResources.Attributes_SetupCleanup_MustNotReturnAsyncEnumerable_MessageFormat)), |
| 22 | + "Usage", |
| 23 | + DiagnosticSeverity.Error, |
| 24 | + isEnabledByDefault: true, |
| 25 | + description: AnalyzerHelper.GetResourceString(nameof(BenchmarkDotNetAnalyzerResources.Attributes_SetupCleanup_MustNotReturnAsyncEnumerable_Description))); |
| 26 | + |
| 27 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => new DiagnosticDescriptor[] |
| 28 | + { |
| 29 | + MustNotReturnAsyncEnumerableRule, |
| 30 | + }.ToImmutableArray(); |
| 31 | + |
| 32 | + private static readonly string[] SetupCleanupAttributeMetadataNames = |
| 33 | + [ |
| 34 | + "BenchmarkDotNet.Attributes.GlobalSetupAttribute", |
| 35 | + "BenchmarkDotNet.Attributes.GlobalCleanupAttribute", |
| 36 | + "BenchmarkDotNet.Attributes.IterationSetupAttribute", |
| 37 | + "BenchmarkDotNet.Attributes.IterationCleanupAttribute", |
| 38 | + ]; |
| 39 | + |
| 40 | + public override void Initialize(AnalysisContext analysisContext) |
| 41 | + { |
| 42 | + analysisContext.EnableConcurrentExecution(); |
| 43 | + analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); |
| 44 | + |
| 45 | + analysisContext.RegisterCompilationStartAction(ctx => |
| 46 | + { |
| 47 | + // Only run if BenchmarkDotNet.Annotations is referenced. |
| 48 | + if (AnalyzerHelper.GetBenchmarkAttributeTypeSymbol(ctx.Compilation) == null) |
| 49 | + { |
| 50 | + return; |
| 51 | + } |
| 52 | + |
| 53 | + var attributeSymbols = ImmutableArray.CreateBuilder<INamedTypeSymbol>(SetupCleanupAttributeMetadataNames.Length); |
| 54 | + foreach (var metadataName in SetupCleanupAttributeMetadataNames) |
| 55 | + { |
| 56 | + var symbol = ctx.Compilation.GetTypeByMetadataName(metadataName); |
| 57 | + if (symbol != null) |
| 58 | + { |
| 59 | + attributeSymbols.Add(symbol); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + if (attributeSymbols.Count == 0) |
| 64 | + { |
| 65 | + return; |
| 66 | + } |
| 67 | + |
| 68 | + var asyncEnumerableInterfaceSymbol = ctx.Compilation.GetTypeByMetadataName("System.Collections.Generic.IAsyncEnumerable`1"); |
| 69 | + var captured = (attributeSymbols.ToImmutable(), asyncEnumerableInterfaceSymbol); |
| 70 | + ctx.RegisterSyntaxNodeAction(c => AnalyzeMethod(c, captured), SyntaxKind.MethodDeclaration); |
| 71 | + }); |
| 72 | + } |
| 73 | + |
| 74 | + private static void AnalyzeMethod( |
| 75 | + SyntaxNodeAnalysisContext context, |
| 76 | + (ImmutableArray<INamedTypeSymbol> AttributeSymbols, INamedTypeSymbol? AsyncEnumerableInterfaceSymbol) captured) |
| 77 | + { |
| 78 | + if (context.Node is not MethodDeclarationSyntax methodDeclarationSyntax) |
| 79 | + { |
| 80 | + return; |
| 81 | + } |
| 82 | + |
| 83 | + if (context.SemanticModel.GetDeclaredSymbol(methodDeclarationSyntax) is not IMethodSymbol methodSymbol) |
| 84 | + { |
| 85 | + return; |
| 86 | + } |
| 87 | + |
| 88 | + // Find which (if any) setup/cleanup attribute is applied. |
| 89 | + INamedTypeSymbol? matchedAttribute = null; |
| 90 | + foreach (var attributeData in methodSymbol.GetAttributes()) |
| 91 | + { |
| 92 | + foreach (var candidate in captured.AttributeSymbols) |
| 93 | + { |
| 94 | + if (SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, candidate)) |
| 95 | + { |
| 96 | + matchedAttribute = candidate; |
| 97 | + break; |
| 98 | + } |
| 99 | + } |
| 100 | + if (matchedAttribute != null) break; |
| 101 | + } |
| 102 | + |
| 103 | + if (matchedAttribute == null) |
| 104 | + { |
| 105 | + return; |
| 106 | + } |
| 107 | + |
| 108 | + // Mirrors ReflectionExtensions.IsAsyncEnumerable: exact IAsyncEnumerable<T> short-circuit, then |
| 109 | + // public-instance GetAsyncEnumerator pattern, then interface fallback. The runtime validator |
| 110 | + // also explicitly skips awaitable types — if the return type happens to be both awaitable AND |
| 111 | + // an async enumerable, BenchmarkDotNet awaits it instead of rejecting it (BDN1701 covers that |
| 112 | + // ambiguity separately). |
| 113 | + var returnType = methodSymbol.ReturnType; |
| 114 | + if (!AsyncTypeShapes.IsAsyncEnumerable(returnType, captured.AsyncEnumerableInterfaceSymbol)) |
| 115 | + { |
| 116 | + return; |
| 117 | + } |
| 118 | + |
| 119 | + if (AsyncTypeShapes.IsAwaitable(returnType)) |
| 120 | + { |
| 121 | + return; |
| 122 | + } |
| 123 | + |
| 124 | + var attributeShortName = matchedAttribute.Name.EndsWith("Attribute") |
| 125 | + ? matchedAttribute.Name.Substring(0, matchedAttribute.Name.Length - "Attribute".Length) |
| 126 | + : matchedAttribute.Name; |
| 127 | + |
| 128 | + context.ReportDiagnostic(Diagnostic.Create( |
| 129 | + MustNotReturnAsyncEnumerableRule, |
| 130 | + methodDeclarationSyntax.ReturnType.GetLocation(), |
| 131 | + attributeShortName, |
| 132 | + methodSymbol.Name)); |
| 133 | + } |
| 134 | + |
| 135 | +} |
0 commit comments