From d06828f29c81959d02cd7108b6423e3e1d2a1967 Mon Sep 17 00:00:00 2001 From: Glenn Watson <5834289+glennawatson@users.noreply.github.com> Date: Sun, 22 Nov 2026 04:01:30 +1100 Subject: [PATCH] feat: add compile-time generators for views, AutoPersist, validation, and Android controls - Add [RegisterView] and [RegisterView] to generate GeneratedViewRegistrations.RegisterGeneratedViews for IReactiveUIBuilder without assembly scanning. - Add [AutoPersist] to generate static AutoPersistMetadata from [DataContract] and [DataMember] attributes at compile time. - Add [ReactiveValidation] to generate ConfigureValidation() wiring DataAnnotations attributes onto ReactiveProperty properties via the reflection-free AddValidation overload. - Add [WireUpControls], [WireUpResource], and [IgnoreResource] in ReactiveUI.SourceGenerators.Android to generate compile-time FindViewById wiring. - Update public API baselines, documentation, and unit and incremental caching tests. --- .../AttributeDefinitions.cs | 21 ++ .../AutoPersist/AutoPersistGenerator.cs | 172 ++++++++++++ .../AutoPersist/Models/AutoPersistInfo.cs | 16 ++ .../Core/Helpers/TrackingNames.cs | 12 + .../Models/ReactiveValidationInfo.cs | 14 + .../Models/ValidatedPropertyInfo.cs | 16 ++ .../ReactiveValidationGenerator.cs | 250 +++++++++++++++++ .../RegisterView/Models/RegisteredViewInfo.cs | 16 ++ .../RegisterView/RegisterViewGenerator.cs | 265 ++++++++++++++++++ .../Models/WireUpControlsInfo.cs | 18 ++ .../WireUpControls/Models/WiredControlInfo.cs | 14 + .../WireUpControls/WireUpControlsGenerator.cs | 249 ++++++++++++++++ .../Android/IgnoreResourceAttribute.cs | 14 + .../Android/WireUpControlsAttribute.cs | 18 ++ .../Android/WireUpResourceAttribute.cs | 19 ++ .../AutoPersistAttribute.cs | 14 + .../PublicAPI/net10.0/PublicAPI.txt | 59 ++++ .../PublicAPI/net11.0/PublicAPI.txt | 59 ++++ .../PublicAPI/net47/PublicAPI.txt | 59 ++++ .../PublicAPI/net471/PublicAPI.txt | 59 ++++ .../PublicAPI/net472/PublicAPI.txt | 59 ++++ .../PublicAPI/net48/PublicAPI.txt | 59 ++++ .../PublicAPI/net481/PublicAPI.txt | 59 ++++ src/ReactiveUI.SourceGenerators/README.md | 4 + .../ReactiveValidationAttribute.cs | 14 + .../RegisterViewAttribute.cs | 21 ++ .../RegisterViewAttribute{T}.cs | 26 ++ .../UnitTests/AutoPersistGeneratorTests.cs | 100 +++++++ .../UnitTests/IncrementalCachingTests.cs | 50 ++++ .../ReactiveValidationGeneratorTests.cs | 100 +++++++ .../UnitTests/RegisterViewGeneratorTests.cs | 101 +++++++ .../UnitTests/WireUpControlsGeneratorTests.cs | 150 ++++++++++ 32 files changed, 2107 insertions(+) create mode 100644 src/ReactiveUI.SourceGenerators.Roslyn/AutoPersist/AutoPersistGenerator.cs create mode 100644 src/ReactiveUI.SourceGenerators.Roslyn/AutoPersist/Models/AutoPersistInfo.cs create mode 100644 src/ReactiveUI.SourceGenerators.Roslyn/ReactiveValidation/Models/ReactiveValidationInfo.cs create mode 100644 src/ReactiveUI.SourceGenerators.Roslyn/ReactiveValidation/Models/ValidatedPropertyInfo.cs create mode 100644 src/ReactiveUI.SourceGenerators.Roslyn/ReactiveValidation/ReactiveValidationGenerator.cs create mode 100644 src/ReactiveUI.SourceGenerators.Roslyn/RegisterView/Models/RegisteredViewInfo.cs create mode 100644 src/ReactiveUI.SourceGenerators.Roslyn/RegisterView/RegisterViewGenerator.cs create mode 100644 src/ReactiveUI.SourceGenerators.Roslyn/WireUpControls/Models/WireUpControlsInfo.cs create mode 100644 src/ReactiveUI.SourceGenerators.Roslyn/WireUpControls/Models/WiredControlInfo.cs create mode 100644 src/ReactiveUI.SourceGenerators.Roslyn/WireUpControls/WireUpControlsGenerator.cs create mode 100644 src/ReactiveUI.SourceGenerators/Android/IgnoreResourceAttribute.cs create mode 100644 src/ReactiveUI.SourceGenerators/Android/WireUpControlsAttribute.cs create mode 100644 src/ReactiveUI.SourceGenerators/Android/WireUpResourceAttribute.cs create mode 100644 src/ReactiveUI.SourceGenerators/AutoPersistAttribute.cs create mode 100644 src/ReactiveUI.SourceGenerators/ReactiveValidationAttribute.cs create mode 100644 src/ReactiveUI.SourceGenerators/RegisterViewAttribute.cs create mode 100644 src/ReactiveUI.SourceGenerators/RegisterViewAttribute{T}.cs create mode 100644 src/tests/ReactiveUI.SourceGenerators.Tests/UnitTests/AutoPersistGeneratorTests.cs create mode 100644 src/tests/ReactiveUI.SourceGenerators.Tests/UnitTests/ReactiveValidationGeneratorTests.cs create mode 100644 src/tests/ReactiveUI.SourceGenerators.Tests/UnitTests/RegisterViewGeneratorTests.cs create mode 100644 src/tests/ReactiveUI.SourceGenerators.Tests/UnitTests/WireUpControlsGeneratorTests.cs diff --git a/src/ReactiveUI.SourceGenerators.Roslyn/AttributeDefinitions.cs b/src/ReactiveUI.SourceGenerators.Roslyn/AttributeDefinitions.cs index 8a77cc7d..395701ea 100644 --- a/src/ReactiveUI.SourceGenerators.Roslyn/AttributeDefinitions.cs +++ b/src/ReactiveUI.SourceGenerators.Roslyn/AttributeDefinitions.cs @@ -41,6 +41,27 @@ internal static class AttributeDefinitions /// The metadata name of [ReactiveCollection]. public const string ReactiveCollectionAttributeType = "ReactiveUI.SourceGenerators.ReactiveCollectionAttribute"; + /// The metadata name of [RegisterView]. + public const string RegisterViewAttributeType = "ReactiveUI.SourceGenerators.RegisterViewAttribute"; + + /// The metadata name of [RegisterView<T>]. + public const string RegisterViewGenericAttributeType = "ReactiveUI.SourceGenerators.RegisterViewAttribute`1"; + + /// The metadata name of [AutoPersist]. + public const string AutoPersistAttributeType = "ReactiveUI.SourceGenerators.AutoPersistAttribute"; + + /// The metadata name of [ReactiveValidation]. + public const string ReactiveValidationAttributeType = "ReactiveUI.SourceGenerators.ReactiveValidationAttribute"; + + /// The metadata name of [WireUpControls]. + public const string WireUpControlsAttributeType = "ReactiveUI.SourceGenerators.Android.WireUpControlsAttribute"; + + /// The metadata name of [WireUpResource]. + public const string WireUpResourceAttributeType = "ReactiveUI.SourceGenerators.Android.WireUpResourceAttribute"; + + /// The metadata name of [IgnoreResource]. + public const string IgnoreResourceAttributeType = "ReactiveUI.SourceGenerators.Android.IgnoreResourceAttribute"; + /// The attribute that excludes a generated control host from code coverage. public const string ExcludeFromCodeCoverage = "[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]"; } diff --git a/src/ReactiveUI.SourceGenerators.Roslyn/AutoPersist/AutoPersistGenerator.cs b/src/ReactiveUI.SourceGenerators.Roslyn/AutoPersist/AutoPersistGenerator.cs new file mode 100644 index 00000000..3737ea9b --- /dev/null +++ b/src/ReactiveUI.SourceGenerators.Roslyn/AutoPersist/AutoPersistGenerator.cs @@ -0,0 +1,172 @@ +// Copyright (c) 2019-2026 ReactiveUI and Contributors. All rights reserved. +// ReactiveUI and Contributors licenses this file to you under the MIT license. +// See the LICENSE file in the project root for full license information. + +using System.Threading; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using ReactiveUI.SourceGenerators.CodeGeneration; +using ReactiveUI.SourceGenerators.Extensions; +using ReactiveUI.SourceGenerators.Helpers; +using ReactiveUI.SourceGenerators.Models; + +namespace ReactiveUI.SourceGenerators; + +/// Generates a compile-time AutoPersistMetadata static property for classes marked with [AutoPersist]. +[Generator(LanguageNames.CSharp)] +public sealed class AutoPersistGenerator : IIncrementalGenerator +{ + /// The metadata name of DataContractAttribute. + private const string DataContractAttributeName = "System.Runtime.Serialization.DataContractAttribute"; + + /// The metadata name of DataMemberAttribute. + private const string DataMemberAttributeName = "System.Runtime.Serialization.DataMemberAttribute"; + + /// The fully qualified generator name written to generated-code attributes. + private static readonly string GeneratorName = typeof(AutoPersistGenerator).FullName!; + + /// The generator assembly version written to generated-code attributes. + private static readonly string GeneratorVersion = typeof(AutoPersistGenerator).Assembly.GetName().Version.ToString(); + + /// The GeneratedCode attribute stamped on generated members. + private static readonly string GeneratedCodeAttribute = SourceWriterExtensions.GeneratedCodeAttribute(GeneratorName, GeneratorVersion); + + /// + public void Initialize(IncrementalGeneratorInitializationContext context) + { + var targets = + context.SyntaxProvider + .ForAttributeWithMetadataName( + AttributeDefinitions.AutoPersistAttributeType, + static (node, _) => node is ClassDeclarationSyntax, + static (ctx, token) => ExtractInfo(in ctx, token)) + .Where(static x => x is not null) + .Select(static (x, _) => x!) + .WithTrackingName(TrackingNames.AutoPersistTypes); + + context.RegisterSourceOutput( + targets.Combine(context.ReactiveUiIntegration()), + static (spc, input) => spc.AddSource( + $"{input.Left.TargetInfo.FileHintName}.AutoPersist.g.cs", + GenerateSource(input.Left, input.Right))); + } + + /// Extracts [DataContract] and [DataMember] metadata from an attributed class. + /// The generator attribute syntax context. + /// The cancellation token. + /// The extracted metadata, or when the class is not partial. + private static AutoPersistInfo? ExtractInfo(in GeneratorAttributeSyntaxContext context, CancellationToken token) + { + if (!((ClassDeclarationSyntax)context.TargetNode).Modifiers.Any(SyntaxKind.PartialKeyword)) + { + return null; + } + + token.ThrowIfCancellationRequested(); + + var classSymbol = (INamedTypeSymbol)context.TargetSymbol; + var hasDataContract = HasAttributeInHierarchy(classSymbol, DataContractAttributeName); + + using var propertyNames = ArrayBuilder.Rent(); + foreach (var member in classSymbol.GetMembers()) + { + token.ThrowIfCancellationRequested(); + + if (member is not IPropertySymbol { IsStatic: false, DeclaredAccessibility: Accessibility.Public } property) + { + continue; + } + + if (HasAttribute(property, DataMemberAttributeName)) + { + propertyNames.Add(property.Name); + } + } + + return new(TargetInfo.From(classSymbol), hasDataContract, propertyNames.ToEquatableArray()); + } + + /// Checks whether a type or any of its base types carries the specified attribute. + /// The type symbol. + /// The full metadata name of the attribute. + /// if found; otherwise . + private static bool HasAttributeInHierarchy(INamedTypeSymbol typeSymbol, string attributeMetadataName) + { + for (var current = typeSymbol; current is not null; current = current.BaseType) + { + if (HasAttribute(current, attributeMetadataName)) + { + return true; + } + } + + return false; + } + + /// Checks whether a symbol directly carries the specified attribute. + /// The symbol to inspect. + /// The full metadata name of the attribute. + /// if found; otherwise . + private static bool HasAttribute(ISymbol symbol, string attributeMetadataName) + { + foreach (var attribute in symbol.GetAttributes()) + { + if (attribute.AttributeClass?.ToDisplayString() == attributeMetadataName) + { + return true; + } + } + + return false; + } + + /// Generates the partial class declaring AutoPersistMetadata. + /// The extracted persistence metadata. + /// The detected ReactiveUI integration. + /// The generated C# source. + private static string GenerateSource(AutoPersistInfo info, ReactiveUiIntegration integration) + { + var metadataType = $"{integration.Namespace}.AutoPersistHelperMixins.AutoPersistMetadata"; + var hasDataContractLiteral = info.HasDataContract ? "true" : "false"; + + var writer = SourceWriter.Rent(); + _ = writer.AutoGenerated() + .DisableWarningsEnableNullable() + .BlankLine(); + + var depth = writer.OpenNamespace(info.TargetInfo.TargetNamespace) + + writer.OpenContainingTypes(info.TargetInfo.ParentInfo); + + _ = writer.OpenPartialType(info.TargetInfo) + .Summary("Gets compile-time AutoPersist metadata generated without runtime reflection.") + .Line(GeneratedCodeAttribute) + .Line(SourceWriterExtensions.ExcludeFromCodeCoverageAttribute) + .Append("public static ").Append(metadataType).Line(" AutoPersistMetadata { get; } =") + .Indent() + .Append("new ").Append(metadataType).Append('(').Append(hasDataContractLiteral) + .Append(", new global::System.Collections.Generic.HashSet(global::System.StringComparer.Ordinal)"); + + if (info.PersistablePropertyNames.IsEmpty) + { + _ = writer.Line(");"); + } + else + { + _ = writer.EndLine().OpenBlock(); + foreach (var name in info.PersistablePropertyNames) + { + _ = writer.Append(SymbolDisplay.FormatLiteral(name, quote: true)).Line(","); + } + + _ = writer.Outdent().Line("});"); + } + + _ = writer.Outdent() + .CloseBlock() + .CloseBlocks(depth) + .RestoreNullableAndWarnings(); + + return writer.ToStringAndReturn(); + } +} diff --git a/src/ReactiveUI.SourceGenerators.Roslyn/AutoPersist/Models/AutoPersistInfo.cs b/src/ReactiveUI.SourceGenerators.Roslyn/AutoPersist/Models/AutoPersistInfo.cs new file mode 100644 index 00000000..48883ccd --- /dev/null +++ b/src/ReactiveUI.SourceGenerators.Roslyn/AutoPersist/Models/AutoPersistInfo.cs @@ -0,0 +1,16 @@ +// Copyright (c) 2019-2026 ReactiveUI and Contributors. All rights reserved. +// ReactiveUI and Contributors licenses this file to you under the MIT license. +// See the LICENSE file in the project root for full license information. + +using ReactiveUI.SourceGenerators.Helpers; + +namespace ReactiveUI.SourceGenerators.Models; + +/// Describes compile-time persistence metadata extracted from a type marked with [AutoPersist]. +/// The target type metadata. +/// Whether the target type is annotated with [DataContract]. +/// The public instance property names annotated with [DataMember]. +internal sealed record AutoPersistInfo( + TargetInfo TargetInfo, + bool HasDataContract, + EquatableArray PersistablePropertyNames); diff --git a/src/ReactiveUI.SourceGenerators.Roslyn/Core/Helpers/TrackingNames.cs b/src/ReactiveUI.SourceGenerators.Roslyn/Core/Helpers/TrackingNames.cs index 31b7958f..26721c3c 100644 --- a/src/ReactiveUI.SourceGenerators.Roslyn/Core/Helpers/TrackingNames.cs +++ b/src/ReactiveUI.SourceGenerators.Roslyn/Core/Helpers/TrackingNames.cs @@ -48,4 +48,16 @@ internal static class TrackingNames /// The [ViewModelControlHost] models. internal const string ViewModelControlHosts = nameof(ViewModelControlHosts); + + /// The [RegisterView] models. + internal const string RegisteredViews = nameof(RegisteredViews); + + /// The [AutoPersist] models. + internal const string AutoPersistTypes = nameof(AutoPersistTypes); + + /// The [ReactiveValidation] models. + internal const string ReactiveValidationTypes = nameof(ReactiveValidationTypes); + + /// The [WireUpControls] models. + internal const string WireUpControlsTypes = nameof(WireUpControlsTypes); } diff --git a/src/ReactiveUI.SourceGenerators.Roslyn/ReactiveValidation/Models/ReactiveValidationInfo.cs b/src/ReactiveUI.SourceGenerators.Roslyn/ReactiveValidation/Models/ReactiveValidationInfo.cs new file mode 100644 index 00000000..13d117db --- /dev/null +++ b/src/ReactiveUI.SourceGenerators.Roslyn/ReactiveValidation/Models/ReactiveValidationInfo.cs @@ -0,0 +1,14 @@ +// Copyright (c) 2019-2026 ReactiveUI and Contributors. All rights reserved. +// ReactiveUI and Contributors licenses this file to you under the MIT license. +// See the LICENSE file in the project root for full license information. + +using ReactiveUI.SourceGenerators.Helpers; + +namespace ReactiveUI.SourceGenerators.Models; + +/// Describes compile-time DataAnnotations validation wiring for a class marked with [ReactiveValidation]. +/// The target type metadata. +/// The validated ReactiveProperty<T> properties on the class. +internal sealed record ReactiveValidationInfo( + TargetInfo TargetInfo, + EquatableArray Properties); diff --git a/src/ReactiveUI.SourceGenerators.Roslyn/ReactiveValidation/Models/ValidatedPropertyInfo.cs b/src/ReactiveUI.SourceGenerators.Roslyn/ReactiveValidation/Models/ValidatedPropertyInfo.cs new file mode 100644 index 00000000..18273c20 --- /dev/null +++ b/src/ReactiveUI.SourceGenerators.Roslyn/ReactiveValidation/Models/ValidatedPropertyInfo.cs @@ -0,0 +1,16 @@ +// Copyright (c) 2019-2026 ReactiveUI and Contributors. All rights reserved. +// ReactiveUI and Contributors licenses this file to you under the MIT license. +// See the LICENSE file in the project root for full license information. + +using ReactiveUI.SourceGenerators.Helpers; + +namespace ReactiveUI.SourceGenerators.Models; + +/// Describes a ReactiveProperty<T> property and its DataAnnotations validation attributes. +/// The property name on the declaring class. +/// The display name from [Display(Name = ...)], or the property name. +/// The validation attributes applied to the property. +internal sealed record ValidatedPropertyInfo( + string PropertyName, + string DisplayName, + EquatableArray ValidationAttributes); diff --git a/src/ReactiveUI.SourceGenerators.Roslyn/ReactiveValidation/ReactiveValidationGenerator.cs b/src/ReactiveUI.SourceGenerators.Roslyn/ReactiveValidation/ReactiveValidationGenerator.cs new file mode 100644 index 00000000..6fcc5571 --- /dev/null +++ b/src/ReactiveUI.SourceGenerators.Roslyn/ReactiveValidation/ReactiveValidationGenerator.cs @@ -0,0 +1,250 @@ +// Copyright (c) 2019-2026 ReactiveUI and Contributors. All rights reserved. +// ReactiveUI and Contributors licenses this file to you under the MIT license. +// See the LICENSE file in the project root for full license information. + +using System.Threading; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using ReactiveUI.SourceGenerators.CodeGeneration; +using ReactiveUI.SourceGenerators.Extensions; +using ReactiveUI.SourceGenerators.Helpers; +using ReactiveUI.SourceGenerators.Models; + +namespace ReactiveUI.SourceGenerators; + +/// Generates a compile-time ConfigureValidation method for classes marked with [ReactiveValidation]. +[Generator(LanguageNames.CSharp)] +public sealed class ReactiveValidationGenerator : IIncrementalGenerator +{ + /// The metadata name of ValidationAttribute. + private const string ValidationAttributeName = "System.ComponentModel.DataAnnotations.ValidationAttribute"; + + /// The metadata name of DisplayAttribute. + private const string DisplayAttributeName = "System.ComponentModel.DataAnnotations.DisplayAttribute"; + + /// Initial builder capacity padding beyond the attribute type name length. + private const int AttributeExpressionPadding = 64; + + /// The fully qualified generator name written to generated-code attributes. + private static readonly string GeneratorName = typeof(ReactiveValidationGenerator).FullName!; + + /// The generator assembly version written to generated-code attributes. + private static readonly string GeneratorVersion = typeof(ReactiveValidationGenerator).Assembly.GetName().Version.ToString(); + + /// The GeneratedCode attribute stamped on generated members. + private static readonly string GeneratedCodeAttribute = SourceWriterExtensions.GeneratedCodeAttribute(GeneratorName, GeneratorVersion); + + /// + public void Initialize(IncrementalGeneratorInitializationContext context) + { + var targets = + context.SyntaxProvider + .ForAttributeWithMetadataName( + AttributeDefinitions.ReactiveValidationAttributeType, + static (node, _) => node is ClassDeclarationSyntax, + static (ctx, token) => ExtractInfo(in ctx, token)) + .Where(static x => x is not null) + .Select(static (x, _) => x!) + .WithTrackingName(TrackingNames.ReactiveValidationTypes); + + context.RegisterSourceOutput( + targets.Combine(context.ReactiveUiIntegration()), + static (spc, input) => spc.AddSource( + $"{input.Left.TargetInfo.FileHintName}.ReactiveValidation.g.cs", + GenerateSource(input.Left, input.Right))); + } + + /// Extracts DataAnnotations validation attributes from ReactiveProperty<T> properties on the target class. + /// The generator attribute syntax context. + /// The cancellation token. + /// The extracted validation model, or when the class is not partial. + private static ReactiveValidationInfo? ExtractInfo(in GeneratorAttributeSyntaxContext context, CancellationToken token) + { + if (!((ClassDeclarationSyntax)context.TargetNode).Modifiers.Any(SyntaxKind.PartialKeyword)) + { + return null; + } + + token.ThrowIfCancellationRequested(); + + var classSymbol = (INamedTypeSymbol)context.TargetSymbol; + using var properties = ArrayBuilder.Rent(); + + foreach (var member in classSymbol.GetMembers()) + { + token.ThrowIfCancellationRequested(); + + if (member is not IPropertySymbol { IsStatic: false } property || !IsReactivePropertyType(property.Type)) + { + continue; + } + + if (TryExtractValidatedProperty(property) is { } validated) + { + properties.Add(validated); + } + } + + return new(TargetInfo.From(classSymbol), properties.ToEquatableArray()); + } + + /// Extracts validation attributes and display name for a single ReactiveProperty<T> property. + /// The property symbol. + /// The validated property info, or if no validation attributes are present. + private static ValidatedPropertyInfo? TryExtractValidatedProperty(IPropertySymbol property) + { + string? displayName = null; + using var validationAttributes = ArrayBuilder.Rent(); + + foreach (var attribute in property.GetAttributes()) + { + if (attribute.AttributeClass is not { } attributeClass) + { + continue; + } + + if (attributeClass.ToDisplayString() == DisplayAttributeName) + { + displayName = TryGetDisplayName(attribute) ?? displayName; + continue; + } + + if (DerivesFrom(attributeClass, ValidationAttributeName)) + { + validationAttributes.Add(AttributeInfo.Create(attribute)); + } + } + + return validationAttributes.Count > 0 + ? new(property.Name, displayName ?? property.Name, validationAttributes.ToEquatableArray()) + : null; + } + + /// Extracts the Name named argument from a [Display] attribute. + /// The attribute data. + /// The display name, or if not specified. + private static string? TryGetDisplayName(AttributeData attribute) + { + foreach (var named in attribute.NamedArguments) + { + if (named.Key == "Name" && named.Value.Value is string nameValue) + { + return nameValue; + } + } + + return null; + } + + /// Checks whether a type symbol is ReactiveProperty<T>. + /// The property type symbol. + /// if the type is ReactiveProperty<T>; otherwise . + private static bool IsReactivePropertyType(ITypeSymbol typeSymbol) => + typeSymbol is INamedTypeSymbol { Name: "ReactiveProperty", TypeArguments.Length: 1 }; + + /// Checks whether equals or derives from the named base type. + /// The attribute type symbol. + /// The base type metadata name. + /// if it derives from the base type; otherwise . + private static bool DerivesFrom(INamedTypeSymbol typeSymbol, string baseMetadataName) + { + for (var current = typeSymbol; current is not null; current = current.BaseType) + { + if (current.ToDisplayString() == baseMetadataName) + { + return true; + } + } + + return false; + } + + /// Generates the partial class containing ConfigureValidation(). + /// The validation model. + /// The detected ReactiveUI integration. + /// The generated C# source. + private static string GenerateSource(ReactiveValidationInfo info, ReactiveUiIntegration integration) + { + var mixinsType = $"{integration.Namespace}.ReactivePropertyMixins"; + + var writer = SourceWriter.Rent(); + _ = writer.AutoGenerated() + .DisableWarningsEnableNullable() + .BlankLine(); + + var depth = writer.OpenNamespace(info.TargetInfo.TargetNamespace) + + writer.OpenContainingTypes(info.TargetInfo.ParentInfo); + + _ = writer.OpenPartialType(info.TargetInfo) + .Summary("Wires DataAnnotations validation attributes on ReactiveProperty properties without runtime reflection.") + .Line(GeneratedCodeAttribute) + .Line(SourceWriterExtensions.ExcludeFromCodeCoverageAttribute) + .Line("private void ConfigureValidation()") + .OpenBlock(); + + foreach (var property in info.Properties) + { + _ = writer.Append("if (this.").Append(property.PropertyName).Line(" is not null)") + .OpenBlock() + .Append(mixinsType).Append(".AddValidation(this.").Append(property.PropertyName) + .Append(", ").Append(SymbolDisplay.FormatLiteral(property.DisplayName, quote: true)); + + foreach (var attribute in property.ValidationAttributes) + { + _ = writer.Append(", ").Append(FormatAttributeInstantiation(attribute)); + } + + _ = writer.Line(");") + .CloseBlock(); + } + + _ = writer.CloseBlock() + .CloseBlock() + .CloseBlocks(depth) + .RestoreNullableAndWarnings(); + + return writer.ToStringAndReturn(); + } + + /// Formats an as a C# new AttributeType(...) { ... } expression. + /// The attribute info. + /// The C# object-creation expression. + private static string FormatAttributeInstantiation(AttributeInfo attribute) + { + var ctorArgs = attribute.ConstructorArgumentInfo.AsSpan(); + var namedArgs = attribute.NamedArgumentInfo.AsSpan(); + var builder = PooledBuilder.Rent(attribute.TypeName.Length + AttributeExpressionPadding); + + _ = builder.Append("new ").Append(attribute.TypeName).Append('('); + for (var i = 0; i < ctorArgs.Length; i++) + { + if (i > 0) + { + _ = builder.Append(", "); + } + + _ = builder.Append(ctorArgs[i].Expression); + } + + _ = builder.Append(')'); + + if (!namedArgs.IsEmpty) + { + _ = builder.Append(" { "); + for (var i = 0; i < namedArgs.Length; i++) + { + if (i > 0) + { + _ = builder.Append(", "); + } + + _ = builder.Append(namedArgs[i].Name).Append(" = ").Append(namedArgs[i].Value.Expression); + } + + _ = builder.Append(" }"); + } + + return PooledBuilder.ToStringAndReturn(builder); + } +} diff --git a/src/ReactiveUI.SourceGenerators.Roslyn/RegisterView/Models/RegisteredViewInfo.cs b/src/ReactiveUI.SourceGenerators.Roslyn/RegisterView/Models/RegisteredViewInfo.cs new file mode 100644 index 00000000..203effc8 --- /dev/null +++ b/src/ReactiveUI.SourceGenerators.Roslyn/RegisterView/Models/RegisteredViewInfo.cs @@ -0,0 +1,16 @@ +// Copyright (c) 2019-2026 ReactiveUI and Contributors. All rights reserved. +// ReactiveUI and Contributors licenses this file to you under the MIT license. +// See the LICENSE file in the project root for full license information. + +namespace ReactiveUI.SourceGenerators.Models; + +/// Describes a view registration extracted from [RegisterView] or [RegisterView<TViewModel>]. +/// The fully qualified view type name. +/// The fully qualified view model type name. +/// The optional view contract, or for the default contract. +/// Whether to register the view as a singleton. +internal sealed record RegisteredViewInfo( + string ViewTypeName, + string ViewModelTypeName, + string? Contract, + bool IsSingleton); diff --git a/src/ReactiveUI.SourceGenerators.Roslyn/RegisterView/RegisterViewGenerator.cs b/src/ReactiveUI.SourceGenerators.Roslyn/RegisterView/RegisterViewGenerator.cs new file mode 100644 index 00000000..c8e09d66 --- /dev/null +++ b/src/ReactiveUI.SourceGenerators.Roslyn/RegisterView/RegisterViewGenerator.cs @@ -0,0 +1,265 @@ +// Copyright (c) 2019-2026 ReactiveUI and Contributors. All rights reserved. +// ReactiveUI and Contributors licenses this file to you under the MIT license. +// See the LICENSE file in the project root for full license information. + +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Threading; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using ReactiveUI.SourceGenerators.CodeGeneration; +using ReactiveUI.SourceGenerators.Extensions; +using ReactiveUI.SourceGenerators.Helpers; +using ReactiveUI.SourceGenerators.Models; + +namespace ReactiveUI.SourceGenerators; + +/// Generates a compile-time RegisterGeneratedViews extension method for all views marked with [RegisterView]. +[Generator(LanguageNames.CSharp)] +public sealed class RegisterViewGenerator : IIncrementalGenerator +{ + /// The fully qualified generator name written to generated-code attributes. + private static readonly string GeneratorName = typeof(RegisterViewGenerator).FullName!; + + /// The generator assembly version written to generated-code attributes. + private static readonly string GeneratorVersion = typeof(RegisterViewGenerator).Assembly.GetName().Version.ToString(); + + /// The GeneratedCode attribute stamped on the generated class. + private static readonly string GeneratedCodeAttribute = SourceWriterExtensions.GeneratedCodeAttribute(GeneratorName, GeneratorVersion); + + /// + public void Initialize(IncrementalGeneratorInitializationContext context) + { + var nonGenericViews = + context.SyntaxProvider + .ForAttributeWithMetadataName( + AttributeDefinitions.RegisterViewAttributeType, + static (node, _) => node is ClassDeclarationSyntax, + static (ctx, token) => ExtractRegistrations(in ctx, isGeneric: false, token)) + .SelectMany(static (items, _) => items); + + var genericViews = + context.SyntaxProvider + .ForAttributeWithMetadataName( + AttributeDefinitions.RegisterViewGenericAttributeType, + static (node, _) => node is ClassDeclarationSyntax, + static (ctx, token) => ExtractRegistrations(in ctx, isGeneric: true, token)) + .SelectMany(static (items, _) => items); + + var allViews = nonGenericViews + .Collect() + .Combine(genericViews.Collect()) + .Select(static (pair, _) => MergeAndSort(pair.Left, pair.Right)) + .WithTrackingName(TrackingNames.RegisteredViews); + + context.RegisterSourceOutput( + allViews.Combine(context.ReactiveUiIntegration()), + static (spc, input) => + { + if (input.Left.IsEmpty) + { + return; + } + + spc.AddSource( + "GeneratedViewRegistrations.g.cs", + GenerateSource(input.Left, input.Right)); + }); + } + + /// Extracts view registration entries from an attributed view class. + /// The generator attribute syntax context. + /// Whether the attribute matched was the generic RegisterViewAttribute<TViewModel>. + /// The cancellation token. + /// The extracted registration entries. + private static EquatableArray ExtractRegistrations( + in GeneratorAttributeSyntaxContext context, + bool isGeneric, + CancellationToken token) + { + token.ThrowIfCancellationRequested(); + + var classSymbol = (INamedTypeSymbol)context.TargetSymbol; + if (classSymbol.IsAbstract || !classSymbol.TypeParameters.IsEmpty) + { + return default; + } + + var viewTypeName = classSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + using var builder = ArrayBuilder.Rent(); + + foreach (var attribute in context.Attributes) + { + token.ThrowIfCancellationRequested(); + + if (TryCreateRegistration(classSymbol, viewTypeName, attribute, isGeneric) is { } registration) + { + builder.Add(registration); + } + } + + return builder.ToEquatableArray(); + } + + /// Creates a single registration entry from an attribute application. + /// The view class symbol. + /// The fully qualified view type name. + /// The attribute data. + /// Whether the attribute is generic. + /// The registration info, or if the view model type could not be determined. + private static RegisteredViewInfo? TryCreateRegistration( + INamedTypeSymbol classSymbol, + string viewTypeName, + AttributeData attribute, + bool isGeneric) + { + var viewModelTypeName = isGeneric + ? GetGenericViewModelTypeName(attribute) + : InferViewModelTypeName(classSymbol); + + if (viewModelTypeName is null) + { + return null; + } + + string? contract = null; + var isSingleton = false; + + foreach (var named in attribute.NamedArguments) + { + if (named.Key == "Contract" && named.Value.Value is string contractValue) + { + contract = contractValue; + } + else if (named.Key == "IsSingleton" && named.Value.Value is bool singletonValue) + { + isSingleton = singletonValue; + } + } + + return new(viewTypeName, viewModelTypeName, contract, isSingleton); + } + + /// Gets the view model type name from RegisterViewAttribute<TViewModel>. + /// The attribute data. + /// The fully qualified view model type name, or . + private static string? GetGenericViewModelTypeName(AttributeData attribute) => + attribute.AttributeClass is { TypeArguments.Length: 1 } attrClass + ? attrClass.TypeArguments[0].ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) + : null; + + /// Infers the view model type name from an implemented IViewFor<T> interface or [IViewFor<T>] attribute. + /// The view class symbol. + /// The fully qualified view model type name, or . + private static string? InferViewModelTypeName(INamedTypeSymbol classSymbol) + { + foreach (var iface in classSymbol.AllInterfaces) + { + if (iface.Name == "IViewFor" && iface.TypeArguments.Length == 1) + { + return iface.TypeArguments[0].ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + } + } + + foreach (var attr in classSymbol.GetAttributes()) + { + if (attr.AttributeClass is { Name: "IViewForAttribute", TypeArguments.Length: 1 } attrClass) + { + return attrClass.TypeArguments[0].ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + } + } + + return null; + } + + /// Merges and deterministically sorts all extracted view registrations. + /// Registrations from non-generic [RegisterView]. + /// Registrations from generic [RegisterView<T>]. + /// A sorted, value-equatable list of registrations. + private static EquatableArray MergeAndSort( + ImmutableArray left, + ImmutableArray right) + { + if (left.IsEmpty && right.IsEmpty) + { + return default; + } + + var list = new List(left.Length + right.Length); + list.AddRange(left); + list.AddRange(right); + list.Sort(static (a, b) => + { + var cmp = string.CompareOrdinal(a.ViewTypeName, b.ViewTypeName); + if (cmp != 0) + { + return cmp; + } + + cmp = string.CompareOrdinal(a.ViewModelTypeName, b.ViewModelTypeName); + return cmp != 0 ? cmp : string.CompareOrdinal(a.Contract, b.Contract); + }); + + using var builder = ArrayBuilder.Rent(); + foreach (var item in list) + { + builder.Add(item); + } + + return builder.ToEquatableArray(); + } + + /// Generates the GeneratedViewRegistrations static extension class. + /// The collected view registrations. + /// The detected ReactiveUI integration. + /// The generated C# source. + private static string GenerateSource(EquatableArray views, ReactiveUiIntegration integration) + { + var builderNamespace = $"{integration.DeclarationNamespace}.Builder"; + var builderInterface = $"{integration.Namespace}.Builder.IReactiveUIBuilder"; + + var writer = SourceWriter.Rent(); + _ = writer.AutoGenerated() + .DisableWarningsEnableNullable() + .BlankLine(); + + var depth = writer.OpenNamespace(builderNamespace); + _ = writer.Summary("Compile-time view registration extensions generated for types marked with [RegisterView].") + .Line(GeneratedCodeAttribute) + .Line(SourceWriterExtensions.ExcludeFromCodeCoverageAttribute) + .Line("public static class GeneratedViewRegistrations") + .OpenBlock() + .Summary("Registers all views marked with [RegisterView] in this assembly without runtime reflection.") + .Append("public static ").Append(builderInterface).Append(" RegisterGeneratedViews(this ").Append(builderInterface).Line(" builder)") + .OpenBlock() + .Line("if (builder is null) { throw new global::System.ArgumentNullException(nameof(builder)); }"); + + foreach (var view in views) + { + if (view.Contract is null) + { + var methodName = view.IsSingleton ? "RegisterSingletonView" : "RegisterView"; + _ = writer.Append("builder.").Append(methodName) + .Append('<').Append(view.ViewTypeName).Append(", ").Append(view.ViewModelTypeName).Line(">();"); + } + else + { + var registerMethod = view.IsSingleton ? "RegisterLazySingleton" : "Register"; + _ = writer.Append("builder.WithRegistration(static resolver => resolver.") + .Append(registerMethod) + .Append('<').Append(integration.ViewNamespace).Append(".IViewFor<").Append(view.ViewModelTypeName).Append(">>(") + .Append("static () => new ").Append(view.ViewTypeName).Append("(), ") + .Append(SymbolDisplay.FormatLiteral(view.Contract, quote: true)).Line("));"); + } + } + + _ = writer.Line("return builder;") + .CloseBlock() + .CloseBlock() + .CloseBlocks(depth) + .RestoreNullableAndWarnings(); + + return writer.ToStringAndReturn(); + } +} diff --git a/src/ReactiveUI.SourceGenerators.Roslyn/WireUpControls/Models/WireUpControlsInfo.cs b/src/ReactiveUI.SourceGenerators.Roslyn/WireUpControls/Models/WireUpControlsInfo.cs new file mode 100644 index 00000000..2cbafceb --- /dev/null +++ b/src/ReactiveUI.SourceGenerators.Roslyn/WireUpControls/Models/WireUpControlsInfo.cs @@ -0,0 +1,18 @@ +// Copyright (c) 2019-2026 ReactiveUI and Contributors. All rights reserved. +// ReactiveUI and Contributors licenses this file to you under the MIT license. +// See the LICENSE file in the project root for full license information. + +using ReactiveUI.SourceGenerators.Helpers; + +namespace ReactiveUI.SourceGenerators.Models; + +/// Describes compile-time Android control wire-up for a class marked with [WireUpControls]. +/// The target type metadata. +/// Whether the target class derives from Android.App.Activity. +/// Whether the target class derives from Android.Views.View. +/// The properties to wire. +internal sealed record WireUpControlsInfo( + TargetInfo TargetInfo, + bool IsActivity, + bool IsView, + EquatableArray Controls); diff --git a/src/ReactiveUI.SourceGenerators.Roslyn/WireUpControls/Models/WiredControlInfo.cs b/src/ReactiveUI.SourceGenerators.Roslyn/WireUpControls/Models/WiredControlInfo.cs new file mode 100644 index 00000000..8f059c26 --- /dev/null +++ b/src/ReactiveUI.SourceGenerators.Roslyn/WireUpControls/Models/WiredControlInfo.cs @@ -0,0 +1,14 @@ +// Copyright (c) 2019-2026 ReactiveUI and Contributors. All rights reserved. +// ReactiveUI and Contributors licenses this file to you under the MIT license. +// See the LICENSE file in the project root for full license information. + +namespace ReactiveUI.SourceGenerators.Models; + +/// Describes a single Android view property to wire via FindViewById. +/// The property name on the declaring class. +/// The fully qualified view type name (non-nullable). +/// The Resource.Id member name. +internal sealed record WiredControlInfo( + string PropertyName, + string PropertyTypeName, + string ResourceName); diff --git a/src/ReactiveUI.SourceGenerators.Roslyn/WireUpControls/WireUpControlsGenerator.cs b/src/ReactiveUI.SourceGenerators.Roslyn/WireUpControls/WireUpControlsGenerator.cs new file mode 100644 index 00000000..37f090db --- /dev/null +++ b/src/ReactiveUI.SourceGenerators.Roslyn/WireUpControls/WireUpControlsGenerator.cs @@ -0,0 +1,249 @@ +// Copyright (c) 2019-2026 ReactiveUI and Contributors. All rights reserved. +// ReactiveUI and Contributors licenses this file to you under the MIT license. +// See the LICENSE file in the project root for full license information. + +using System.Threading; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using ReactiveUI.SourceGenerators.CodeGeneration; +using ReactiveUI.SourceGenerators.Helpers; +using ReactiveUI.SourceGenerators.Models; + +namespace ReactiveUI.SourceGenerators.Android; + +/// Generates a compile-time WireUpControls method for Android classes marked with [WireUpControls]. +[Generator(LanguageNames.CSharp)] +public sealed class WireUpControlsGenerator : IIncrementalGenerator +{ + /// The metadata name of Android.App.Activity. + private const string AndroidActivityTypeName = "Android.App.Activity"; + + /// The metadata name of Android.Views.View. + private const string AndroidViewTypeName = "Android.Views.View"; + + /// The fully qualified generator name written to generated-code attributes. + private static readonly string GeneratorName = typeof(WireUpControlsGenerator).FullName!; + + /// The generator assembly version written to generated-code attributes. + private static readonly string GeneratorVersion = typeof(WireUpControlsGenerator).Assembly.GetName().Version.ToString(); + + /// The GeneratedCode attribute stamped on generated members. + private static readonly string GeneratedCodeAttribute = SourceWriterExtensions.GeneratedCodeAttribute(GeneratorName, GeneratorVersion); + + /// + public void Initialize(IncrementalGeneratorInitializationContext context) + { + var targets = + context.SyntaxProvider + .ForAttributeWithMetadataName( + AttributeDefinitions.WireUpControlsAttributeType, + static (node, _) => node is ClassDeclarationSyntax, + static (ctx, token) => ExtractInfo(in ctx, token)) + .Where(static x => x is not null) + .Select(static (x, _) => x!) + .WithTrackingName(TrackingNames.WireUpControlsTypes); + + context.RegisterSourceOutput( + targets, + static (spc, info) => spc.AddSource( + $"{info.TargetInfo.FileHintName}.WireUpControls.g.cs", + GenerateSource(info))); + } + + /// Extracts Android view properties to wire from an attributed class. + /// The generator attribute syntax context. + /// The cancellation token. + /// The wire-up metadata, or when the class is not partial. + private static WireUpControlsInfo? ExtractInfo(in GeneratorAttributeSyntaxContext context, CancellationToken token) + { + if (!((ClassDeclarationSyntax)context.TargetNode).Modifiers.Any(SyntaxKind.PartialKeyword)) + { + return null; + } + + token.ThrowIfCancellationRequested(); + + var classSymbol = (INamedTypeSymbol)context.TargetSymbol; + var explicitOptIn = GetExplicitOptIn(context.Attributes[0]); + var isActivity = DerivesFrom(classSymbol, AndroidActivityTypeName); + var isView = DerivesFrom(classSymbol, AndroidViewTypeName); + + using var controls = ArrayBuilder.Rent(); + + foreach (var member in classSymbol.GetMembers()) + { + token.ThrowIfCancellationRequested(); + + if (member is IPropertySymbol { IsStatic: false, SetMethod: not null } property + && TryCreateWiredControl(property, explicitOptIn) is { } wired) + { + controls.Add(wired); + } + } + + return new(TargetInfo.From(classSymbol), isActivity, isView, controls.ToEquatableArray()); + } + + /// Reads the ExplicitOptIn named argument from [WireUpControls]. + /// The attribute data. + /// if explicit opt-in is enabled; otherwise . + private static bool GetExplicitOptIn(AttributeData attribute) + { + foreach (var named in attribute.NamedArguments) + { + if (named.Key == "ExplicitOptIn" && named.Value.Value is bool value) + { + return value; + } + } + + return false; + } + + /// Determines whether a property should be wired and builds its . + /// The property symbol. + /// Whether explicit opt-in mode is enabled. + /// The wired control info, or if the property should be skipped. + private static WiredControlInfo? TryCreateWiredControl(IPropertySymbol property, bool explicitOptIn) + { + if (HasAttribute(property, AttributeDefinitions.IgnoreResourceAttributeType)) + { + return null; + } + + var hasWireUpResource = TryGetWireUpResourceName(property, out var resourceOverride); + if (explicitOptIn && !hasWireUpResource) + { + return null; + } + + if (!explicitOptIn && !hasWireUpResource && property.Type is INamedTypeSymbol propType && !DerivesFrom(propType, AndroidViewTypeName)) + { + return null; + } + + var nonNullableType = property.Type.WithNullableAnnotation(NullableAnnotation.NotAnnotated); + var typeName = nonNullableType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + var resourceName = string.IsNullOrEmpty(resourceOverride) ? property.Name : resourceOverride!; + + return new(property.Name, typeName, resourceName); + } + + /// Checks whether a property carries [WireUpResource] and returns its optional resource name override. + /// The property symbol. + /// The resource name override, if specified. + /// if [WireUpResource] is present; otherwise . + private static bool TryGetWireUpResourceName(IPropertySymbol property, out string? resourceOverride) + { + resourceOverride = null; + foreach (var attribute in property.GetAttributes()) + { + if (attribute.AttributeClass?.ToDisplayString() != AttributeDefinitions.WireUpResourceAttributeType) + { + continue; + } + + if (!attribute.ConstructorArguments.IsEmpty && attribute.ConstructorArguments[0].Value is string name) + { + resourceOverride = name; + } + + return true; + } + + return false; + } + + /// Checks whether a symbol directly carries the named attribute. + /// The symbol to inspect. + /// The full metadata name of the attribute. + /// if present; otherwise . + private static bool HasAttribute(ISymbol symbol, string attributeMetadataName) + { + foreach (var attribute in symbol.GetAttributes()) + { + if (attribute.AttributeClass?.ToDisplayString() == attributeMetadataName) + { + return true; + } + } + + return false; + } + + /// Checks whether equals or derives from the named type. + /// The type symbol. + /// The full metadata name of the base type. + /// if it derives from the base type; otherwise . + private static bool DerivesFrom(INamedTypeSymbol typeSymbol, string baseMetadataName) + { + for (var current = typeSymbol; current is not null; current = current.BaseType) + { + if (current.ToDisplayString() == baseMetadataName) + { + return true; + } + } + + return false; + } + + /// Generates the partial class containing compile-time WireUpControls. + /// The wire-up metadata. + /// The generated C# source. + private static string GenerateSource(WireUpControlsInfo info) + { + var writer = SourceWriter.Rent(); + _ = writer.AutoGenerated() + .DisableWarningsEnableNullable() + .BlankLine(); + + var depth = writer.OpenNamespace(info.TargetInfo.TargetNamespace) + + writer.OpenContainingTypes(info.TargetInfo.ParentInfo); + + _ = writer.OpenPartialType(info.TargetInfo); + + if (info.IsActivity || info.IsView) + { + _ = writer.Summary("Wires child Android views to properties using FindViewById without runtime reflection.") + .Line(GeneratedCodeAttribute) + .Line(SourceWriterExtensions.ExcludeFromCodeCoverageAttribute) + .Line("private void WireUpControls()") + .OpenBlock(); + + foreach (var control in info.Controls) + { + _ = writer.Append("this.").Append(control.PropertyName) + .Append(" = this.FindViewById<").Append(control.PropertyTypeName) + .Append(">(Resource.Id.").Append(control.ResourceName).Line(")!;"); + } + + _ = writer.CloseBlock(); + } + else + { + _ = writer.Summary("Wires child Android views from the inflated root view using FindViewById without runtime reflection.") + .Line(GeneratedCodeAttribute) + .Line(SourceWriterExtensions.ExcludeFromCodeCoverageAttribute) + .Line("private void WireUpControls(global::Android.Views.View rootView)") + .OpenBlock() + .Line("if (rootView is null) { throw new global::System.ArgumentNullException(nameof(rootView)); }"); + + foreach (var control in info.Controls) + { + _ = writer.Append("this.").Append(control.PropertyName) + .Append(" = rootView.FindViewById<").Append(control.PropertyTypeName) + .Append(">(Resource.Id.").Append(control.ResourceName).Line(")!;"); + } + + _ = writer.CloseBlock(); + } + + _ = writer.CloseBlock() + .CloseBlocks(depth) + .RestoreNullableAndWarnings(); + + return writer.ToStringAndReturn(); + } +} diff --git a/src/ReactiveUI.SourceGenerators/Android/IgnoreResourceAttribute.cs b/src/ReactiveUI.SourceGenerators/Android/IgnoreResourceAttribute.cs new file mode 100644 index 00000000..8fa38f77 --- /dev/null +++ b/src/ReactiveUI.SourceGenerators/Android/IgnoreResourceAttribute.cs @@ -0,0 +1,14 @@ +// Copyright (c) 2019-2026 ReactiveUI and Contributors. All rights reserved. +// ReactiveUI and Contributors licenses this file to you under the MIT license. +// See the LICENSE file in the project root for full license information. + +using System; +using System.Diagnostics; + +namespace ReactiveUI.SourceGenerators.Android; + +/// Excludes a property from compile-time wiring by . +[Conditional(KeepAttributes.Symbol)] +[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] +[DebuggerDisplay("IgnoreResourceAttribute")] +public sealed class IgnoreResourceAttribute : Attribute; diff --git a/src/ReactiveUI.SourceGenerators/Android/WireUpControlsAttribute.cs b/src/ReactiveUI.SourceGenerators/Android/WireUpControlsAttribute.cs new file mode 100644 index 00000000..ef7b966a --- /dev/null +++ b/src/ReactiveUI.SourceGenerators/Android/WireUpControlsAttribute.cs @@ -0,0 +1,18 @@ +// Copyright (c) 2019-2026 ReactiveUI and Contributors. All rights reserved. +// ReactiveUI and Contributors licenses this file to you under the MIT license. +// See the LICENSE file in the project root for full license information. + +using System; +using System.Diagnostics; + +namespace ReactiveUI.SourceGenerators.Android; + +/// Generates a compile-time WireUpControls method that assigns Android views using FindViewById without reflection. +[Conditional(KeepAttributes.Symbol)] +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +[DebuggerDisplay("WireUpControlsAttribute: ExplicitOptIn = {ExplicitOptIn}")] +public sealed class WireUpControlsAttribute : Attribute +{ + /// Gets or sets a value indicating whether only properties marked with are wired. + public bool ExplicitOptIn { get; set; } +} diff --git a/src/ReactiveUI.SourceGenerators/Android/WireUpResourceAttribute.cs b/src/ReactiveUI.SourceGenerators/Android/WireUpResourceAttribute.cs new file mode 100644 index 00000000..4f2a684d --- /dev/null +++ b/src/ReactiveUI.SourceGenerators/Android/WireUpResourceAttribute.cs @@ -0,0 +1,19 @@ +// Copyright (c) 2019-2026 ReactiveUI and Contributors. All rights reserved. +// ReactiveUI and Contributors licenses this file to you under the MIT license. +// See the LICENSE file in the project root for full license information. + +using System; +using System.Diagnostics; + +namespace ReactiveUI.SourceGenerators.Android; + +/// Marks a property to be wired by the compile-time generator, optionally overriding the Android resource name. +/// The optional Resource.Id member name; defaults to the property name. +[Conditional(KeepAttributes.Symbol)] +[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] +[DebuggerDisplay("WireUpResourceAttribute: ResourceNameOverride = {ResourceNameOverride}")] +public sealed class WireUpResourceAttribute(string? resourceNameOverride = null) : Attribute +{ + /// Gets the optional Android Resource.Id member name override. + public string? ResourceNameOverride { get; } = resourceNameOverride; +} diff --git a/src/ReactiveUI.SourceGenerators/AutoPersistAttribute.cs b/src/ReactiveUI.SourceGenerators/AutoPersistAttribute.cs new file mode 100644 index 00000000..0f02b573 --- /dev/null +++ b/src/ReactiveUI.SourceGenerators/AutoPersistAttribute.cs @@ -0,0 +1,14 @@ +// Copyright (c) 2019-2026 ReactiveUI and Contributors. All rights reserved. +// ReactiveUI and Contributors licenses this file to you under the MIT license. +// See the LICENSE file in the project root for full license information. + +using System; +using System.Diagnostics; + +namespace ReactiveUI.SourceGenerators; + +/// Generates a compile-time AutoPersistMetadata property for a [DataContract] reactive object without runtime reflection. +[Conditional(KeepAttributes.Symbol)] +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +[DebuggerDisplay("AutoPersistAttribute")] +public sealed class AutoPersistAttribute : Attribute; diff --git a/src/ReactiveUI.SourceGenerators/PublicAPI/net10.0/PublicAPI.txt b/src/ReactiveUI.SourceGenerators/PublicAPI/net10.0/PublicAPI.txt index 6992b2b1..01dbcd24 100644 --- a/src/ReactiveUI.SourceGenerators/PublicAPI/net10.0/PublicAPI.txt +++ b/src/ReactiveUI.SourceGenerators/PublicAPI/net10.0/PublicAPI.txt @@ -10,6 +10,13 @@ namespace ReactiveUI.SourceGenerators PrivateProtected = 5, Init = 6, } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("AutoPersistAttribute")] + public sealed class AutoPersistAttribute : System.Attribute + { + public AutoPersistAttribute() { } + } [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple=false, Inherited=false)] [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] [System.Diagnostics.DebuggerDisplay("BindableDerivedListAttribute: AccessModifier = {AccessModifier}")] @@ -85,6 +92,58 @@ namespace ReactiveUI.SourceGenerators public string? OutputScheduler { get; set; } public bool RunInBackground { get; set; } } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("ReactiveValidationAttribute")] + public sealed class ReactiveValidationAttribute : System.Attribute + { + public ReactiveValidationAttribute() { } + } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=true, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("RegisterViewAttribute: Contract = {Contract}, IsSingleton = {IsSingleton}")] + public sealed class RegisterViewAttribute : System.Attribute + { + public RegisterViewAttribute() { } + public string? Contract { get; set; } + public bool IsSingleton { get; set; } + } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=true, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("RegisterViewAttribute<{ViewModelType.Name}>: Contract = {Contract}, IsSingleton = {IsSingleton}")] + public sealed class RegisterViewAttribute : System.Attribute where TViewModel : class + { + public RegisterViewAttribute() { } + public string? Contract { get; set; } + public bool IsSingleton { get; set; } + public System.Type ViewModelType { get; } + } +} +namespace ReactiveUI.SourceGenerators.Android +{ + [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("IgnoreResourceAttribute")] + public sealed class IgnoreResourceAttribute : System.Attribute + { + public IgnoreResourceAttribute() { } + } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("WireUpControlsAttribute: ExplicitOptIn = {ExplicitOptIn}")] + public sealed class WireUpControlsAttribute : System.Attribute + { + public WireUpControlsAttribute() { } + public bool ExplicitOptIn { get; set; } + } + [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("WireUpResourceAttribute: ResourceNameOverride = {ResourceNameOverride}")] + public sealed class WireUpResourceAttribute : System.Attribute + { + public WireUpResourceAttribute(string? resourceNameOverride = null) { } + public string? ResourceNameOverride { get; } + } } namespace ReactiveUI.SourceGenerators.WinForms { diff --git a/src/ReactiveUI.SourceGenerators/PublicAPI/net11.0/PublicAPI.txt b/src/ReactiveUI.SourceGenerators/PublicAPI/net11.0/PublicAPI.txt index 6992b2b1..01dbcd24 100644 --- a/src/ReactiveUI.SourceGenerators/PublicAPI/net11.0/PublicAPI.txt +++ b/src/ReactiveUI.SourceGenerators/PublicAPI/net11.0/PublicAPI.txt @@ -10,6 +10,13 @@ namespace ReactiveUI.SourceGenerators PrivateProtected = 5, Init = 6, } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("AutoPersistAttribute")] + public sealed class AutoPersistAttribute : System.Attribute + { + public AutoPersistAttribute() { } + } [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple=false, Inherited=false)] [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] [System.Diagnostics.DebuggerDisplay("BindableDerivedListAttribute: AccessModifier = {AccessModifier}")] @@ -85,6 +92,58 @@ namespace ReactiveUI.SourceGenerators public string? OutputScheduler { get; set; } public bool RunInBackground { get; set; } } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("ReactiveValidationAttribute")] + public sealed class ReactiveValidationAttribute : System.Attribute + { + public ReactiveValidationAttribute() { } + } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=true, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("RegisterViewAttribute: Contract = {Contract}, IsSingleton = {IsSingleton}")] + public sealed class RegisterViewAttribute : System.Attribute + { + public RegisterViewAttribute() { } + public string? Contract { get; set; } + public bool IsSingleton { get; set; } + } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=true, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("RegisterViewAttribute<{ViewModelType.Name}>: Contract = {Contract}, IsSingleton = {IsSingleton}")] + public sealed class RegisterViewAttribute : System.Attribute where TViewModel : class + { + public RegisterViewAttribute() { } + public string? Contract { get; set; } + public bool IsSingleton { get; set; } + public System.Type ViewModelType { get; } + } +} +namespace ReactiveUI.SourceGenerators.Android +{ + [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("IgnoreResourceAttribute")] + public sealed class IgnoreResourceAttribute : System.Attribute + { + public IgnoreResourceAttribute() { } + } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("WireUpControlsAttribute: ExplicitOptIn = {ExplicitOptIn}")] + public sealed class WireUpControlsAttribute : System.Attribute + { + public WireUpControlsAttribute() { } + public bool ExplicitOptIn { get; set; } + } + [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("WireUpResourceAttribute: ResourceNameOverride = {ResourceNameOverride}")] + public sealed class WireUpResourceAttribute : System.Attribute + { + public WireUpResourceAttribute(string? resourceNameOverride = null) { } + public string? ResourceNameOverride { get; } + } } namespace ReactiveUI.SourceGenerators.WinForms { diff --git a/src/ReactiveUI.SourceGenerators/PublicAPI/net47/PublicAPI.txt b/src/ReactiveUI.SourceGenerators/PublicAPI/net47/PublicAPI.txt index 6992b2b1..01dbcd24 100644 --- a/src/ReactiveUI.SourceGenerators/PublicAPI/net47/PublicAPI.txt +++ b/src/ReactiveUI.SourceGenerators/PublicAPI/net47/PublicAPI.txt @@ -10,6 +10,13 @@ namespace ReactiveUI.SourceGenerators PrivateProtected = 5, Init = 6, } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("AutoPersistAttribute")] + public sealed class AutoPersistAttribute : System.Attribute + { + public AutoPersistAttribute() { } + } [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple=false, Inherited=false)] [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] [System.Diagnostics.DebuggerDisplay("BindableDerivedListAttribute: AccessModifier = {AccessModifier}")] @@ -85,6 +92,58 @@ namespace ReactiveUI.SourceGenerators public string? OutputScheduler { get; set; } public bool RunInBackground { get; set; } } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("ReactiveValidationAttribute")] + public sealed class ReactiveValidationAttribute : System.Attribute + { + public ReactiveValidationAttribute() { } + } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=true, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("RegisterViewAttribute: Contract = {Contract}, IsSingleton = {IsSingleton}")] + public sealed class RegisterViewAttribute : System.Attribute + { + public RegisterViewAttribute() { } + public string? Contract { get; set; } + public bool IsSingleton { get; set; } + } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=true, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("RegisterViewAttribute<{ViewModelType.Name}>: Contract = {Contract}, IsSingleton = {IsSingleton}")] + public sealed class RegisterViewAttribute : System.Attribute where TViewModel : class + { + public RegisterViewAttribute() { } + public string? Contract { get; set; } + public bool IsSingleton { get; set; } + public System.Type ViewModelType { get; } + } +} +namespace ReactiveUI.SourceGenerators.Android +{ + [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("IgnoreResourceAttribute")] + public sealed class IgnoreResourceAttribute : System.Attribute + { + public IgnoreResourceAttribute() { } + } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("WireUpControlsAttribute: ExplicitOptIn = {ExplicitOptIn}")] + public sealed class WireUpControlsAttribute : System.Attribute + { + public WireUpControlsAttribute() { } + public bool ExplicitOptIn { get; set; } + } + [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("WireUpResourceAttribute: ResourceNameOverride = {ResourceNameOverride}")] + public sealed class WireUpResourceAttribute : System.Attribute + { + public WireUpResourceAttribute(string? resourceNameOverride = null) { } + public string? ResourceNameOverride { get; } + } } namespace ReactiveUI.SourceGenerators.WinForms { diff --git a/src/ReactiveUI.SourceGenerators/PublicAPI/net471/PublicAPI.txt b/src/ReactiveUI.SourceGenerators/PublicAPI/net471/PublicAPI.txt index 6992b2b1..01dbcd24 100644 --- a/src/ReactiveUI.SourceGenerators/PublicAPI/net471/PublicAPI.txt +++ b/src/ReactiveUI.SourceGenerators/PublicAPI/net471/PublicAPI.txt @@ -10,6 +10,13 @@ namespace ReactiveUI.SourceGenerators PrivateProtected = 5, Init = 6, } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("AutoPersistAttribute")] + public sealed class AutoPersistAttribute : System.Attribute + { + public AutoPersistAttribute() { } + } [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple=false, Inherited=false)] [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] [System.Diagnostics.DebuggerDisplay("BindableDerivedListAttribute: AccessModifier = {AccessModifier}")] @@ -85,6 +92,58 @@ namespace ReactiveUI.SourceGenerators public string? OutputScheduler { get; set; } public bool RunInBackground { get; set; } } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("ReactiveValidationAttribute")] + public sealed class ReactiveValidationAttribute : System.Attribute + { + public ReactiveValidationAttribute() { } + } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=true, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("RegisterViewAttribute: Contract = {Contract}, IsSingleton = {IsSingleton}")] + public sealed class RegisterViewAttribute : System.Attribute + { + public RegisterViewAttribute() { } + public string? Contract { get; set; } + public bool IsSingleton { get; set; } + } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=true, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("RegisterViewAttribute<{ViewModelType.Name}>: Contract = {Contract}, IsSingleton = {IsSingleton}")] + public sealed class RegisterViewAttribute : System.Attribute where TViewModel : class + { + public RegisterViewAttribute() { } + public string? Contract { get; set; } + public bool IsSingleton { get; set; } + public System.Type ViewModelType { get; } + } +} +namespace ReactiveUI.SourceGenerators.Android +{ + [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("IgnoreResourceAttribute")] + public sealed class IgnoreResourceAttribute : System.Attribute + { + public IgnoreResourceAttribute() { } + } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("WireUpControlsAttribute: ExplicitOptIn = {ExplicitOptIn}")] + public sealed class WireUpControlsAttribute : System.Attribute + { + public WireUpControlsAttribute() { } + public bool ExplicitOptIn { get; set; } + } + [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("WireUpResourceAttribute: ResourceNameOverride = {ResourceNameOverride}")] + public sealed class WireUpResourceAttribute : System.Attribute + { + public WireUpResourceAttribute(string? resourceNameOverride = null) { } + public string? ResourceNameOverride { get; } + } } namespace ReactiveUI.SourceGenerators.WinForms { diff --git a/src/ReactiveUI.SourceGenerators/PublicAPI/net472/PublicAPI.txt b/src/ReactiveUI.SourceGenerators/PublicAPI/net472/PublicAPI.txt index 6992b2b1..01dbcd24 100644 --- a/src/ReactiveUI.SourceGenerators/PublicAPI/net472/PublicAPI.txt +++ b/src/ReactiveUI.SourceGenerators/PublicAPI/net472/PublicAPI.txt @@ -10,6 +10,13 @@ namespace ReactiveUI.SourceGenerators PrivateProtected = 5, Init = 6, } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("AutoPersistAttribute")] + public sealed class AutoPersistAttribute : System.Attribute + { + public AutoPersistAttribute() { } + } [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple=false, Inherited=false)] [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] [System.Diagnostics.DebuggerDisplay("BindableDerivedListAttribute: AccessModifier = {AccessModifier}")] @@ -85,6 +92,58 @@ namespace ReactiveUI.SourceGenerators public string? OutputScheduler { get; set; } public bool RunInBackground { get; set; } } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("ReactiveValidationAttribute")] + public sealed class ReactiveValidationAttribute : System.Attribute + { + public ReactiveValidationAttribute() { } + } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=true, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("RegisterViewAttribute: Contract = {Contract}, IsSingleton = {IsSingleton}")] + public sealed class RegisterViewAttribute : System.Attribute + { + public RegisterViewAttribute() { } + public string? Contract { get; set; } + public bool IsSingleton { get; set; } + } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=true, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("RegisterViewAttribute<{ViewModelType.Name}>: Contract = {Contract}, IsSingleton = {IsSingleton}")] + public sealed class RegisterViewAttribute : System.Attribute where TViewModel : class + { + public RegisterViewAttribute() { } + public string? Contract { get; set; } + public bool IsSingleton { get; set; } + public System.Type ViewModelType { get; } + } +} +namespace ReactiveUI.SourceGenerators.Android +{ + [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("IgnoreResourceAttribute")] + public sealed class IgnoreResourceAttribute : System.Attribute + { + public IgnoreResourceAttribute() { } + } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("WireUpControlsAttribute: ExplicitOptIn = {ExplicitOptIn}")] + public sealed class WireUpControlsAttribute : System.Attribute + { + public WireUpControlsAttribute() { } + public bool ExplicitOptIn { get; set; } + } + [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("WireUpResourceAttribute: ResourceNameOverride = {ResourceNameOverride}")] + public sealed class WireUpResourceAttribute : System.Attribute + { + public WireUpResourceAttribute(string? resourceNameOverride = null) { } + public string? ResourceNameOverride { get; } + } } namespace ReactiveUI.SourceGenerators.WinForms { diff --git a/src/ReactiveUI.SourceGenerators/PublicAPI/net48/PublicAPI.txt b/src/ReactiveUI.SourceGenerators/PublicAPI/net48/PublicAPI.txt index 6992b2b1..01dbcd24 100644 --- a/src/ReactiveUI.SourceGenerators/PublicAPI/net48/PublicAPI.txt +++ b/src/ReactiveUI.SourceGenerators/PublicAPI/net48/PublicAPI.txt @@ -10,6 +10,13 @@ namespace ReactiveUI.SourceGenerators PrivateProtected = 5, Init = 6, } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("AutoPersistAttribute")] + public sealed class AutoPersistAttribute : System.Attribute + { + public AutoPersistAttribute() { } + } [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple=false, Inherited=false)] [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] [System.Diagnostics.DebuggerDisplay("BindableDerivedListAttribute: AccessModifier = {AccessModifier}")] @@ -85,6 +92,58 @@ namespace ReactiveUI.SourceGenerators public string? OutputScheduler { get; set; } public bool RunInBackground { get; set; } } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("ReactiveValidationAttribute")] + public sealed class ReactiveValidationAttribute : System.Attribute + { + public ReactiveValidationAttribute() { } + } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=true, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("RegisterViewAttribute: Contract = {Contract}, IsSingleton = {IsSingleton}")] + public sealed class RegisterViewAttribute : System.Attribute + { + public RegisterViewAttribute() { } + public string? Contract { get; set; } + public bool IsSingleton { get; set; } + } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=true, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("RegisterViewAttribute<{ViewModelType.Name}>: Contract = {Contract}, IsSingleton = {IsSingleton}")] + public sealed class RegisterViewAttribute : System.Attribute where TViewModel : class + { + public RegisterViewAttribute() { } + public string? Contract { get; set; } + public bool IsSingleton { get; set; } + public System.Type ViewModelType { get; } + } +} +namespace ReactiveUI.SourceGenerators.Android +{ + [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("IgnoreResourceAttribute")] + public sealed class IgnoreResourceAttribute : System.Attribute + { + public IgnoreResourceAttribute() { } + } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("WireUpControlsAttribute: ExplicitOptIn = {ExplicitOptIn}")] + public sealed class WireUpControlsAttribute : System.Attribute + { + public WireUpControlsAttribute() { } + public bool ExplicitOptIn { get; set; } + } + [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("WireUpResourceAttribute: ResourceNameOverride = {ResourceNameOverride}")] + public sealed class WireUpResourceAttribute : System.Attribute + { + public WireUpResourceAttribute(string? resourceNameOverride = null) { } + public string? ResourceNameOverride { get; } + } } namespace ReactiveUI.SourceGenerators.WinForms { diff --git a/src/ReactiveUI.SourceGenerators/PublicAPI/net481/PublicAPI.txt b/src/ReactiveUI.SourceGenerators/PublicAPI/net481/PublicAPI.txt index 6992b2b1..01dbcd24 100644 --- a/src/ReactiveUI.SourceGenerators/PublicAPI/net481/PublicAPI.txt +++ b/src/ReactiveUI.SourceGenerators/PublicAPI/net481/PublicAPI.txt @@ -10,6 +10,13 @@ namespace ReactiveUI.SourceGenerators PrivateProtected = 5, Init = 6, } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("AutoPersistAttribute")] + public sealed class AutoPersistAttribute : System.Attribute + { + public AutoPersistAttribute() { } + } [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple=false, Inherited=false)] [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] [System.Diagnostics.DebuggerDisplay("BindableDerivedListAttribute: AccessModifier = {AccessModifier}")] @@ -85,6 +92,58 @@ namespace ReactiveUI.SourceGenerators public string? OutputScheduler { get; set; } public bool RunInBackground { get; set; } } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("ReactiveValidationAttribute")] + public sealed class ReactiveValidationAttribute : System.Attribute + { + public ReactiveValidationAttribute() { } + } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=true, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("RegisterViewAttribute: Contract = {Contract}, IsSingleton = {IsSingleton}")] + public sealed class RegisterViewAttribute : System.Attribute + { + public RegisterViewAttribute() { } + public string? Contract { get; set; } + public bool IsSingleton { get; set; } + } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=true, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("RegisterViewAttribute<{ViewModelType.Name}>: Contract = {Contract}, IsSingleton = {IsSingleton}")] + public sealed class RegisterViewAttribute : System.Attribute where TViewModel : class + { + public RegisterViewAttribute() { } + public string? Contract { get; set; } + public bool IsSingleton { get; set; } + public System.Type ViewModelType { get; } + } +} +namespace ReactiveUI.SourceGenerators.Android +{ + [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("IgnoreResourceAttribute")] + public sealed class IgnoreResourceAttribute : System.Attribute + { + public IgnoreResourceAttribute() { } + } + [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("WireUpControlsAttribute: ExplicitOptIn = {ExplicitOptIn}")] + public sealed class WireUpControlsAttribute : System.Attribute + { + public WireUpControlsAttribute() { } + public bool ExplicitOptIn { get; set; } + } + [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple=false, Inherited=false)] + [System.Diagnostics.Conditional("REACTIVEUI_SOURCEGENERATORS_KEEP_ATTRIBUTES")] + [System.Diagnostics.DebuggerDisplay("WireUpResourceAttribute: ResourceNameOverride = {ResourceNameOverride}")] + public sealed class WireUpResourceAttribute : System.Attribute + { + public WireUpResourceAttribute(string? resourceNameOverride = null) { } + public string? ResourceNameOverride { get; } + } } namespace ReactiveUI.SourceGenerators.WinForms { diff --git a/src/ReactiveUI.SourceGenerators/README.md b/src/ReactiveUI.SourceGenerators/README.md index 467d9ddb..388c6aa6 100644 --- a/src/ReactiveUI.SourceGenerators/README.md +++ b/src/ReactiveUI.SourceGenerators/README.md @@ -61,6 +61,10 @@ For .NET Framework 4.8 and older, add [Polyfill](https://github.com/SimonCropp/P | `[BindableDerivedList]` | A derived list for a `ReadOnlyObservableCollection` field | | `[ReactiveCollection]` | Change notifications for an `ObservableCollection` field | | `[RoutedControlHost]`, `[ViewModelControlHost]` | WinForms hosts that show the view for a view model | +| `[RegisterView]`, `[RegisterView]` | A `GeneratedViewRegistrations.RegisterGeneratedViews(IReactiveUIBuilder)` extension method for reflection-free view registration | +| `[AutoPersist]` | A static `AutoPersistMetadata` property capturing `[DataContract]` / `[DataMember]` metadata at compile time | +| `[ReactiveValidation]` | A `ConfigureValidation()` method wiring DataAnnotations attributes onto `ReactiveProperty` properties without reflection | +| `[WireUpControls]`, `[WireUpResource]`, `[IgnoreResource]` | A compile-time `WireUpControls()` / `WireUpControls(View)` method for Android using `FindViewById(Resource.Id.*)` | ## Roslyn and Visual Studio support diff --git a/src/ReactiveUI.SourceGenerators/ReactiveValidationAttribute.cs b/src/ReactiveUI.SourceGenerators/ReactiveValidationAttribute.cs new file mode 100644 index 00000000..100ea460 --- /dev/null +++ b/src/ReactiveUI.SourceGenerators/ReactiveValidationAttribute.cs @@ -0,0 +1,14 @@ +// Copyright (c) 2019-2026 ReactiveUI and Contributors. All rights reserved. +// ReactiveUI and Contributors licenses this file to you under the MIT license. +// See the LICENSE file in the project root for full license information. + +using System; +using System.Diagnostics; + +namespace ReactiveUI.SourceGenerators; + +/// Generates a compile-time ConfigureValidation method that wires DataAnnotations attributes on ReactiveProperty<T> properties without reflection. +[Conditional(KeepAttributes.Symbol)] +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +[DebuggerDisplay("ReactiveValidationAttribute")] +public sealed class ReactiveValidationAttribute : Attribute; diff --git a/src/ReactiveUI.SourceGenerators/RegisterViewAttribute.cs b/src/ReactiveUI.SourceGenerators/RegisterViewAttribute.cs new file mode 100644 index 00000000..9706f191 --- /dev/null +++ b/src/ReactiveUI.SourceGenerators/RegisterViewAttribute.cs @@ -0,0 +1,21 @@ +// Copyright (c) 2019-2026 ReactiveUI and Contributors. All rights reserved. +// ReactiveUI and Contributors licenses this file to you under the MIT license. +// See the LICENSE file in the project root for full license information. + +using System; +using System.Diagnostics; + +namespace ReactiveUI.SourceGenerators; + +/// Registers a view with GeneratedViewRegistrations.RegisterGeneratedViews without runtime assembly scanning. +[Conditional(KeepAttributes.Symbol)] +[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] +[DebuggerDisplay("RegisterViewAttribute: Contract = {Contract}, IsSingleton = {IsSingleton}")] +public sealed class RegisterViewAttribute : Attribute +{ + /// Gets or sets the optional view contract. + public string? Contract { get; set; } + + /// Gets or sets a value indicating whether to register the view as a singleton. + public bool IsSingleton { get; set; } +} diff --git a/src/ReactiveUI.SourceGenerators/RegisterViewAttribute{T}.cs b/src/ReactiveUI.SourceGenerators/RegisterViewAttribute{T}.cs new file mode 100644 index 00000000..8411e919 --- /dev/null +++ b/src/ReactiveUI.SourceGenerators/RegisterViewAttribute{T}.cs @@ -0,0 +1,26 @@ +// Copyright (c) 2019-2026 ReactiveUI and Contributors. All rights reserved. +// ReactiveUI and Contributors licenses this file to you under the MIT license. +// See the LICENSE file in the project root for full license information. + +using System; +using System.Diagnostics; + +namespace ReactiveUI.SourceGenerators; + +/// Registers a view for with GeneratedViewRegistrations.RegisterGeneratedViews without runtime assembly scanning. +/// The view model type associated with the view. +[Conditional(KeepAttributes.Symbol)] +[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] +[DebuggerDisplay("RegisterViewAttribute<{ViewModelType.Name}>: Contract = {Contract}, IsSingleton = {IsSingleton}")] +public sealed class RegisterViewAttribute : Attribute + where TViewModel : class +{ + /// Gets the view model type associated with the view. + public Type ViewModelType => typeof(TViewModel); + + /// Gets or sets the optional view contract. + public string? Contract { get; set; } + + /// Gets or sets a value indicating whether to register the view as a singleton. + public bool IsSingleton { get; set; } +} diff --git a/src/tests/ReactiveUI.SourceGenerators.Tests/UnitTests/AutoPersistGeneratorTests.cs b/src/tests/ReactiveUI.SourceGenerators.Tests/UnitTests/AutoPersistGeneratorTests.cs new file mode 100644 index 00000000..bdc24fc6 --- /dev/null +++ b/src/tests/ReactiveUI.SourceGenerators.Tests/UnitTests/AutoPersistGeneratorTests.cs @@ -0,0 +1,100 @@ +// Copyright (c) 2019-2026 ReactiveUI and Contributors. All rights reserved. +// ReactiveUI and Contributors licenses this file to you under the MIT license. +// See the LICENSE file in the project root for full license information. + +namespace ReactiveUI.SourceGenerator.Tests; + +/// Tests compile-time persistence metadata generation for [AutoPersist]. +public sealed class AutoPersistGeneratorTests +{ + /// Verifies AutoPersistMetadata captures [DataContract] and [DataMember] properties without reflection. + /// A task representing the asynchronous test. + [Test] + public async Task GeneratesAutoPersistMetadataForDataContractClass() + { + const string source = """ + using System.Runtime.Serialization; + using ReactiveUI; + using ReactiveUI.SourceGenerators; + + namespace TestNs; + + [DataContract] + [AutoPersist] + public partial class AppState : ReactiveObject + { + [DataMember] + public string Title { get; set; } = string.Empty; + + [DataMember] + public int Count { get; set; } + + public string Ephemeral { get; set; } = string.Empty; + } + """; + + var (generatedSource, errors) = RunGenerator(source); + + await Assert.That(generatedSource).IsNotNull(); + await Assert.That(errors).IsEmpty(); + await Assert.That(generatedSource!).Contains("public static global::ReactiveUI.AutoPersistHelperMixins.AutoPersistMetadata AutoPersistMetadata { get; } ="); + await Assert.That(generatedSource!).Contains( + "new global::ReactiveUI.AutoPersistHelperMixins.AutoPersistMetadata(" + + "true, new global::System.Collections.Generic.HashSet(global::System.StringComparer.Ordinal)"); + await Assert.That(generatedSource!).Contains("\"Title\","); + await Assert.That(generatedSource!).Contains("\"Count\","); + await Assert.That(generatedSource!).DoesNotContain("\"Ephemeral\""); + } + + /// Verifies non-partial classes marked with [AutoPersist] are ignored. + /// A task representing the asynchronous test. + [Test] + public async Task IgnoresNonPartialClass() + { + const string source = """ + using System.Runtime.Serialization; + using ReactiveUI.SourceGenerators; + + namespace TestNs; + + [DataContract] + [AutoPersist] + public sealed class NonPartialState + { + [DataMember] + public string Title { get; set; } = string.Empty; + } + """; + + var (generatedSource, errors) = RunGenerator(source); + + await Assert.That(generatedSource).IsNull(); + await Assert.That(errors).IsEmpty(); + } + + /// Runs against the given source. + /// The C# source text. + /// The generated source text (or null) and any error diagnostics. + private static (string? GeneratedSource, ImmutableArray Errors) RunGenerator(string source) + { + var parseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp13); + var compilation = CSharpCompilation.Create( + "AutoPersistTest", + [CSharpSyntaxTree.ParseText(source, parseOptions)], + TestCompilationReferences.CreatePortableDefault(), + new(OutputKind.DynamicallyLinkedLibrary)); + + GeneratorDriver driver = CSharpGeneratorDriver.Create( + [new AutoPersistGenerator().AsSourceGenerator()], + parseOptions: parseOptions); + driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); + + var runResult = driver.GetRunResult(); + var generated = !runResult.GeneratedTrees.IsEmpty ? runResult.GeneratedTrees[0].ToString() : null; + var errors = outputCompilation.GetDiagnostics() + .Where(static d => d.Severity == DiagnosticSeverity.Error) + .ToImmutableArray(); + + return (generated, errors); + } +} diff --git a/src/tests/ReactiveUI.SourceGenerators.Tests/UnitTests/IncrementalCachingTests.cs b/src/tests/ReactiveUI.SourceGenerators.Tests/UnitTests/IncrementalCachingTests.cs index 2771b265..39c3d85b 100644 --- a/src/tests/ReactiveUI.SourceGenerators.Tests/UnitTests/IncrementalCachingTests.cs +++ b/src/tests/ReactiveUI.SourceGenerators.Tests/UnitTests/IncrementalCachingTests.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for full license information. using System.Runtime.CompilerServices; +using ReactiveUI.SourceGenerators.Android; using ReactiveUI.SourceGenerators.Helpers; using ReactiveUI.SourceGenerators.WinForms; @@ -142,6 +143,55 @@ namespace TestNs; "partial class FirstHost", "partial class ThirdHost"); + /// An unrelated edit leaves every [AutoPersist] type cached; editing one type reruns only that type. + /// A task to monitor the async. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [Test] + public Task AutoPersistCachesPerType() => AssertCachesPerType( + new AutoPersistGenerator(), + TrackingNames.AutoPersistTypes, + """ + using System.Runtime.Serialization; + using ReactiveUI.SourceGenerators; + namespace TestNs; + [DataContract, AutoPersist] public partial class FirstState { [DataMember] public int Alpha { get; set; } } + [DataContract, AutoPersist] public partial class SecondState { [DataMember] public int Beta { get; set; } } + """, + "Alpha", + "Gamma"); + + /// An unrelated edit leaves every [ReactiveValidation] type cached; editing one type reruns only that type. + /// A task to monitor the async. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [Test] + public Task ReactiveValidationCachesPerType() => AssertCachesPerType( + new ReactiveValidationGenerator(), + TrackingNames.ReactiveValidationTypes, + """ + using ReactiveUI.SourceGenerators; + namespace TestNs; + [ReactiveValidation] public partial class FirstValidated { } + [ReactiveValidation] public partial class SecondValidated { } + """, + "partial class FirstValidated", + "partial class ThirdValidated"); + + /// An unrelated edit leaves every [WireUpControls] type cached; editing one type reruns only that type. + /// A task to monitor the async. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [Test] + public Task WireUpControlsCachesPerType() => AssertCachesPerType( + new WireUpControlsGenerator(), + TrackingNames.WireUpControlsTypes, + """ + using ReactiveUI.SourceGenerators.Android; + namespace TestNs; + [WireUpControls] public partial class FirstScreen { } + [WireUpControls] public partial class SecondScreen { } + """, + "partial class FirstScreen", + "partial class ThirdScreen"); + /// Runs a generator, then reruns it after an unrelated edit and after an edit to one of two types. /// The generator. /// The tracking name of the generator's per-type step. diff --git a/src/tests/ReactiveUI.SourceGenerators.Tests/UnitTests/ReactiveValidationGeneratorTests.cs b/src/tests/ReactiveUI.SourceGenerators.Tests/UnitTests/ReactiveValidationGeneratorTests.cs new file mode 100644 index 00000000..eeb544ce --- /dev/null +++ b/src/tests/ReactiveUI.SourceGenerators.Tests/UnitTests/ReactiveValidationGeneratorTests.cs @@ -0,0 +1,100 @@ +// Copyright (c) 2019-2026 ReactiveUI and Contributors. All rights reserved. +// ReactiveUI and Contributors licenses this file to you under the MIT license. +// See the LICENSE file in the project root for full license information. + +namespace ReactiveUI.SourceGenerator.Tests; + +/// Tests compile-time DataAnnotations validation wiring for [ReactiveValidation]. +public sealed class ReactiveValidationGeneratorTests +{ + /// Minimal stubs for ReactiveProperty<T> and ReactivePropertyMixins.AddValidation so the generated output compiles against the AOT-safe overload. + private const string ValidationStubs = """ + namespace ReactiveUI + { + public sealed class ReactiveProperty { } + + public static class ReactivePropertyMixins + { + public static ReactiveProperty AddValidation( + this ReactiveProperty self, + string? displayName, + params global::System.ComponentModel.DataAnnotations.ValidationAttribute[] attributes) => self; + } + } + """; + + /// Verifies ConfigureValidation() wires all validation attributes and [Display(Name = ...)] without reflection. + /// A task representing the asynchronous test. + [Test] + public async Task GeneratesConfigureValidationForAnnotatedReactiveProperties() + { + const string source = """ + using System.ComponentModel.DataAnnotations; + using ReactiveUI; + using ReactiveUI.SourceGenerators; + + namespace TestNs; + + [ReactiveValidation] + public partial class RegistrationViewModel + { + [Display(Name = "User Name")] + [Required(ErrorMessage = "Name is required")] + [StringLength(50, MinimumLength = 3)] + public ReactiveProperty Name { get; } = new(); + + [Range(18, 120)] + public ReactiveProperty Age { get; } = new(); + + public ReactiveProperty Unvalidated { get; } = new(); + + public RegistrationViewModel() => ConfigureValidation(); + } + """; + + var (generatedSource, errors) = RunGenerator(source); + + await Assert.That(generatedSource).IsNotNull(); + await Assert.That(errors).IsEmpty(); + await Assert.That(generatedSource!).Contains("private void ConfigureValidation()"); + await Assert.That(generatedSource!).Contains("\"User Name\""); + await Assert.That(generatedSource!).Contains("new global::System.ComponentModel.DataAnnotations.RequiredAttribute() { ErrorMessage = \"Name is required\" }"); + await Assert.That(generatedSource!).Contains("new global::System.ComponentModel.DataAnnotations.StringLengthAttribute(50) { MinimumLength = 3 }"); + await Assert.That(generatedSource!).Contains("new global::System.ComponentModel.DataAnnotations.RangeAttribute(18, 120)"); + await Assert.That(generatedSource!).DoesNotContain("this.Unvalidated"); + } + + /// Runs against the given source with AOT-safe ReactivePropertyMixins stubs. + /// The C# source text. + /// The generated source text (or null) and any error diagnostics. + private static (string? GeneratedSource, ImmutableArray Errors) RunGenerator(string source) + { + var parseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp13); + var references = TestCompilationReferences.CreatePortableDefault() + .Where(static r => r.Display?.EndsWith("ReactiveUI.dll", StringComparison.OrdinalIgnoreCase) != true) + .Append(MetadataReference.CreateFromFile(typeof(System.ComponentModel.DataAnnotations.RequiredAttribute).Assembly.Location)) + .ToImmutableArray(); + + var compilation = CSharpCompilation.Create( + "ReactiveValidationTest", + [ + CSharpSyntaxTree.ParseText(ValidationStubs, parseOptions, path: "Stubs.cs"), + CSharpSyntaxTree.ParseText(source, parseOptions, path: "ViewModel.cs"), + ], + references, + new(OutputKind.DynamicallyLinkedLibrary)); + + GeneratorDriver driver = CSharpGeneratorDriver.Create( + [new ReactiveValidationGenerator().AsSourceGenerator()], + parseOptions: parseOptions); + driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); + + var runResult = driver.GetRunResult(); + var generated = !runResult.GeneratedTrees.IsEmpty ? runResult.GeneratedTrees[0].ToString() : null; + var errors = outputCompilation.GetDiagnostics() + .Where(static d => d.Severity == DiagnosticSeverity.Error) + .ToImmutableArray(); + + return (generated, errors); + } +} diff --git a/src/tests/ReactiveUI.SourceGenerators.Tests/UnitTests/RegisterViewGeneratorTests.cs b/src/tests/ReactiveUI.SourceGenerators.Tests/UnitTests/RegisterViewGeneratorTests.cs new file mode 100644 index 00000000..c7910ef0 --- /dev/null +++ b/src/tests/ReactiveUI.SourceGenerators.Tests/UnitTests/RegisterViewGeneratorTests.cs @@ -0,0 +1,101 @@ +// Copyright (c) 2019-2026 ReactiveUI and Contributors. All rights reserved. +// ReactiveUI and Contributors licenses this file to you under the MIT license. +// See the LICENSE file in the project root for full license information. + +namespace ReactiveUI.SourceGenerator.Tests; + +/// Tests compile-time view registration generation for [RegisterView]. +public sealed class RegisterViewGeneratorTests +{ + /// Verifies generic, inferred, contract, and singleton view registrations generate clean compilable code. + /// A task representing the asynchronous test. + [Test] + public async Task GeneratesRegisterGeneratedViewsForAnnotatedViews() + { + const string source = """ + using ReactiveUI; + using ReactiveUI.Binding; + using ReactiveUI.SourceGenerators; + + namespace TestNs; + + public sealed class FirstViewModel : ReactiveObject { } + public sealed class SecondViewModel : ReactiveObject { } + + [RegisterView] + public sealed class FirstView : IViewFor + { + public FirstViewModel? ViewModel { get; set; } + object? IViewFor.ViewModel { get => ViewModel; set => ViewModel = (FirstViewModel?)value; } + } + + [RegisterView(Contract = "Dialog", IsSingleton = true)] + public sealed class SecondView : IViewFor + { + public SecondViewModel? ViewModel { get; set; } + object? IViewFor.ViewModel { get => ViewModel; set => ViewModel = (SecondViewModel?)value; } + } + + [RegisterView] + public abstract class AbstractIgnoredView : IViewFor + { + public FirstViewModel? ViewModel { get; set; } + object? IViewFor.ViewModel { get => ViewModel; set => ViewModel = (FirstViewModel?)value; } + } + """; + + var (generatedSource, diagnostics) = RunGenerator(source); + + await Assert.That(generatedSource).IsNotNull(); + await Assert.That(diagnostics).IsEmpty(); + await Assert.That(generatedSource!).Contains("public static class GeneratedViewRegistrations"); + await Assert.That(generatedSource!).Contains("builder.RegisterView();"); + await Assert.That(generatedSource!).Contains( + "builder.WithRegistration(static resolver => resolver.RegisterLazySingleton<" + + "global::ReactiveUI.Binding.IViewFor>(" + + "static () => new global::TestNs.SecondView(), \"Dialog\"));"); + await Assert.That(generatedSource!).DoesNotContain("AbstractIgnoredView"); + } + + /// Verifies no source is emitted when no classes carry [RegisterView]. + /// A task representing the asynchronous test. + [Test] + public async Task EmitsNothingWhenNoViewsMarked() + { + const string source = """ + namespace TestNs; + public sealed class PlainClass { } + """; + + var (generatedSource, diagnostics) = RunGenerator(source); + + await Assert.That(generatedSource).IsNull(); + await Assert.That(diagnostics).IsEmpty(); + } + + /// Runs against the given source and returns the generated file and compile errors. + /// The C# source text. + /// The generated source text (or null) and any error diagnostics. + private static (string? GeneratedSource, ImmutableArray Errors) RunGenerator(string source) + { + var parseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp13); + var compilation = CSharpCompilation.Create( + "RegisterViewTest", + [CSharpSyntaxTree.ParseText(source, parseOptions)], + TestCompilationReferences.CreatePortableDefault(), + new(OutputKind.DynamicallyLinkedLibrary)); + + GeneratorDriver driver = CSharpGeneratorDriver.Create( + [new RegisterViewGenerator().AsSourceGenerator()], + parseOptions: parseOptions); + driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); + + var runResult = driver.GetRunResult(); + var generated = !runResult.GeneratedTrees.IsEmpty ? runResult.GeneratedTrees[0].ToString() : null; + var errors = outputCompilation.GetDiagnostics() + .Where(static d => d.Severity == DiagnosticSeverity.Error) + .ToImmutableArray(); + + return (generated, errors); + } +} diff --git a/src/tests/ReactiveUI.SourceGenerators.Tests/UnitTests/WireUpControlsGeneratorTests.cs b/src/tests/ReactiveUI.SourceGenerators.Tests/UnitTests/WireUpControlsGeneratorTests.cs new file mode 100644 index 00000000..485a2fe2 --- /dev/null +++ b/src/tests/ReactiveUI.SourceGenerators.Tests/UnitTests/WireUpControlsGeneratorTests.cs @@ -0,0 +1,150 @@ +// Copyright (c) 2019-2026 ReactiveUI and Contributors. All rights reserved. +// ReactiveUI and Contributors licenses this file to you under the MIT license. +// See the LICENSE file in the project root for full license information. + +using ReactiveUI.SourceGenerators.Android; + +namespace ReactiveUI.SourceGenerator.Tests; + +/// Tests compile-time Android control wire-up generation for [WireUpControls]. +public sealed class WireUpControlsGeneratorTests +{ + /// Minimal Android stubs for cross-platform generator testing. + private const string AndroidStubs = """ + namespace Android.Views + { + public class View + { + public T? FindViewById(int id) where T : View => default; + } + } + + namespace Android.App + { + public class Activity + { + public T? FindViewById(int id) where T : global::Android.Views.View => default; + } + } + + namespace Android.Widget + { + public class TextView : global::Android.Views.View { } + public class Button : global::Android.Views.View { } + } + + namespace TestNs + { + public static class Resource + { + public static class Id + { + public const int TitleText = 1; + public const int submit_btn = 2; + } + } + } + """; + + /// Verifies WireUpControls() is generated for an Activity with resource overrides and ignored properties. + /// A task representing the asynchronous test. + [Test] + public async Task GeneratesParameterlessWireUpControlsForActivity() + { + const string source = """ + using Android.App; + using Android.Widget; + using ReactiveUI.SourceGenerators.Android; + + namespace TestNs; + + [WireUpControls] + public partial class MainActivity : Activity + { + public TextView? TitleText { get; private set; } + + [WireUpResource("submit_btn")] + public Button? SubmitButton { get; private set; } + + [IgnoreResource] + public TextView? IgnoredLabel { get; private set; } + + public string NonViewProperty { get; set; } = string.Empty; + + public void Init() => WireUpControls(); + } + """; + + var (generatedSource, errors) = RunGenerator(source); + + await Assert.That(generatedSource).IsNotNull(); + await Assert.That(errors).IsEmpty(); + await Assert.That(generatedSource!).Contains("private void WireUpControls()"); + await Assert.That(generatedSource!).Contains("this.TitleText = this.FindViewById(Resource.Id.TitleText)!;"); + await Assert.That(generatedSource!).Contains("this.SubmitButton = this.FindViewById(Resource.Id.submit_btn)!;"); + await Assert.That(generatedSource!).DoesNotContain("IgnoredLabel"); + await Assert.That(generatedSource!).DoesNotContain("NonViewProperty"); + } + + /// Verifies WireUpControls(View rootView) and ExplicitOptIn = true work for Fragment-like classes. + /// A task representing the asynchronous test. + [Test] + public async Task GeneratesRootViewOverloadAndRespectsExplicitOptIn() + { + const string source = """ + using Android.Views; + using Android.Widget; + using ReactiveUI.SourceGenerators.Android; + + namespace TestNs; + + [WireUpControls(ExplicitOptIn = true)] + public partial class ProfileFragment + { + [WireUpResource] + public TextView? TitleText { get; private set; } + + public Button? NotOptedIn { get; private set; } + + public void Init(View root) => WireUpControls(root); + } + """; + + var (generatedSource, errors) = RunGenerator(source); + + await Assert.That(generatedSource).IsNotNull(); + await Assert.That(errors).IsEmpty(); + await Assert.That(generatedSource!).Contains("private void WireUpControls(global::Android.Views.View rootView)"); + await Assert.That(generatedSource!).Contains("this.TitleText = rootView.FindViewById(Resource.Id.TitleText)!;"); + await Assert.That(generatedSource!).DoesNotContain("NotOptedIn"); + } + + /// Runs against the given source with Android stubs. + /// The C# source text. + /// The generated source text (or null) and any error diagnostics. + private static (string? GeneratedSource, ImmutableArray Errors) RunGenerator(string source) + { + var parseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp13); + var compilation = CSharpCompilation.Create( + "WireUpControlsTest", + [ + CSharpSyntaxTree.ParseText(AndroidStubs, parseOptions, path: "AndroidStubs.cs"), + CSharpSyntaxTree.ParseText(source, parseOptions, path: "Activity.cs"), + ], + TestCompilationReferences.CreatePortableDefault(), + new(OutputKind.DynamicallyLinkedLibrary)); + + GeneratorDriver driver = CSharpGeneratorDriver.Create( + [new WireUpControlsGenerator().AsSourceGenerator()], + parseOptions: parseOptions); + driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); + + var runResult = driver.GetRunResult(); + var generated = !runResult.GeneratedTrees.IsEmpty ? runResult.GeneratedTrees[0].ToString() : null; + var errors = outputCompilation.GetDiagnostics() + .Where(static d => d.Severity == DiagnosticSeverity.Error) + .ToImmutableArray(); + + return (generated, errors); + } +}