Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Disable source generators for abstract types #260

Merged
merged 2 commits into from
May 24, 2022
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
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,15 @@ public sealed partial class ObservableValidatorValidateAllPropertiesGenerator :
/// <inheritdoc/>
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// Get all class declarations
// Get all class declarations. We intentionally skip generating code for abstract types, as that would never be used.
// The methods that are generated by this generator are retrieved through reflection using the type of the invoking
// instance as discriminator, which means a type that is abstract could never be used (since it couldn't be instantiated).
IncrementalValuesProvider<INamedTypeSymbol> typeSymbols =
context.SyntaxProvider
.CreateSyntaxProvider(
static (node, _) => node is ClassDeclarationSyntax,
static (context, _) => (context.Node, Symbol: (INamedTypeSymbol)context.SemanticModel.GetDeclaredSymbol(context.Node)!))
.Where(static item => item.Node.IsFirstSyntaxDeclarationForSymbol(item.Symbol))
.Where(static item => !item.Symbol.IsAbstract && item.Node.IsFirstSyntaxDeclarationForSymbol(item.Symbol))
.Select(static (item, _) => item.Symbol);

// Get the types that inherit from ObservableValidator and gather their info
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,13 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
// definitions (it might happen if a recipient has partial declarations). To do this, all pairs
// of class declarations and associated symbols are gathered, and then only the pair where the
// class declaration is the first syntax reference for the associated symbol is kept.
// Just like with the ObservableValidator generator, we also intentionally skip abstract types.
IncrementalValuesProvider<INamedTypeSymbol> typeSymbols =
context.SyntaxProvider
.CreateSyntaxProvider(
static (node, _) => node is ClassDeclarationSyntax,
static (context, _) => (context.Node, Symbol: (INamedTypeSymbol)context.SemanticModel.GetDeclaredSymbol(context.Node)!))
.Where(static item => item.Node.IsFirstSyntaxDeclarationForSymbol(item.Symbol))
.Where(static item => !item.Symbol.IsAbstract && item.Node.IsFirstSyntaxDeclarationForSymbol(item.Symbol))
.Select(static (item, _) => item.Symbol);

// Get the target IRecipient<TMessage> interfaces and filter out other types
Expand Down
29 changes: 26 additions & 3 deletions tests/CommunityToolkit.Mvvm.UnitTests/Test_IRecipientGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
// See the LICENSE file in the project root for more information.

using System;
using System.Linq;
using System.Reflection;
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.VisualStudio.TestTools.UnitTesting;

Expand Down Expand Up @@ -52,9 +54,20 @@ public void Test_IRecipientGenerator_TypeWithMultipleClassDeclarations()
_ = Messaging.__Internals.__IMessengerExtensions.CreateAllMessagesRegistratorWithToken<int>(recipient);
}

public sealed class RecipientWithSomeMessages :
IRecipient<MessageA>,
IRecipient<MessageB>
[TestMethod]
public void Test_IRecipientGenerator_AbstractTypesDoNotTriggerCodeGeneration()
{
MethodInfo? createAllPropertiesValidatorMethod = typeof(Messaging.__Internals.__IMessengerExtensions)
.GetMethods(BindingFlags.Static | BindingFlags.Public)
.Where(static m => m.Name == "CreateAllMessagesRegistratorWithToken")
.Where(static m => m.GetParameters() is { Length: 1 } parameters && parameters[0].ParameterType == typeof(AbstractModelWithValidatablePropertyIRecipientInterfaces))
.FirstOrDefault();

// We need to validate that no methods are generated for abstract types, so we just check this method doesn't exist
Assert.IsNull(createAllPropertiesValidatorMethod);
}

public sealed class RecipientWithSomeMessages : IRecipient<MessageA>, IRecipient<MessageB>
{
public MessageA? A { get; private set; }

Expand Down Expand Up @@ -91,4 +104,14 @@ public void Receive(MessageA message)
partial class RecipientWithMultipleClassDeclarations
{
}

public abstract class AbstractModelWithValidatablePropertyIRecipientInterfaces : IRecipient<MessageA>, IRecipient<MessageB>
{
public abstract void Receive(MessageA message);

public void Receive(MessageB message)
{

}
}
}
20 changes: 20 additions & 0 deletions tests/CommunityToolkit.Mvvm.UnitTests/Test_ObservableValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,19 @@ public void Test_ObservableValidator_VerifyTrimmingAnnotation()
#endif
}

[TestMethod]
public void Test_ObservableRecipient_AbstractTypesDoNotTriggerCodeGeneration()
{
MethodInfo? createAllPropertiesValidatorMethod = typeof(ComponentModel.__Internals.__ObservableValidatorExtensions)
.GetMethods(BindingFlags.Static | BindingFlags.Public)
.Where(static m => m.Name == "CreateAllPropertiesValidator")
.Where(static m => m.GetParameters() is { Length: 1 } parameters && parameters[0].ParameterType == typeof(AbstractModelWithValidatableProperty))
.FirstOrDefault();

// We need to validate that no methods are generated for abstract types, so we just check this method doesn't exist
Assert.IsNull(createAllPropertiesValidatorMethod);
}

public class Person : ObservableValidator
{
private string? name;
Expand Down Expand Up @@ -777,4 +790,11 @@ public partial class PersonWithPartialDeclaration
[Range(10, 1000)]
public int Number { get; set; }
}

public abstract class AbstractModelWithValidatableProperty : ObservableValidator
{
[Required]
[MinLength(2)]
public string? Name { get; set; }
}
}