diff --git a/CLAUDE.md b/CLAUDE.md index 8116f1aa..46687203 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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`, `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 diff --git a/src/ReactiveUI.Binding.SourceGenerators/Generators/SourceGeneratorsCompilation.cs b/src/ReactiveUI.Binding.SourceGenerators/Generators/SourceGeneratorsCompilation.cs index 1350163d..ad6ef83e 100644 --- a/src/ReactiveUI.Binding.SourceGenerators/Generators/SourceGeneratorsCompilation.cs +++ b/src/ReactiveUI.Binding.SourceGenerators/Generators/SourceGeneratorsCompilation.cs @@ -43,6 +43,7 @@ internal static class SourceGeneratorsCompilation Func isVariable = static (node, _) => node is VariableDeclaratorSyntax; Func isMethod = static (node, _) => node is MethodDeclarationSyntax; Func isType = static (node, _) => node is TypeDeclarationSyntax; + Func 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); @@ -50,6 +51,11 @@ internal static class SourceGeneratorsCompilation 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 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) @@ -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, @@ -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); + } } /// Runs one attribute's pipeline and gathers what it describes. diff --git a/src/ReactiveUI.Binding.SourceGenerators/Helpers/SourceGeneratorsMemberExtractor.cs b/src/ReactiveUI.Binding.SourceGenerators/Helpers/SourceGeneratorsMemberExtractor.cs index 3cee4bf7..a3e814db 100644 --- a/src/ReactiveUI.Binding.SourceGenerators/Helpers/SourceGeneratorsMemberExtractor.cs +++ b/src/ReactiveUI.Binding.SourceGenerators/Helpers/SourceGeneratorsMemberExtractor.cs @@ -75,6 +75,15 @@ internal static class SourceGeneratorsMemberExtractor /// The accessor body every generated accessor declaration carries. It never runs. private const string GetAccessor = "get { throw null; }"; + /// The setter body a generated read-write declaration carries. It never runs. + private const string SetAccessor = "set { throw null; }"; + + /// The namespace of Windows Forms, whose views [IViewFor] writes without a BindingRoot property. + private const string WinFormsNamespace = "System.Windows.Forms"; + + /// The namespaces whose controls [IViewFor] generates a view for: WPF and WinForms, WinUI, MAUI, Avalonia and Uno. + private static readonly string[] ViewBaseNamespaces = ["System.Windows", "Microsoft.UI.Xaml", "Microsoft.Maui", "Avalonia", "Windows.UI.Xaml"]; + /// Describes the property [Reactive] generates from a field. /// The attribute context. /// Cancellation token. @@ -181,6 +190,46 @@ internal static class SourceGeneratorsMemberExtractor : null; } + /// Describes the IViewFor<T> implementation [IViewFor] adds to a view. + /// The attribute context. + /// Cancellation token. + /// + /// The interface and the properties that implement it, or null when no runtime declares IViewFor<T>, the + /// view model does not bind, the class is not partial, or it is not a UI control. + /// + /// + /// 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 ViewModel and the explicit IViewFor.ViewModel; every + /// view but a Windows Forms one also gains BindingRoot. The view model is bound where the class is declared, as + /// the view locator binds it. + /// + 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); + } + /// Gets the name ReactiveUI.SourceGenerators gives the property it generates from a field. /// The field's name. /// The name without an m_ or leading-underscore prefix, its first letter upper case. @@ -441,6 +490,34 @@ private static int PrefixLength(string name) return start; } + /// Finds the UI framework of the control a class derives from, among those [IViewFor] generates a view for. + /// The class. + /// + /// for a Windows Forms control, the matching entry of + /// for any other, or null when no base type's full name starts with one. + /// + 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; + } + /// Writes a type's fully qualified name. /// The type. /// The name, starting with global:: where the type has a namespace. diff --git a/src/ReactiveUI.Binding.SourceGenerators/Helpers/ViewRegistrationExtractor.cs b/src/ReactiveUI.Binding.SourceGenerators/Helpers/ViewRegistrationExtractor.cs index e9f8be9f..7b922507 100644 --- a/src/ReactiveUI.Binding.SourceGenerators/Helpers/ViewRegistrationExtractor.cs +++ b/src/ReactiveUI.Binding.SourceGenerators/Helpers/ViewRegistrationExtractor.cs @@ -143,6 +143,21 @@ internal static bool KeepsOneInstance(AttributeData attribute) return false; } + /// Names the flavour of the runtime the compilation references. + /// The consumer compilation. + /// The flavour's view namespace with the trailing dot, or null when neither runtime is referenced. + 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; + } + /// Names the flavour an IViewFor<T> definition belongs to. /// The interface's open definition. /// The lean runtime's IViewFor<T>, or null when it is not referenced. @@ -158,21 +173,6 @@ internal static bool KeepsOneInstance(AttributeData attribute) return SymbolEqualityComparer.Default.Equals(definition, reactive) ? Constants.ReactiveViewNamespacePrefix : null; } - /// Names the flavour of the runtime the compilation references. - /// The consumer compilation. - /// The flavour's view namespace with the trailing dot, or null when neither runtime is referenced. - 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; - } - /// Builds the registration for a view, reading the view attributes of the flavour it belongs to. /// The view type. /// The view model type. diff --git a/src/tests/ReactiveUI.Binding.SourceGenerators.Tests/SourceGeneratorsContractTests.cs b/src/tests/ReactiveUI.Binding.SourceGenerators.Tests/SourceGeneratorsContractTests.cs index c8fc64f5..be4227d2 100644 --- a/src/tests/ReactiveUI.Binding.SourceGenerators.Tests/SourceGeneratorsContractTests.cs +++ b/src/tests/ReactiveUI.Binding.SourceGenerators.Tests/SourceGeneratorsContractTests.cs @@ -181,6 +181,99 @@ public static string Run() } """; + /// + /// Views that ReactiveUI.SourceGenerators makes implement IViewFor<T> from [IViewFor], binding a + /// [BindableDerivedList] list and a [Reactive] property from inside and outside the view. + /// + /// A stand-in Windows Forms control is the base, because that generator only writes views for UI controls. + 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 _source = new ObservableCollection(); + + [Reactive] + private string? _title; + + [BindableDerivedList] + private ReadOnlyObservableCollection? _entries; + + public LogViewModel() => _entries = new ReadOnlyObservableCollection(_source); + } + + [IViewFor] + 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}|generic:{view.Heading}|named:{named.Heading}"; + } + } + } + """; + + /// Views that ReactiveUI.SourceGenerators gives IViewFor<T> bind their generated members, in both runtimes. + /// Whether to reference the System.Reactive flavour rather than the lean one. + /// Whether the build opts into interceptors. + /// A task representing the asynchronous test operation. + [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(); + } + } + /// Every member ReactiveUI.SourceGenerators writes binds, observes and writes at run time, in both runtimes. /// Whether to reference the System.Reactive flavour rather than the lean one. /// Whether the build opts into interceptors. @@ -240,5 +333,6 @@ private static ImmutableArray 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(), ]; } diff --git a/src/tests/ReactiveUI.Binding.SourceGenerators.Tests/SourceGeneratorsDeclarationTests.cs b/src/tests/ReactiveUI.Binding.SourceGenerators.Tests/SourceGeneratorsDeclarationTests.cs index 982b3e45..1e53e54c 100644 --- a/src/tests/ReactiveUI.Binding.SourceGenerators.Tests/SourceGeneratorsDeclarationTests.cs +++ b/src/tests/ReactiveUI.Binding.SourceGenerators.Tests/SourceGeneratorsDeclarationTests.cs @@ -62,6 +62,23 @@ public static class ReactiveCommand { } } """; + /// The namespace of the lean runtime's view types. + private const string ViewRuntime = "ReactiveUI.Binding"; + + /// The namespace of the System.Reactive runtime's view types. + private const string ReactiveViewRuntime = "ReactiveUI.Binding.Reactive"; + + /// Stand-in view types of the lean runtime. + private const string ViewRuntimeTypes = "namespace ReactiveUI.Binding { public interface IViewFor { } public interface IViewFor : IViewFor { } }"; + + /// Stand-in controls of each UI framework the views derive from. + private const string Controls = """ + namespace System.Windows.Controls { public class UserControl { } } + namespace System.Windows.Forms { public class UserControl { } } + namespace Avalonia.Controls { public class UserControl { } } + namespace Microsoft.Maui.Controls { public class ContentPage { } } + """; + /// ReactiveUI.SourceGenerators' attributes, as its 4.0.0 library declares them. private static readonly MetadataReference Attributes = MetadataReference.CreateFromFile(typeof(ReactiveUI.SourceGenerators.ReactiveAttribute).Assembly.Location); @@ -270,6 +287,75 @@ public async Task IReactiveObject_AddsInterface() public async Task IReactiveObject_WithoutInterfaceOrPartial_DeclaresNothing(string source, string reactiveUI) => await Assert.That(Declarations(source, reactiveUI)).IsEqualTo(None); + /// + /// A view marked [IViewFor] implements IViewFor<T> with the properties ReactiveUI.SourceGenerators + /// writes, in the flavour the compilation references. A Windows Forms view has no BindingRoot. + /// + /// The attribute, in its generic or its string form. + /// The control the view derives from. + /// The namespace of the referenced runtime's view types. + /// Whether the view gains a BindingRoot property. + /// A task representing the asynchronous test operation. + [Test] + [Arguments("[IViewFor]", "System.Windows.Controls.UserControl", ViewRuntime, true)] + [Arguments("[IViewFor(\"Model\")]", "Avalonia.Controls.UserControl", ViewRuntime, true)] + [Arguments("[IViewFor]", "System.Windows.Forms.UserControl", ViewRuntime, false)] + [Arguments("[IViewFor]", "Microsoft.Maui.Controls.ContentPage", ReactiveViewRuntime, true)] + public async Task IViewFor_AddsInterfaceAndViewModel(string attribute, string baseType, string runtime, bool hasBindingRoot) + { + var declarations = Declarations( + $"public class Model {{ }} {attribute} public partial class View : {baseType} {{ }}", + Controls + RuntimeViewTypes(runtime)); + + await Assert.That(declarations).Contains($"partial class View : global::{runtime}.IViewFor"); + await Assert.That(declarations).Contains("public global::Model ViewModel { get { throw null; } set { throw null; } }"); + await Assert.That(declarations).Contains($"object global::{runtime}.IViewFor.ViewModel {{ get {{ throw null; }} set {{ throw null; }} }}"); + await Assert.That(declarations.Contains("BindingRoot", StringComparison.Ordinal)).IsEqualTo(hasBindingRoot); + } + + /// + /// A view gains nothing when it is not a UI control, no runtime declares IViewFor<T>, the view model's + /// name does not bind, or the class is not partial. + /// + /// The view. + /// Stand-in declarations of the runtime the consumer references, or empty for none. + /// A task representing the asynchronous test operation. + [Test] + [Arguments("[IViewFor] public partial class View : Plain { }", ViewRuntimeTypes)] + [Arguments("[IViewFor] public partial class View : System.Windows.Controls.UserControl { }", "")] + [Arguments("[IViewFor(\"Missing\")] public partial class View : System.Windows.Controls.UserControl { }", ViewRuntimeTypes)] + [Arguments("[IViewFor] public class View : System.Windows.Controls.UserControl { }", ViewRuntimeTypes)] + [Arguments("[IViewFor] public partial struct View { }", ViewRuntimeTypes)] + [Arguments("[IViewFor(\"\")] public partial class View : System.Windows.Controls.UserControl { }", ViewRuntimeTypes)] + [Arguments("[IViewFor(null)] public partial class View : System.Windows.Controls.UserControl { }", ViewRuntimeTypes)] + [Arguments("[IViewFor] public partial class View : System.Windows.Controls.UserControl { }", ViewRuntimeTypes)] + public async Task IViewFor_WithoutControlRuntimeOrPartial_DeclaresNothing(string source, string runtime) => + await Assert.That(Declarations($"public class Model {{ }} public class Plain {{ }} {source}", Controls + runtime)).IsEqualTo(None); + + /// A view marked both [IReactiveObject] and [IViewFor] implements both interfaces. + /// A task representing the asynchronous test operation. + [Test] + public async Task IViewForAndIReactiveObject_AddBothInterfaces() => + await Assert.That(Declarations( + "public class Model { } [IReactiveObject] [IViewFor] public partial class View : System.Windows.Controls.UserControl { }", + $"{Controls}{ViewRuntimeTypes} namespace ReactiveUI {{ public interface IReactiveObject {{ }} }}")) + .Contains("partial class View : global::ReactiveUI.IReactiveObject, global::ReactiveUI.Binding.IViewFor"); + + /// + /// An access modifier is read only from its own named argument: another argument is stepped over, and a value that is + /// not an access modifier leaves the default. + /// + /// The attribute, with its named arguments. + /// The member the attribute is placed on. + /// The declaration the member gets. + /// A task representing the asynchronous test operation. + [Test] + [Arguments("[ReactiveCommand(CanExecute = nameof(CanSave))]", "private void Save() { } private IObservable CanSave => null;", "public global::ReactiveUI.ReactiveCommand<")] + [Arguments("[Reactive(SetModifier = \"Private\")]", "private string _name;", "public string Name { get { throw null; } set { } }")] + public async Task NamedArguments_ReadOnlyTheirOwnValue(string attribute, string member, string declared) => + await Assert.That(Declarations($"using System; public partial class Model {{ {attribute} {member} }}", PrimitivesReactiveUI)) + .Contains(declared); + /// Members are grouped by the type they belong to, in the order the types are first seen. /// A task representing the asynchronous test operation. [Test] @@ -321,6 +407,12 @@ public partial class Model } """; + /// Declares a runtime's stand-in view types in its namespace. + /// The namespace of the runtime's view types. + /// The stand-in declarations. + private static string RuntimeViewTypes(string runtime) => + $"namespace {runtime} {{ public interface IViewFor {{ }} public interface IViewFor : IViewFor {{ }} }}"; + /// Runs the declarations pipeline over a model, and returns the declarations it wrote. /// The model, which may use ReactiveUI.SourceGenerators' attributes unqualified. /// Stand-in declarations of the ReactiveUI the consumer references.