diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs index cf0a71d8..e23348f7 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs @@ -25,42 +25,39 @@ partial class ID2D1ShaderGenerator using (writer.WriteBlock()) { - writer.WriteLine($"global::System.ReadOnlySpan bytes = new byte[]"); + writer.WriteLine("global::System.ReadOnlySpan bytes = new byte[]"); + writer.WriteLine("{"); + writer.IncreaseIndent(); - using (writer.WriteBlock()) - { - // Write the bytes like so: - // - // b[0], b[1], b[2], b[3], - // b[4], b[5], - // b[6], b[7], - // b[8], - // b[9], - // b[10], - // b[11], - // b[12], - // b[13], - // b[14], - // b[15], - // b[16], - // b[17] - SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(info.EffectId.AsSpan()[..4], writer); - writer.WriteLine(","); - SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(info.EffectId.AsSpan()[4..6], writer); - writer.WriteLine(","); - SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(info.EffectId.AsSpan()[6..8], writer); - writer.WriteLine(","); - writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[8])},"); - writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[9])},"); - writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[10])},"); - writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[11])},"); - writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[12])},"); - writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[13])},"); - writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[14])},"); - writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[15])},"); - writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[16])},"); - writer.WriteLine(SyntaxFormattingHelper.GetByteExpression(info.EffectId[17])); - } + // Write the bytes like so: + // + // b[0], b[1], b[2], b[3], + // b[4], b[5], + // b[6], b[7], + // b[8], + // b[9], + // b[10], + // b[11], + // b[12], + // b[13], + // b[14], + // b[15] + SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(info.EffectId.AsSpan()[..4], writer); + writer.WriteLine(","); + SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(info.EffectId.AsSpan()[4..6], writer); + writer.WriteLine(","); + SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(info.EffectId.AsSpan()[6..8], writer); + writer.WriteLine(","); + writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[8])},"); + writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[9])},"); + writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[10])},"); + writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[11])},"); + writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[12])},"); + writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[13])},"); + writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[14])},"); + writer.WriteLine(SyntaxFormattingHelper.GetByteExpression(info.EffectId[15])); + writer.DecreaseIndent(); + writer.WriteLine("};"); writer.WriteLine(); writer.WriteLine("return ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(bytes));"); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateHlslSourceProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateHlslSourceProperty.Syntax.cs index 3a508bd5..18b07eb7 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateHlslSourceProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateHlslSourceProperty.Syntax.cs @@ -17,9 +17,11 @@ partial class ID2D1ShaderGenerator public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { writer.WriteLine("readonly string global::ComputeSharp.D2D1.__Internals.ID2D1Shader.HlslSource =>"); + writer.IncreaseIndent(); writer.WriteLine("\"\"\""); - writer.WriteLine(info.HlslInfoKey.HlslSource, isMultiline: true); + writer.Write(info.HlslInfoKey.HlslSource, isMultiline: true); writer.WriteLine("\"\"\";"); + writer.DecreaseIndent(); } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs index 1c15a7df..32b0acb7 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs @@ -35,6 +35,7 @@ partial class ID2D1ShaderGenerator } // Get a reference to the data through the generated native layout type + writer.WriteLine(); writer.WriteLine("ref readonly ConstantBuffer buffer = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(data));"); // Generate loading statements for each captured field diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs index 50c429f4..4f822624 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs @@ -1,10 +1,5 @@ -using System; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Helpers; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.D2D1.SourceGenerators; @@ -21,7 +16,7 @@ partial class ID2D1ShaderGenerator /// The instance to write into. public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - writer.WriteLine("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputDescriptions => "); + writer.Write("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputDescriptions => "); // If there are no input descriptions, just return a default expression. // Otherwise, return the shared array with cached input descriptions. @@ -36,36 +31,44 @@ partial class ID2D1ShaderGenerator } /// - /// Registers a callback to generate an additional data member, if needed. + /// Registers a callback to generate an additional type, if needed. /// /// The input instance with gathered shader info. - /// The registered callbacks to generate additional data members. - public static void RegisterAdditionalDataMemberSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder> callbacks) + /// The registered callbacks to generate additional types. + public static void RegisterAdditionalTypeSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder> callbacks) { - // If there are no input descriptions, there is nothing to di - if (info.ResourceTextureDescriptions.IsEmpty) + // If there are no necessary data members, stop here + if (info.InputDescriptions.IsEmpty && + info.ResourceTextureDescriptions.IsEmpty) { return; } - // Declare the shared array with input descriptions + // Declare the additional data type static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer) { - writer.WriteLine("""/// The singleton array instance."""); - writer.WriteLine("""public static readonly global::ComputeSharp.D2D1.Interop.D2D1InputDescription[] InputDescriptions = """); + writer.WriteLine($$"""/// """); + writer.WriteLine($$"""/// A container type for additional data needed by the shader."""); + writer.WriteLine($$"""/// """); + writer.WriteLine($$"""[global::System.CodeDom.Compiler.GeneratedCode("{{typeof(ID2D1ShaderGenerator).FullName}}", "{{typeof(ID2D1ShaderGenerator).Assembly.GetName().Version}}")]"""); + writer.WriteLine($$"""[global::System.Diagnostics.DebuggerNonUserCode]"""); + writer.WriteLine($$"""[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]"""); + writer.WriteLine($$"""file static class Data"""); - // Initialize all input descriptions using (writer.WriteBlock()) { - for (int i = 0; i < info.InputDescriptions.Length; i++) + using ImmutableArrayBuilder> dataMembers = ImmutableArrayBuilder>.Rent(); + + RegisterAdditionalDataMemberSyntax(info, dataMembers); + ResourceTextureDescriptions.RegisterAdditionalDataMemberSyntax(info, dataMembers); + + for (int i = 0; i < dataMembers.WrittenSpan.Length; i++) { - InputDescription description = info.InputDescriptions[i]; + dataMembers.WrittenSpan[i](info, writer); - writer.Write($$"""new global::ComputeSharp.D2D1.Interop.D2D1InputDescription({description.Index}, {description.Filter}) { LevelOfDetailCount = {{description.LevelOfDetailCount}} }"""); - - if (i < info.InputDescriptions.Length - 1) + if (i < dataMembers.WrittenSpan.Length - 1) { - writer.WriteLine(","); + writer.WriteLine(); } } } @@ -75,46 +78,45 @@ partial class ID2D1ShaderGenerator } /// - /// Gets any type declarations for additional members. + /// Registers a callback to generate an additional data member, if needed. /// - /// The additional members that are needed. - /// Any type declarations for additional members. - public static TypeDeclarationSyntax[] GetDataTypeDeclarations(MemberDeclarationSyntax[] memberDeclarations) + /// The input instance with gathered shader info. + /// The registered callbacks to generate additional data members. + public static void RegisterAdditionalDataMemberSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder> callbacks) { - if (memberDeclarations.Length == 0) + // If there are no input descriptions, there is nothing to di + if (info.InputDescriptions.IsEmpty) { - return Array.Empty(); + return; } - // Create the container type declaration: - // - // /// - // /// A container type for additional data needed by the shader. - // /// - // [global::System.CodeDom.Compiler.GeneratedCode("...", "...")] - // [global::System.Diagnostics.DebuggerNonUserCode] - // [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] - // file static class Data - // { - // - // } - TypeDeclarationSyntax dataTypeDeclaration = - ClassDeclaration("Data") - .AddModifiers(Token(SyntaxKind.FileKeyword), Token(SyntaxKind.StaticKeyword)) - .AddAttributeLists( - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments( - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).FullName))), - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).Assembly.GetName().Version.ToString())))))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage"))))) - .AddMembers(memberDeclarations) - .WithLeadingTrivia( - Comment("/// "), - Comment("/// A container type for input descriptions."), - Comment("/// ")); + // Declare the shared array with input descriptions + static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer) + { + writer.WriteLine("""/// The singleton array instance."""); + writer.WriteLine("""public static readonly global::ComputeSharp.D2D1.Interop.D2D1InputDescription[] InputDescriptions = """); + writer.WriteLine("""{"""); + writer.IncreaseIndent(); - return new[] { dataTypeDeclaration }; + // Initialize all input descriptions + for (int i = 0; i < info.InputDescriptions.Length; i++) + { + InputDescription description = info.InputDescriptions[i]; + + writer.Write($$"""new global::ComputeSharp.D2D1.Interop.D2D1InputDescription({{description.Index}}, global::ComputeSharp.D2D1.D2D1Filter.{{description.Filter}}) { LevelOfDetailCount = {{description.LevelOfDetailCount}} }"""); + + if (i < info.InputDescriptions.Length - 1) + { + writer.WriteLine(","); + } + } + + writer.DecreaseIndent(); + writer.WriteLine(); + writer.WriteLine("};"); + } + + callbacks.Add(Callback); } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs index 4d536efa..3a8a9e00 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs @@ -16,7 +16,7 @@ partial class ID2D1ShaderGenerator /// The instance to write into. public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - writer.WriteLine("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputTypes => "); + writer.Write("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputTypes => "); // If there are no inputs, simply return a default expression. Otherwise, create // a ReadOnlyMemory instance from the memory manager. @@ -64,28 +64,32 @@ partial class ID2D1ShaderGenerator writer.WriteLine(); writer.WriteLine("/// The RVA data with the input type info."); writer.WriteLine("private static global::System.ReadOnlySpan Data => new[]"); + writer.WriteLine("{"); + writer.IncreaseIndent(); // Input types, one per line in the RVA field initializer - using (writer.WriteBlock()) + for (int i = 0; i < info.InputTypes.Length; i++) { - for (int i = 0; i < info.InputTypes.Length; i++) - { - writer.Write("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType."); - writer.Write(info.InputTypes[i] == 0 ? "Simple" : "Complex"); + writer.Write("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType."); + writer.Write(info.InputTypes[i] == 0 ? "Simple" : "Complex"); - if (i < info.InputTypes.Length - 1) - { - writer.WriteLine(","); - } + if (i < info.InputTypes.Length - 1) + { + writer.WriteLine(","); } } + writer.DecreaseIndent(); + writer.WriteLine(); + writer.WriteLine("};"); + writer.WriteLine(); + // Add the remaining members for the memory manager writer.WriteLine(""" /// - public override unsafe global::System.Span GetSpan + public override unsafe global::System.Span GetSpan() { - return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.InteropServices.MemoryMarshal(Data)), Data.Length); + return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(Data)), Data.Length); } /// @@ -98,7 +102,7 @@ partial class ID2D1ShaderGenerator /// public override unsafe global::System.Buffers.MemoryHandle Pin(int elementIndex) { - return new(Unsafe.AsPointer(ref Unsafe.AsRef(in Data[elementIndex])), pinnable: this); + return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in Data[elementIndex])), pinnable: this); } /// diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs index 2c021ad6..3ef62dc6 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs @@ -36,7 +36,7 @@ partial class ID2D1ShaderGenerator .Select(static name => $"global::ComputeSharp.D2D1.D2D1CompileOptions.{name.Trim()}") .Aggregate("", static (left, right) => left.Length > 0 ? $"{left} | {right}" : right); - writer.Write($"readonly ComputeSharp.D2D1.D2D1CompileOptions global::ComputeSharp.D2D1.__Internals.ID2D1Shader.CompileOptions => {compileOptionsExpression};"); + writer.WriteLine($"readonly ComputeSharp.D2D1.D2D1CompileOptions global::ComputeSharp.D2D1.__Internals.ID2D1Shader.CompileOptions => {compileOptionsExpression};"); } /// @@ -46,7 +46,7 @@ partial class ID2D1ShaderGenerator /// The instance to write into. public static void WriteHlslBytecodeSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - writer.WriteLine("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ResourceTextureDescriptions => "); + writer.Write("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.HlslBytecode => "); // If there is no bytecode, just return a default expression. // Otherwise, return the memory manager backed memory instance. @@ -77,7 +77,7 @@ partial class ID2D1ShaderGenerator static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer) { writer.WriteLine($$"""/// """); - writer.WriteLine($$""" implementation to get the HLSL bytecode."""); + writer.WriteLine($$"""/// implementation to get the HLSL bytecode."""); writer.WriteLine($$"""/// """); writer.WriteLine($$"""[global::System.CodeDom.Compiler.GeneratedCode("{{typeof(ID2D1ShaderGenerator).FullName}}", "{{typeof(ID2D1ShaderGenerator).Assembly.GetName().Version}}")]"""); writer.WriteLine($$"""[global::System.Diagnostics.DebuggerNonUserCode]"""); @@ -93,18 +93,19 @@ partial class ID2D1ShaderGenerator // RVA field (with the compiled HLSL bytecode, on a single line) writer.WriteLine(); writer.WriteLine("/// The RVA data with the HLSL bytecode."); - writer.Write("private static global::System.ReadOnlySpan Data => new[] { "); + writer.Write("private static global::System.ReadOnlySpan Data => new byte[] { "); SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(((HlslBytecodeInfo.Success)info.HlslInfo).Bytecode.AsSpan(), writer); writer.WriteLine(" };"); + writer.WriteLine(); // Add the remaining members for the memory manager writer.WriteLine(""" /// - public override unsafe global::System.Span GetSpan + public override unsafe global::System.Span GetSpan() { - return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.InteropServices.MemoryMarshal(Data)), Data.Length); + return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(Data)), Data.Length); } /// @@ -117,7 +118,7 @@ partial class ID2D1ShaderGenerator /// public override unsafe global::System.Buffers.MemoryHandle Pin(int elementIndex) { - return new(Unsafe.AsPointer(ref Unsafe.AsRef(in Data[elementIndex])), pinnable: this); + return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in Data[elementIndex])), pinnable: this); } /// diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs index 54e5242e..d22e2de0 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs @@ -95,6 +95,11 @@ partial class ID2D1ShaderGenerator // Declare fields for every mapped item from the shader layout for (int i = 0; i < info.Fields.Length; i++) { + if (i > 0) + { + writer.WriteLine(); + } + switch (info.Fields[i]) { case FieldInfo.Primitive { TypeName: "System.Boolean" } primitive: diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs index 914f54e9..76e4f735 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs @@ -16,7 +16,7 @@ partial class ID2D1ShaderGenerator /// The instance to write into. public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - writer.WriteLine("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ResourceTextureDescriptions => "); + writer.Write("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ResourceTextureDescriptions => "); // If there are no resource texture descriptions, just return a default expression. // Otherwise, return a memory instance from the generated static readonly array. @@ -48,22 +48,25 @@ partial class ID2D1ShaderGenerator { writer.WriteLine("""/// The singleton array instance."""); writer.WriteLine("""public static readonly global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription[] ResourceTextureDescriptions ="""); + writer.WriteLine("""{"""); + writer.IncreaseIndent(); // Initialize all resource texture descriptions - using (writer.WriteBlock()) + for (int i = 0; i < info.ResourceTextureDescriptions.Length; i++) { - for (int i = 0; i < info.ResourceTextureDescriptions.Length; i++) + ResourceTextureDescription description = info.ResourceTextureDescriptions[i]; + + writer.Write($"new global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription({description.Index}, {description.Rank})"); + + if (i < info.ResourceTextureDescriptions.Length - 1) { - ResourceTextureDescription description = info.ResourceTextureDescriptions[i]; - - writer.Write($"new global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription({description.Index}, {description.Rank})"); - - if (i < info.ResourceTextureDescriptions.Length - 1) - { - writer.WriteLine(","); - } + writer.WriteLine(","); } } + + writer.DecreaseIndent(); + writer.WriteLine(); + writer.WriteLine("};"); } callbacks.Add(Callback); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs index 044b2e32..d968e554 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Immutable; using System.Linq; using ComputeSharp.D2D1.SourceGenerators.Models; @@ -8,7 +7,6 @@ using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Text; namespace ComputeSharp.D2D1.SourceGenerators; @@ -196,48 +194,46 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator // Generate the source files, if any context.RegisterSourceOutput(outputInfo, static (context, item) => { - PropertyDeclarationSyntax effectIdProperty = EffectId.GetSyntax(item.EffectId); - PropertyDeclarationSyntax effectDisplayNameProperty = EffectMetadata.GetEffectDisplayNameSyntax(item.EffectDisplayName); - PropertyDeclarationSyntax effectDescriptionProperty = EffectMetadata.GetEffectDescriptionSyntax(item.EffectDescription); - PropertyDeclarationSyntax effectCategoryProperty = EffectMetadata.GetEffectCategorySyntax(item.EffectCategory); - PropertyDeclarationSyntax effectAuthorProperty = EffectMetadata.GetEffectAuthorSyntax(item.EffectAuthor); - PropertyDeclarationSyntax inputCountProperty = InputCount.GetSyntax(item.InputTypes.Length); - PropertyDeclarationSyntax inputTypesProperty = InputTypes.GetSyntax(item.InputTypes, out TypeDeclarationSyntax[] inputTypesAdditionalTypes); - PropertyDeclarationSyntax inputDescriptionsProperty = InputDescriptions.GetSyntax(item.InputDescriptions, out MemberDeclarationSyntax[] inputDescriptionsAdditionalDataMembers); - PropertyDeclarationSyntax resourceTextureDescriptionsProperty = ResourceTextureDescriptions.GetSyntax(item.ResourceTextureDescriptions, out MemberDeclarationSyntax[] resourceTexturesAditionalDataMembers); - PropertyDeclarationSyntax hlslStringProperty = HlslSource.GetSyntax(item.HlslInfoKey.HlslSource, item.Hierarchy.Hierarchy.Length); - PropertyDeclarationSyntax hlslBytecodeProperty = LoadBytecode.GetHlslBytecodeSyntax(item.HlslInfo, out Func fixup, out TypeDeclarationSyntax[] hlslBytecodeAdditionalTypes); - PropertyDeclarationSyntax shaderProfileProperty = LoadBytecode.GetShaderProfileSyntax(item.HlslInfoKey.EffectiveShaderProfile); - PropertyDeclarationSyntax compileOptionsProperty = LoadBytecode.GetCompileOptionsSyntax(item.HlslInfoKey.EffectiveCompileOptions); - PropertyDeclarationSyntax bufferPrecisionProperty = OutputBuffer.GetBufferPrecisionSyntax(item.BufferPrecision); - PropertyDeclarationSyntax channelDepthProperty = OutputBuffer.GetChannelDepthSyntax(item.ChannelDepth); - PropertyDeclarationSyntax pixelOptionsProperty = PixelOptions.GetSyntax(item.PixelOptions); + using ImmutableArrayBuilder> declaredMembers = ImmutableArrayBuilder>.Rent(); - MethodDeclarationSyntax initializeFromDispatchDataMethod = InitializeFromDispatchData.GetSyntax(item.Fields); - MethodDeclarationSyntax loadDispatchDataMethod = LoadDispatchData.GetSyntax(item.Hierarchy, item.Fields, item.ConstantBufferSizeInBytes, out TypeDeclarationSyntax[] loadDispatchDataAditionalTypes); + declaredMembers.Add(EffectId.WriteSyntax); + declaredMembers.Add(EffectMetadata.WriteEffectDisplayNameSyntax); + declaredMembers.Add(EffectMetadata.WriteEffectDescriptionSyntax); + declaredMembers.Add(EffectMetadata.WriteEffectCategorySyntax); + declaredMembers.Add(EffectMetadata.WriteEffectAuthorSyntax); + declaredMembers.Add(InputCount.WriteSyntax); + declaredMembers.Add(InputTypes.WriteSyntax); + declaredMembers.Add(InputDescriptions.WriteSyntax); + declaredMembers.Add(ResourceTextureDescriptions.WriteSyntax); + declaredMembers.Add(PixelOptions.WriteSyntax); + declaredMembers.Add(OutputBuffer.WriteBufferPrecisionSyntax); + declaredMembers.Add(OutputBuffer.WriteChannelDepthSyntax); + declaredMembers.Add(LoadBytecode.WriteShaderProfileSyntax); + declaredMembers.Add(LoadBytecode.WriteCompileOptionsSyntax); + declaredMembers.Add(HlslSource.WriteSyntax); + declaredMembers.Add(LoadBytecode.WriteHlslBytecodeSyntax); + declaredMembers.Add(InitializeFromDispatchData.WriteSyntax); + declaredMembers.Add(LoadDispatchData.WriteSyntax); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMembers( - hierarchyInfo: item.Hierarchy, - memberDeclarations: new (MemberDeclarationSyntax, bool)[] - { - (effectIdProperty, false), (effectDisplayNameProperty, false), (effectDescriptionProperty, false), (effectCategoryProperty, false), (effectAuthorProperty, false), - (inputCountProperty, false), (inputTypesProperty, false), (inputDescriptionsProperty, false), (resourceTextureDescriptionsProperty, false), (hlslStringProperty, false), - (hlslBytecodeProperty, false), (shaderProfileProperty, false), (compileOptionsProperty, false), (bufferPrecisionProperty, false), (channelDepthProperty, false), - (pixelOptionsProperty, false), (initializeFromDispatchDataMethod, true), (loadDispatchDataMethod, true) - }, - additionalMemberDeclarations: new TypeDeclarationSyntax[][] - { - loadDispatchDataAditionalTypes, - InputDescriptions.GetDataTypeDeclarations(new[] { inputDescriptionsAdditionalDataMembers, resourceTexturesAditionalDataMembers }.SelectMany(static members => members).ToArray()), - inputTypesAdditionalTypes, hlslBytecodeAdditionalTypes - } - .SelectMany(static types => types) - .Cast() - .ToArray()); + using ImmutableArrayBuilder> additionalTypes = ImmutableArrayBuilder>.Rent(); - SourceText sourceText = fixup(compilationUnit); + LoadDispatchData.RegisterAdditionalTypeSyntax(item, additionalTypes); + InputDescriptions.RegisterAdditionalTypeSyntax(item, additionalTypes); + InputTypes.RegisterAdditionalTypeSyntax(item, additionalTypes); + LoadBytecode.RegisterAdditionalTypeSyntax(item, additionalTypes); - context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.g.cs", sourceText); + using IndentedTextWriter writer = IndentedTextWriter.Rent(); + + item.Hierarchy.WriteSyntax(item, writer, declaredMembers.WrittenSpan); + + foreach (IndentedTextWriter.Callback additionalType in additionalTypes.WrittenSpan) + { + writer.WriteLine(); + + additionalType(item, writer); + } + + context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.g.cs", writer.ToString()); }); } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs b/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs index 2fce1242..9497cf23 100644 --- a/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs +++ b/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs @@ -61,9 +61,8 @@ internal sealed class IndentedTextWriter : IDisposable { this.builder = builder; this.currentIndentationLevel = 0; - this.currentIndentation = DefaultIndentation; + this.currentIndentation = ""; this.availableIndentations = new string[4]; - this.availableIndentations[0] = ""; for (int i = 1, n = this.availableIndentations.Length; i < n; i++) @@ -158,11 +157,14 @@ internal sealed class IndentedTextWriter : IDisposable { // There are no new lines left, so the content can be written as a single line WriteRawText(content); + + break; } else { // Write the current line WriteRawText(content[..newLineIndex]); + WriteLine(); // Move past the new line character (the result could be an empty span) content = content[(newLineIndex + 1)..]; diff --git a/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs b/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs index 520bd83b..6452144d 100644 --- a/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs +++ b/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs @@ -42,6 +42,55 @@ internal sealed partial record HierarchyInfo(string FullyQualifiedMetadataName, hierarchy.ToImmutable()); } + /// + /// Writes syntax for the current hierarchy into a target writer. + /// + /// The type of state to pass to callbacks. + /// The input state to pass to callbacks. + /// The target instance to write text to. + /// The callbacks to use to write members into the declared type. + public void WriteSyntax(T state, IndentedTextWriter writer, ReadOnlySpan> memberCallbacks) + { + // Write the generated file header + writer.WriteLine("// "); + writer.WriteLine("#pragma warning disable"); + writer.WriteLine(); + + // Declare the file scoped namespace, if needed + if (Namespace.Length > 0) + { + writer.WriteLine($"namespace {Namespace};"); + writer.WriteLine(); + } + + // Declare all the opening types until the inner-most one + for (int i = Hierarchy.Length - 1; i >= 0; i--) + { + writer.WriteLine($$"""/// """); + writer.WriteLine($$"""partial {{Hierarchy[i].GetTypeKeyword()}} {{Hierarchy[i].QualifiedName}}"""); + writer.WriteLine($$"""{"""); + writer.IncreaseIndent(); + } + + // Generate all nested members + for (int i = 0; i < memberCallbacks.Length; i++) + { + if (i > 0) + { + writer.WriteLine(); + } + + memberCallbacks[i](state, writer); + } + + // Close all scopes and reduce the indentation + for (int i = 0; i < Hierarchy.Length; i++) + { + writer.DecreaseIndent(); + writer.WriteLine("}"); + } + } + /// /// Gets the fully qualified type name for the current instance. /// diff --git a/src/ComputeSharp.SourceGeneration/Models/TypeInfo.cs b/src/ComputeSharp.SourceGeneration/Models/TypeInfo.cs index 9341a459..95439d24 100644 --- a/src/ComputeSharp.SourceGeneration/Models/TypeInfo.cs +++ b/src/ComputeSharp.SourceGeneration/Models/TypeInfo.cs @@ -13,6 +13,21 @@ namespace ComputeSharp.SourceGeneration.Models; /// Whether the type is a record type. internal sealed record TypeInfo(string QualifiedName, TypeKind Kind, bool IsRecord) { + /// + /// Gets the keyword for the current type kind. + /// + /// The keyword for the current type kind. + public string GetTypeKeyword() + { + return Kind switch + { + TypeKind.Struct => "struct", + TypeKind.Interface => "interface", + TypeKind.Class when IsRecord => "record", + _ => "class" + }; + } + /// /// Creates a instance for the current info. ///