Switch [AutoConstructor] generator to incremental

このコミットが含まれているのは:
Sergio Pedri committed 2021-12-08 11:17:07 +01:00
1 親 1216d511a7
コミット 0aba871d52
5ファイル変更
+205 -149

検索条件に一致するファイルはありません

-54
ファイルの表示
@@ -1,54 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
public sealed partial class AutoConstructorGenerator
{
/// <summary>
/// An <see cref="ISyntaxContextReceiver"/> that selects candidate nodes to process.
/// </summary>
private sealed class SyntaxReceiver : ISyntaxContextReceiver
{
/// <summary>
/// The list of info gathered during exploration.
/// </summary>
private readonly List<Item> gatheredInfo = new();
/// <summary>
/// Gets the collection of gathered info to process.
/// </summary>
public IReadOnlyCollection<Item> GatheredInfo => this.gatheredInfo;
/// <inheritdoc/>
public void OnVisitSyntaxNode(GeneratorSyntaxContext context)
{
if (context.Node is StructDeclarationSyntax { AttributeLists: { Count: > 0 } } structDeclaration &&
context.SemanticModel.GetDeclaredSymbol(structDeclaration) is INamedTypeSymbol structSymbol &&
context.SemanticModel.Compilation.GetTypeByMetadataName(typeof(AutoConstructorAttribute).FullName) is INamedTypeSymbol attributeSymbol &&
structSymbol.GetAttributes().FirstOrDefault(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, attributeSymbol)) is AttributeData attributeData &&
attributeData.ApplicationSyntaxReference is SyntaxReference syntaxReference &&
syntaxReference.GetSyntax() is AttributeSyntax attributeSyntax)
{
this.gatheredInfo.Add(new Item(structDeclaration, structSymbol, attributeSyntax, attributeData));
}
}
/// <summary>
/// A model for a group of item representing a discovered type to process.
/// </summary>
/// <param name="StructDeclaration">The <see cref="StructDeclarationSyntax"/> instance for the target struct declaration.</param>
/// <param name="StructSymbol">The <see cref="INamedTypeSymbol"/> instance for <paramref name="StructDeclaration"/>.</param>
/// <param name="AttributeSyntax">The <see cref="AttributeSyntax"/> instance for the target attribute over <paramref name="StructDeclaration"/>.</param>
/// <param name="AttributeData">The <see cref="AttributeData"/> instance for <paramref name="AttributeSyntax"/>.</param>
public sealed record Item(
StructDeclarationSyntax StructDeclaration,
INamedTypeSymbol StructSymbol,
AttributeSyntax AttributeSyntax,
AttributeData AttributeData);
}
}
+120 -80
ファイルの表示
@@ -1,111 +1,151 @@
using System.Collections.Immutable;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using ComputeSharp.SourceGenerators.Diagnostics;
using ComputeSharp.SourceGenerators.Extensions;
using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle;
namespace ComputeSharp.SourceGenerators;
/// <summary>
/// A source generator creating constructors for types annotated with <see cref="AutoConstructorAttribute"/>.
/// </summary>
[Generator]
public sealed partial class AutoConstructorGenerator : ISourceGenerator
[Generator(LanguageNames.CSharp)]
public sealed partial class AutoConstructorGenerator : IIncrementalGenerator
{
/// <inheritdoc/>
public void Initialize(GeneratorInitializationContext context)
public void Initialize(IncrementalGeneratorInitializationContext context)
{
context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver());
}
// Get all declared struct symbols with the [AutoConstructor] attribute
IncrementalValuesProvider<INamedTypeSymbol> structDeclarations =
context.SyntaxProvider
.CreateSyntaxProvider(
static (node, token) => node is StructDeclarationSyntax structDeclaration,
static (context, token) => (INamedTypeSymbol?)context.SemanticModel.GetDeclaredSymbol(context.Node, token))
.Where(static symbol => symbol is not null &&
symbol.GetAttributes().Any(static a => a.AttributeClass?.ToDisplayString() == typeof(AutoConstructorAttribute).FullName))!;
/// <inheritdoc/>
public void Execute(GeneratorExecutionContext context)
{
// Get the syntax receiver with the candidate nodes
if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver)
{
return;
}
// Get the type hierarchy and fields info
IncrementalValuesProvider<(HierarchyInfo Left, ImmutableArray<ParameterInfo> Right)> constructorInfo =
structDeclarations
.Select(static (item, token) => (Hierarchy: HierarchyInfo.From(item), Parameters: Ctor.GetData(item)))
.Where(static item => !item.Parameters.IsEmpty)
.WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer<ParameterInfo>.Default.ForImmutableArray());
foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo)
// Generate the constructors
context.RegisterSourceOutput(constructorInfo, static (context, item) =>
{
try
{
OnExecute(context, item.StructDeclaration, item.StructSymbol);
}
catch
{
context.ReportDiagnostic(AutoConstructorGeneratorError, item.AttributeSyntax, item.StructSymbol);
}
}
CompilationUnitSyntax compilationUnit = Ctor.GetSyntax(item.Left, item.Right);
context.AddSource($"{item.Left.FilenameHint}.Ctor", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8));
});
}
/// <summary>
/// Processes a given target type.
/// A helper with all logic to generate the constructor declarations.
/// </summary>
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to use.</param>
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> node to process.</param>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for <paramref name="structDeclaration"/>.</param>
private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol)
private static class Ctor
{
// Extract the info on the type to process
var namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces));
var structName = structDeclaration.Identifier.Text;
var structModifiers = structDeclaration.Modifiers;
var fields = (
from fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>()
where !fieldSymbol.IsConst && !fieldSymbol.IsStatic && !fieldSymbol.IsFixedSizeBuffer
let typeName = fieldSymbol.Type!.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)
let fieldFullType = ParseTypeName(typeName)
select (Type: fieldFullType, Identifier: Identifier(fieldSymbol.Name))).ToImmutableArray();
// Create the constructor declaration for the type. This will
// produce a constructor with simple initialization of all variables:
//
// public MyType(Foo a, Bar b, Baz c, ...)
// {
// this.a = a;
// this.b = b;
// this.c = c;
// ...
// }
var structDeclarationSyntax =
StructDeclaration(structName).WithModifiers(structModifiers).AddMembers(
ConstructorDeclaration(structName)
.AddModifiers(Token(SyntaxKind.PublicKeyword))
.AddParameterListParameters(fields.Select(field => Parameter(field.Identifier).WithType(field.Type)).ToArray())
.AddBodyStatements(fields.Select(field => ParseStatement($"this.{field.Identifier} = {field.Identifier};")).ToArray()));
TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax;
// Add all parent types in ascending order, if any
foreach (var parentType in structDeclaration.Ancestors().OfType<TypeDeclarationSyntax>())
/// <summary>
/// Gets the sequence of <see cref="ParameterInfo"/> items for all fields in the input type.
/// </summary>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> being inspected.</param>
/// <returns>The sequence of <see cref="ParameterInfo"/> items for all fields in <paramref name="structDeclarationSymbol"/>.</returns>
public static ImmutableArray<ParameterInfo> GetData(INamedTypeSymbol structDeclarationSymbol)
{
typeDeclarationSyntax = parentType
.WithMembers(SingletonList<MemberDeclarationSyntax>(typeDeclarationSyntax))
.WithConstraintClauses(List<TypeParameterConstraintClauseSyntax>())
.WithBaseList(null)
.WithAttributeLists(List<AttributeListSyntax>())
.WithoutTrivia();
return (
from fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>()
where fieldSymbol is { IsConst: false, IsStatic: false, IsFixedSizeBuffer: false }
let typeName = fieldSymbol.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)
select new ParameterInfo(typeName, fieldSymbol.Name)).ToImmutableArray();
}
// Create the compilation unit with the namespace and target member.
// From this, we can finally generate the source code to output.
var source =
CompilationUnit().AddMembers(
FileScopedNamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax)
.WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList())))
.NormalizeWhitespace(eol: "\n")
.ToFullString();
/// <summary>
/// Gets the <see cref="CompilationUnitSyntax"/> instance for a given type and sequence of parameters.
/// </summary>
/// <param name="hierarchyInfo">The type hierarchy info.</param>
/// <param name="parameters">The sequence of parameters to initialize.</param>
/// <returns>A <see cref="CompilationUnitSyntax"/> instance for a specified type.</returns>
public static CompilationUnitSyntax GetSyntax(HierarchyInfo hierarchyInfo, ImmutableArray<ParameterInfo> parameters)
{
// Create the constructor declaration for the type. This will
// produce a constructor with simple initialization of all variables:
//
// public MyType(Foo a, Bar b, Baz c, ...)
// {
// this.a = a;
// this.b = b;
// this.c = c;
// ...
// }
ConstructorDeclarationSyntax constructorDeclaration =
ConstructorDeclaration(hierarchyInfo.Names[0])
.AddModifiers(Token(SyntaxKind.PublicKeyword))
.AddParameterListParameters(parameters.Select(field => Parameter(Identifier(field.Name)).WithType(IdentifierName(field.Type))).ToArray())
.AddBodyStatements(parameters.Select(field => ParseStatement($"this.{field.Name} = {field.Name};")).ToArray());
// Add the partial type
context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8));
// Add the unsafe modifier, if needed
if (parameters.Any(static param => param.Type.Contains("*")))
{
constructorDeclaration = constructorDeclaration.AddModifiers(Token(SyntaxKind.UnsafeKeyword));
}
// Constructor attributes
AttributeListSyntax[] attributes =
{
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(AutoConstructorGenerator).FullName))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(AutoConstructorGenerator).Assembly.GetName().Version.ToString())))))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage"))))
};
// Create the partial shader type declaration with the given method implementation.
// This code produces a struct declaration as follows:
//
// partial struct <SHADER_TYPE>
// {
// <METHOD>
// }
StructDeclarationSyntax structDeclarationSyntax =
StructDeclaration(hierarchyInfo.Names[0])
.AddModifiers(Token(SyntaxKind.PartialKeyword))
.AddMembers(constructorDeclaration.AddAttributeLists(attributes));
TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax;
// Add all parent types in ascending order, if any
foreach (string parentType in hierarchyInfo.Names.AsSpan().Slice(1))
{
typeDeclarationSyntax =
ClassDeclaration(parentType)
.AddModifiers(Token(SyntaxKind.PartialKeyword))
.AddMembers(typeDeclarationSyntax);
}
// Create the compilation unit with disabled warnings, target namespace and generated type.
// This will produce code as follows:
//
// #pragma warning disable
//
// namespace <NAMESPACE>;
//
// <TYPE_HIERARCHY>
return
CompilationUnit().AddMembers(
FileScopedNamespaceDeclaration(IdentifierName(hierarchyInfo.Namespace))
.AddMembers(typeDeclarationSyntax)
.WithNamespaceKeyword(Token(TriviaList(
Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))),
SyntaxKind.NamespaceKeyword,
TriviaList())))
.NormalizeWhitespace(eol: "\n");
}
}
}
+59
ファイルの表示
@@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
namespace ComputeSharp.SourceGenerators.Extensions;
/// <summary>
/// Extension methods for <see cref="IEqualityComparer{T}"/>.
/// </summary>
internal static class IEqualityComparerExtensions
{
/// <summary>
/// Gets an <see cref="IEqualityComparer{T}"/> for an <see cref="ImmutableArray{T}"/> sequence.
/// </summary>
/// <typeparam name="T">The type of items to compare.</typeparam>
/// <param name="comparer">The compare for individual <typeparamref name="T"/> items.</param>
public static IEqualityComparer<ImmutableArray<T>> ForImmutableArray<T>(this IEqualityComparer<T> comparer)
{
return new Comparer<T>(comparer);
}
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for an <see cref="ImmutableArray{T}"/> value.
/// </summary>
public sealed class Comparer<T> : IEqualityComparer<ImmutableArray<T>>
{
/// <summary>
/// The <typeparamref name="T"/> comparer.
/// </summary>
private readonly IEqualityComparer<T> comparer;
/// <summary>
/// Creates a new <see cref="Comparer{T}"/> instance with the specified parameters.
/// </summary>
/// <param name="comparer">The <typeparamref name="T"/> comparer.</param>
public Comparer(IEqualityComparer<T> comparer)
{
this.comparer = comparer;
}
/// <inheritdoc/>
public bool Equals(ImmutableArray<T> x, ImmutableArray<T> y)
{
return
x == y ||
x.SequenceEqual(y, this.comparer);
}
/// <inheritdoc/>
public int GetHashCode(ImmutableArray<T> obj)
{
HashCode hashCode = default;
hashCode.AddRange(obj, this.comparer);
return hashCode.ToHashCode();
}
}
}
+8
ファイルの表示
@@ -0,0 +1,8 @@
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A model describing info on a constructor parameter.
/// </summary>
/// <param name="Type">The fully qualified type name.</param>
/// <param name="Name">The parameter name.</param>
internal sealed record ParameterInfo(string Type, string Name);
+18 -15
ファイルの表示
@@ -27,7 +27,7 @@ public class AutoConstructorGeneratorTests
namespace MyFancyApp.Sample
{
public partial interface IFoo<T> : IFluff
public partial class IFoo<T> : IFluff
where T : notnull, new()
{
public partial class Foo
@@ -44,25 +44,28 @@ public class AutoConstructorGeneratorTests
}
}";
string expected = @"
string expected = $@"
#pragma warning disable
namespace MyFancyApp.Sample;
public partial interface IFoo<T>
{
public partial class Foo
{
public readonly partial struct Test
{
partial class IFoo<T>
{{
partial class Foo
{{
partial struct Test
{{
[global::System.CodeDom.Compiler.GeneratedCode(""ComputeSharp.SourceGenerators.AutoConstructorGenerator"", ""{typeof(AutoConstructorGenerator).Assembly.GetName().Version}"")]
[global::System.Diagnostics.DebuggerNonUserCode]
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public Test(float a, global::System.Numerics.Vector2 b, global::ComputeSharp.ReadWriteBuffer<global::System.Numerics.Vector4> c, global::ComputeSharp.ReadWriteBuffer<int> d)
{
{{
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
}
}
}";
}}
}}
}}
}}";
VerifyGeneratedMethodLines<AutoConstructorGenerator>(source, 0, expected);
}
@@ -75,7 +78,7 @@ public class AutoConstructorGeneratorTests
/// <param name="index">The target index to check in the resulting output.</param>
/// <param name="expectedBody">The expected body to compare with the generated code.</param>
private static void VerifyGeneratedMethodLines<TGenerator>(string source, int index, string expectedBody)
where TGenerator : class, ISourceGenerator, new()
where TGenerator : class, IIncrementalGenerator, new()
{
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source);
@@ -87,7 +90,7 @@ public class AutoConstructorGeneratorTests
CSharpCompilation compilation = CSharpCompilation.Create("original", new SyntaxTree[] { syntaxTree }, references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
ISourceGenerator generator = new TGenerator();
IIncrementalGenerator generator = new TGenerator();
CSharpGeneratorDriver driver = CSharpGeneratorDriver.Create(generator);