Skip to content

Incremental Source Generator - Not generating empty file, when last syntax node is deleted #61162

@lskyum

Description

@lskyum

The issue described here happens when when editing C# source with Visual Studio 2022. The generator seems to work, but it doesn't generate an empty source file, when the syntax provider should find zero syntax nodes. Instead it seems to use some cached syntax nodes.

Version Used:
4.0.1

Steps to Reproduce:
Using Visual Studio 2022 (Version 17.1.6)

  1. Compile the generator ListMethodInvocationsGenerator (code below) and reference it in a test project. (For example a Class Library or Console App)
  2. Add some method invocations, for example Console.WriteLine (observe that InvokedMethods.g.cs now lists the method names)
  3. Delete all the method invocations again, and observe that the InvokedMethods.g.cs still contains something.
[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 >>")
			.Where(m => m != null)
			.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());
		});
	}
}

Expected Behavior:
I would expect the file InvokedMethods.g.cs to be empty after deleting all method invocations in the code.

Actual Behavior:
Instead InvokedMethods.g.cs contains one or more of the deleted method invocations.
Note that when restarting Visual Studio, the generator produces an empty file, so maybe the is a bug in the caching?

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions