admin管理员组

文章数量:1333451

Simple source generator that tries to obtain DeclarationSyntaxReference for classes in defined namespaces.

public class XmlCommentIncrementalGenerator : IIncrementalGenerator
{
    public void Initialize(IncrementalGeneratorInitializationContext context)
    {
        var members = context.CompilationProvider
            .Select((compilation, _) => {
                var names = compilation.GlobalNamespace.GetNamespaceMembers()
                    .Where(x => x.Name.Contains("SourceGenTest") || x.Name.Contains("SomeLib")) //gets the namespaces
                    .SelectMany(x=> x.GetMembers()) //gets classes
                    .Select(x => $"{x.Name}  DSR:{x.DeclaringSyntaxReferences.FirstOrDefault()}");

                return names.ToImmutableArray();
            });

        context.RegisterSourceOutput(members, (ctx, array) => {
            string output = "//" + string.Join("\n//", array);
            ctx.AddSource("Output.g.cs", SourceText.From(output, Encoding.UTF8));
        }
        );
    }
}

Solution structure:

  • SourceGenTest - base project, console app, has reference to SourceGen and SomeLib
  • SourceGen - where the sg lives
  • SomeLib - some lib, has no references. Is referenced by SourceGenTest

Output of the sg:

//ClassInBaseProj  DSR:Microsoft.CodeAnalysis.CSharp.SimpleSyntaxReference
//ClassInLib       DSR:

As you can see the class that is in base project (ClassInBaseProj from SourceGenTest) has the DeclaringSyntaxReference, while the ClassInLib doesn't.

Is it possible to obtain the DeclaringSyntaxReferences even for classes from referenced project?

What are the other options?

In the end I am trying to gather the xml comments from properties and also their default values. I figured I need the DeclaringSyntaxReferences for that, but if there is some other solution, please don't hesitate to share it..

Full source code.

Thanks!

本文标签: cIIncrementalGenerator Obtaining DeclaringSyntaxReferences from ltProjectReference classesStack Overflow