Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/ReactiveUI.SourceGenerators.Roslyn/AttributeDefinitions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,27 @@ internal static class AttributeDefinitions
/// <summary>The metadata name of <c>[ReactiveCollection]</c>.</summary>
public const string ReactiveCollectionAttributeType = "ReactiveUI.SourceGenerators.ReactiveCollectionAttribute";

/// <summary>The metadata name of <c>[RegisterView]</c>.</summary>
public const string RegisterViewAttributeType = "ReactiveUI.SourceGenerators.RegisterViewAttribute";

/// <summary>The metadata name of <c>[RegisterView&lt;T&gt;]</c>.</summary>
public const string RegisterViewGenericAttributeType = "ReactiveUI.SourceGenerators.RegisterViewAttribute`1";

/// <summary>The metadata name of <c>[AutoPersist]</c>.</summary>
public const string AutoPersistAttributeType = "ReactiveUI.SourceGenerators.AutoPersistAttribute";

/// <summary>The metadata name of <c>[ReactiveValidation]</c>.</summary>
public const string ReactiveValidationAttributeType = "ReactiveUI.SourceGenerators.ReactiveValidationAttribute";

/// <summary>The metadata name of <c>[WireUpControls]</c>.</summary>
public const string WireUpControlsAttributeType = "ReactiveUI.SourceGenerators.Android.WireUpControlsAttribute";

/// <summary>The metadata name of <c>[WireUpResource]</c>.</summary>
public const string WireUpResourceAttributeType = "ReactiveUI.SourceGenerators.Android.WireUpResourceAttribute";

/// <summary>The metadata name of <c>[IgnoreResource]</c>.</summary>
public const string IgnoreResourceAttributeType = "ReactiveUI.SourceGenerators.Android.IgnoreResourceAttribute";

/// <summary>The attribute that excludes a generated control host from code coverage.</summary>
public const string ExcludeFromCodeCoverage = "[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]";
}
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>Generates a compile-time <c>AutoPersistMetadata</c> static property for classes marked with <c>[AutoPersist]</c>.</summary>
[Generator(LanguageNames.CSharp)]
public sealed class AutoPersistGenerator : IIncrementalGenerator
{
/// <summary>The metadata name of <c>DataContractAttribute</c>.</summary>
private const string DataContractAttributeName = "System.Runtime.Serialization.DataContractAttribute";

/// <summary>The metadata name of <c>DataMemberAttribute</c>.</summary>
private const string DataMemberAttributeName = "System.Runtime.Serialization.DataMemberAttribute";

/// <summary>The fully qualified generator name written to generated-code attributes.</summary>
private static readonly string GeneratorName = typeof(AutoPersistGenerator).FullName!;

/// <summary>The generator assembly version written to generated-code attributes.</summary>
private static readonly string GeneratorVersion = typeof(AutoPersistGenerator).Assembly.GetName().Version.ToString();

/// <summary>The <c>GeneratedCode</c> attribute stamped on generated members.</summary>
private static readonly string GeneratedCodeAttribute = SourceWriterExtensions.GeneratedCodeAttribute(GeneratorName, GeneratorVersion);

/// <inheritdoc/>
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)));
}

/// <summary>Extracts <c>[DataContract]</c> and <c>[DataMember]</c> metadata from an attributed class.</summary>
/// <param name="context">The generator attribute syntax context.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The extracted metadata, or <see langword="null"/> when the class is not partial.</returns>
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<string>.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());
}

/// <summary>Checks whether a type or any of its base types carries the specified attribute.</summary>
/// <param name="typeSymbol">The type symbol.</param>
/// <param name="attributeMetadataName">The full metadata name of the attribute.</param>
/// <returns><see langword="true"/> if found; otherwise <see langword="false"/>.</returns>
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;
}

/// <summary>Checks whether a symbol directly carries the specified attribute.</summary>
/// <param name="symbol">The symbol to inspect.</param>
/// <param name="attributeMetadataName">The full metadata name of the attribute.</param>
/// <returns><see langword="true"/> if found; otherwise <see langword="false"/>.</returns>
private static bool HasAttribute(ISymbol symbol, string attributeMetadataName)
{
foreach (var attribute in symbol.GetAttributes())
{
if (attribute.AttributeClass?.ToDisplayString() == attributeMetadataName)
{
return true;
}
}

return false;
}

/// <summary>Generates the partial class declaring <c>AutoPersistMetadata</c>.</summary>
/// <param name="info">The extracted persistence metadata.</param>
/// <param name="integration">The detected ReactiveUI integration.</param>
/// <returns>The generated C# source.</returns>
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<string>(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();
}
}
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>Describes compile-time persistence metadata extracted from a type marked with <c>[AutoPersist]</c>.</summary>
/// <param name="TargetInfo">The target type metadata.</param>
/// <param name="HasDataContract">Whether the target type is annotated with <c>[DataContract]</c>.</param>
/// <param name="PersistablePropertyNames">The public instance property names annotated with <c>[DataMember]</c>.</param>
internal sealed record AutoPersistInfo(
TargetInfo TargetInfo,
bool HasDataContract,
EquatableArray<string> PersistablePropertyNames);
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,16 @@ internal static class TrackingNames

/// <summary>The <c>[ViewModelControlHost]</c> models.</summary>
internal const string ViewModelControlHosts = nameof(ViewModelControlHosts);

/// <summary>The <c>[RegisterView]</c> models.</summary>
internal const string RegisteredViews = nameof(RegisteredViews);

/// <summary>The <c>[AutoPersist]</c> models.</summary>
internal const string AutoPersistTypes = nameof(AutoPersistTypes);

/// <summary>The <c>[ReactiveValidation]</c> models.</summary>
internal const string ReactiveValidationTypes = nameof(ReactiveValidationTypes);

/// <summary>The <c>[WireUpControls]</c> models.</summary>
internal const string WireUpControlsTypes = nameof(WireUpControlsTypes);
}
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>Describes compile-time DataAnnotations validation wiring for a class marked with <c>[ReactiveValidation]</c>.</summary>
/// <param name="TargetInfo">The target type metadata.</param>
/// <param name="Properties">The validated <c>ReactiveProperty&lt;T&gt;</c> properties on the class.</param>
internal sealed record ReactiveValidationInfo(
TargetInfo TargetInfo,
EquatableArray<ValidatedPropertyInfo> Properties);
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>Describes a <c>ReactiveProperty&lt;T&gt;</c> property and its DataAnnotations validation attributes.</summary>
/// <param name="PropertyName">The property name on the declaring class.</param>
/// <param name="DisplayName">The display name from <c>[Display(Name = ...)]</c>, or the property name.</param>
/// <param name="ValidationAttributes">The validation attributes applied to the property.</param>
internal sealed record ValidatedPropertyInfo(
string PropertyName,
string DisplayName,
EquatableArray<AttributeInfo> ValidationAttributes);
Loading
Loading