-
-
Notifications
You must be signed in to change notification settings - Fork 0
feat: add AOT-safe ViewLocator with source-generated view dispatch #15
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
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
224 changes: 224 additions & 0 deletions
224
src/ReactiveUI.Binding.SourceGenerators/Generators/ViewLocatorDispatchGenerator.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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<T></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(" }"); | ||
| } | ||
| } |
84 changes: 84 additions & 0 deletions
84
src/ReactiveUI.Binding.SourceGenerators/Helpers/ViewRegistrationExtractor.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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<T></c>. | ||
| /// </summary> | ||
| internal static class ViewRegistrationExtractor | ||
| { | ||
| /// <summary> | ||
| /// Extracts a <see cref="ViewRegistrationInfo"/> from a class that implements <c>IViewFor<T></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<T></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; | ||
| } | ||
| } |
18 changes: 18 additions & 0 deletions
18
src/ReactiveUI.Binding.SourceGenerators/Models/ViewRegistrationInfo.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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<T></c> implementations and <c>Map<TVM,TView>()</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>; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.