简体   繁体   中英

Why is this incremental source generator invoked when nothing changes

The following source generator creates a new record type on initialization. It then selects the symbol for this type in another step, and generates a dummy file with a timestamp.

Since the underlying record type is only generated once on initialization, and does not change anymore thereafter, I would've expected the next transformation step to be invoked only once. However, it seems to be updated every time I type anything whatsoever in my IDE (Rider 2022.3.1), ie test2.g.cs is re-generated each time with an updated timestamp.

Why does that happen - and how can I prevent these unnecessary updates?

public class TestGenerator : IIncrementalGenerator
{
    public void Initialize(IncrementalGeneratorInitializationContext context)
    {
        // Create test1.g.cs on initialization
        context.RegisterPostInitializationOutput(context => context.AddSource("test1.g.cs", "public record TestRecord();"));

        // Find the type symbol for the previously generated record, and generate test2.g.cs based on this
        context.RegisterSourceOutput(
            context.SyntaxProvider.CreateSyntaxProvider(
                static (context, _) => context is RecordDeclarationSyntax s && s.Identifier.Text.Equals("TestRecord"),
                static (context, _) => context.SemanticModel.GetDeclaredSymbol(context.Node) as INamedTypeSymbol
                ).Where(x => x is not null),
            (context, symbol) => context.AddSource("test2.g.gs", $"// Found: {symbol is not null} at {DateTime.UtcNow}")
            );
    }
}

Turns out this was caused by referencing the analyzer project directly.

When packaging it into a NuGet package and referencing that, caching works as expected.

Don't include symbols in the pipeline. They root compilations in memory, and won't compare equal across different compilations.

Instead, you should be creating a data model (with proper equality semantics - preferably with records). The data model should only include what you really need for generation, not including symbols, syntax nodes, compilation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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