C#增量源发电机缓存错误?
我正在尝试通过制作一个简单的生成器来围绕新的Roslyn增量源生成器,该发电机在称为InvokedMethods.g.cs的文件中列出了所有调用方法。
它几乎有效,但是在Visual Studio打字时存在问题。或更具体地,当删除最后一个方法调用时,因为那时源生成器不会像我期望的那样产生空文件。
我要么不完全了解创建的方式应该有效的方式(很可能),否则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());
});
}
}
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.
It almost works, but there is an issue when typing in 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?
[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());
});
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果没有Invocation Expressions,则不会调用您的RegisterSourceOutput的委托。如果需要一个空白输出文件,则可以添加谓词并进行compilationunitsyntax。当找不到方法时,这将使您能够生成空白文件。
Your delegate for RegisterSourceOutput will not be called if there are no InvocationExpressions. If you want a blank output file, you could add a predicate and transform for CompilationUnitSyntax. That will allow you to generate the blank file when no methods are found.