Skip to content

Instantly share code, notes, and snippets.

@enisn
Created January 15, 2022 10:47
Show Gist options
  • Save enisn/52cb3f5e49ce9c68c44d69bf99986db2 to your computer and use it in GitHub Desktop.
Save enisn/52cb3f5e49ce9c68c44d69bf99986db2 to your computer and use it in GitHub Desktop.
Mastering at Source Generators - AttributeSyntaxReceiver
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Awesome.Generators;
public class AttributeSyntaxReceiver<TAttribute> : ISyntaxReceiver
where TAttribute : Attribute
{
public IList<ClassDeclarationSyntax> Classes { get; } = new List<ClassDeclarationSyntax>();
public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
{
if (syntaxNode is ClassDeclarationSyntax classDeclarationSyntax &&
classDeclarationSyntax.AttributeLists.Count > 0 &&
classDeclarationSyntax.AttributeLists
.Any(al => al.Attributes
.Any(a => a.Name.ToString().EnsureEndsWith("Attribute").Equals(typeof(TAttribute).Name))))
{
Classes.Add(classDeclarationSyntax);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment