From 6ca7ec0c0b9661f4a963054ab544b364c474a454 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 18 Nov 2020 19:06:21 +0100 Subject: [PATCH] Fixed [AutoConstructor] source generator --- .../AutoConstructorAttributeGenerator.cs | 150 +++++++----------- 1 file changed, 59 insertions(+), 91 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/AutoConstructorAttributeGenerator.cs b/src/ComputeSharp.SourceGenerators/AutoConstructorAttributeGenerator.cs index 2af1cf1e..21ea8e27 100644 --- a/src/ComputeSharp.SourceGenerators/AutoConstructorAttributeGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/AutoConstructorAttributeGenerator.cs @@ -1,14 +1,13 @@ -using System; -using System.Collections.Generic; -using System.Collections.Immutable; +using System.Collections.Immutable; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -namespace Mustache +namespace ComputeSharp.SourceGenerators { [Generator] public class AutoConstructorAttributeGenerator : ISourceGenerator @@ -16,110 +15,79 @@ namespace Mustache /// public void Initialize(GeneratorInitializationContext context) { - //context.RegisterForSyntaxNotifications(() => new SyntaxReceiver()); } /// public void Execute(GeneratorExecutionContext context) { string attributeSource = @" - using System; + using System; - namespace ComputeSharp + namespace ComputeSharp + { + /// + /// A shader that indicates that a target shader type should get an automatic constructor for all fields. + /// + [AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)] + internal sealed class AutoConstructorAttribute : Attribute { - /// - /// A shader that indicates that a target shader type should get an automatic constructor for all fields. - /// - [AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)] - internal sealed class AutoConstructorAttribute : Attribute - { - } - }"; + } + }"; // Add the GenerateConstructor attribute context.AddSource("__ComputeSharp_AutoConstructorAttribute", SourceText.From(attributeSource, Encoding.UTF8)); - // Ensure we have access to the local syntax receiver - //if (context.SyntaxReceiver is not SyntaxReceiver syntaxReceiver) return; - - // Create a new compilation with the new custom attribute - //CSharpParseOptions options = (CSharpParseOptions)((CSharpCompilation)context.Compilation).SyntaxTrees[0].Options; - //Compilation compilation = context.Compilation.AddSyntaxTrees(CSharpSyntaxTree.ParseText(SourceText.From(attributeSource, Encoding.UTF8), options)); - - // Get the new attribute from the compilation - //INamedTypeSymbol attributeSymbol = compilation.GetTypeByMetadataName("ComputeSharp.AutoConstructorAttribute")!; - - // Loop over the candidate struct declarations, and keep the ones that are actually annotated - foreach (var structSymbol in - //from structDeclaration in syntaxReceiver.CandidateTypes + // Find all the [AutoConstructor] usages + ImmutableArray attributes = ( from tree in context.Compilation.SyntaxTrees - from node in tree.GetRoot().DescendantNodes() - where node.IsKind(SyntaxKind.Attribute) && - node is - let semanticModel = compilation.GetSemanticModel(structDeclaration.SyntaxTree) - let symbol = semanticModel.GetDeclaredSymbol(structDeclaration) - let attributes = symbol.GetAttributes() - where attributes.Any(attribute => attribute.AttributeClass!.Equals(attributeSymbol, SymbolEqualityComparer.Default)) - select symbol) + from attribute in tree.GetRoot().DescendantNodes().OfType() + where attribute.Name.ToString() == "AutoConstructor" + select attribute).ToImmutableArray(); + + foreach (AttributeSyntax attribute in attributes) { - string namespaceName = structSymbol.ContainingNamespace.ToDisplayString(); + StructDeclarationSyntax structDeclaration = attribute.FirstAncestorOrSelf()!; + SemanticModel semanticModel = context.Compilation.GetSemanticModel(structDeclaration.SyntaxTree); + INamedTypeSymbol structDeclarationSymbol = semanticModel.GetDeclaredSymbol(structDeclaration)!; - // Begin constructing the type - StringBuilder source = new(); - source.AppendLine($"namespace {namespaceName}"); - source.AppendLine("{"); + // Extract the info on the type to process + var namespaceName = structDeclarationSymbol.ContainingNamespace.Name; + var structName = structDeclaration.Identifier.Text; + var structModifiers = structDeclaration.Modifiers; + var fields = ( + from fieldDeclaration in structDeclaration.Members.OfType() + let fieldType = fieldDeclaration.Declaration.Type + let typeName = semanticModel.GetTypeInfo(fieldType).Type!.ToDisplayString() + let fieldFullType = ParseTypeName(typeName) + from fieldVariable in fieldDeclaration.Declaration.Variables + select (Type: fieldFullType, fieldVariable.Identifier)).ToImmutableArray(); - // Visibility - source.Append(structSymbol.DeclaredAccessibility switch - { - Accessibility.Private => "private", - Accessibility.ProtectedAndInternal => "protected internal", - Accessibility.Protected => "protected", - Accessibility.Internal => "internal", - Accessibility.ProtectedOrInternal => "private protected", - Accessibility.Public => "public", - _ => throw new ArgumentException(), - }); - source.Append(" "); + // 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; + // ... + // } + // + // This will be placed inside the original namespace, and with all the + // necessary using directive at the top for the input parameters. + var source = + CompilationUnit().AddMembers( + NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers( + 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())))) + .NormalizeWhitespace() + .ToFullString(); - // Readonly - if (structSymbol.IsReadOnly) source.Append("readonly "); - - // End the type declaration - source.Append("partial struct"); - source.AppendLine("{"); - - // Constructor - source.AppendLine($"public {structSymbol.Name}("); - - // Parameters - var fieldSymbols = structSymbol.GetMembers().Where(symbol => symbol.Kind == SymbolKind.Field).Cast().ToImmutableArray(); - - source.AppendLine(string.Join($",{Environment.NewLine}", fieldSymbols.Select(field => $"{field.Type} {field.Name}"))); - - source.AppendLine(") { }"); - } - } - - /// - /// Created on demand before each generation pass - /// - private sealed class SyntaxReceiver : ISyntaxReceiver - { - /// - /// Gets the list of candidate struct declarations. - /// - public List CandidateTypes { get; } = new(); - - /// - public void OnVisitSyntaxNode(SyntaxNode syntaxNode) - { - // Track all structs with at least one attribute - if (syntaxNode is StructDeclarationSyntax structDeclarationSyntax && - structDeclarationSyntax.AttributeLists.Count > 0) - { - CandidateTypes.Add(structDeclarationSyntax); - } + // Add the partial type + context.AddSource($"__ComputeSharp_AutoConstructorAttribute_{structDeclarationSymbol.Name}", SourceText.From(source, Encoding.UTF8)); } } }