简体   繁体   English

C# 增量源生成器缓存错误?

[英]C# Incremental Source Generator caching bug?

I'm trying to wrap my head around the new Roslyn Incremental Source Generators, by making a simple generator, that lists all invoked methods in a file called InvokedMethods.g.cs.我试图通过制作一个简单的生成器来了解新的 Roslyn 增量源生成器,该生成器在一个名为 InvokedMethods.g.cs 的文件中列出所有调用的方法。

It almost works, but there is an issue when typing in Visual Studio.几乎可以工作,但在 Visual Studio 中键入时出现问题。 Or more specfically, when deleting the last method invocation, because then the source generator doesn't produce an empty file, as I would expect it to do.或者更具体地说,在删除最后一个方法调用时,因为源生成器不会像我期望的那样生成空文件。

Either I don't fully understand the way CreateSyntaxProvider is supposed to work (which is quite likely) otherwise there is a bug in the Visual Studio 2022 implementation?要么我不完全理解 CreateSyntaxProvider 应该如何工作(这很可能),否则 Visual Studio 2022 实现中存在错误?

[Generator]
public class ListMethodInvocationsGenerator : IIncrementalGenerator
{
    public void Initialize(IncrementalGeneratorInitializationContext context)
    {
        IncrementalValueProvider<ImmutableArray<string>> invokedMethodsProvider = context.SyntaxProvider.CreateSyntaxProvider(
                predicate: (node, _) => node is InvocationExpressionSyntax,
                transform: (ctx, _) => (ctx.SemanticModel.GetSymbolInfo(ctx.Node).Symbol)?.Name ?? "<< method not found >>")
            .Collect();

        context.RegisterSourceOutput(invokedMethodsProvider, (SourceProductionContext spc, ImmutableArray<string> invokedMethods) =>
        {
            var src = new StringBuilder();
            foreach (var method in invokedMethods)
            {
                src.AppendLine("// " + method);
            }
            spc.AddSource("InvokedMethods.g.cs", src.ToString());
        });
    }
}

Your delegate for RegisterSourceOutput will not be called if there are no InvocationExpressions.如果没有 InvocationExpressions,则不会调用 RegisterSourceOutput 的委托。 If you want a blank output file, you could add a predicate and transform for CompilationUnitSyntax.如果你想要一个空白的 output 文件,你可以为 CompilationUnitSyntax 添加一个谓词和转换。 That will allow you to generate the blank file when no methods are found.这将允许您在没有找到方法时生成空白文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM