Created
January 14, 2022 19:07
-
-
Save enisn/edc904eeede666f5feeab37072b39900 to your computer and use it in GitHub Desktop.
A syntax receiver for CodeAnalysis applications that handles attributes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using DotNurse.CodeAnalysis.Extensions; | |
using Microsoft.CodeAnalysis; | |
using Microsoft.CodeAnalysis.CSharp.Syntax; | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace DotNurse.CodeAnalysis; | |
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); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* This file presents usage of AttributeSyntaxReceiver | |
*/ | |
using Microsoft.CodeAnalysis; | |
namespace DotNurse.AutoBackend.Controllers; | |
[Generator] | |
public class SampleGenerator : ISourceGenerator | |
{ | |
public void Initialize(GeneratorInitializationContext context) | |
{ | |
// Register for syntax receiver with attribute | |
context.RegisterForSyntaxNotifications(() => new AttributeSyntaxReceiver<YourAttribute>()); | |
} | |
public void Execute(GeneratorExecutionContext context) | |
{ | |
if (context.SyntaxReceiver is AttributeSyntaxReceiver<YourAttribute> syntaxReceiver) | |
{ | |
// Do your stuff. | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment