1

I'm trying to develop a source generator that I can theoretically add to my projects, and for the given project have it find classes that are marked up with a specific attribute, and then build a corresponding generated file for each.

I've set up unit tests that effectively use GeneratorDriver to instantiate and run generators and evaluate their output.

Problem

Classes exist in a secondary project referenced from the test project. The compilation does not appear to include syntaxTree's for the other project.

I've tried calling CreateCompilation with a simple program.cs body, and calling .AddReferences(MetadataReference.CreateFromFile(typeof(User).Assembly.Location), and then passing that to the in driver.

At runtime, my syntax trees are still all the same (perhaps because I assume that reference is treated like an assembly reference.

I assume in normal situations, generators will run with the context of projects they are referenced from as an Analyzer, but for the purposes of my unit testing, is there a way I can effectively set the compilation to be another project, or reference another project (such that when I walk the different syntax trees, I can access those classes marked with attributes in an external assembly)?

Ronnyek
  • 482
  • 5
  • 16
  • I think you need to provide your syntax trees as "strings". You cannot provide them as `MetadataReference`. – Youssef13 Apr 06 '22 at 17:59

1 Answers1

1

So I managed to get this fixed by creating a workspace (with Microsoft.CodeAnalysis.Workspaces) and loaded my other project in, got the compilation from that, and passed that to my GeneratorDriver.

My Generator isn't working 100% yet, but this definitely got me past the hurdle.

Ronnyek
  • 482
  • 5
  • 16
  • how did you get a workspace doesn't that require a `HostServices`? how did you load the projects? by file? maybe any examples? – Patrick Beynio Apr 13 '22 at 19:17
  • were you maybe using `Microsoft.CodeAnalysis.CSharp.Workspaces` and `Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create` more specifically? – Patrick Beynio Apr 13 '22 at 19:33