From 0aba871d523cd6d961fb7ca8301504641946d3f4 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 7 Dec 2021 12:31:51 +0100 Subject: [PATCH] Switch [AutoConstructor] generator to incremental --- ...AutoConstructorGenerator.SyntaxReceiver.cs | 54 ----- .../AutoConstructorGenerator.cs | 200 +++++++++++------- .../Extensions/IEqualityComparerExtensions.cs | 59 ++++++ .../Models/ParameterInfo.cs | 8 + .../AutoConstructorGeneratorTests.cs | 33 +-- 5 files changed, 205 insertions(+), 149 deletions(-) delete mode 100644 src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.SyntaxReceiver.cs create mode 100644 src/ComputeSharp.SourceGenerators/Extensions/IEqualityComparerExtensions.cs create mode 100644 src/ComputeSharp.SourceGenerators/Models/ParameterInfo.cs diff --git a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.SyntaxReceiver.cs b/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.SyntaxReceiver.cs deleted file mode 100644 index 478303bb..00000000 --- a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.SyntaxReceiver.cs +++ /dev/null @@ -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; - -/// -public sealed partial class AutoConstructorGenerator -{ - /// - /// An that selects candidate nodes to process. - /// - private sealed class SyntaxReceiver : ISyntaxContextReceiver - { - /// - /// The list of info gathered during exploration. - /// - private readonly List gatheredInfo = new(); - - /// - /// Gets the collection of gathered info to process. - /// - public IReadOnlyCollection GatheredInfo => this.gatheredInfo; - - /// - 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)); - } - } - - /// - /// A model for a group of item representing a discovered type to process. - /// - /// The instance for the target struct declaration. - /// The instance for . - /// The instance for the target attribute over . - /// The instance for . - public sealed record Item( - StructDeclarationSyntax StructDeclaration, - INamedTypeSymbol StructSymbol, - AttributeSyntax AttributeSyntax, - AttributeData AttributeData); - } -} diff --git a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs b/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs index 1aac7f97..f04c3e04 100644 --- a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs @@ -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; /// /// A source generator creating constructors for types annotated with . /// -[Generator] -public sealed partial class AutoConstructorGenerator : ISourceGenerator +[Generator(LanguageNames.CSharp)] +public sealed partial class AutoConstructorGenerator : IIncrementalGenerator { /// - 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 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))!; - /// - 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 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.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)); + }); } /// - /// Processes a given target type. + /// A helper with all logic to generate the constructor declarations. /// - /// The input instance to use. - /// The node to process. - /// The for . - 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() - 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()) + /// + /// Gets the sequence of items for all fields in the input type. + /// + /// The being inspected. + /// The sequence of items for all fields in . + public static ImmutableArray GetData(INamedTypeSymbol structDeclarationSymbol) { - typeDeclarationSyntax = parentType - .WithMembers(SingletonList(typeDeclarationSyntax)) - .WithConstraintClauses(List()) - .WithBaseList(null) - .WithAttributeLists(List()) - .WithoutTrivia(); + return ( + from fieldSymbol in structDeclarationSymbol.GetMembers().OfType() + 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(); + /// + /// Gets the instance for a given type and sequence of parameters. + /// + /// The type hierarchy info. + /// The sequence of parameters to initialize. + /// A instance for a specified type. + public static CompilationUnitSyntax GetSyntax(HierarchyInfo hierarchyInfo, ImmutableArray 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 + // { + // + // } + 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 ; + // + // + return + CompilationUnit().AddMembers( + FileScopedNamespaceDeclaration(IdentifierName(hierarchyInfo.Namespace)) + .AddMembers(typeDeclarationSyntax) + .WithNamespaceKeyword(Token(TriviaList( + Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), + SyntaxKind.NamespaceKeyword, + TriviaList()))) + .NormalizeWhitespace(eol: "\n"); + } } } diff --git a/src/ComputeSharp.SourceGenerators/Extensions/IEqualityComparerExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/IEqualityComparerExtensions.cs new file mode 100644 index 00000000..306d8c11 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Extensions/IEqualityComparerExtensions.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace ComputeSharp.SourceGenerators.Extensions; + +/// +/// Extension methods for . +/// +internal static class IEqualityComparerExtensions +{ + /// + /// Gets an for an sequence. + /// + /// The type of items to compare. + /// The compare for individual items. + public static IEqualityComparer> ForImmutableArray(this IEqualityComparer comparer) + { + return new Comparer(comparer); + } + + /// + /// An implementation for an value. + /// + public sealed class Comparer : IEqualityComparer> + { + /// + /// The comparer. + /// + private readonly IEqualityComparer comparer; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The comparer. + public Comparer(IEqualityComparer comparer) + { + this.comparer = comparer; + } + + /// + public bool Equals(ImmutableArray x, ImmutableArray y) + { + return + x == y || + x.SequenceEqual(y, this.comparer); + } + + /// + public int GetHashCode(ImmutableArray obj) + { + HashCode hashCode = default; + + hashCode.AddRange(obj, this.comparer); + + return hashCode.ToHashCode(); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/Models/ParameterInfo.cs b/src/ComputeSharp.SourceGenerators/Models/ParameterInfo.cs new file mode 100644 index 00000000..137df444 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/ParameterInfo.cs @@ -0,0 +1,8 @@ +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A model describing info on a constructor parameter. +/// +/// The fully qualified type name. +/// The parameter name. +internal sealed record ParameterInfo(string Type, string Name); diff --git a/tests/ComputeSharp.Tests.SourceGenerators/AutoConstructorGeneratorTests.cs b/tests/ComputeSharp.Tests.SourceGenerators/AutoConstructorGeneratorTests.cs index ca2cc0af..db4eb6c6 100644 --- a/tests/ComputeSharp.Tests.SourceGenerators/AutoConstructorGeneratorTests.cs +++ b/tests/ComputeSharp.Tests.SourceGenerators/AutoConstructorGeneratorTests.cs @@ -27,7 +27,7 @@ public class AutoConstructorGeneratorTests namespace MyFancyApp.Sample { - public partial interface IFoo : IFluff + public partial class IFoo : 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 - { - public partial class Foo - { - public readonly partial struct Test - { + partial class IFoo + {{ + 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 c, global::ComputeSharp.ReadWriteBuffer d) - { + {{ this.a = a; this.b = b; this.c = c; this.d = d; - } - } - } - }"; + }} + }} + }} + }}"; VerifyGeneratedMethodLines(source, 0, expected); } @@ -75,7 +78,7 @@ public class AutoConstructorGeneratorTests /// The target index to check in the resulting output. /// The expected body to compare with the generated code. private static void VerifyGeneratedMethodLines(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);