|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | + |
| 4 | +using System.Collections.Immutable; |
| 5 | +using Microsoft.CodeAnalysis; |
| 6 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 7 | +using Microsoft.CodeAnalysis.Diagnostics; |
| 8 | +using Microsoft.CodeAnalysis.Operations; |
| 9 | + |
| 10 | +namespace Microsoft.EntityFrameworkCore; |
| 11 | + |
| 12 | +/// <summary> |
| 13 | +/// Reports calls to <c>System.Linq.AsyncEnumerable.ToAsyncEnumerable<TSource>(IEnumerable<TSource>)</c> |
| 14 | +/// whose source is an <c>IQueryable<T></c>. The conversion forces the queryable to be enumerated synchronously, |
| 15 | +/// defeating the purpose of using <c>await foreach</c>. EF Core's <c>AsAsyncEnumerable<T>()</c> is the |
| 16 | +/// intended async-friendly alternative. |
| 17 | +/// </summary> |
| 18 | +[DiagnosticAnalyzer(LanguageNames.CSharp)] |
| 19 | +public sealed class ToAsyncEnumerableOnQueryableDiagnosticAnalyzer : DiagnosticAnalyzer |
| 20 | +{ |
| 21 | + private static readonly DiagnosticDescriptor Descriptor |
| 22 | + = new( |
| 23 | + EFDiagnostics.ToAsyncEnumerableOnQueryable, |
| 24 | + title: AnalyzerStrings.ToAsyncEnumerableOnQueryableTitle, |
| 25 | + messageFormat: AnalyzerStrings.ToAsyncEnumerableOnQueryableMessageFormat, |
| 26 | + category: "Usage", |
| 27 | + defaultSeverity: DiagnosticSeverity.Warning, |
| 28 | + isEnabledByDefault: true); |
| 29 | + |
| 30 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics |
| 31 | + => [Descriptor]; |
| 32 | + |
| 33 | + public override void Initialize(AnalysisContext context) |
| 34 | + { |
| 35 | + context.EnableConcurrentExecution(); |
| 36 | + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); |
| 37 | + |
| 38 | + context.RegisterOperationAction(AnalyzeInvocation, OperationKind.Invocation); |
| 39 | + } |
| 40 | + |
| 41 | + private static void AnalyzeInvocation(OperationAnalysisContext context) |
| 42 | + { |
| 43 | + var invocation = (IInvocationOperation)context.Operation; |
| 44 | + var targetMethod = invocation.TargetMethod; |
| 45 | + |
| 46 | + if (targetMethod.Name != "ToAsyncEnumerable") |
| 47 | + { |
| 48 | + return; |
| 49 | + } |
| 50 | + |
| 51 | + // Only flag the System.Linq.AsyncEnumerable.ToAsyncEnumerable<TSource>(IEnumerable<TSource>) overload. |
| 52 | + // Other libraries may define methods with the same name (e.g. on Channel<T>, IObservable<T>) — we don't |
| 53 | + // want to false-positive on those. |
| 54 | + var containingType = targetMethod.ContainingType; |
| 55 | + if (containingType is null |
| 56 | + || containingType.Name != "AsyncEnumerable" |
| 57 | + || containingType.ContainingNamespace?.ToDisplayString() != "System.Linq") |
| 58 | + { |
| 59 | + return; |
| 60 | + } |
| 61 | + |
| 62 | + // The source is exposed as Arguments[0].Value for an extension method invocation. Peel any |
| 63 | + // chained implicit conversions to recover the user-written expression's type — a single C# |
| 64 | + // expression can produce stacked IConversionOperation nodes in the Roslyn tree. An explicit |
| 65 | + // cast to IEnumerable<T> (e.g. ((IEnumerable<T>)q).ToAsyncEnumerable()) shows up as |
| 66 | + // IsImplicit: false, so the loop stops there and the underlying IQueryable type is hidden — |
| 67 | + // a deliberate opt-out. Mirrors the WalkDownConversion(predicate) helper used across |
| 68 | + // dotnet/roslyn-analyzers. |
| 69 | + if (invocation.Arguments.Length == 0) |
| 70 | + { |
| 71 | + return; |
| 72 | + } |
| 73 | + |
| 74 | + var sourceOperation = invocation.Arguments[0].Value; |
| 75 | + while (sourceOperation is IConversionOperation { IsImplicit: true } conversion) |
| 76 | + { |
| 77 | + sourceOperation = conversion.Operand; |
| 78 | + } |
| 79 | + |
| 80 | + if (sourceOperation.Type is not { } sourceType || !ImplementsGenericIQueryable(sourceType)) |
| 81 | + { |
| 82 | + return; |
| 83 | + } |
| 84 | + |
| 85 | + context.ReportDiagnostic(Diagnostic.Create(Descriptor, GetInvocationLocation(invocation))); |
| 86 | + } |
| 87 | + |
| 88 | + private static bool ImplementsGenericIQueryable(ITypeSymbol type) |
| 89 | + { |
| 90 | + if (IsGenericIQueryable(type)) |
| 91 | + { |
| 92 | + return true; |
| 93 | + } |
| 94 | + |
| 95 | + foreach (var iface in type.AllInterfaces) |
| 96 | + { |
| 97 | + if (IsGenericIQueryable(iface)) |
| 98 | + { |
| 99 | + return true; |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + return false; |
| 104 | + |
| 105 | + static bool IsGenericIQueryable(ITypeSymbol candidate) |
| 106 | + => candidate is INamedTypeSymbol { Name: "IQueryable", TypeArguments.Length: 1 } named |
| 107 | + && named.ContainingNamespace?.ToDisplayString() == "System.Linq"; |
| 108 | + } |
| 109 | + |
| 110 | + private static Location GetInvocationLocation(IInvocationOperation invocation) |
| 111 | + { |
| 112 | + if (invocation.Syntax is not InvocationExpressionSyntax invocationExpression) |
| 113 | + { |
| 114 | + return invocation.Syntax.GetLocation(); |
| 115 | + } |
| 116 | + |
| 117 | + var targetNode = invocationExpression.Expression; |
| 118 | + |
| 119 | + while (targetNode is MemberAccessExpressionSyntax memberAccess) |
| 120 | + { |
| 121 | + targetNode = memberAccess.Name; |
| 122 | + } |
| 123 | + |
| 124 | + // Generic name case (e.g. `AsyncEnumerable.ToAsyncEnumerable<T>(q)`): point at just the identifier. |
| 125 | + if (targetNode is GenericNameSyntax genericName) |
| 126 | + { |
| 127 | + return genericName.Identifier.GetLocation(); |
| 128 | + } |
| 129 | + |
| 130 | + return targetNode.GetLocation(); |
| 131 | + } |
| 132 | +} |
0 commit comments