Skip to content

Instantly share code, notes, and snippets.

@xoofx
Last active December 10, 2022 14:03
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xoofx/ddcc713d941417de48524c200e74db14 to your computer and use it in GitHub Desktop.
Save xoofx/ddcc713d941417de48524c200e74db14 to your computer and use it in GitHub Desktop.
Roslyn Source Generator optimized for build time only usage
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using Microsoft.CodeAnalysis.Text;
namespace SourceGenLib
{
// Shows how to build a source generator that will run only at build time
// but not at IDE time.
// When running at IDE time, the Execute method can be called 5+ times per ~keystrokes/changes in the file.
// If your source generator generates code that doesn't require the user to know about it
// better to generate the code only at build time to save more valuable IDE time.
[Generator]
public class MySourceGenerator : ISourceGenerator
{
public void Execute(GeneratorExecutionContext context)
{
// Don't run if not in buildtime
if (!IsBuildTime) return;
// ...
}
public void Initialize(GeneratorInitializationContext context)
{
// Register only when running from VBCSCompiler/csc
if (IsBuildTime)
{
// ...
context.RegisterForSyntaxNotifications(() => new BuildableReceiver());
}
}
// Entry assembly is null in VS IDE
// At build time, it is `csc` or `VBCSCompiler`
private static readonly bool IsBuildTime = Assembly.GetEntryAssembly() != null;
// Receiver example
internal class BuildableReceiver : ISyntaxReceiver
{
public List<ClassDeclarationSyntax> CandidateClasses { get; } = new List<ClassDeclarationSyntax>();
public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
{
if (syntaxNode is ClassDeclarationSyntax cds)
{
CandidateClasses.Add(cds);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment