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
11 changes: 8 additions & 3 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -589,9 +589,14 @@ and nothing is generated. A class marked `[IReactiveObject]` looks as if it rais

`SourceGeneratorsCompilation` closes that gap:

- It reads `[Reactive]`, `[ReactiveCollection]`, `[BindableDerivedList]`, `[ReactiveCommand]` and `[IReactiveObject]`
by metadata name. `SourceGeneratorsMemberExtractor` turns each into a declaration with the name, type and
accessibility ReactiveUI.SourceGenerators gives the member. Accessor bodies are `throw null;`; they never run.
- It reads `[Reactive]`, `[ReactiveCollection]`, `[BindableDerivedList]`, `[ReactiveCommand]`, `[IReactiveObject]`
and both forms of `[IViewFor]` by metadata name. `SourceGeneratorsMemberExtractor` turns each into a declaration with
the name, type and accessibility ReactiveUI.SourceGenerators gives the member. Accessor bodies are `throw null;`; they
never run.
- A view marked `[IViewFor]` gains `IViewFor<T>`, `ViewModel` and the explicit `IViewFor.ViewModel`, and every view but
a Windows Forms one gains `BindingRoot`. Like that generator, it gains them only when it is a partial class deriving
from a WPF, Windows Forms, WinUI, MAUI, Avalonia or Uno control. The view model is bound where the class is declared,
as the view locator binds it. A type marked both `[IReactiveObject]` and `[IViewFor]` gains both interfaces.
- The declarations go into one file, parsed once per change to them, and added to a private copy of the compilation.
The file is never emitted.
- `BindingGenerator.Detect` reads every call site from that copy, through `CallSiteContext`. A compilation that uses
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,19 @@ internal static class SourceGeneratorsCompilation
Func<SyntaxNode, CancellationToken, bool> isVariable = static (node, _) => node is VariableDeclaratorSyntax;
Func<SyntaxNode, CancellationToken, bool> isMethod = static (node, _) => node is MethodDeclarationSyntax;
Func<SyntaxNode, CancellationToken, bool> isType = static (node, _) => node is TypeDeclarationSyntax;
Func<SyntaxNode, CancellationToken, bool> isClass = static (node, _) => node is ClassDeclarationSyntax;

var reactive = Collect(in context, Constants.SourceGeneratorsReactiveAttributeMetadataName, isVariable, SourceGeneratorsMemberExtractor.ExtractReactive);
var collections = Collect(in context, Constants.SourceGeneratorsReactiveCollectionAttributeMetadataName, isVariable, SourceGeneratorsMemberExtractor.ExtractReactiveCollection);
var derivedLists = Collect(in context, Constants.SourceGeneratorsBindableDerivedListAttributeMetadataName, isVariable, SourceGeneratorsMemberExtractor.ExtractBindableDerivedList);
var commands = Collect(in context, Constants.SourceGeneratorsReactiveCommandAttributeMetadataName, isMethod, SourceGeneratorsMemberExtractor.ExtractReactiveCommand);
var reactiveObjects = Collect(in context, Constants.SourceGeneratorsIReactiveObjectAttributeMetadataName, isType, SourceGeneratorsMemberExtractor.ExtractIReactiveObject);

// The generic and the string forms of [IViewFor] are different metadata names, so each needs its own pipeline.
Func<GeneratorAttributeSyntaxContext, CancellationToken, SourceGeneratorsMember?> extractView = SourceGeneratorsMemberExtractor.ExtractIViewFor;
var genericViews = Collect(in context, Constants.SourceGeneratorsGenericIViewForAttributeMetadataName, isClass, extractView);
var namedViews = Collect(in context, Constants.SourceGeneratorsIViewForAttributeMetadataName, isClass, extractView);

// XAML pages are read once per change to the file; their types are resolved against the compilation.
var xamlFields = context.AdditionalTextsProvider
.Combine(context.AnalyzerConfigOptionsProvider)
Expand All @@ -61,13 +67,17 @@ internal static class SourceGeneratorsCompilation
.Select(static (data, ct) => XamlMemberResolver.Resolve(RoslynArray.Unwrap(data.Left), data.Right, ct));

var declarations = reactiveObjects
.Combine(genericViews)
.Combine(namedViews)
.Combine(reactive)
.Combine(collections)
.Combine(derivedLists)
.Combine(commands)
.Combine(xamlFields)
.Select(static (data, _) => WriteDeclarations(
data.Left.Left.Left.Left.Left,
data.Left.Left.Left.Left.Left.Left.Left,
data.Left.Left.Left.Left.Left.Left.Right,
data.Left.Left.Left.Left.Left.Right,
data.Left.Left.Left.Left.Right,
data.Left.Left.Left.Right,
data.Left.Left.Right,
Expand Down Expand Up @@ -144,13 +154,19 @@ private static void Add(
order.Add(member.Declaration);
}

// A type marked both [IReactiveObject] and [IViewFor] implements both interfaces.
if (member.Interface is { } implemented)
{
interfaces[member.Declaration] = implemented;
return;
interfaces[member.Declaration] = interfaces.TryGetValue(member.Declaration, out var existing)
? $"{existing}, {implemented}"
: implemented;
}

list.Add(member.Property!);
// [IViewFor] adds an interface and the properties that implement it.
if (member.Property is { } property)
{
list.Add(property);
}
}

/// <summary>Runs one attribute's pipeline and gathers what it describes.</summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,15 @@ internal static class SourceGeneratorsMemberExtractor
/// <summary>The accessor body every generated accessor declaration carries. It never runs.</summary>
private const string GetAccessor = "get { throw null; }";

/// <summary>The setter body a generated read-write declaration carries. It never runs.</summary>
private const string SetAccessor = "set { throw null; }";

/// <summary>The namespace of Windows Forms, whose views <c>[IViewFor]</c> writes without a <c>BindingRoot</c> property.</summary>
private const string WinFormsNamespace = "System.Windows.Forms";

/// <summary>The namespaces whose controls <c>[IViewFor]</c> generates a view for: WPF and WinForms, WinUI, MAUI, Avalonia and Uno.</summary>
private static readonly string[] ViewBaseNamespaces = ["System.Windows", "Microsoft.UI.Xaml", "Microsoft.Maui", "Avalonia", "Windows.UI.Xaml"];

/// <summary>Describes the property <c>[Reactive]</c> generates from a field.</summary>
/// <param name="context">The attribute context.</param>
/// <param name="ct">Cancellation token.</param>
Expand Down Expand Up @@ -181,6 +190,46 @@ internal static class SourceGeneratorsMemberExtractor
: null;
}

/// <summary>Describes the <c>IViewFor&lt;T&gt;</c> implementation <c>[IViewFor]</c> adds to a view.</summary>
/// <param name="context">The attribute context.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>
/// The interface and the properties that implement it, or null when no runtime declares <c>IViewFor&lt;T&gt;</c>, the
/// view model does not bind, the class is not partial, or it is not a UI control.
/// </returns>
/// <remarks>
/// ReactiveUI.SourceGenerators only writes a view for a control of a UI framework it knows, so a class with any other
/// base gains nothing here either. Every view gains <c>ViewModel</c> and the explicit <c>IViewFor.ViewModel</c>; every
/// view but a Windows Forms one also gains <c>BindingRoot</c>. The view model is bound where the class is declared, as
/// the view locator binds it.
/// </remarks>
internal static SourceGeneratorsMember? ExtractIViewFor(GeneratorAttributeSyntaxContext context, CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
var view = (INamedTypeSymbol)context.TargetSymbol;
if (ViewBaseNamespace(view) is not { } baseNamespace
|| ViewRegistrationExtractor.ReferencedViewNamespace(context.SemanticModel.Compilation) is not { } prefix
|| ViewRegistrationExtractor.ResolveViewModel(context.Attributes[0], context.SemanticModel, context.TargetNode.SpanStart, ct) is not { } viewModel
|| PartialTypeRaisePlugin.DescribeDeclaration(view) is not { } declaration)
{
return null;
}

var viewModelType = TypeName(viewModel);
var members = new PooledStringBuilder()
.Append(PublicAccessibility).Append(' ').Append(viewModelType).Append(" ViewModel { ").Append(GetAccessor).Append(' ').Append(SetAccessor).Append(" } ");
if (baseNamespace != WinFormsNamespace)
{
_ = members.Append(PublicAccessibility).Append(' ').Append(viewModelType).Append(" BindingRoot { ").Append(GetAccessor).Append(" } ");
}

var property = members
.Append("object global::").Append(prefix).Append("IViewFor.ViewModel { ").Append(GetAccessor).Append(' ').Append(SetAccessor).Append(" }")
.ToStringAndReturn();

return new(declaration, $"global::{prefix}IViewFor<{viewModelType}>", property);
}

/// <summary>Gets the name ReactiveUI.SourceGenerators gives the property it generates from a field.</summary>
/// <param name="fieldName">The field's name.</param>
/// <returns>The name without an <c>m_</c> or leading-underscore prefix, its first letter upper case.</returns>
Expand Down Expand Up @@ -441,6 +490,34 @@ private static int PrefixLength(string name)
return start;
}

/// <summary>Finds the UI framework of the control a class derives from, among those <c>[IViewFor]</c> generates a view for.</summary>
/// <param name="view">The class.</param>
/// <returns>
/// <see cref="WinFormsNamespace"/> for a Windows Forms control, the matching entry of <see cref="ViewBaseNamespaces"/>
/// for any other, or null when no base type's full name starts with one.
/// </returns>
private static string? ViewBaseNamespace(INamedTypeSymbol view)
{
for (var current = view.BaseType; current is not null; current = current.BaseType)
{
var name = current.ToDisplayString();
if (name.StartsWith(WinFormsNamespace, StringComparison.Ordinal))
{
return WinFormsNamespace;
}

foreach (var prefix in ViewBaseNamespaces)
{
if (name.StartsWith(prefix, StringComparison.Ordinal))
{
return prefix;
}
}
}

return null;
}

/// <summary>Writes a type's fully qualified name.</summary>
/// <param name="type">The type.</param>
/// <returns>The name, starting with <c>global::</c> where the type has a namespace.</returns>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,21 @@ internal static bool KeepsOneInstance(AttributeData attribute)
return false;
}

/// <summary>Names the flavour of the runtime the compilation references.</summary>
/// <param name="compilation">The consumer compilation.</param>
/// <returns>The flavour's view namespace with the trailing dot, or null when neither runtime is referenced.</returns>
internal static string? ReferencedViewNamespace(Compilation compilation)
{
if (compilation.GetTypeByMetadataName(Constants.IViewForGenericMetadataName) is not null)
{
return Constants.LeanViewNamespacePrefix;
}

return compilation.GetTypeByMetadataName(Constants.ReactiveIViewForGenericMetadataName) is not null
? Constants.ReactiveViewNamespacePrefix
: null;
}

/// <summary>Names the flavour an <c>IViewFor&lt;T&gt;</c> definition belongs to.</summary>
/// <param name="definition">The interface's open definition.</param>
/// <param name="lean">The lean runtime's <c>IViewFor&lt;T&gt;</c>, or null when it is not referenced.</param>
Expand All @@ -158,21 +173,6 @@ internal static bool KeepsOneInstance(AttributeData attribute)
return SymbolEqualityComparer.Default.Equals(definition, reactive) ? Constants.ReactiveViewNamespacePrefix : null;
}

/// <summary>Names the flavour of the runtime the compilation references.</summary>
/// <param name="compilation">The consumer compilation.</param>
/// <returns>The flavour's view namespace with the trailing dot, or null when neither runtime is referenced.</returns>
private static string? ReferencedViewNamespace(Compilation compilation)
{
if (compilation.GetTypeByMetadataName(Constants.IViewForGenericMetadataName) is not null)
{
return Constants.LeanViewNamespacePrefix;
}

return compilation.GetTypeByMetadataName(Constants.ReactiveIViewForGenericMetadataName) is not null
? Constants.ReactiveViewNamespacePrefix
: null;
}

/// <summary>Builds the registration for a view, reading the view attributes of the flavour it belongs to.</summary>
/// <param name="view">The view type.</param>
/// <param name="viewModel">The view model type.</param>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,99 @@ public static string Run()
}
""";

/// <summary>
/// Views that ReactiveUI.SourceGenerators makes implement <c>IViewFor&lt;T&gt;</c> from <c>[IViewFor]</c>, binding a
/// <c>[BindableDerivedList]</c> list and a <c>[Reactive]</c> property from inside and outside the view.
/// </summary>
/// <remarks>A stand-in Windows Forms control is the base, because that generator only writes views for UI controls.</remarks>
internal const string ViewScenario = """
using System;
using System.Collections.ObjectModel;
using ReactiveUI.SourceGenerators;
using RUNTIME_NAMESPACE;
using RxObject = RUNTIME_REACTIVE_OBJECT;

namespace System.Windows.Forms
{
public class UserControl { }
}

namespace Contract
{
public partial class LogViewModel : RxObject
{
private readonly ObservableCollection<string> _source = new ObservableCollection<string>();

[Reactive]
private string? _title;

[BindableDerivedList]
private ReadOnlyObservableCollection<string>? _entries;

public LogViewModel() => _entries = new ReadOnlyObservableCollection<string>(_source);
}

[IViewFor<LogViewModel>]
public partial class LogView : System.Windows.Forms.UserControl
{
public string? Heading { get; set; }

public object? EntriesSource { get; set; }

public IDisposable BindEntries() => this.OneWayBind(ViewModel, static vm => vm.Entries, static v => v.EntriesSource);
}

[IViewFor("LogViewModel")]
public partial class NamedLogView : System.Windows.Forms.UserControl
{
public string? Heading { get; set; }
}

public static class Usage
{
public static string Run()
{
var vm = new LogViewModel();
var view = new LogView { ViewModel = vm };
using var a = view.BindEntries();
using var b = view.OneWayBind(vm, static x => x.Title, static v => v.Heading);

var named = new NamedLogView { ViewModel = vm };
using var c = named.OneWayBind(vm, static x => x.Title, static v => v.Heading);
vm.Title = "Log";

return $"entries:{view.EntriesSource is ReadOnlyObservableCollection<string>}|generic:{view.Heading}|named:{named.Heading}";
}
}
}
""";

/// <summary>Views that ReactiveUI.SourceGenerators gives <c>IViewFor&lt;T&gt;</c> bind their generated members, in both runtimes.</summary>
/// <param name="useReactiveRuntime">Whether to reference the System.Reactive flavour rather than the lean one.</param>
/// <param name="intercept">Whether the build opts into interceptors.</param>
/// <returns>A task representing the asynchronous test operation.</returns>
[Test]
[Arguments(false, false)]
[Arguments(true, false)]
[Arguments(false, true)]
[Arguments(true, true)]
public async Task ViewsFromIViewForAttribute_BindAtRunTime(bool useReactiveRuntime, bool intercept)
{
var result = RunBeside(ViewScenario, useReactiveRuntime, intercept);
await Assert.That(result.CompilationErrors.Select(static d => d.ToString())).IsEmpty();

var (assembly, context) = TestHelper.EmitAndLoad(result);
try
{
var run = assembly.GetType("Contract.Usage")!.GetMethod("Run", BindingFlags.Public | BindingFlags.Static)!;
await Assert.That((string)run.Invoke(null, null)!).IsEqualTo("entries:True|generic:Log|named:Log");
}
finally
{
context.Unload();
}
}

/// <summary>Every member ReactiveUI.SourceGenerators writes binds, observes and writes at run time, in both runtimes.</summary>
/// <param name="useReactiveRuntime">Whether to reference the System.Reactive flavour rather than the lean one.</param>
/// <param name="intercept">Whether the build opts into interceptors.</param>
Expand Down Expand Up @@ -240,5 +333,6 @@ private static ImmutableArray<ISourceGenerator> SourceGeneratorsGenerators() =>
new sg::ReactiveUI.SourceGenerators.BindableDerivedListGenerator().AsSourceGenerator(),
new sg::ReactiveUI.SourceGenerators.ReactiveCommandGenerator().AsSourceGenerator(),
new sg::ReactiveUI.SourceGenerators.ReactiveObjectGenerator().AsSourceGenerator(),
new sg::ReactiveUI.SourceGenerators.IViewForGenerator().AsSourceGenerator(),
];
}
Loading
Loading