From 545f4b6ca435d8030e8b3bb04e8da8ecdfe74e07 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 20 Oct 2023 23:14:52 +0200 Subject: [PATCH] Move constant buffer syntax to shared project --- ...scriptorGenerator.ConstantBuffer.Syntax.cs | 342 ----------------- .../D2DPixelShaderDescriptorGenerator.cs | 3 +- ...mputeSharp.SourceGeneration.Hlsl.projitems | 1 + .../ConstantBufferSyntaxWriter.cs | 363 ++++++++++++++++++ 4 files changed, 366 insertions(+), 343 deletions(-) create mode 100644 src/ComputeSharp.SourceGeneration.Hlsl/SyntaxWriters/ConstantBufferSyntaxWriter.cs diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ConstantBuffer.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ConstantBuffer.Syntax.cs index 84706137..515b8a26 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ConstantBuffer.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ConstantBuffer.Syntax.cs @@ -1,9 +1,6 @@ -using System.Linq; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; -using ComputeSharp.SourceGeneration.Mappings; -using ComputeSharp.SourceGeneration.Models; namespace ComputeSharp.D2D1.SourceGenerators; @@ -74,344 +71,5 @@ partial class D2DPixelShaderDescriptorGenerator writer.WriteLine("return global::ComputeSharp.D2D1.Generated.ConstantBufferMarshaller.ToManaged(in buffer);"); } } - - /// - /// Registers a callback to generate additional types, if needed. - /// - /// The type of model providing the necessary info. - /// The input instance with gathered shader info. - /// The registered callbacks to generate additional types. - /// The using directives needed by the generated code. - public static void RegisterAdditionalTypesSyntax( - TInfo info, - ImmutableArrayBuilder> callbacks, - ImmutableHashSetBuilder usingDirectives) - where TInfo : class, IConstantBufferInfo - { - // If there are no fields, there is no need for a constant buffer type - if (info.Fields.IsEmpty) - { - return; - } - - _ = usingDirectives.Add("global::System.CodeDom.Compiler"); - _ = usingDirectives.Add("global::System.Diagnostics"); - _ = usingDirectives.Add("global::System.Diagnostics.CodeAnalysis"); - _ = usingDirectives.Add("global::System.Runtime.CompilerServices"); - _ = usingDirectives.Add("global::System.Runtime.InteropServices"); - - // Declare the ConstantBuffer type - static void ConstantBufferCallback(TInfo info, IndentedTextWriter writer) - { - string fullyQualifiedTypeName = info.Hierarchy.GetFullyQualifiedTypeName(); - - writer.WriteLine($"""/// """); - writer.WriteLine($"""/// A type representing the constant buffer native layout for ."""); - writer.WriteLine($"""/// """); - writer.WriteGeneratedAttributes(GeneratorName, useFullyQualifiedTypeNames: false); - writer.WriteLine($"""[StructLayout(LayoutKind.Explicit, Size = {info.ConstantBufferSizeInBytes})]"""); - writer.WriteLine($"""file struct ConstantBuffer"""); - - using (writer.WriteBlock()) - { - // Declare fields for every mapped item from the shader layout - writer.WriteLineSeparatedMembers(info.Fields.AsSpan(), (field, writer) => - { - switch (field) - { - case FieldInfo.Primitive { TypeName: "System.Boolean" } primitive: - - // Append a field as a global::ComputeSharp.Bool value (will use the implicit conversion from bool values) - writer.WriteFieldXmlSummary(field, fullyQualifiedTypeName); - writer.WriteFieldXmlRemarks(field); - writer.WriteLine($"""[FieldOffset({primitive.Offset})]"""); - writer.WriteLine($"""public global::ComputeSharp.Bool {string.Join("_", primitive.FieldPath.Select(static path => path.Name))};"""); - break; - case FieldInfo.Primitive primitive: - - // Append primitive fields of other types with their mapped names - writer.WriteFieldXmlSummary(field, fullyQualifiedTypeName); - writer.WriteFieldXmlRemarks(field); - writer.WriteLine($"""[FieldOffset({primitive.Offset})]"""); - writer.WriteLine($"""public {HlslKnownTypes.GetMappedName(primitive.TypeName)} {string.Join("_", primitive.FieldPath.Select(static path => path.Name))};"""); - break; - - case FieldInfo.NonLinearMatrix matrix: - string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}"); - string fieldNamePrefix = string.Join("_", matrix.FieldPath.Select(static path => path.Name)); - - // Declare a field for every row of the matrix type - for (int j = 0; j < matrix.Rows; j++) - { - writer.WriteLineIf(j > 0); - writer.WriteFieldXmlSummary(field, fullyQualifiedTypeName); - writer.WriteFieldXmlRemarks(field, row: j); - writer.WriteLine($"""[FieldOffset({matrix.Offsets[j]})]"""); - writer.WriteLine($"""public {rowTypeName} {fieldNamePrefix}_{j};"""); - } - - break; - } - }); - } - } - - // Declare the ConstantBufferMarshaller type - static void ConstantBufferMarshallerCallback(TInfo info, IndentedTextWriter writer) - { - string fullyQualifiedTypeName = info.Hierarchy.GetFullyQualifiedTypeName(); - - writer.WriteLine($"""/// """); - writer.WriteLine($"""/// A type containing marshalling logic for shaders of type ."""); - writer.WriteLine($"""/// """); - writer.WriteGeneratedAttributes(GeneratorName, useFullyQualifiedTypeNames: false); - writer.WriteLine($"""file static class ConstantBufferMarshaller"""); - - using (writer.WriteBlock()) - { - // Define the ToManaged method (native constant buffer to managed shader type) - writer.WriteLine($"""/// """); - writer.WriteLine($"""/// Marshals native constant buffer data to managed instances."""); - writer.WriteLine($"""/// """); - writer.WriteLine($"""/// The input native constant buffer."""); - writer.WriteLine($"""/// The marshalled instance."""); - writer.WriteLine($"""[MethodImpl(MethodImplOptions.AggressiveInlining)]"""); - writer.WriteLine($"""[SkipLocalsInit]"""); - writer.WriteLine($"public static {fullyQualifiedTypeName} ToManaged(in ConstantBuffer buffer)"); - - using (writer.WriteBlock()) - { - writer.WriteLine($"Unsafe.SkipInit(out {fullyQualifiedTypeName} shader);"); - writer.WriteLine(); - - // Generate loading statements for each captured field - foreach (FieldInfo fieldInfo in info.Fields) - { - switch (fieldInfo) - { - case FieldInfo.Primitive primitive: - - // Read a nested primitive value - writer.WriteFieldAccessExpression(fieldInfo); - writer.WriteLine($" = buffer.{string.Join("_", primitive.FieldPath.Select(static path => path.Name))};"); - break; - - case FieldInfo.NonLinearMatrix matrix: - string primitiveTypeName = matrix.ElementName.ToLowerInvariant(); - string matrixHlslTypeName = $"{primitiveTypeName}{matrix.Rows}x{matrix.Columns}"; - string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}"); - string fieldNamePrefix = string.Join("_", matrix.FieldPath.Select(static path => path.Name)); - - // Get a reference to the whole matrix field, just once for all rows - writer.WriteLine(skipIfPresent: true); - writer.Write($"ref {matrixHlslTypeName} __{fieldNamePrefix} = ref "); - writer.WriteFieldAccessExpression(fieldInfo); - writer.WriteLine(";"); - writer.WriteLine(); - - // Read all rows of a given matrix type - for (int j = 0; j < matrix.Rows; j++) - { - writer.WriteLine($"Unsafe.As<{primitiveTypeName}, {rowTypeName}>(ref __{fieldNamePrefix}.M{j + 1}1) = buffer.{fieldNamePrefix}_{j};"); - } - - writer.WriteLine(); - break; - } - } - - writer.WriteLine(skipIfPresent: true); - writer.WriteLine("return shader;"); - } - - // Define the FromManaged method (managed shader type to native constant buffer) - writer.WriteLine(); - writer.WriteLine($"""/// """); - writer.WriteLine($"""/// Marshals managed instances to native constant buffer data."""); - writer.WriteLine($"""/// """); - writer.WriteLine($"""/// The input native constant buffer."""); - writer.WriteLine($"""/// The marshalled instance."""); - writer.WriteLine($"""[MethodImpl(MethodImplOptions.AggressiveInlining)]"""); - writer.WriteLine($"""[SkipLocalsInit]"""); - writer.WriteLine($"public static void FromManaged(in {fullyQualifiedTypeName} shader, out ConstantBuffer buffer)"); - - using (writer.WriteBlock()) - { - // Generate loading statements for each captured field - foreach (FieldInfo fieldInfo in info.Fields) - { - switch (fieldInfo) - { - case FieldInfo.Primitive primitive: - - // Assign a primitive value - writer.Write($"buffer.{string.Join("_", primitive.FieldPath.Select(static path => path.Name))} = "); - writer.WriteFieldAccessExpression(fieldInfo); - writer.WriteLine(";"); - break; - - case FieldInfo.NonLinearMatrix matrix: - string primitiveTypeName = matrix.ElementName.ToLowerInvariant(); - string matrixHlslTypeName = $"{primitiveTypeName}{matrix.Rows}x{matrix.Columns}"; - string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}"); - string fieldNamePrefix = string.Join("_", matrix.FieldPath.Select(static path => path.Name)); - - // Get a reference to the whole matrix field, just once for all rows - writer.WriteLine(skipIfPresent: true); - writer.Write($"ref {matrixHlslTypeName} __{fieldNamePrefix} = ref "); - writer.WriteFieldAccessExpression(fieldInfo); - writer.WriteLine(";"); - writer.WriteLine(); - - // Assign all rows of a given matrix type - for (int j = 0; j < matrix.Rows; j++) - { - writer.WriteLine($"buffer.{fieldNamePrefix}_{j} = Unsafe.As<{primitiveTypeName}, {rowTypeName}>(ref __{fieldNamePrefix}.M{j + 1}1);"); - } - - writer.WriteLine(); - break; - } - } - } - - using ImmutableHashSetBuilder<(string ContainerType, string FieldName)> generatedAccessors = new(); - - // Define all field accessors. Note that these are generated regardless of the accessibility - // of the field they're getting the value for. This simplifies the rest of the code, and allows - // stripping the readonly-ness of the field references, and has no binary size impact anyway. - // This is because the fields are compiled to be exactly equivalent to direct field references. - foreach (FieldInfo fieldInfo in info.Fields) - { - for (int i = 0; i < fieldInfo.FieldPath.Length; i++) - { - FieldPathPart pathPart = fieldInfo.FieldPath[i]; - - // Get the friendly type name for the field: - // - If the part path is a nested struct, the type name is embedded - // - Otherwise, get the correct HLSL mapped type name for the field - string typeName = pathPart switch - { - FieldPathPart.Nested nested => nested.TypeName, - FieldPathPart.Leaf when fieldInfo.TypeName is "System.Boolean" => "global::ComputeSharp.Bool", - _ => HlslKnownTypes.GetMappedName(fieldInfo.TypeName) - }; - - // Get the friendly type name for the field. If this nested field is the - // first path, then the parent is the shader type itself. Otherwise, the - // container path is the type of the previous containing type of the field. - string containingTypeName = i == 0 - ? fullyQualifiedTypeName - : ((FieldPathPart.Nested)fieldInfo.FieldPath[i - 1]).TypeName; - - // Make sure to skip repeated field accessors. It's possible for some accessors to end up - // being required, in case a shader type had multiple fields of the same nested struct type. - // To avoid so, we just add the containing type and name to an hashset that we update. - if (!generatedAccessors.Add((containingTypeName, pathPart.Name))) - { - continue; - } - - writer.WriteLine(); - - // If there is no unspeakable name, we can reference the field directly. This means we can both - // use that in XML docs to refer to it (and inherit the docs), and we don't need an explicit name. - if (pathPart.UnspeakableName is null) - { - writer.WriteLine($""" - /// - /// The input value. - /// A mutable reference to . - [UnsafeAccessor(UnsafeAccessorKind.Field)] - private static extern ref {typeName} {pathPart.Name}(this ref readonly {containingTypeName} value); - """, isMultiline: true); - } - else - { - writer.WriteLine($""" - /// Gets a reference to the unspeakable field "{pathPart.Name}" of type . - /// The input value. - /// A mutable reference to the unspeakable field "{pathPart.Name}". - [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "{pathPart.UnspeakableName}")] - private static extern ref {typeName} {pathPart.Name}(this ref readonly {containingTypeName} value); - """, isMultiline: true); - } - } - } - } - } - - callbacks.Add(ConstantBufferCallback); - callbacks.Add(ConstantBufferMarshallerCallback); - } - } -} - -/// -file static class IndentedTextWriterExtensions -{ - /// - /// Writes the XML summary for a given field. - /// - /// The instance to write into. - /// The input field to write the XML summary for. - /// The fully qualified type name of the containing type. - public static void WriteFieldXmlSummary(this IndentedTextWriter writer, FieldInfo fieldInfo, string fullyQualifiedTypeName) - { - if (fieldInfo.FieldPath[0].UnspeakableName is null) - { - writer.WriteLine($"""/// """); - } - else - { - writer.WriteLine($"""/// The unspeakable field "{fieldInfo.FieldPath[0].Name}" of ."""); - } - } - - /// - /// Writes the XML remarks for a given field, if needed. - /// - /// The instance to write into. - /// The input field to write the XML remarks for, if needed. - /// The row for the field, if this is a matrix type. - public static void WriteFieldXmlRemarks(this IndentedTextWriter writer, FieldInfo fieldInfo, int? row = null) - { - // The remarks are only needed if the field is nested - if (fieldInfo.FieldPath is not [.., FieldPathPart.Nested nested, FieldPathPart.Leaf leaf]) - { - return; - } - - // Write the correct remarks depending on whether the field can be referenced directly - if (leaf.UnspeakableName is null) - { - writer.Write($"""/// Serialized field mapping to"""); - writer.WriteIf(row is not null, $""" row {row} of"""); - writer.WriteLine($""" ."""); - } - else - { - writer.Write($"""/// Serialized field mapping to"""); - writer.WriteIf(row is not null, $""" row {row} of"""); - writer.WriteLine($""" the unspeakable field "{leaf.Name}" of ."""); - } - } - - /// - /// Writes an expression to access a given field. - /// - /// The instance to write into. - /// The input field to write the expression for. - public static void WriteFieldAccessExpression(this IndentedTextWriter writer, FieldInfo fieldInfo) - { - writer.Write("shader"); - - // Invoke all generated field accessors to get to the target field. - // Because they're extension methods, we can chain them sequentially. - // This simplifies the formatting and makes the code easier to read. - foreach (FieldPathPart part in fieldInfo.FieldPath) - { - writer.Write($".{part.Name}()"); - } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs index 5f6d96c4..7574a56c 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs @@ -4,6 +4,7 @@ using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; +using ComputeSharp.SourceGeneration.SyntaxWriters; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -233,7 +234,7 @@ public sealed partial class D2DPixelShaderDescriptorGenerator : IIncrementalGene using ImmutableArrayBuilder> additionalTypes = new(); using ImmutableHashSetBuilder usingDirectives = new(); - ConstantBuffer.RegisterAdditionalTypesSyntax(item, additionalTypes, usingDirectives); + ConstantBufferSyntaxWriter.RegisterAdditionalTypesSyntax(GeneratorName, item, additionalTypes, usingDirectives); InputDescriptions.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives); InputTypes.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives); HlslBytecode.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives); diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems index 220630d5..e6cb2cda 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems +++ b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems @@ -31,5 +31,6 @@ + \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxWriters/ConstantBufferSyntaxWriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxWriters/ConstantBufferSyntaxWriter.cs new file mode 100644 index 00000000..e948fcd6 --- /dev/null +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxWriters/ConstantBufferSyntaxWriter.cs @@ -0,0 +1,363 @@ +using System.Linq; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Mappings; +using ComputeSharp.SourceGeneration.Models; + +namespace ComputeSharp.SourceGeneration.SyntaxWriters; + +/// +/// A helper responsible for writing the constant buffer syntax for shader types. +/// +internal static partial class ConstantBufferSyntaxWriter +{ + /// + /// The name of generator to include in the generated code. + /// + private static string? generatorName; + + /// + /// Registers a callback to generate additional types, if needed. + /// + /// The type of model providing the necessary info. + /// The name of generator to include in the generated code. + /// The input instance with gathered shader info. + /// The registered callbacks to generate additional types. + /// The using directives needed by the generated code. + public static void RegisterAdditionalTypesSyntax( + string generatorName, + TInfo info, + ImmutableArrayBuilder> callbacks, + ImmutableHashSetBuilder usingDirectives) + where TInfo : class, IConstantBufferInfo + { + // Store the generator name for later. This avoids needing closures for each callback below. + // It is assumed that all calls to this method will have the same argument in each assembly. + ConstantBufferSyntaxWriter.generatorName = generatorName; + + // If there are no fields, there is no need for a constant buffer type + if (info.Fields.IsEmpty) + { + return; + } + + _ = usingDirectives.Add("global::System.CodeDom.Compiler"); + _ = usingDirectives.Add("global::System.Diagnostics"); + _ = usingDirectives.Add("global::System.Diagnostics.CodeAnalysis"); + _ = usingDirectives.Add("global::System.Runtime.CompilerServices"); + _ = usingDirectives.Add("global::System.Runtime.InteropServices"); + + // Declare the ConstantBuffer type + static void ConstantBufferCallback(TInfo info, IndentedTextWriter writer) + { + string fullyQualifiedTypeName = info.Hierarchy.GetFullyQualifiedTypeName(); + + writer.WriteLine($"""/// """); + writer.WriteLine($"""/// A type representing the constant buffer native layout for ."""); + writer.WriteLine($"""/// """); + writer.WriteGeneratedAttributes(ConstantBufferSyntaxWriter.generatorName!, useFullyQualifiedTypeNames: false); + writer.WriteLine($"""[StructLayout(LayoutKind.Explicit, Size = {info.ConstantBufferSizeInBytes})]"""); + writer.WriteLine($"""file struct ConstantBuffer"""); + + using (writer.WriteBlock()) + { + // Declare fields for every mapped item from the shader layout + writer.WriteLineSeparatedMembers(info.Fields.AsSpan(), (field, writer) => + { + switch (field) + { + case FieldInfo.Primitive { TypeName: "System.Boolean" } primitive: + + // Append a field as a global::ComputeSharp.Bool value (will use the implicit conversion from bool values) + writer.WriteFieldXmlSummary(field, fullyQualifiedTypeName); + writer.WriteFieldXmlRemarks(field); + writer.WriteLine($"""[FieldOffset({primitive.Offset})]"""); + writer.WriteLine($"""public global::ComputeSharp.Bool {string.Join("_", primitive.FieldPath.Select(static path => path.Name))};"""); + break; + case FieldInfo.Primitive primitive: + + // Append primitive fields of other types with their mapped names + writer.WriteFieldXmlSummary(field, fullyQualifiedTypeName); + writer.WriteFieldXmlRemarks(field); + writer.WriteLine($"""[FieldOffset({primitive.Offset})]"""); + writer.WriteLine($"""public {HlslKnownTypes.GetMappedName(primitive.TypeName)} {string.Join("_", primitive.FieldPath.Select(static path => path.Name))};"""); + break; + + case FieldInfo.NonLinearMatrix matrix: + string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}"); + string fieldNamePrefix = string.Join("_", matrix.FieldPath.Select(static path => path.Name)); + + // Declare a field for every row of the matrix type + for (int j = 0; j < matrix.Rows; j++) + { + writer.WriteLineIf(j > 0); + writer.WriteFieldXmlSummary(field, fullyQualifiedTypeName); + writer.WriteFieldXmlRemarks(field, row: j); + writer.WriteLine($"""[FieldOffset({matrix.Offsets[j]})]"""); + writer.WriteLine($"""public {rowTypeName} {fieldNamePrefix}_{j};"""); + } + + break; + } + }); + } + } + + // Declare the ConstantBufferMarshaller type + static void ConstantBufferMarshallerCallback(TInfo info, IndentedTextWriter writer) + { + string fullyQualifiedTypeName = info.Hierarchy.GetFullyQualifiedTypeName(); + + writer.WriteLine($"""/// """); + writer.WriteLine($"""/// A type containing marshalling logic for shaders of type ."""); + writer.WriteLine($"""/// """); + writer.WriteGeneratedAttributes(ConstantBufferSyntaxWriter.generatorName!, useFullyQualifiedTypeNames: false); + writer.WriteLine($"""file static class ConstantBufferMarshaller"""); + + using (writer.WriteBlock()) + { + // Define the ToManaged method (native constant buffer to managed shader type) + writer.WriteLine($"""/// """); + writer.WriteLine($"""/// Marshals native constant buffer data to managed instances."""); + writer.WriteLine($"""/// """); + writer.WriteLine($"""/// The input native constant buffer."""); + writer.WriteLine($"""/// The marshalled instance."""); + writer.WriteLine($"""[MethodImpl(MethodImplOptions.AggressiveInlining)]"""); + writer.WriteLine($"""[SkipLocalsInit]"""); + writer.WriteLine($"public static {fullyQualifiedTypeName} ToManaged(in ConstantBuffer buffer)"); + + using (writer.WriteBlock()) + { + writer.WriteLine($"Unsafe.SkipInit(out {fullyQualifiedTypeName} shader);"); + writer.WriteLine(); + + // Generate loading statements for each captured field + foreach (FieldInfo fieldInfo in info.Fields) + { + switch (fieldInfo) + { + case FieldInfo.Primitive primitive: + + // Read a nested primitive value + writer.WriteFieldAccessExpression(fieldInfo); + writer.WriteLine($" = buffer.{string.Join("_", primitive.FieldPath.Select(static path => path.Name))};"); + break; + + case FieldInfo.NonLinearMatrix matrix: + string primitiveTypeName = matrix.ElementName.ToLowerInvariant(); + string matrixHlslTypeName = $"{primitiveTypeName}{matrix.Rows}x{matrix.Columns}"; + string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}"); + string fieldNamePrefix = string.Join("_", matrix.FieldPath.Select(static path => path.Name)); + + // Get a reference to the whole matrix field, just once for all rows + writer.WriteLine(skipIfPresent: true); + writer.Write($"ref {matrixHlslTypeName} __{fieldNamePrefix} = ref "); + writer.WriteFieldAccessExpression(fieldInfo); + writer.WriteLine(";"); + writer.WriteLine(); + + // Read all rows of a given matrix type + for (int j = 0; j < matrix.Rows; j++) + { + writer.WriteLine($"Unsafe.As<{primitiveTypeName}, {rowTypeName}>(ref __{fieldNamePrefix}.M{j + 1}1) = buffer.{fieldNamePrefix}_{j};"); + } + + writer.WriteLine(); + break; + } + } + + writer.WriteLine(skipIfPresent: true); + writer.WriteLine("return shader;"); + } + + // Define the FromManaged method (managed shader type to native constant buffer) + writer.WriteLine(); + writer.WriteLine($"""/// """); + writer.WriteLine($"""/// Marshals managed instances to native constant buffer data."""); + writer.WriteLine($"""/// """); + writer.WriteLine($"""/// The input native constant buffer."""); + writer.WriteLine($"""/// The marshalled instance."""); + writer.WriteLine($"""[MethodImpl(MethodImplOptions.AggressiveInlining)]"""); + writer.WriteLine($"""[SkipLocalsInit]"""); + writer.WriteLine($"public static void FromManaged(in {fullyQualifiedTypeName} shader, out ConstantBuffer buffer)"); + + using (writer.WriteBlock()) + { + // Generate loading statements for each captured field + foreach (FieldInfo fieldInfo in info.Fields) + { + switch (fieldInfo) + { + case FieldInfo.Primitive primitive: + + // Assign a primitive value + writer.Write($"buffer.{string.Join("_", primitive.FieldPath.Select(static path => path.Name))} = "); + writer.WriteFieldAccessExpression(fieldInfo); + writer.WriteLine(";"); + break; + + case FieldInfo.NonLinearMatrix matrix: + string primitiveTypeName = matrix.ElementName.ToLowerInvariant(); + string matrixHlslTypeName = $"{primitiveTypeName}{matrix.Rows}x{matrix.Columns}"; + string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}"); + string fieldNamePrefix = string.Join("_", matrix.FieldPath.Select(static path => path.Name)); + + // Get a reference to the whole matrix field, just once for all rows + writer.WriteLine(skipIfPresent: true); + writer.Write($"ref {matrixHlslTypeName} __{fieldNamePrefix} = ref "); + writer.WriteFieldAccessExpression(fieldInfo); + writer.WriteLine(";"); + writer.WriteLine(); + + // Assign all rows of a given matrix type + for (int j = 0; j < matrix.Rows; j++) + { + writer.WriteLine($"buffer.{fieldNamePrefix}_{j} = Unsafe.As<{primitiveTypeName}, {rowTypeName}>(ref __{fieldNamePrefix}.M{j + 1}1);"); + } + + writer.WriteLine(); + break; + } + } + } + + using ImmutableHashSetBuilder<(string ContainerType, string FieldName)> generatedAccessors = new(); + + // Define all field accessors. Note that these are generated regardless of the accessibility + // of the field they're getting the value for. This simplifies the rest of the code, and allows + // stripping the readonly-ness of the field references, and has no binary size impact anyway. + // This is because the fields are compiled to be exactly equivalent to direct field references. + foreach (FieldInfo fieldInfo in info.Fields) + { + for (int i = 0; i < fieldInfo.FieldPath.Length; i++) + { + FieldPathPart pathPart = fieldInfo.FieldPath[i]; + + // Get the friendly type name for the field: + // - If the part path is a nested struct, the type name is embedded + // - Otherwise, get the correct HLSL mapped type name for the field + string typeName = pathPart switch + { + FieldPathPart.Nested nested => nested.TypeName, + FieldPathPart.Leaf when fieldInfo.TypeName is "System.Boolean" => "global::ComputeSharp.Bool", + _ => HlslKnownTypes.GetMappedName(fieldInfo.TypeName) + }; + + // Get the friendly type name for the field. If this nested field is the + // first path, then the parent is the shader type itself. Otherwise, the + // container path is the type of the previous containing type of the field. + string containingTypeName = i == 0 + ? fullyQualifiedTypeName + : ((FieldPathPart.Nested)fieldInfo.FieldPath[i - 1]).TypeName; + + // Make sure to skip repeated field accessors. It's possible for some accessors to end up + // being required, in case a shader type had multiple fields of the same nested struct type. + // To avoid so, we just add the containing type and name to an hashset that we update. + if (!generatedAccessors.Add((containingTypeName, pathPart.Name))) + { + continue; + } + + writer.WriteLine(); + + // If there is no unspeakable name, we can reference the field directly. This means we can both + // use that in XML docs to refer to it (and inherit the docs), and we don't need an explicit name. + if (pathPart.UnspeakableName is null) + { + writer.WriteLine($""" + /// + /// The input value. + /// A mutable reference to . + [UnsafeAccessor(UnsafeAccessorKind.Field)] + private static extern ref {typeName} {pathPart.Name}(this ref readonly {containingTypeName} value); + """, isMultiline: true); + } + else + { + writer.WriteLine($""" + /// Gets a reference to the unspeakable field "{pathPart.Name}" of type . + /// The input value. + /// A mutable reference to the unspeakable field "{pathPart.Name}". + [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "{pathPart.UnspeakableName}")] + private static extern ref {typeName} {pathPart.Name}(this ref readonly {containingTypeName} value); + """, isMultiline: true); + } + } + } + } + } + + callbacks.Add(ConstantBufferCallback); + callbacks.Add(ConstantBufferMarshallerCallback); + } +} + +/// +file static class IndentedTextWriterExtensions +{ + /// + /// Writes the XML summary for a given field. + /// + /// The instance to write into. + /// The input field to write the XML summary for. + /// The fully qualified type name of the containing type. + public static void WriteFieldXmlSummary(this IndentedTextWriter writer, FieldInfo fieldInfo, string fullyQualifiedTypeName) + { + if (fieldInfo.FieldPath[0].UnspeakableName is null) + { + writer.WriteLine($"""/// """); + } + else + { + writer.WriteLine($"""/// The unspeakable field "{fieldInfo.FieldPath[0].Name}" of ."""); + } + } + + /// + /// Writes the XML remarks for a given field, if needed. + /// + /// The instance to write into. + /// The input field to write the XML remarks for, if needed. + /// The row for the field, if this is a matrix type. + public static void WriteFieldXmlRemarks(this IndentedTextWriter writer, FieldInfo fieldInfo, int? row = null) + { + // The remarks are only needed if the field is nested + if (fieldInfo.FieldPath is not [.., FieldPathPart.Nested nested, FieldPathPart.Leaf leaf]) + { + return; + } + + // Write the correct remarks depending on whether the field can be referenced directly + if (leaf.UnspeakableName is null) + { + writer.Write($"""/// Serialized field mapping to"""); + writer.WriteIf(row is not null, $""" row {row} of"""); + writer.WriteLine($""" ."""); + } + else + { + writer.Write($"""/// Serialized field mapping to"""); + writer.WriteIf(row is not null, $""" row {row} of"""); + writer.WriteLine($""" the unspeakable field "{leaf.Name}" of ."""); + } + } + + /// + /// Writes an expression to access a given field. + /// + /// The instance to write into. + /// The input field to write the expression for. + public static void WriteFieldAccessExpression(this IndentedTextWriter writer, FieldInfo fieldInfo) + { + writer.Write("shader"); + + // Invoke all generated field accessors to get to the target field. + // Because they're extension methods, we can chain them sequentially. + // This simplifies the formatting and makes the code easier to read. + foreach (FieldPathPart part in fieldInfo.FieldPath) + { + writer.Write($".{part.Name}()"); + } + } +} \ No newline at end of file