skip to content

In a C# incremental source generator for [AutoDescribe], how do RegisterPostInitializationOutput, ForAttributeWithMetadataName and RegisterSourceOutput divide the work?

level: seniorimportance: should knowfreq 30%

answer

  1. Initialize describes, it does not generate
  2. fixed source first
  3. metadata name with the Attribute suffix
  4. model in, text out
  5. 99x per the cookbook

basics

~10 s

RegisterPostInitializationOutput emits the fixed [AutoDescribe] attribute, ForAttributeWithMetadataName finds the types marked with it and turns each into a small model, and RegisterSourceOutput turns each model into a generated file with AddSource.

solid answer

~30 s

An `IIncrementalGenerator` only describes a pipeline in `Initialize`. `RegisterPostInitializationOutput` adds input-free source, here the `AutoDescribeAttribute` class, so user code can apply it. `context.SyntaxProvider.ForAttributeWithMetadataName("Demo.AutoDescribeAttribute", predicate, transform)` yields one value per marked declaration; the transform gets `TargetSymbol` and the semantic model and should return a value-equatable record of strings. `RegisterSourceOutput` receives each model and calls `AddSource` with a unique hint name. Roslyn's cookbook says `ForAttributeWithMetadataName` is at least 99x more efficient than `CreateSyntaxProvider`, and the older `ISourceGenerator` API is deprecated because it reruns everything on every compilation.

code

csharp · 28 lines
csharp
[Generator]
public sealed class AutoDescribeGenerator : IIncrementalGenerator
{
    public void Initialize(IncrementalGeneratorInitializationContext context)
    {
        context.RegisterPostInitializationOutput(static ctx => ctx.AddSource("AutoDescribeAttribute.g.cs",
            "namespace Demo { [System.AttributeUsage(System.AttributeTargets.Struct)] internal sealed class AutoDescribeAttribute : System.Attribute { } }"));

        var models = context.SyntaxProvider.ForAttributeWithMetadataName(
            "Demo.AutoDescribeAttribute",
            predicate: static (node, _) => true,
            transform: static (ctx, _) =>
            {
                var type = (INamedTypeSymbol)ctx.TargetSymbol;
                var props = type.GetMembers().OfType<IPropertySymbol>()
                    .Where(p => !p.IsStatic && p.DeclaredAccessibility == Accessibility.Public)
                    .Select(p => $"{p.Name} = {{{p.Name}}}");
                string? ns = type.ContainingNamespace.IsGlobalNamespace ? null : type.ContainingNamespace.ToDisplayString();
                return new DescribeModel(ns, type.Name, $"{type.Name} ({string.Join(", ", props)})");
            });

        context.RegisterSourceOutput(models, static (spc, m) => spc.AddSource($"{m.TypeName}.Describe.g.cs",
            (m.Namespace is null ? "" : $"namespace {m.Namespace};\n") +
            $"partial record struct {m.TypeName}\n{{\n    public partial string Describe() => $\"{m.Body}\";\n}}\n"));
    }
}

internal sealed record DescribeModel(string? Namespace, string TypeName, string Body);

go deeper

for a junior

Recall that a generator has an Initialize method that wires up steps, and that a marker attribute tells it which types to work on.

for a middle

Explain the three registrations in order and what flows between them: fixed attribute source, one model per target, one file per model.

for a senior

Justify ForAttributeWithMetadataName over CreateSyntaxProvider with the cookbook's numbers, keep the transform's output equatable, and avoid hint-name clashes that end in CS8785.

for a principal

Treat the pipeline as a cost every user pays in builds and editors, and set rules for generators your teams ship: marker attributes only, no base-type scanning.

## The shape of an incremental generator An incremental generator is a class marked `[Generator]` that implements `Microsoft.CodeAnalysis.IIncrementalGenerator`, an interface with a single method, `Initialize(IncrementalGeneratorInitializationContext context)`. `Initialize` does no generation itself. It **describes a pipeline**: which inputs to watch, how to transform them, and which outputs to register. The compiler (and the IDE) then runs that pipeline on every compilation and reuses cached results wherever a step's output did not change. The older `ISourceGenerator` interface, with its `Initialize` and `Execute` pair and syntax receivers, is **deprecated** in Roslyn's documentation in favour of incremental generators; the current compiler sources mark implementing it obsolete. Its `Execute` receives the whole current `Compilation` on each generation pass with no cached steps in between, so whatever it computes is recomputed every time it runs. ## Three registrations, three jobs For an `[AutoDescribe]` generator that fills `public partial string Describe();` on a `partial record struct`, the pipeline has three parts: 1. **`RegisterPostInitializationOutput`** adds fixed source that depends on nothing, typically the **marker attribute** itself (`Demo.AutoDescribeAttribute`). It runs before anything else, takes no inputs, and its output becomes part of the compilation the rest of the pipeline and the user's code see, so `[AutoDescribe]` binds without the user referencing any extra assembly. 2. **`SyntaxProvider.ForAttributeWithMetadataName`** finds the targets. It takes the attribute's fully qualified metadata name including the `Attribute` suffix, a cheap syntactic `predicate`, and a `transform` that receives a `GeneratorAttributeSyntaxContext` with `TargetNode`, `TargetSymbol`, `SemanticModel` and the matching `Attributes`. It returns an `IncrementalValuesProvider<T>` of whatever model the transform builds. 3. **`RegisterSourceOutput`** turns each model into text with `SourceProductionContext.AddSource(hintName, source)`. Hint names must be unique within a generator; a duplicate makes `AddSource` throw `ArgumentException`, which the compiler reports as generator failure **CS8785**. Between steps 2 and 3 the provider can be reshaped with `Select`, `Where`, `Combine` (pair with another provider, such as the analyzer config options) and `Collect` (gather all values into one `ImmutableArray<T>` when a single file must list every target). ## Why `ForAttributeWithMetadataName` and not `CreateSyntaxProvider` `CreateSyntaxProvider(predicate, transform)` runs your predicate over syntax nodes and your transform with a `GeneratorSyntaxContext`, and leaves you to work out whether an attribute really binds to *your* attribute type. Roslyn's cookbook recommends a marker attribute plus `ForAttributeWithMetadataName` for every generator that inspects syntax, stating it is **at least 99x more efficient** than `CreateSyntaxProvider` and often more. Roslyn's implementation first skips syntax trees that contain no attribute list at all and then checks attribute names syntactically, so most files never reach your predicate or the binder. Its documentation adds one detail worth knowing: for a partial type, only the declarations that **syntactically** carry the attribute are returned, and each part that carries it is returned separately. | Choice | Discovers targets by | Cost profile | |---|---|---| | `ForAttributeWithMetadataName` | Attribute binding to one metadata name | Skips files with no candidate attribute | | `CreateSyntaxProvider` | Your predicate over syntax nodes | Your predicate and transform decide everything | | Scanning for a base type or interface | Walking every type's bases | Cannot be done incrementally; the cookbook advises against it | ## What the transform should return The transform runs with full semantic information, but its **return value is what gets cached**. Return a small, value-equatable record of strings, such as the namespace, the type name and the member list, never the `ISymbol` or `SyntaxNode` itself. Equal models let the driver skip `RegisterSourceOutput` entirely on edits that did not affect the type. (The caching mechanics are a topic of their own.) ## Mistakes that cost users - **Doing heavy work in the predicate.** The predicate receives only a `SyntaxNode` and should be a cheap shape check, such as "is this a record struct declaration"; anything that needs symbols belongs in the transform. - **Marker attributes declared in every project.** If several projects that see each other's internals each get the generated `internal` attribute, the compiler warns about the duplicates. The cookbook's remedy is to mark it with `Microsoft.CodeAnalysis.EmbeddedAttribute`, calling `AddEmbeddedAttributeDefinition` in the post-initialization callback (Roslyn 4.14 and later). - **Scanning for a base type or interface instead of an attribute.** The cookbook calls this very expensive and impossible to do incrementally, because every type's bases must be checked on every run. - **Assuming generators see each other.** With the standard outputs, each generator sees the same input compilation; one generator's attribute or helper type is not visible to another. ## Putting it together - Post-initialization: emit the attribute, so the user's `[AutoDescribe]` compiles. - Syntax provider: one model per marked record struct. - Source output: one `Price.Describe.g.cs` per model, written with a string builder rather than by constructing `SyntaxNode`s, which the cookbook discourages as slow and awkward to format. - Diagnostics: `SourceProductionContext.ReportDiagnostic` exists, but the cookbook recommends a separate analyzer for user-facing diagnostics because reporting from the generator without breaking incrementality is hard.

  • What happens if two [AutoDescribe] types in different namespaces share a name and the hint name is just the type name?
    Both models call `AddSource` with the same hint name. Hint names must be unique within one generator, so `AddSource` throws `ArgumentException`, and the compiler reports CS8785, generator failed to generate source; that generator contributes nothing, and the build then fails wherever user code relied on its output. Include the namespace, or the fully qualified name, in the hint name.
  • When would you use Collect in this pipeline?
    When one output depends on all targets together, such as a registry file listing every `[AutoDescribe]` type. `Collect` turns the `IncrementalValuesProvider<T>` into an `IncrementalValueProvider<ImmutableArray<T>>`, so `RegisterSourceOutput` runs once with the whole set. The trade-off is that any change to any target reruns that single output, so per-type files stay on the uncollected provider.

  • Initialize should generate the source directly, once per build.
  • ForAttributeWithMetadataName takes the short name, AutoDescribe, without the suffix.
  • The marker attribute must ship in a separate runtime package.
  • CreateSyntaxProvider is the recommended way to find attributed types.
  • Implementing ISourceGenerator is still the standard way to write one.