Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move a couple of APIs from the generator driver into extension methods #54285

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public static CSharpGeneratorDriver Create(params ISourceGenerator[] generators)
/// <param name="incrementalGenerators">The incremental generators to create this driver with</param>
/// <returns>A new <see cref="CSharpGeneratorDriver"/> instance.</returns>
public static CSharpGeneratorDriver Create(params IIncrementalGenerator[] incrementalGenerators)
=> Create(incrementalGenerators.Select(WrapGenerator), additionalTexts: null);
=> Create(incrementalGenerators.Select(GeneratorExtensions.AsSourceGenerator), additionalTexts: null);

/// <summary>
/// Creates a new instance of <see cref="CSharpGeneratorDriver"/> with the specified <see cref="ISourceGenerator"/>s and the provided options or default.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ public void TestLoadGenerators()
{
AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location);
var generators = reference.GetGeneratorsForAllLanguages();
var typeNames = generators.Select(g => GeneratorDriver.GetGeneratorType(g).FullName);
var typeNames = generators.Select(g => g.GetGeneratorType().FullName);

AssertEx.SetEqual(new[]
{
Expand Down Expand Up @@ -291,7 +291,7 @@ public void TestLoadCSharpGenerators()
AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location);
var generators = reference.GetGenerators(LanguageNames.CSharp);

var typeNames = generators.Select(g => GeneratorDriver.GetGeneratorType(g).FullName);
var typeNames = generators.Select(g => g.GetGeneratorType().FullName);
AssertEx.SetEqual(new[]
{
"Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestGenerator",
Expand All @@ -313,7 +313,7 @@ public void TestLoadVisualBasicGenerators()
AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location);
var generators = reference.GetGenerators(LanguageNames.VisualBasic);

var typeNames = generators.Select(g => GeneratorDriver.GetGeneratorType(g).FullName);
var typeNames = generators.Select(g => g.GetGeneratorType().FullName);
AssertEx.SetEqual(new[]
{
"Microsoft.CodeAnalysis.UnitTests.VisualBasicOnlyGenerator",
Expand Down Expand Up @@ -436,7 +436,7 @@ public void TestLoadedGeneratorOrderIsDeterministic()
{
AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location);

var csharpGenerators = reference.GetGenerators(LanguageNames.CSharp).Select(g => GeneratorDriver.GetGeneratorType(g).FullName).ToArray();
var csharpGenerators = reference.GetGenerators(LanguageNames.CSharp).Select(g => g.GetGeneratorType().FullName).ToArray();
Assert.Equal(10, csharpGenerators.Length);
Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+SomeType+NestedGenerator", csharpGenerators[0]);
Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestGenerator", csharpGenerators[1]);
Expand All @@ -449,7 +449,7 @@ public void TestLoadedGeneratorOrderIsDeterministic()
Assert.Equal("Microsoft.CodeAnalysis.UnitTests.TestSourceAndIncrementalGenerator", csharpGenerators[8]);
Assert.Equal("Microsoft.CodeAnalysis.UnitTests.VisualBasicAndCSharpGenerator", csharpGenerators[9]);

var vbGenerators = reference.GetGenerators(LanguageNames.VisualBasic).Select(g => GeneratorDriver.GetGeneratorType(g).FullName).ToArray();
var vbGenerators = reference.GetGenerators(LanguageNames.VisualBasic).Select(g => g.GetGeneratorType().FullName).ToArray();
Assert.Equal(5, vbGenerators.Length);
Assert.Equal("Microsoft.CodeAnalysis.UnitTests.CSharpAndVisualBasicGenerator", vbGenerators[0]);
Assert.Equal("Microsoft.CodeAnalysis.UnitTests.TestIncrementalGenerator", vbGenerators[1]);
Expand All @@ -458,7 +458,7 @@ public void TestLoadedGeneratorOrderIsDeterministic()
Assert.Equal("Microsoft.CodeAnalysis.UnitTests.VisualBasicOnlyGenerator", vbGenerators[4]);

// generators load in language order (C#, F#, VB), and *do not* include duplicates
var allGenerators = reference.GetGeneratorsForAllLanguages().Select(g => GeneratorDriver.GetGeneratorType(g).FullName).ToArray();
var allGenerators = reference.GetGeneratorsForAllLanguages().Select(g => g.GetGeneratorType().FullName).ToArray();
Assert.Equal(12, allGenerators.Length);
Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+SomeType+NestedGenerator", allGenerators[0]);
Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestGenerator", allGenerators[1]);
Expand Down
5 changes: 3 additions & 2 deletions src/Compilers/Core/Portable/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ Microsoft.CodeAnalysis.Emit.EmitDifferenceResult.UpdatedMethods.get -> System.Co
Microsoft.CodeAnalysis.Emit.EmitDifferenceResult.UpdatedTypes.get -> System.Collections.Immutable.ImmutableArray<System.Reflection.Metadata.TypeDefinitionHandle>
Microsoft.CodeAnalysis.GeneratorAttribute.GeneratorAttribute(string! firstLanguage, params string![]! additionalLanguages) -> void
Microsoft.CodeAnalysis.GeneratorAttribute.Languages.get -> string![]!
Microsoft.CodeAnalysis.GeneratorExtensions
Microsoft.CodeAnalysis.IFieldSymbol.IsExplicitlyNamedTupleElement.get -> bool
Microsoft.CodeAnalysis.GeneratorExecutionContext.SyntaxContextReceiver.get -> Microsoft.CodeAnalysis.ISyntaxContextReceiver?
Microsoft.CodeAnalysis.GeneratorInitializationContext.RegisterForSyntaxNotifications(Microsoft.CodeAnalysis.SyntaxContextReceiverCreator! receiverCreator) -> void
Expand Down Expand Up @@ -89,10 +90,10 @@ override Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>.DefaultVis
override Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>.Visit(Microsoft.CodeAnalysis.IOperation? operation, TArgument argument) -> object?
static Microsoft.CodeAnalysis.FileLinePositionSpan.operator !=(Microsoft.CodeAnalysis.FileLinePositionSpan left, Microsoft.CodeAnalysis.FileLinePositionSpan right) -> bool
static Microsoft.CodeAnalysis.FileLinePositionSpan.operator ==(Microsoft.CodeAnalysis.FileLinePositionSpan left, Microsoft.CodeAnalysis.FileLinePositionSpan right) -> bool
static Microsoft.CodeAnalysis.GeneratorExtensions.AsSourceGenerator(this Microsoft.CodeAnalysis.IIncrementalGenerator! incrementalGenerator) -> Microsoft.CodeAnalysis.ISourceGenerator!
static Microsoft.CodeAnalysis.GeneratorExtensions.GetGeneratorType(this Microsoft.CodeAnalysis.ISourceGenerator! generator) -> System.Type!
static Microsoft.CodeAnalysis.LineMapping.operator !=(Microsoft.CodeAnalysis.LineMapping left, Microsoft.CodeAnalysis.LineMapping right) -> bool
static Microsoft.CodeAnalysis.LineMapping.operator ==(Microsoft.CodeAnalysis.LineMapping left, Microsoft.CodeAnalysis.LineMapping right) -> bool
static Microsoft.CodeAnalysis.GeneratorDriver.GetGeneratorType(Microsoft.CodeAnalysis.ISourceGenerator! generator) -> System.Type!
static Microsoft.CodeAnalysis.GeneratorDriver.WrapGenerator(Microsoft.CodeAnalysis.IIncrementalGenerator! incrementalGenerator) -> Microsoft.CodeAnalysis.ISourceGenerator!
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Collect<TSource>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source) -> Microsoft.CodeAnalysis.IncrementalValueProvider<System.Collections.Immutable.ImmutableArray<TSource>>
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Combine<TLeft, TRight>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TLeft> provider1, Microsoft.CodeAnalysis.IncrementalValueProvider<TRight> provider2) -> Microsoft.CodeAnalysis.IncrementalValueProvider<(TLeft Left, TRight Right)>
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Combine<TLeft, TRight>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TLeft> provider1, Microsoft.CodeAnalysis.IncrementalValueProvider<TRight> provider2) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<(TLeft Left, TRight Right)>
Expand Down
34 changes: 4 additions & 30 deletions src/Compilers/Core/Portable/SourceGeneration/GeneratorDriver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public abstract class GeneratorDriver

internal GeneratorDriver(GeneratorDriverState state)
{
Debug.Assert(state.Generators.GroupBy(s => GetGeneratorType(s)).Count() == state.Generators.Length); // ensure we don't have duplicate generator types
Debug.Assert(state.Generators.GroupBy(s => s.GetGeneratorType()).Count() == state.Generators.Length); // ensure we don't have duplicate generator types
_state = state;
}

Expand Down Expand Up @@ -130,32 +130,6 @@ static ImmutableArray<GeneratedSourceResult> getGeneratorSources(GeneratorState
}
}

/// <summary>
/// Returns the underlying type of a given generator
/// </summary>
/// <remarks>
/// For <see cref="IIncrementalGenerator"/>s we create a wrapper type that also implements
/// <see cref="ISourceGenerator"/>. This method will unwrap and return the underlying type
/// in those cases.
/// </remarks>
/// <param name="generator">The generator to get the type of</param>
/// <returns>The underlying generator type</returns>
public static Type GetGeneratorType(ISourceGenerator generator)
{
if (generator is IncrementalGeneratorWrapper igw)
{
return igw.Generator.GetType();
}
return generator.GetType();
}

/// <summary>
/// Wraps an <see cref="IIncrementalGenerator"/> in an <see cref="ISourceGenerator"/> object that can be used to construct a <see cref="GeneratorDriver"/>
/// </summary>
/// <param name="incrementalGenerator">The incremental generator to wrap</param>
/// <returns>A wrapped generator that can be passed to a generator driver</returns>
public static ISourceGenerator WrapGenerator(IIncrementalGenerator incrementalGenerator) => new IncrementalGeneratorWrapper(incrementalGenerator);

internal GeneratorDriverState RunGeneratorsCore(Compilation compilation, DiagnosticBag? diagnosticsBag, CancellationToken cancellationToken = default)
{
// with no generators, there is no work to do
Expand Down Expand Up @@ -300,7 +274,7 @@ internal GeneratorDriverState RunGeneratorsCore(Compilation compilation, Diagnos
private ImmutableArray<GeneratedSyntaxTree> ParseAdditionalSources(ISourceGenerator generator, ImmutableArray<GeneratedSourceText> generatedSources, CancellationToken cancellationToken)
{
var trees = ArrayBuilder<GeneratedSyntaxTree>.GetInstance(generatedSources.Length);
var type = GetGeneratorType(generator);
var type = generator.GetGeneratorType();
var prefix = GetFilePathPrefixForGenerator(generator);
foreach (var source in generatedSources)
{
Expand Down Expand Up @@ -330,7 +304,7 @@ private static GeneratorState SetGeneratorException(CommonMessageProvider provid
isEnabledByDefault: true,
customTags: WellKnownDiagnosticTags.AnalyzerException);

var diagnostic = Diagnostic.Create(descriptor, Location.None, GetGeneratorType(generator).Name, e.GetType().Name, e.Message);
var diagnostic = Diagnostic.Create(descriptor, Location.None, generator.GetGeneratorType().Name, e.GetType().Name, e.Message);

diagnosticBag?.Add(diagnostic);
return new GeneratorState(generatorState.Info, e, diagnostic);
Expand All @@ -353,7 +327,7 @@ private static ImmutableArray<Diagnostic> FilterDiagnostics(Compilation compilat

internal static string GetFilePathPrefixForGenerator(ISourceGenerator generator)
{
var type = GetGeneratorType(generator);
var type = generator.GetGeneratorType();
return Path.Combine(type.Assembly.GetName().Name ?? string.Empty, type.FullName!);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Text;

namespace Microsoft.CodeAnalysis
{
public static class GeneratorExtensions
{
/// <summary>
/// Returns the underlying type of a given generator
/// </summary>
/// <remarks>
/// For <see cref="IIncrementalGenerator"/>s a wrapper is created that also implements
/// <see cref="ISourceGenerator"/>. This method will unwrap and return the underlying type
/// in those cases.
/// </remarks>
/// <param name="generator">The generator to get the type of</param>
/// <returns>The underlying generator type</returns>
public static Type GetGeneratorType(this ISourceGenerator generator)
{
if (generator is IncrementalGeneratorWrapper igw)
{
return igw.Generator.GetType();
}
return generator.GetType();
}

/// <summary>
/// Converts an <see cref="IIncrementalGenerator"/> in an <see cref="ISourceGenerator"/> object that can be used when constructing a <see cref="GeneratorDriver"/>
/// </summary>
/// <param name="incrementalGenerator">The incremental generator to wrap</param>
/// <returns>A wrapped generator that can be passed to a generator driver</returns>
public static ISourceGenerator AsSourceGenerator(this IIncrementalGenerator incrementalGenerator) => new IncrementalGeneratorWrapper(incrementalGenerator);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public SourceGeneratedDocumentIdentity(DocumentId documentId, string hintName, s

public static string GetGeneratorTypeName(ISourceGenerator generator)
{
return GeneratorDriver.GetGeneratorType(generator).FullName!;
return generator.GetGeneratorType().FullName!;
}

public static string GetGeneratorAssemblyName(ISourceGenerator generator)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public TestGeneratorReference(ISourceGenerator generator)
}

public TestGeneratorReference(IIncrementalGenerator generator)
: this(GeneratorDriver.WrapGenerator(generator))
: this(generator.AsSourceGenerator())
{
}

Expand Down