Search code examples
c#roslynroslyn-code-analysis

C# Use SourceGenerator with CSharpCompilation


Leading Question

Is it possible to use ISourceGenerator with CSharpCompilation.Create(...)?

Background

I've created a Roslyn SourceGenerator based on ISourceGenerator. This generator creates some partial classes with code that I don't want to write myself and can be generated from attributes and stuff. It works well in VisualStudio.

I've also created another programm that generates C# code and uses CSharpCompilation.Create(...) to compile it in memory.

Now I want to combine the two, so the later programm can skip the parts that the SourceGenerator will generate while compiling the code.

I know SourceGenerators are not stable, so is this use case already implemented?

I tryed to use MetadataReference.CreateFromFile(typeof(MyGenerator).Assembly.Location) and feed it to CSharpCompilation.Create(references: x) but it didn't work =/

I know for Analyzers there is an extension method WithAnalyzers, but Analyzers work differently...


Solution

  • There's a GeneratorDriver API that you can use. As a caveat, as of this writing the API is still considered beta and could change, but I suspect as long as you stick to the process below it should be good.

    Basically how the API is works is you:

    1. Call CSharpGeneratorDriver.Create, passing in the list of generators.
    2. Call this method which you pass in your compilation, and it gives you a new compilation with the generated trees added.