I'm attempting to develop a source generator to auto-implement an interface on partial classes with that interface.
I believe this has to be a common use case for Microsoft's new Source Generators, and is even listed as a use case in the Roslyn Source Generator Cookbook, but with no example implementation.
I've searched but have struggled to find questions targeting this scenario in Roslyn Analyzers.
In the cookbook, they use a SyntaxReceiver class to filter which syntax nodes should be processed by the Execute
call:
class SluggableSyntaxReceiver : ISyntaxReceiver
{
public List<ClassDeclarationSyntax> ClassesToAugment { get; } = new List<ClassDeclarationSyntax>();
public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
{
// Business logic to decide what we're interested in goes here
if(syntaxNode is ClassDeclarationSyntax cds && cds.HasInterface("IChangeTracked"))
ClassesToAugment.Add(cds)
}
}
Check out the cookbook for the implementation details of the generator.
What I am trying to nail down is how to implement my HasInterface
extension on the ClassDeclarationSyntax node.
public static bool HasInterface(this ClassDeclarationSyntax source, string interfaceName)
{
IEnumerable<TypeSyntax> baseTypes = source.BaseList.Types.Select(baseType=>baseType.Type);
// Ideally some call to do something like...
return baseTypes.Any(baseType=>baseType.Name==interfaceName);
}
How do I:
- take the BaseList property from the ClassDeclarationSyntax,
- determine if the class is partial or not
- access the interfaces
- determine if any of the interfaces is of a specific type.