最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - IIncrementalGenerator: Obtaining DeclaringSyntaxReferences from <ProjectReference classes - Stack Overflow

programmeradmin0浏览0评论

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!

发布评论

评论列表(0)

  1. 暂无评论