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

roslyn - C# Source generator accessing code from "Referenced Project(s)" - Stack Overflow

programmeradmin2浏览0评论

I'm writing a source generator which will generate factories to create instances of object(s).

Since the source generator generates code that's related to tests, I'm going to install the source generator in the actual test project.

Now, assume that the source project contains a simple record, such as a Person, I want the source generator to find this one, and then based on that one, generate some code.

Here's the source generator currently:

    public void Initialize(IncrementalGeneratorInitializationContext context)
    {
        IncrementalValueProvider<ImmutableArray<TypeBuilderMetadata?>> provider = context
            .SyntaxProvider.CreateSyntaxProvider(
                (node, token) =>
                {
                    token.ThrowIfCancellationRequested();

                    return node is RecordDeclarationSyntax;
                },
                (ctx, token) =>
                {
                    token.ThrowIfCancellationRequested();

                    var symbol = (RecordDeclarationSyntax)ctx.Node;

                    if (ctx.SemanticModel.GetDeclaredSymbol(symbol, token) is not INamedTypeSymbol recordSymbol)
                    {
                        return null;
                    }

                    var fullTypeName = recordSymbol.ToDisplayString();
                    var typeNamespace = recordSymbol.GetFullNamespace();

                    return NewTypeBuilderDefinition(recordSymbol, recordSymbol);
                }
            )
            .Where(builder => builder is not null)
            .Collect();

        context.RegisterSourceOutput(provider, this.GenerateSource);
    }

Now, since the test project doesn't contain any 'Record' definitions, the source generator will never generate code. This is because the SyntaxProvider does look at the current project, and not at the entire compilation.

Is there a way to look at the syntax trees of the entire compilation?

发布评论

评论列表(0)

  1. 暂无评论