I am trying to run C# source generators in-memory using the following code snippet:
var syntaxTree = await SyntaxTreeFromRelativeFile("testdata/IMyInterface.cs");
var compilation = CSharpCompilation.Create("compilation", ImmutableArray.Create(syntaxTree), References);
var generator = new ProxyGenerator();
GeneratorDriver driver = CSharpGeneratorDriver.Create(generator);
driver = driver.RunGenerators(compilation);
References
is set to the necessary sources to compile the code:
public static readonly ImmutableArray<MetadataReference> References = ImmutableArray.Create<MetadataReference>(
// System
MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
MetadataReference.CreateFromFile(typeof(GCSettings).Assembly.Location),
MetadataReference.CreateFromFile(typeof(Attribute).Assembly.Location),
MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location),
// JetBrains
MetadataReference.CreateFromFile(typeof(UsedImplicitlyAttribute).Assembly.Location),
// some custom ones
);
While the generator runs just fine this way, it sadly doesn't have the desired affect, because the source generator relies on an attribute to know whether to generate source for the specified type. The exact source is something along the following:
[MyAttribute]
public interface IMyInterface { /* ... */ }
The source generator picks up the attribute correctly, but it gets resolved to an ExtendedErrorTypeSymbol
with the result kind being NotAnAttributeType
. However, the extended error type symbol also has a candidate symbol, which is the exact symbol I expect it to match.
This is surprising to me, because clearly the type is an attribute, and running the source generator as part of the normal compilation actually does generate all the right types. This seems to imply that there is something strange going on because of the in-memory nature of this run specifically.
As far as I can tell, my list of References
covers everything that is needed to correctly realise that something is an attribute (mscorlib
, System.Runtime
, netstandard
, and System.Core
), though perhaps there is another MetadataReference
missing?
I did find this GitHub issue which seems to describe a very similar, if not the same problem.
I'd love to know if I did something wrong here, if there are other references I am missing, or whether I am missing something completely else altogether.
DiagnosticBag
, do not see it either? – Quackery