Skip to content

Instantly share code, notes, and snippets.

@enisn
Created January 14, 2022 19:07
Show Gist options
  • Save enisn/edc904eeede666f5feeab37072b39900 to your computer and use it in GitHub Desktop.
Save enisn/edc904eeede666f5feeab37072b39900 to your computer and use it in GitHub Desktop.
A syntax receiver for CodeAnalysis applications that handles attributes
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 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