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
6 changes: 5 additions & 1 deletion src/ReactiveUI.Binding.SourceGenerators/BindingGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,10 @@ namespace ReactiveUI.Binding.SourceGenerators;

/// <summary>
/// The main incremental source generator entry point for ReactiveUI property observation and binding.
/// Orchestrates two pipelines:
/// Orchestrates three pipelines:
/// Pipeline A (Type Detection): Detects notification mechanisms and generates high-affinity fallback binders.
/// Pipeline B (Invocation Detection): Detects WhenChanged/WhenChanging/Bind calls and generates per-invocation code.
/// Pipeline C (View Dispatch): Scans IViewFor&lt;T&gt; implementations and generates AOT-safe view locator dispatch.
/// </summary>
[Generator]
public class BindingGenerator : IIncrementalGenerator
Expand Down Expand Up @@ -91,6 +92,9 @@ internal static partial class __ReactiveUIGeneratedBindings
consolidated,
static (ctx, data) => RegistrationGenerator.Generate(ctx, data));

// Pipeline C: View locator dispatch (IViewFor<T> scanning)
ViewLocatorDispatchGenerator.Register(context);

// Pipeline B: Invocation detection (separate pipelines per API)
// Each invocation generator receives supportsCallerArgExpr to control dispatch strategy
WhenChangedInvocationGenerator.Register(context, allClasses, supportsCallerArgExpr);
Expand Down
5 changes: 5 additions & 0 deletions src/ReactiveUI.Binding.SourceGenerators/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,11 @@ internal static class Constants
/// </summary>
internal const string BindCommandMethodName = "BindCommand";

/// <summary>
/// Metadata name for the open generic <c>IViewFor&lt;T&gt;</c> interface used for view resolution.
/// </summary>
internal const string IViewForGenericMetadataName = "ReactiveUI.Binding.IViewFor`1";

/// <summary>
/// Metadata name for the <c>IBindingTypeConverter</c> interface used for custom type conversions.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
// Copyright (c) 2019-2026 ReactiveUI Association Incorporated. All rights reserved.
// ReactiveUI Association Incorporated licenses this file to you under the MIT license.
// See the LICENSE file in the project root for full license information.

using System.Collections.Immutable;
using System.Text;

using Microsoft.CodeAnalysis;

using ReactiveUI.Binding.SourceGenerators.Helpers;
using ReactiveUI.Binding.SourceGenerators.Models;

namespace ReactiveUI.Binding.SourceGenerators.Generators;

/// <summary>
/// Generates the AOT-safe view dispatch code for <see cref="ViewRegistrationInfo"/> entries.
/// Emits a type-switch function that resolves views without reflection.
/// </summary>
internal static class ViewLocatorDispatchGenerator
{
/// <summary>
/// Registers the view locator dispatch pipeline into the incremental generator.
/// Scans for classes implementing <c>IViewFor&lt;T&gt;</c> and generates a dispatch method.
/// </summary>
/// <param name="context">The incremental generator initialization context.</param>
internal static void Register(IncrementalGeneratorInitializationContext context)
{
// Reuse Pipeline A's class-with-base-list predicate
var viewRegistrations = context.SyntaxProvider
.CreateSyntaxProvider(
predicate: RoslynHelpers.IsClassWithBaseList,
transform: ViewRegistrationExtractor.ExtractFromIViewForImplementation)
.Where(static x => x is not null)
.Select(static (x, _) => x!);

// Collect and deduplicate
var collected = viewRegistrations.Collect();

context.RegisterSourceOutput(collected, static (ctx, data) => Generate(ctx, data));
}

/// <summary>
/// Generates the ViewDispatch.g.cs source file from collected view registrations.
/// </summary>
/// <param name="context">The source production context.</param>
/// <param name="registrations">All detected view registration infos.</param>
internal static void Generate(SourceProductionContext context, ImmutableArray<ViewRegistrationInfo> registrations)
{
if (!ExtractorValidation.HasItems(registrations))
{
return;
}

// Deduplicate by ViewModel fully qualified name (first occurrence wins)
var deduplicated = Deduplicate(registrations);

var sb = new StringBuilder(2048 + (deduplicated.Count * 512));
GenerateSource(sb, deduplicated);
context.AddSource("ViewDispatch.g.cs", sb.ToString());
}

/// <summary>
/// Deduplicates view registrations by view model fully qualified name.
/// </summary>
/// <param name="registrations">The raw registrations.</param>
/// <returns>A deduplicated list of registrations.</returns>
private static List<ViewRegistrationInfo> Deduplicate(ImmutableArray<ViewRegistrationInfo> registrations)
{
var seen = new HashSet<string>(StringComparer.Ordinal);
var result = new List<ViewRegistrationInfo>(registrations.Length);

for (var i = 0; i < registrations.Length; i++)
{
var reg = registrations[i];
if (seen.Add(reg.ViewModelFullyQualifiedName))
{
result.Add(reg);
}
}

return result;
}

/// <summary>
/// Generates the full source output into the StringBuilder.
/// </summary>
/// <param name="sb">The string builder to write to.</param>
/// <param name="registrations">The deduplicated registrations.</param>
private static void GenerateSource(StringBuilder sb, List<ViewRegistrationInfo> registrations)
{
sb.AppendLine("// <auto-generated/>")
.AppendLine("#pragma warning disable")
.AppendLine()
.AppendLine("namespace ReactiveUI.Binding")
.AppendLine("{")
.AppendLine(" internal static partial class __ReactiveUIGeneratedBindings")
.AppendLine(" {");

// Static field initializer to trigger registration
sb.AppendLine(" /// <summary>")
.AppendLine(" /// Triggers view dispatch registration when the generated bindings class is loaded.")
.AppendLine(" /// </summary>")
.AppendLine(" private static readonly bool __viewDispatchRegistered = __RegisterViewDispatch();")
.AppendLine();

// Registration method
sb.AppendLine(" /// <summary>")
.AppendLine(" /// Registers the source-generated view dispatch function with")
.AppendLine(" /// <see cref=\"global::ReactiveUI.Binding.DefaultViewLocator\"/>.")
.AppendLine(" /// Called once via static field initializer when this class is first accessed.")
.AppendLine(" /// </summary>")
.AppendLine(" /// <returns>Always returns <see langword=\"true\"/>.</returns>")
.AppendLine(" private static bool __RegisterViewDispatch()")
.AppendLine(" {")
.AppendLine(" global::ReactiveUI.Binding.DefaultViewLocator.SetGeneratedViewDispatch(")
.AppendLine(" __TryResolveView);")
.AppendLine(" return true;")
.AppendLine(" }")
.AppendLine();

// Dispatch method
sb.AppendLine(" /// <summary>")
.AppendLine(" /// Compile-time generated type-switch dispatch for view resolution.")
.AppendLine(" /// Attempts to resolve a view for the given view model instance without reflection.")
.AppendLine(" /// </summary>")
.AppendLine(" /// <param name=\"instance\">The view model instance to resolve a view for.</param>")
.AppendLine(" /// <param name=\"contract\">The contract string (empty string for default).</param>")
.AppendLine(" /// <returns>The resolved view, or <see langword=\"null\"/> if no generated mapping exists.</returns>")
.AppendLine(" private static global::ReactiveUI.Binding.IViewFor __TryResolveView(")
.AppendLine(" object instance, string contract)")
.AppendLine(" {");

for (var i = 0; i < registrations.Count; i++)
{
var reg = registrations[i];
var resolverMethodName = "__ResolveView_" + i;

sb.Append(" // ").Append(reg.ViewModelFullyQualifiedName)
.Append(" -> ").AppendLine(reg.ViewFullyQualifiedName)
.Append(" if (instance is ").Append(reg.ViewModelFullyQualifiedName).AppendLine(")")
.AppendLine(" {")
.Append(" return ").Append(resolverMethodName).AppendLine("(contract);")
.AppendLine(" }")
.AppendLine();
}

sb.AppendLine(" // No compile-time mapping found; fall back to runtime resolution.")
.AppendLine(" return null;")
.AppendLine(" }");

// Per-view resolver methods
for (var i = 0; i < registrations.Count; i++)
{
GenerateResolverMethod(sb, registrations[i], i);
}

sb.AppendLine(" }")
.AppendLine("}");
}

/// <summary>
/// Generates a per-view-model resolver method.
/// </summary>
/// <param name="sb">The string builder.</param>
/// <param name="reg">The view registration info.</param>
/// <param name="index">The unique index for method naming.</param>
private static void GenerateResolverMethod(StringBuilder sb, ViewRegistrationInfo reg, int index)
{
var methodName = "__ResolveView_" + index;

sb.AppendLine()
.AppendLine(" /// <summary>")
.Append(" /// Resolves a view for <see cref=\"")
.Append(reg.ViewModelFullyQualifiedName).AppendLine("\"/>.");

if (reg.HasParameterlessConstructor)
{
sb.AppendLine(" /// Tries the service locator first, then falls back to direct construction.");
}
else
{
sb.AppendLine(" /// Service locator only — no direct construction available.");
}

sb.AppendLine(" /// </summary>")
.AppendLine(" /// <param name=\"contract\">The contract string (empty string for default).</param>")
.AppendLine(" /// <returns>The resolved view, or <see langword=\"null\"/> if resolution fails.</returns>")
.Append(" private static global::ReactiveUI.Binding.IViewFor ")
.Append(methodName).AppendLine("(string contract)")
.AppendLine(" {");

// Normalize contract
sb.AppendLine(" // Normalize contract: empty string means no contract (null for Splat lookup).")
.AppendLine(" string svcContract = contract.Length == 0 ? null : contract;")
.AppendLine();

// Service locator lookup
sb.AppendLine(" // Prefer service-locator-registered view (supports DI-configured instances).")
.AppendLine(" var view = global::Splat.AppLocator.Current")
.Append(" .GetService<global::ReactiveUI.Binding.IViewFor<")
.Append(reg.ViewModelFullyQualifiedName).AppendLine(">>(")
.AppendLine(" svcContract);")
.AppendLine(" if (view != null)")
.AppendLine(" {")
.AppendLine(" return view;")
.AppendLine(" }");

// Direct construction fallback
if (reg.HasParameterlessConstructor)
{
sb.AppendLine()
.Append(" // Fallback: direct construction (")
.Append(reg.ViewFullyQualifiedName).AppendLine(" has a parameterless constructor).")
.Append(" return new ").Append(reg.ViewFullyQualifiedName).AppendLine("();");
}
else
{
sb.AppendLine()
.AppendLine(" return null;");
}

sb.AppendLine(" }");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// Copyright (c) 2019-2026 ReactiveUI Association Incorporated. All rights reserved.
// ReactiveUI Association Incorporated licenses this file to you under the MIT license.
// See the LICENSE file in the project root for full license information.

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;

using ReactiveUI.Binding.SourceGenerators.Models;

namespace ReactiveUI.Binding.SourceGenerators.Helpers;

/// <summary>
/// Extracts <see cref="ViewRegistrationInfo"/> from class declarations implementing <c>IViewFor&lt;T&gt;</c>.
/// </summary>
internal static class ViewRegistrationExtractor
{
/// <summary>
/// Extracts a <see cref="ViewRegistrationInfo"/> from a class that implements <c>IViewFor&lt;T&gt;</c>.
/// </summary>
/// <param name="context">The generator syntax context.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>A <see cref="ViewRegistrationInfo"/> if the class implements <c>IViewFor&lt;T&gt;</c>; otherwise, <see langword="null"/>.</returns>
internal static ViewRegistrationInfo? ExtractFromIViewForImplementation(
GeneratorSyntaxContext context,
CancellationToken ct)
{
var classDecl = (ClassDeclarationSyntax)context.Node;
var semanticModel = context.SemanticModel;
var typeSymbol = semanticModel.GetDeclaredSymbol(classDecl, ct) as INamedTypeSymbol;

if (typeSymbol is null || typeSymbol.IsAbstract)
{
return null;
}

var iViewForGeneric = semanticModel.Compilation.GetTypeByMetadataName(
Constants.IViewForGenericMetadataName);

// Walk AllInterfaces to find IViewFor<T>
var allInterfaces = typeSymbol.AllInterfaces;
for (var i = 0; i < allInterfaces.Length; i++)
{
ct.ThrowIfCancellationRequested();
var iface = allInterfaces[i];

if (iViewForGeneric is object
&& iface.IsGenericType
&& SymbolEqualityComparer.Default.Equals(iface.OriginalDefinition, iViewForGeneric)
&& iface.TypeArguments.Length == 1)
{
var viewModelType = iface.TypeArguments[0];
var viewModelFqn = viewModelType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
var viewFqn = typeSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
var hasParameterlessCtor = HasAccessibleParameterlessConstructor(typeSymbol);

return new ViewRegistrationInfo(viewModelFqn, viewFqn, hasParameterlessCtor);
}
}

return null;
}

/// <summary>
/// Checks whether the type has an accessible parameterless constructor (public or internal).
/// </summary>
/// <param name="type">The type to check.</param>
/// <returns><see langword="true"/> if a parameterless constructor is accessible; otherwise, <see langword="false"/>.</returns>
private static bool HasAccessibleParameterlessConstructor(INamedTypeSymbol type)
{
var constructors = type.InstanceConstructors;
for (var i = 0; i < constructors.Length; i++)
{
var ctor = constructors[i];
if (ctor.Parameters.Length == 0
&& (ctor.DeclaredAccessibility == Accessibility.Public
|| ctor.DeclaredAccessibility == Accessibility.Internal))
{
return true;
}
}

return false;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Copyright (c) 2019-2026 ReactiveUI Association Incorporated. All rights reserved.
// ReactiveUI Association Incorporated licenses this file to you under the MIT license.
// See the LICENSE file in the project root for full license information.

namespace ReactiveUI.Binding.SourceGenerators.Models;

/// <summary>
/// Value-equatable POCO representing a view-to-view-model mapping detected at compile time.
/// Produced by scanning <c>IViewFor&lt;T&gt;</c> implementations and <c>Map&lt;TVM,TView&gt;()</c> call sites.
/// Contains no ISymbol, SyntaxNode, or Location references.
/// </summary>
/// <param name="ViewModelFullyQualifiedName">The fully qualified name of the view model type (global:: prefixed).</param>
/// <param name="ViewFullyQualifiedName">The fully qualified name of the view type (global:: prefixed).</param>
/// <param name="HasParameterlessConstructor">Whether the view type has a parameterless constructor for direct instantiation.</param>
internal sealed record ViewRegistrationInfo(
string ViewModelFullyQualifiedName,
string ViewFullyQualifiedName,
bool HasParameterlessConstructor) : IEquatable<ViewRegistrationInfo>;
7 changes: 7 additions & 0 deletions src/ReactiveUI.Binding/Builder/IReactiveUIBindingBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,13 @@ IReactiveUIBindingBuilder WithPlatformModule<T>(T module)
/// <returns>The builder instance for chaining.</returns>
IReactiveUIBindingBuilder WithCommandBinder(ICreatesCommandBinding binder);

/// <summary>
/// Configures the default view locator with explicit view-to-view-model mappings.
/// </summary>
/// <param name="configure">An action that receives a <see cref="ViewMappingBuilder"/> for registering mappings.</param>
/// <returns>The builder instance for chaining.</returns>
IReactiveUIBindingBuilder ConfigureViewLocator(Action<ViewMappingBuilder> configure);

/// <summary>
/// Builds the application and returns the configured instance.
/// </summary>
Expand Down
Loading
Loading