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
3 changes: 2 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,11 @@ CI targets both .NET 8.0 and .NET 10.0 SDKs.
- `src/ExpressiveSharp.Generator/ExpressiveGenerator.cs` — main generator entry point
- `src/ExpressiveSharp.Generator/Emitter/ExpressionTreeEmitter.cs` — maps IOperation nodes to `Expression.*` factory calls (the heart of code generation). Uses `varPrefix` to ensure unique local variable names across multi-lambda emitters
- `src/ExpressiveSharp.Generator/Interpretation/ExpressiveInterpreter.cs` — validates and prepares `[Expressive]` members
- `src/ExpressiveSharp.Generator/PolyfillInterceptorGenerator.cs` — interceptor generation. Dedicated emitters for complex methods (Join, GroupJoin, GroupBy multi-lambda), enhanced generic fallback (`EmitGenericSingleLambda`) for single-lambda methods with non-lambda arg forwarding, `[PolyfillTarget]` support for custom target types
- `src/ExpressiveSharp.Generator/PolyfillInterceptorGenerator.cs` — interceptor generation. Dedicated emitters for complex methods (Join, GroupJoin, GroupBy multi-lambda), enhanced generic fallback (`EmitGenericSingleLambda`) for single-lambda methods with non-lambda arg forwarding, `[PolyfillTarget]` support for custom target types. Emits each stub's **declared** receiver and return types, so stubs on derived markers such as `IOrderedExpressiveQueryable<T>` work
- `src/ExpressiveSharp/Services/ExpressiveResolver.cs` — runtime expression registry lookup
- `src/ExpressiveSharp/PolyfillTargetAttribute.cs` — specifies a non-`Queryable` target type for interceptor forwarding (e.g., `EntityFrameworkQueryableExtensions`)
- `src/ExpressiveSharp/Extensions/ExpressiveQueryableLinqExtensions.cs` — delegate-based LINQ stubs on `IExpressiveQueryable<T>` (~85 intercepted + ~15 passthrough methods)
- `src/ExpressiveSharp/IOrderedExpressiveQueryable.cs` — zero-member marker bridging `IOrderedQueryable<T>` and `IExpressiveQueryable<T>`, returned by `OrderBy` and required by `ThenBy` (matching `System.Linq.Queryable`). Deliberately **no** ordered × includable cross-product: `Include`/`AsNoTracking` must precede the ordering. `AsExpressive` has an `IOrderedQueryable<T>` overload so ordering interceptors re-wrap with no generator-side factory selection
- `src/ExpressiveSharp.EntityFrameworkCore/Extensions/ExpressiveQueryableEfCoreExtensions.cs` — EF Core-specific stubs: chain-continuity (AsNoTracking, TagWith, etc.), Include/ThenInclude, and async lambda methods (AnyAsync, SumAsync, etc.)
- `src/ExpressiveSharp.EntityFrameworkCore/IIncludableExpressiveQueryable.cs` — hybrid interface bridging `IIncludableQueryable` and `IExpressiveQueryable` for Include/ThenInclude chain continuity
- `src/ExpressiveSharp.EntityFrameworkCore.RelationalExtensions.Abstractions/WindowFunction.cs` — public marker methods for all SQL window functions (ranking, aggregate, navigation). All throw at runtime; translated to SQL by the method call translator
Expand Down
6 changes: 6 additions & 0 deletions docs/guide/integrations/custom-providers.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,12 @@ The query runs through your provider's own translation pipeline after Expressive
1. Expanded `[Expressive]` member accesses into their generated expression trees
2. Normalized the tree via the built-in transformers (null-conditional flattening, block lifting, tuple comparison flattening)

If your provider returns its own `IExpressiveQueryable<T>` wrapper from
`IQueryProvider.CreateQuery<TElement>`, that wrapper should also implement
`IOrderedExpressiveQueryable<T>` — as `ExpressiveMongoQueryable<T>` does. Otherwise `AsExpressive`
re-wraps it after `OrderBy`/`ThenBy` and any extra interfaces it carries (an async cursor source,
a provider-specific query interface) stop being observable.

## LINQ to Objects

The same extension works on `IEnumerable<T>.AsQueryable()`:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ private static void AnalyzeInvocation(SyntaxNodeAnalysisContext context, INamedT
// — that scenario is owned by EXP0026 (a higher-severity Warning with its own codefix
// for adding the missing `using`). Reporting both would just be duplicate noise.
if (expressiveQueryableOpenGeneric is not null
&& FindExpressiveSiblingNamespace(context.SemanticModel.Compilation, calledName, expressiveQueryableOpenGeneric) is not null)
&& FindExpressiveSiblingNamespace(context.SemanticModel.Compilation, calledName) is not null)
{
return;
}
Expand All @@ -111,38 +111,39 @@ private static void AnalyzeInvocation(SyntaxNodeAnalysisContext context, INamedT
/// string when found — used to suggest a `using` directive that would bring the
/// sibling overload into scope.
/// </summary>
private static string? FindExpressiveSiblingNamespace(Compilation compilation, string methodName, INamedTypeSymbol expressiveQueryableOpenGeneric)
private static string? FindExpressiveSiblingNamespace(Compilation compilation, string methodName)
{
foreach (var reference in compilation.References)
{
if (compilation.GetAssemblyOrModuleSymbol(reference) is not IAssemblySymbol assembly)
continue;
var match = SearchNamespace(assembly.GlobalNamespace, methodName, expressiveQueryableOpenGeneric);
var match = SearchNamespace(assembly.GlobalNamespace, methodName);
if (match is not null) return match;
}
return SearchNamespace(compilation.Assembly.GlobalNamespace, methodName, expressiveQueryableOpenGeneric);
return SearchNamespace(compilation.Assembly.GlobalNamespace, methodName);
}

private static string? SearchNamespace(INamespaceSymbol ns, string methodName, INamedTypeSymbol expressiveQueryableOpenGeneric)
private static string? SearchNamespace(INamespaceSymbol ns, string methodName)
{
foreach (var type in ns.GetTypeMembers())
{
if (!type.IsStatic) continue;
foreach (var member in type.GetMembers(methodName))
{
// Is-or-implements, not exact construction: stubs can be declared on a derived
// marker (IOrderedExpressiveQueryable<T> for ThenBy) and must still be found.
if (member is IMethodSymbol method
&& method.IsExtensionMethod
&& method.Parameters.Length > 0
&& method.Parameters[0].Type is INamedTypeSymbol firstParamType
&& SymbolEqualityComparer.Default.Equals(firstParamType.ConstructedFrom, expressiveQueryableOpenGeneric))
&& ExpressiveSymbolHelpers.IsOrImplementsExpressiveQueryable(method.Parameters[0].Type))
{
return type.ContainingNamespace?.ToDisplayString();
}
}
}
foreach (var child in ns.GetNamespaceMembers())
{
var found = SearchNamespace(child, methodName, expressiveQueryableOpenGeneric);
var found = SearchNamespace(child, methodName);
if (found is not null) return found;
}
return null;
Expand Down
54 changes: 44 additions & 10 deletions src/ExpressiveSharp.Generator/PolyfillInterceptorGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ public class PolyfillInterceptorGenerator : IIncrementalGenerator
private const string IExpressiveQueryableOpenTypeName =
"ExpressiveSharp.IExpressiveQueryable<T>";

private const string IOrderedExpressiveQueryableOpenTypeName =
"ExpressiveSharp.IOrderedExpressiveQueryable<T>";

private const string PolyfillTypeName = "ExpressiveSharp.ExpressionPolyfill";
private const string PolyfillMethodName = "Create";

Expand Down Expand Up @@ -601,15 +604,25 @@ private static string MethodId(string op, string fileTag, int line, int col)
}

var isRewritableReturn = method.ReturnType is INamedTypeSymbol rqType
&& rqType.ConstructedFrom.ToDisplayString() == IExpressiveQueryableOpenTypeName;
&& (rqType.ConstructedFrom.ToDisplayString() == IExpressiveQueryableOpenTypeName
|| rqType.ConstructedFrom.ToDisplayString() == IOrderedExpressiveQueryableOpenTypeName);

ITypeSymbol? returnElemType = null;
var returnOpenFqn = "global::ExpressiveSharp.IExpressiveQueryable";
if (isRewritableReturn)
{
returnElemType = ((INamedTypeSymbol)method.ReturnType).TypeArguments[0];
returnOpenFqn = OpenTypeFqn((INamedTypeSymbol)method.ReturnType);
hasAnyAnon = hasAnyAnon || IsAnonymousType(returnElemType);
}

// Interceptor signatures must match the stub's declared types. `method` is reduced, so
// its Parameters[0] is the first non-receiver parameter; the receiver is on ReducedFrom.
var declaredReceiver = (method.ReducedFrom ?? method).Parameters[0].Type;
var receiverOpenFqn = declaredReceiver is INamedTypeSymbol namedReceiver
? OpenTypeFqn(namedReceiver)
: "global::ExpressiveSharp.IExpressiveQueryable";

var scalarReturnFqn = method.ReturnType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);

// ThenBy/ThenByDescending require IOrderedQueryable<T>.
Expand All @@ -622,6 +635,8 @@ private static string MethodId(string op, string fileTag, int line, int col)
string castFqn;
string typeParams;
string returnRef;
string receiverRef;
string returnTypeRef;
string interceptorParamList;
string queryableArgList;

Expand Down Expand Up @@ -671,14 +686,18 @@ private static string MethodId(string op, string fileTag, int line, int col)
? $"global::System.Linq.IOrderedQueryable<{elemRef}>"
: $"global::System.Linq.IQueryable<{elemRef}>";

receiverRef = $"{receiverOpenFqn}<{elemRef}>";

if (isRewritableReturn)
{
var origReturnElem = ((INamedTypeSymbol)origMethod.ReturnType).TypeArguments[0];
returnRef = ResolveTypeFqn(origReturnElem, typeAliases);
returnTypeRef = $"{returnOpenFqn}<{returnRef}>";
}
else
{
returnRef = scalarReturnFqn;
returnTypeRef = returnRef;
}

var interceptorParams = new List<string>();
Expand Down Expand Up @@ -722,10 +741,14 @@ private static string MethodId(string op, string fileTag, int line, int col)
? $"global::System.Linq.IOrderedQueryable<{elemFqn}>"
: $"global::System.Linq.IQueryable<{elemFqn}>";

receiverRef = $"{receiverOpenFqn}<{elemFqn}>";

returnRef = isRewritableReturn
? returnElemType!.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)
: scalarReturnFqn;

returnTypeRef = isRewritableReturn ? $"{returnOpenFqn}<{returnRef}>" : returnRef;

var interceptorParams = new List<string>();
var queryableArgs = new List<string>();
int funcOrdinal = 0;
Expand Down Expand Up @@ -775,8 +798,8 @@ private static string MethodId(string op, string fileTag, int line, int col)
{
return $$"""
{{interceptAttr}}
internal static global::ExpressiveSharp.IExpressiveQueryable<{{returnRef}}> {{MethodId(methodName, fileTag, line, col)}}(
this global::ExpressiveSharp.IExpressiveQueryable<{{elemFqn}}> source,
internal static {{returnTypeRef}} {{MethodId(methodName, fileTag, line, col)}}(
this {{receiverRef}} source,
{{interceptorParamList}})
{
{{allBodies}} return global::ExpressiveSharp.ExpressiveQueryableExtensions.AsExpressive(
Expand All @@ -790,8 +813,8 @@ private static string MethodId(string op, string fileTag, int line, int col)

return $$"""
{{interceptAttr}}
internal static {{returnRef}} {{MethodId(methodName, fileTag, line, col)}}(
this global::ExpressiveSharp.IExpressiveQueryable<{{elemFqn}}> source,
internal static {{returnTypeRef}} {{MethodId(methodName, fileTag, line, col)}}(
this {{receiverRef}} source,
{{interceptorParamList}})
{
{{allBodies}} return {{targetTypeFqn}}.{{methodName}}(
Expand All @@ -806,11 +829,11 @@ private static string MethodId(string op, string fileTag, int line, int col)
{
return $$"""
{{interceptAttr}}
internal static global::ExpressiveSharp.IExpressiveQueryable<{{returnRef}}> {{MethodId(methodName, fileTag, line, col)}}{{typeParams}}(
this global::ExpressiveSharp.IExpressiveQueryable<{{elemRef}}> source,
internal static {{returnTypeRef}} {{MethodId(methodName, fileTag, line, col)}}{{typeParams}}(
this {{receiverRef}} source,
{{interceptorParamList}})
{
{{allBodies}} return (global::ExpressiveSharp.IExpressiveQueryable<{{returnRef}}>)(object)
{{allBodies}} return ({{returnTypeRef}})(object)
global::ExpressiveSharp.ExpressiveQueryableExtensions.AsExpressive(
{{targetTypeFqn}}.{{methodName}}(
({{castFqn}})(object)source,
Expand All @@ -822,8 +845,8 @@ private static string MethodId(string op, string fileTag, int line, int col)

return $$"""
{{interceptAttr}}
internal static {{returnRef}} {{MethodId(methodName, fileTag, line, col)}}{{typeParams}}(
this global::ExpressiveSharp.IExpressiveQueryable<{{elemRef}}> source,
internal static {{returnTypeRef}} {{MethodId(methodName, fileTag, line, col)}}{{typeParams}}(
this {{receiverRef}} source,
{{interceptorParamList}})
{
{{allBodies}} return {{targetTypeFqn}}.{{methodName}}(
Expand All @@ -834,6 +857,17 @@ private static string MethodId(string op, string fileTag, int line, int col)
""";
}

/// <summary>
/// Fully-qualified name with the type-argument list stripped, so a caller can re-append its
/// own (possibly aliased) argument.
/// </summary>
private static string OpenTypeFqn(INamedTypeSymbol type)
{
var fqn = type.ConstructedFrom.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
var idx = fqn.LastIndexOf('<');
return idx >= 0 ? fqn.Substring(0, idx) : fqn;
}

private static bool IsExpressiveQueryable(INamedTypeSymbol type)
{
if (type.ConstructedFrom.ToDisplayString() == IExpressiveQueryableOpenTypeName)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@
namespace ExpressiveSharp.MongoDB.Infrastructure;

/// <remarks>
/// Implements <see cref="IOrderedQueryable{T}"/> so <c>ThenBy</c>/<c>ThenByDescending</c>
/// interceptors can cast the wrapper, and <see cref="IAsyncCursorSource{TDocument}"/> so
/// <c>MongoQueryable.ToListAsync</c> / <c>ToCursorAsync</c> (which cast the source directly,
/// not the provider) accept the wrapper.
/// Implements <see cref="IOrderedExpressiveQueryable{T}"/> so <c>AsExpressive</c> returns this
/// instance unchanged after an ordering operator; re-wrapping would drop
/// <see cref="IAsyncCursorSource{TDocument}"/>, which <c>MongoQueryable.ToListAsync</c> /
/// <c>ToCursorAsync</c> require because they cast the source rather than the provider.
/// </remarks>
internal sealed class ExpressiveMongoQueryable<T> : IExpressiveMongoQueryable<T>, IOrderedQueryable<T>, IAsyncCursorSource<T>
internal sealed class ExpressiveMongoQueryable<T>
: IExpressiveMongoQueryable<T>, IOrderedExpressiveQueryable<T>, IAsyncCursorSource<T>
{
private readonly IQueryable<T> _source;
private readonly ExpressiveMongoQueryProvider _provider;
Expand Down
9 changes: 5 additions & 4 deletions src/ExpressiveSharp/ExpressiveQueryableWrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@
namespace ExpressiveSharp
{
/// <summary>
/// Adapts an <see cref="IQueryable{T}"/> to <see cref="IExpressiveQueryable{T}"/>.
/// Also implements <see cref="IOrderedQueryable{T}"/> so that source-generated
/// <c>ThenBy</c>/<c>ThenByDescending</c> interceptors can cast without throwing.
/// Adapts an <see cref="IQueryable{T}"/> to <see cref="IExpressiveQueryable{T}"/>. Implements
/// <see cref="IOrderedExpressiveQueryable{T}"/> unconditionally so it can serve as the fallback
/// of both <c>AsExpressive</c> overloads; orderedness is enforced by the stub signatures, not
/// by this type.
/// </summary>
internal sealed class ExpressiveQueryableWrapper<T> : IExpressiveQueryable<T>, IOrderedQueryable<T>, IAsyncEnumerable<T>
internal sealed class ExpressiveQueryableWrapper<T> : IOrderedExpressiveQueryable<T>, IAsyncEnumerable<T>
{
private readonly IQueryable<T> _source;

Expand Down
13 changes: 13 additions & 0 deletions src/ExpressiveSharp/Extensions/ExpressiveQueryableExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,18 @@ public static IExpressiveQueryable<T> AsExpressive<T>(
// etc.) remain observable through the returned reference.
=> source as IExpressiveQueryable<T>
?? new ExpressiveQueryableWrapper<T>(source);

/// <summary>
/// Ordered overload, preserving orderedness in the static type. Selected by overload
/// resolution for the results of <see cref="Queryable"/> ordering operators.
/// </summary>
/// <param name="options">
/// Read by the source generator at compile time; ignored at runtime.
/// </param>
public static IOrderedExpressiveQueryable<T> AsExpressive<T>(
this IOrderedQueryable<T> source,
ExpressionRewriteOptions? options = null)
=> source as IOrderedExpressiveQueryable<T>
?? new ExpressiveQueryableWrapper<T>(source);
}
}
Loading
Loading