using System.Collections.Immutable; using System.Linq; using System.Text; using ComputeSharp.Core.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.Core.SourceGenerators; /// /// A source generator creating constructors for types annotated with . /// [Generator(LanguageNames.CSharp)] public sealed class AutoConstructorGenerator : IIncrementalGenerator { /// public void Initialize(IncrementalGeneratorInitializationContext context) { // Get all declared struct symbols with the [AutoConstructor] attribute IncrementalValuesProvider structDeclarations = context.SyntaxProvider .ForAttributeWithMetadataName( "ComputeSharp.AutoConstructorAttribute", static (node, token) => node is StructDeclarationSyntax structDeclaration, static (context, token) => (INamedTypeSymbol)context.TargetSymbol); // Get the type hierarchy and fields info IncrementalValuesProvider<(HierarchyInfo Left, ConstructorInfo Right)> constructorInfo = structDeclarations .Select(static (item, token) => (Hierarchy: HierarchyInfo.From(item), Info: Ctor.GetData(item))) .Where(static item => !item.Info.Parameters.IsEmpty) .WithComparers(HierarchyInfo.Comparer.Default, ConstructorInfo.Comparer.Default); // Generate the constructors context.RegisterSourceOutput(constructorInfo, static (context, item) => { CompilationUnitSyntax compilationUnit = Ctor.GetSyntax(item.Left, item.Right); context.AddSource($"{item.Left.FilenameHint}.Ctor.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); } /// /// A helper with all logic to generate the constructor declarations. /// private static class Ctor { /// /// Gets the sequence of items for all fields in the input type. /// /// The being inspected. /// The instance for . public static ConstructorInfo GetData(INamedTypeSymbol structDeclarationSymbol) { ImmutableArray.Builder parameters = ImmutableArray.CreateBuilder(); ImmutableArray.Builder defaulted = ImmutableArray.CreateBuilder(); foreach (IFieldSymbol fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { // Skip fields that are not instance ones (and also ignore generated fields and fixed size buffers) if (fieldSymbol is not { IsConst: false, IsStatic: false, IsFixedSizeBuffer: false, IsImplicitlyDeclared: false }) { continue; } // Check whether the field is annotated to have a special behavior if (fieldSymbol.Type.TryGetAttributeWithFullMetadataName("ComputeSharp.AutoConstructorBehaviorAttribute", out AttributeData? usageData) && usageData!.ConstructorArguments is { Length: 1 } arguments && arguments[0].Value is (int)AutoConstructorBehavior.IgnoreAndSetToDefault) { defaulted.Add(fieldSymbol.Name); } else { // Track the field normally string typeName = fieldSymbol.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); parameters.Add(new ParameterInfo(typeName, fieldSymbol.Name)); } } return new(parameters.ToImmutableArray(), defaulted.ToImmutableArray()); } /// /// Gets the instance for a given type and sequence of parameters. /// /// The type hierarchy info. /// The instance with the info for the constructor to generate. /// A instance for a specified type. public static CompilationUnitSyntax GetSyntax(HierarchyInfo hierarchyInfo, ConstructorInfo constructorInfo) { // 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.ignored1 = default; // this.ignored2 = default; // this.ignored3 = default; // ... // } ConstructorDeclarationSyntax constructorDeclaration = ConstructorDeclaration(hierarchyInfo.Hierarchy[0].QualifiedName) .AddModifiers(Token(SyntaxKind.PublicKeyword)) .AddParameterListParameters(constructorInfo.Parameters.Select(field => Parameter(Identifier(field.Name)).WithType(IdentifierName(field.Type))).ToArray()) .AddBodyStatements(constructorInfo.Parameters.Select(field => ParseStatement($"this.{field.Name} = {field.Name};")).ToArray()) .AddBodyStatements(constructorInfo.DefaultedFields.Select(field => ParseStatement($"this.{field} = default;")).ToArray()); // Add the unsafe modifier, if needed if (constructorInfo.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")))) }; return hierarchyInfo.GetSyntax(constructorDeclaration.AddAttributeLists(attributes)); } } }