Skip to content

Commit c8a8c38

Browse files
authored
feat: follow WinForms host properties through ReactiveUI.Binding's ObservedProperty (#506)
With ReactiveUI.Binding 8.4.0 or later, the [RoutedControlHost] and [ViewModelControlHost] hosts follow DefaultContent, Content, ViewModel, Router and ViewContractObservable through Binding's ObservedProperty, in the flavour their view API comes from: Create for WhenAnyValue, and Then and Switch for WhenAnyObservable, with static lambdas. ObservedProperty is not intercepted, so it works from generated code, and keeps WhenAnyValue's semantics. With an older ReactiveUI.Binding, or none, the hosts keep following their own PropertyChanged, and the new ControlHostAnalyzer reports RXUISG0022 (Info) on each host. The generator and the analyzer decide from the same ViewApiRules file, which now also picks the view API. There is no package dependency on Binding: the decision follows the Binding the project references.
1 parent 7158aa0 commit c8a8c38

16 files changed

Lines changed: 754 additions & 55 deletions

File tree

‎CLAUDE.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,10 @@ copies (CS0436).
4444
read it from source, so a consumer keeps no reference to the attributes assembly.
4545
- Generators, analyzers and code fixes stay `netstandard2.0`, the Roslyn host's framework. Only the attributes library
4646
targets `$(LibraryTfms)`.
47+
- Never emit a call ReactiveUI.Binding has to intercept (`WhenAny*`, `Bind`, `OneWayBind`, `BindCommand`): its
48+
generator cannot see another generator's output, so the call has no dispatch and throws at run time. Generated code
49+
that follows properties uses Binding's non-intercepted `ObservedProperty` when `ViewApiRules.HasObservedProperty`
50+
finds it (ReactiveUI.Binding 8.4.0 or later), and its own `PropertyChanged` following otherwise.
4751

4852
Generators report only the `RXUISG*` diagnostics about input they cannot generate from (see
4953
[Analyzer Separation](#analyzer-separation-roslyn-best-practice)). Diagnostics about how code should be written, and
@@ -173,6 +177,7 @@ All diagnostics use the `RXUISG` prefix. All suppressions use the `RXUISPR` pref
173177
| `PropertyToReactiveFieldAnalyzer` | RXUISG0016 | Suggests converting auto-properties to `[Reactive]` properties |
174178
| `ReactiveAttributeMisuseAnalyzer` | RXUISG0020 | Detects `[Reactive]` on non-partial or non-partial-type members |
175179
| `ReactiveCommandAnalyzer` | RXUISG0002, RXUISG0008, RXUISG0021 | Reports `[ReactiveCommand]` methods and schedulers the generator skips |
180+
| `ControlHostAnalyzer` | RXUISG0022 | Reports WinForms hosts generated without ReactiveUI.Binding 8.4.0's `ObservedProperty` (Info) |
176181
| `PropertyToReactiveFieldCodeFixProvider` | — | Converts auto-property → `[Reactive]` partial property (C# 13+; C# 14+ with an initializer), else a `[Reactive]` field |
177182
| `ReactiveAttributeMisuseCodeFixProvider` | — | Fixes misuse of `[Reactive]` attribute |
178183

‎README.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -241,7 +241,9 @@ now covers three features this package used to generate. They have been removed
241241
| RXUISG0014, RXUISG0017 and the RXUISPR0002 suppression | Nothing: they only applied to `[ObservableAsProperty]` |
242242

243243
The Windows Forms `[RoutedControlHost]` and `[ViewModelControlHost]` remain. They resolve views through ReactiveUI's
244-
view locator, or through ReactiveUI.Binding's when the project's ReactiveUI is built on it.
244+
view locator, or through ReactiveUI.Binding's when the project's ReactiveUI is built on it. With ReactiveUI.Binding
245+
8.4.0 or later they follow their own properties through Binding's `ObservedProperty`, with `WhenAnyValue`'s semantics;
246+
with anything older they follow them through `PropertyChanged`, and RXUISG0022 notes the difference.
245247

246248
The ReactiveUI.Binding replacements need a ReactiveUI release built on ReactiveUI.Binding. ReactiveUI 24.3 and earlier
247249
are not: there, ReactiveUI's own `ObservableAsPropertyHelper<T>` and `IViewFor<T>` are the ones in use, so

‎src/Directory.Packages.props‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@
2424
<PackageVersion Include="Avalonia.Themes.Fluent" Version="12.1.3" />
2525
<PackageVersion Include="Avalonia.Fonts.Inter" Version="12.1.3" />
2626
<PackageVersion Include="ReactiveUI.Avalonia" Version="12.1.2" />
27+
<PackageVersion Include="ReactiveUI.Binding" Version="8.4.0" />
28+
<PackageVersion Include="ReactiveUI.Binding.Reactive" Version="8.4.0" />
2729
<PackageVersion Include="Avalonia.Diagnostics" Version="11.3.22" />
2830
<PackageVersion Include="Avalonia.Desktop" Version="12.1.3" />
2931
<PackageVersion Include="Microsoft.Extensions.Logging.Debug" Version="10.0.12" />

‎src/ReactiveUI.SourceGenerator.Tests/ReactiveUI.SourceGenerators.Tests.csproj‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,22 @@
3131
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" PrivateAssets="all" VersionOverride="4.14.0" />
3232
<PackageReference Include="DynamicData" PrivateAssets="all" />
3333
<PackageReference Include="ReactiveUI" />
34+
<!-- The hosts' ObservedProperty, in both flavours; Binding's own generators are not run on the tests. -->
35+
<PackageReference Include="ReactiveUI.Binding" ExcludeAssets="analyzers;build;buildTransitive" PrivateAssets="all" />
36+
<PackageReference Include="ReactiveUI.Binding.Reactive" ExcludeAssets="analyzers;build;buildTransitive" PrivateAssets="all" />
3437
<PackageReference Include="ReactiveUI.Reactive" PrivateAssets="all" />
3538
<PackageReference Include="Splat" />
3639
<PackageReference Include="System.Reactive" PrivateAssets="all" />
3740
</ItemGroup>
3841

42+
<!-- The tests reference ReactiveUI.Binding for its runtime types only; its generator and analyzer still reach the
43+
compiler, so they are removed before it runs. -->
44+
<Target Name="RemoveReactiveUIBindingAnalyzers" BeforeTargets="CoreCompile">
45+
<ItemGroup>
46+
<Analyzer Remove="@(Analyzer)" Condition="'%(Filename)' == 'ReactiveUI.Binding.SourceGenerators' or '%(Filename)' == 'ReactiveUI.Binding.Analyzer'" />
47+
</ItemGroup>
48+
</Target>
49+
3950
<ItemGroup>
4051
<Using Include="TUnit.Assertions" />
4152
<Using Include="TUnit.Core" />
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
// Copyright (c) 2019-2026 ReactiveUI Association Incorporated. All rights reserved.
2+
// ReactiveUI Association Incorporated licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for full license information.
4+
5+
using ReactiveUI.SourceGenerators.WinForms;
6+
7+
namespace ReactiveUI.SourceGenerator.Tests;
8+
9+
/// <summary>Unit tests for <see cref="ControlHostAnalyzer" />.</summary>
10+
public sealed class ControlHostAnalyzerTests
11+
{
12+
/// <summary>A WinForms host generated without ObservedProperty.</summary>
13+
private const string WithoutObservedPropertyId = "RXUISG0022";
14+
15+
/// <summary>Both hosts, and a class that is neither.</summary>
16+
private const string HostsSource = """
17+
using ReactiveUI.SourceGenerators.WinForms;
18+
19+
namespace Hosts
20+
{
21+
[RoutedControlHost("System.Windows.Forms.UserControl")]
22+
public partial class RoutedHost { }
23+
24+
[ViewModelControlHost("System.Windows.Forms.UserControl")]
25+
public partial class ViewModelHost { }
26+
27+
[System.Obsolete]
28+
public class NotAHost { }
29+
}
30+
""";
31+
32+
/// <summary>ReactiveUI.Binding without ObservedProperty: a release before 8.4.0.</summary>
33+
private const string BindingWithoutObservedProperty = """
34+
namespace ReactiveUI.Binding
35+
{
36+
public interface IViewFor<T> { }
37+
}
38+
""";
39+
40+
/// <summary>ReactiveUI.Binding 8.4.0 or later, with ObservedProperty.</summary>
41+
private const string BindingWithObservedProperty = """
42+
namespace ReactiveUI.Binding
43+
{
44+
public interface IViewFor<T> { }
45+
46+
public static class ObservedProperty { }
47+
}
48+
""";
49+
50+
/// <summary>Each host is reported when the compilation has no ReactiveUI.Binding with ObservedProperty.</summary>
51+
/// <param name="bindingSource">Source standing in for ReactiveUI.Binding, or none.</param>
52+
/// <returns>A task that represents the asynchronous test operation.</returns>
53+
[Test]
54+
[Arguments("")]
55+
[Arguments(BindingWithoutObservedProperty)]
56+
public async Task ReportsHostsWithoutObservedProperty(string bindingSource)
57+
{
58+
var reported = await GetReported(bindingSource);
59+
60+
await Assert.That(reported).IsEquivalentTo(["RoutedHost", "ViewModelHost"]);
61+
}
62+
63+
/// <summary>No host is reported when ReactiveUI.Binding has ObservedProperty.</summary>
64+
/// <returns>A task that represents the asynchronous test operation.</returns>
65+
[Test]
66+
public async Task DoesNotReportHostsWithObservedProperty() =>
67+
await Assert.That(await GetReported(BindingWithObservedProperty)).IsEmpty();
68+
69+
/// <summary>The diagnostic names the ReactiveUI.Binding version that has ObservedProperty.</summary>
70+
/// <returns>A task that represents the asynchronous test operation.</returns>
71+
[Test]
72+
public async Task NamesTheMinimumBindingVersion()
73+
{
74+
var descriptor = new ControlHostAnalyzer().SupportedDiagnostics[0];
75+
var message = Diagnostic.Create(descriptor, Location.None, "RoutedHost", "8.4.0").GetMessage(System.Globalization.CultureInfo.InvariantCulture);
76+
77+
await Assert.That(descriptor.Id).IsEqualTo(WithoutObservedPropertyId);
78+
await Assert.That(descriptor.DefaultSeverity).IsEqualTo(DiagnosticSeverity.Info);
79+
await Assert.That(message).Contains("ReactiveUI.Binding 8.4.0 or later");
80+
}
81+
82+
/// <summary>A null analysis context is rejected.</summary>
83+
/// <returns>A task that represents the asynchronous test operation.</returns>
84+
[Test]
85+
public async Task InitializeRejectsANullContext() =>
86+
await Assert.That(static () => new ControlHostAnalyzer().Initialize(null!)).Throws<ArgumentNullException>();
87+
88+
/// <summary>Analyzes the hosts with a ReactiveUI.Binding stand-in and gets the text each host is reported at.</summary>
89+
/// <param name="bindingSource">Source standing in for ReactiveUI.Binding, or none.</param>
90+
/// <returns>The source text at each reported location.</returns>
91+
private static async Task<List<string>> GetReported(string bindingSource)
92+
{
93+
var parseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp13);
94+
var tree = CSharpSyntaxTree.ParseText(HostsSource, parseOptions);
95+
var compilation = CSharpCompilation.Create(
96+
nameof(ControlHostAnalyzerTests),
97+
[tree, CSharpSyntaxTree.ParseText(bindingSource, parseOptions)],
98+
TestCompilationReferences.CreateForAssemblies(typeof(object).Assembly, typeof(RoutedControlHostAttribute).Assembly),
99+
new(OutputKind.DynamicallyLinkedLibrary));
100+
var diagnostics = await compilation.WithAnalyzers([new ControlHostAnalyzer()]).GetAnalyzerDiagnosticsAsync();
101+
var text = await tree.GetTextAsync();
102+
103+
var reported = new List<string>();
104+
foreach (var diagnostic in diagnostics)
105+
{
106+
if (diagnostic.Id == WithoutObservedPropertyId)
107+
{
108+
reported.Add(text.ToString(diagnostic.Location.SourceSpan));
109+
}
110+
}
111+
112+
return reported;
113+
}
114+
}

0 commit comments

Comments
 (0)