Skip to content

Source Generators: RegisterReferenceSourceOutput #57589

@chsienki

Description

@chsienki

Background and Motivation

Today we have a source generator API called RegisterImplementationOnlyOutput which allows a generator to indicate that it is generating source code that does not impact the design time experience (i.e. intellisense). Certain hosts, such as the IDE may choose not to run these types of outputs as it knows they are not required.

This works well for things which are truly non visible (such as regex optimization), but cannot be used as soon as the generator adds any code that the user can reference. This proposal creates a 'mirror' API that allows a generator to provide a 'reference' implementation without any actual generated method body.

For generators that spend most of their time introspecting code will not much benefit from these APIs, but any generator where generation is expensive, then this should provide a good balance between speed and IDE correctness.

Proposed API

namespace Microsoft.CodeAnalysis
{
     public readonly struct IncrementalGeneratorInitializationContext
     {
+        public void RegisterReferenceSourceOutput<TSource>(IncrementalValuesProvider<TSource> source, Action<SourceProductionContext, TSource> action);
     }

Usage Examples

[Generator]
internal sealed class Generator : IIncrementalGenerator
{
    public void Initialize(IncrementalGeneratorInitializationContext context)
    {
        var content = context.AdditionalTextsProvider.Select((a, _) => /*extract something of intrest*/);

        context.RegisterImplementationSourceOutput(content, (spc, content) =>
        {
            // do the full, expensive generation
        });

        context.RegisterReferenceSourceOutput(content, (spc, content) =>
        {
            // just build a cheap, method decl skeleton for intelliense etc.
        });
    } 
}

Risks

This is a natural mirror to our already implemented API, but all new output APIs run the risk of making it less clear which to use in which situation.

Metadata

Metadata

Assignees

Labels

Area-CompilersConcept-APIThis issue involves adding, removing, clarification, or modification of an API.Feature - Source GeneratorsSource GeneratorsFeature Requestapi-needs-workAPI needs work before it is approved, it is NOT ready for implementation

Type

No type

Projects

Status

No status

Relationships

None yet

Development

No branches or pull requests

Issue actions