Home > Blockchain >  Canot resolve argument parameters in Roslyn Source Generation
Canot resolve argument parameters in Roslyn Source Generation

Time:04-27

I am having trouble getting parameter values from attributes in a source generator.

I have an IIncrementalSourceGenerator that is supposed to look up a class type and inspect the attributes of that class. There is a single string parameter on the attribute that comes through fine, but the named Type attribute is always null.

[AttributeUsage(AllowMultiple = true)]
public class ExampleAttribute : Attribute
{
  public ExampleAttribute(string name) {}
  public System.Type Kind { get; set; }
  public MyProject.MyColor { get; set; }
}

public enum MyColor { Red, Blue, Green }

[Example("one")] // Works fine
[Example("two", Kind = typeof(string))] // param "Kind" is null
[Example("two", Color = Color.Red)] // totally missing all values
public class ExampleClass
{
  // ...
}

// elsewhere, in a different assembly, I'm detecting this:

new ExampleClass();

I've used myriad methods to obtain the type information, all with the same result. Currently in the "transform" callback of the generator's "CreateSyntaxProvider" call I'm getting the attributes this way:

var nameSyntax = context.Node as ObjectCreationExpressionSyntax.Type as IdentifierNameSyntax;

var typeSymbol = context.SemanticModel.GetSymbolInfo(typeSyntax).Symbol as INamedTypeSymbol;

var attributes = typeSymbol.GetAttributes();

At this point the first of these attributes is fine, attribute.ConstructorArguments has one value with a string Value property of "one".

The second also has a constructor argument value of "two", as well as a single NamedArgument with the key "Kind" but the value is null. On inspection, the private InternalValue property of the argument value is a MissingMetadataTypeSymbol, with an error message that indicates it was trying to resolve the "Type" (System.Type) as "MyProject.Type". No amount of namespace changes or explicit namespace qualification seems to be able to fix this.

The third attribute is completely empty. No constructor arguments, no named parameters at all.

The ExampleAttribute and Example class are in one library, the generator is in another, both are referenced in the application. The library and application both target .NET 6.

CodePudding user response:

So turns out this was caused by referencing the Microsoft.CodeAnalysis.CSharp.Workspaces instead of using Microsoft.CodeAnalysis.Analyzers and Microsoft.CodeAnalysis.CSharp. Kind of unexpected as these are dependencies of the workspaces package and this package is suggested in examples on a few blog articles that are highly ranked on Google, but this will actually cause all kinds of strange issues like syntax highlighting errors on generated code while at the same time kinda sorta working.

  • Related