2

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...

1 Answer 1

2

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.
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Worked like a charm. One important detail is that the SyntaxTree needs to be parsed with the latest version of C# to support SourceGenerators, but the thrown Exception is straight forward.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.