dotnet / roslyn

The Roslyn .NET compiler provides C# and Visual Basic languages with rich code analysis APIs.
https://docs.microsoft.com/dotnet/csharp/roslyn-sdk/
MIT License
18.71k stars 3.98k forks source link

Incremental Source Generators: Concat Extensionmethod #69632

Open LokiMidgard opened 10 months ago

LokiMidgard commented 10 months ago

Background and Motivation

When writing a source code generators and have two IncrementalValuesProvider<T> of the same T and need to merge them the only way today is to collect both to an list and combine those two lists, or do every transformation with both until they get collected, or registered with an output.

The frist is easier, but less efficent, as changing one input, will result in reexecuting the whole pipeline for every element not only the changed. While the later bears the risk that a change in one pipeline is not carried over to the other. You can write a helper function, but that may scatter your code more then nessesary.

Proposed API

namespace Microsoft.CodeAnalysis.Operations
{
namespace Microsoft.CodeAnalysis
{
    public static class IncrementalValueProviderExtensions
    {
+    public static IncrementalValuesProvider<T> Combine<TLeft, TRight>(this IncrementalValuesProvider<T> provider1, IncrementalValuesProvider<T> provider2) => // ...
    }
}

Usage Examples

[Generator(LanguageNames.CSharp)]
public class InvokeGenerator : IIncrementalGenerator
{
    public void Initialize(IncrementalGeneratorInitializationContext context)
    {
        var fromOtherFiles = context.AdditionalTextsProvider.Select((a, cancel) => SomeMethodReturnsString(a));
        var fromCompliation = context.SyntaxProvider.CreateSyntaxProvider((x, _) => x is TypeDeclarationSyntax, (typeDeclaration, _) => SomeOtherMethodReturnsString(typeDeclaration));

        var combination = fromOtherFiles.Concat(fromCompliation).Where((x) => // .. going on
    }
}

Risks

I'm not aware of any specific risk. But adding more APIs increases the learning curve.

jcouv commented 10 months ago

Assigned to @chsienki to triage as area owner for source generator APIs. Please advise: do you champion this? any recommended milestone?

chsienki commented 10 months ago

Thats funny I actually found myself wanting this exact method earlier this week for a personal project, so I'm happy to champion it going forwards. Seems like a nice little win, so should we aim for 17.9 timeframe?