diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs index 061a20e5..cf0a71d8 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs @@ -1,10 +1,5 @@ -using ComputeSharp.D2D1.__Internals; +using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Helpers; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 namespace ComputeSharp.D2D1.SourceGenerators; @@ -15,85 +10,62 @@ partial class ID2D1ShaderGenerator partial class EffectId { /// - /// Creates a instance for the EffectId property. + /// Writes the EffectId property. /// - /// The input instance with the effect GUID. - /// The resulting instance for the EffectId property. - public static PropertyDeclarationSyntax GetSyntax(EquatableArray info) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - // Prepare the initialization text - string effectIdLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(info.AsSpan()); + writer.WriteLine("readonly ref readonly global::System.Guid global::ComputeSharp.D2D1.__Internals.ID2D1Shader.EffectId"); - ExpressionSyntax effectIdExpression = ParseExpression($$"""new byte[] { {{effectIdLiterals}} }"""); + using (writer.WriteBlock()) + { + writer.WriteLine("[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"); + writer.WriteLine("get"); - // Create the local declaration: - // - // global::System.ReadOnlySpan bytes = new byte[] { }; - LocalDeclarationStatementSyntax guidBytesDeclaration = - LocalDeclarationStatement( - VariableDeclaration( - GenericName(Identifier("global::System.ReadOnlySpan")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("bytes")) - .WithInitializer( - EqualsValueClause(effectIdExpression)))); + using (writer.WriteBlock()) + { + writer.WriteLine($"global::System.ReadOnlySpan bytes = new byte[]"); - // Prepare the return statement: - // - // return - // ref global::System.Runtime.CompilerServices.Unsafe.As( - // ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(bytes)); - ReturnStatementSyntax returnStatement = - ReturnStatement( - RefExpression( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.CompilerServices.Unsafe"), - GenericName(Identifier("As")) - .AddTypeArgumentListArguments( - PredefinedType(Token(SyntaxKind.ByteKeyword)), - IdentifierName("global::System.Guid")))) - .AddArgumentListArguments( - Argument( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.InteropServices.MemoryMarshal"), - IdentifierName("GetReference"))) - .AddArgumentListArguments(Argument(IdentifierName("bytes")))) - .WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword))))); + 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])); + } - // This code produces a property declaration as follows: - // - // readonly ref readonly global::System.Guid global::ComputeSharp.D2D1.__Internals.ID2D1Shader.EffectId - // { - // [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - // get - // { - // - // - // } - // } - return - PropertyDeclaration( - RefType(IdentifierName("global::System.Guid")).WithReadOnlyKeyword(Token(SyntaxKind.ReadOnlyKeyword)), - Identifier(nameof(EffectId))) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .AddAccessorListAccessors( - AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) - .AddAttributeLists( - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("global::System.Runtime.CompilerServices.MethodImpl")) - .AddArgumentListArguments( - AttributeArgument( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.CompilerServices.MethodImplOptions"), - IdentifierName("AggressiveInlining"))))))) - .AddBodyStatements(guidBytesDeclaration, returnStatement)); + writer.WriteLine(); + writer.WriteLine("return ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(bytes));"); + } + } } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectMetadataProperties.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectMetadataProperties.Syntax.cs index fee46c11..c78732ad 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectMetadataProperties.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectMetadataProperties.Syntax.cs @@ -1,9 +1,5 @@ -using ComputeSharp.D2D1.__Internals; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 +using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Helpers; namespace ComputeSharp.D2D1.SourceGenerators; @@ -14,69 +10,64 @@ partial class ID2D1ShaderGenerator partial class EffectMetadata { /// - /// Creates a instance for the EffectDisplayName property. + /// Writes the EffectDisplayName property. /// - /// The input effect display name value, if available. - /// The resulting instance for the EffectDisplayName property. - public static PropertyDeclarationSyntax GetEffectDisplayNameSyntax(string? effectDisplayName) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteEffectDisplayNameSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - return GetEffectMetadataSyntax("EffectDisplayName", effectDisplayName); + WriteEffectMetadataSyntax("EffectDisplayName", info.EffectDisplayName, writer); } /// - /// Creates a instance for the EffectDescription property. + /// Writes the EffectDescription property. /// - /// The input effect description value, if available. - /// The resulting instance for the EffectDescription property. - public static PropertyDeclarationSyntax GetEffectDescriptionSyntax(string? effectDescription) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteEffectDescriptionSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - return GetEffectMetadataSyntax("EffectDescription", effectDescription); + WriteEffectMetadataSyntax("EffectDescription", info.EffectDescription, writer); } /// - /// Creates a instance for the EffectCategory property. + /// Writes the EffectCategory property. /// - /// The input effect category value, if available. - /// The resulting instance for the EffectCategory property. - public static PropertyDeclarationSyntax GetEffectCategorySyntax(string? effectCategory) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteEffectCategorySyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - return GetEffectMetadataSyntax("EffectCategory", effectCategory); + WriteEffectMetadataSyntax("EffectCategory", info.EffectCategory, writer); } /// - /// Creates a instance for the EffectAuthor property. + /// Writes the EffectAuthor property. /// - /// The input effect author value, if available. - /// The resulting instance for the EffectAuthor property. - public static PropertyDeclarationSyntax GetEffectAuthorSyntax(string? effectAuthor) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteEffectAuthorSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - return GetEffectMetadataSyntax("EffectAuthor", effectAuthor); + WriteEffectMetadataSyntax("EffectAuthor", info.EffectAuthor, writer); } /// - /// Creates a instance for a given metadata property. + /// Writes a specified metadata property. /// /// The property name to generate. /// The input effect metadata value, if available. - /// The resulting instance for the given metadata property. - private static PropertyDeclarationSyntax GetEffectMetadataSyntax(string propertyName, string? metadataValue) + /// The instance to write into. + private static void WriteEffectMetadataSyntax(string propertyName, string? metadataValue, IndentedTextWriter writer) { - // Get the expression: either a string literal, or just null - ExpressionSyntax metadataValueExpression = metadataValue switch - { - { } => LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(metadataValue)), - _ => LiteralExpression(SyntaxKind.NullLiteralExpression) - }; + writer.Write($"readonly string? global::ComputeSharp.D2D1.__Internals.ID2D1Shader.{propertyName} => "); - // This code produces a method declaration as follows: - // - // readonly string? global::ComputeSharp.D2D1.__Internals.ID2D1Shader. => ; - return - PropertyDeclaration(NullableType(PredefinedType(Token(SyntaxKind.StringKeyword))), Identifier(propertyName)) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithExpressionBody(ArrowExpressionClause(metadataValueExpression)) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + // Append null or the metadata value as a string literal + if (metadataValue is null) + { + writer.WriteLine("null;"); + } + else + { + writer.WriteLine($"\"{metadataValue}\";"); + } } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateHlslSourceProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateHlslSourceProperty.Syntax.cs index 70c3c9e8..3a508bd5 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateHlslSourceProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateHlslSourceProperty.Syntax.cs @@ -1,11 +1,5 @@ -using ComputeSharp.D2D1.__Internals; +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; - -#pragma warning disable CS0618 namespace ComputeSharp.D2D1.SourceGenerators; @@ -16,25 +10,16 @@ partial class ID2D1ShaderGenerator partial class HlslSource { /// - /// Creates a instance for the HlslSource property. + /// Writes the HlslSource property. /// - /// The input HLSL source. - /// The depth of the hierarchy for this type (used to calculate the right indentation). - /// The resulting instance for the HlslSource property. - public static PropertyDeclarationSyntax GetSyntax(string hlslSource, int hierarchyDepth) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - // The indentation level is the current depth + 1 (for the property) - SyntaxToken hlslSourceLiteralExpression = SyntaxTokenHelper.CreateRawMultilineStringLiteral(hlslSource, hierarchyDepth + 1); - - // This code produces a property declaration as follows: - // - // readonly string global::ComputeSharp.D2D1.__Internals.ID2D1Shader.HlslSource => ; - return - PropertyDeclaration(PredefinedType(Token(SyntaxKind.StringKeyword)), Identifier("HlslSource")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithExpressionBody(ArrowExpressionClause(LiteralExpression(SyntaxKind.StringLiteralExpression, hlslSourceLiteralExpression))) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + writer.WriteLine("readonly string global::ComputeSharp.D2D1.__Internals.ID2D1Shader.HlslSource =>"); + writer.WriteLine("\"\"\""); + writer.WriteLine(info.HlslInfoKey.HlslSource, isMultiline: true); + writer.WriteLine("\"\"\";"); } } } \ 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 6848e527..1c15a7df 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs @@ -1,12 +1,5 @@ -using System.Collections.Immutable; -using ComputeSharp.D2D1.__Internals; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Helpers; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 namespace ComputeSharp.D2D1.SourceGenerators; @@ -17,156 +10,63 @@ partial class ID2D1ShaderGenerator partial class InitializeFromDispatchData { /// - /// Creates a instance for the InitializeFromDispatchData method. + /// Writes the InitializeFromDispatchData method. /// - /// The discovered fields of the current shader. - /// The resulting instance for the InitializeFromDispatchData method. - public static MethodDeclarationSyntax GetSyntax(EquatableArray fields) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - // This code produces a method declaration as follows: - // - // readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InitializeFromDispatchData(global::System.ReadOnlySpan data) - // { - // - // } - return - MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier(nameof(InitializeFromDispatchData))) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddParameterListParameters(Parameter(Identifier("data")).WithType( - GenericName(Identifier("global::System.ReadOnlySpan")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))))) - .WithBody(Block(GetDispatchDataUnloadingStatements(fields))); - } + writer.WriteLine("readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InitializeFromDispatchData(global::System.ReadOnlySpan data)"); - /// - /// Gets a sequence of statements to initialize a shader from a serialized dispatch data buffer. - /// - /// The array of values for all captured fields. - /// The sequence of instances to initialize a shader from the serialized dispatch data buffer. - private static ImmutableArray GetDispatchDataUnloadingStatements(ImmutableArray fieldInfos) - { - // If there are no fields, just return no statements - if (fieldInfos.IsEmpty) + using (writer.WriteBlock()) { - return ImmutableArray.Empty; - } - - using ImmutableArrayBuilder statements = ImmutableArrayBuilder.Rent(); - - // Insert the fallback for empty shaders. This will generate the following code: - // - // if (data.IsEmpty) - // { - // return; - // } - statements.Add( - IfStatement( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("data"), - IdentifierName("IsEmpty")), - Block(ReturnStatement()))); - - // ref readonly ConstantBuffer buffer = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(data)); - statements.Add( - LocalDeclarationStatement( - VariableDeclaration(RefType(IdentifierName("ConstantBuffer")).WithReadOnlyKeyword(Token(SyntaxKind.ReadOnlyKeyword))) - .AddVariables( - VariableDeclarator(Identifier("buffer")) - .WithInitializer( - EqualsValueClause(RefExpression( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.CompilerServices.Unsafe"), - GenericName(Identifier("As")) - .AddTypeArgumentListArguments( - PredefinedType(Token(SyntaxKind.ByteKeyword)), - IdentifierName("ConstantBuffer")))) - .AddArgumentListArguments( - Argument( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.InteropServices.MemoryMarshal"), - IdentifierName("GetReference"))) - .AddArgumentListArguments(Argument(IdentifierName("data")))) - .WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword))))))))); - - // Generate loading statements for each captured field - foreach (FieldInfo fieldInfo in fieldInfos) - { - switch (fieldInfo) + // If there are no fields, the method body is just empty + if (info.Fields.IsEmpty) { - case FieldInfo.Primitive primitive: + return; + } - // Read a primitive value: - // - // global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.) = buffer.; - statements.Add( - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.CompilerServices.Unsafe"), - IdentifierName("AsRef"))) - .AddArgumentListArguments( - Argument(MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - ThisExpression(), - IdentifierName(string.Join(".", primitive.FieldPath)))) - .WithRefKindKeyword(Token(SyntaxKind.InKeyword))), - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("buffer"), - IdentifierName(string.Join("_", primitive.FieldPath)))))); - break; + // Insert the fallback for empty shaders. This will generate the following code: + writer.WriteLine("if (data.IsEmpty)"); - case FieldInfo.NonLinearMatrix matrix: - string fieldPath = string.Join(".", matrix.FieldPath); - string fieldNamePrefix = string.Join("_", matrix.FieldPath); + using (writer.WriteBlock()) + { + writer.WriteLine("return;"); + } - // Read all rows of a given matrix type: - // - // global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.)[0] = buffer.; - // global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.)[1] = buffer.; - // ... - // global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.)[N] = buffer.; - for (int j = 0; j < matrix.Rows; j++) - { - statements.Add( - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ElementAccessExpression( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.CompilerServices.Unsafe"), - IdentifierName("AsRef"))) - .AddArgumentListArguments( - Argument(MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - ThisExpression(), - IdentifierName(fieldPath))) - .WithRefKindKeyword(Token(SyntaxKind.InKeyword)))) - .AddArgumentListArguments( - Argument(LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(j)))), - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("buffer"), - IdentifierName($"{fieldNamePrefix}_{j}"))))); - } + // Get a reference to the data through the generated native layout type + writer.WriteLine("ref readonly ConstantBuffer buffer = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(data));"); - break; + // Generate loading statements for each captured field + foreach (FieldInfo fieldInfo in info.Fields) + { + switch (fieldInfo) + { + case FieldInfo.Primitive primitive: + + // Read a primitive value + writer.WriteLine($"global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.{string.Join(".", primitive.FieldPath)}) = buffer.{string.Join("_", primitive.FieldPath)};"); + break; + + case FieldInfo.NonLinearMatrix matrix: + string fieldPath = string.Join(".", matrix.FieldPath); + string fieldNamePrefix = string.Join("_", matrix.FieldPath); + + // Read all rows of a given matrix type: + // + // global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.)[0] = buffer.; + // global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.)[1] = buffer.; + // ... + // global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.)[N] = buffer.; + for (int j = 0; j < matrix.Rows; j++) + { + writer.WriteLine($"global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.{fieldPath})[0] = buffer.{fieldNamePrefix}_{j};"); + } + + break; + } } } - - return statements.ToImmutable(); } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputCountProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputCountProperty.Syntax.cs index e92a4b0e..ba8579df 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputCountProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputCountProperty.Syntax.cs @@ -1,9 +1,5 @@ -using ComputeSharp.D2D1.__Internals; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 +using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Helpers; namespace ComputeSharp.D2D1.SourceGenerators; @@ -16,21 +12,13 @@ partial class ID2D1ShaderGenerator private static partial class InputCount { /// - /// Creates a instance for the InputCount property. + /// Writes the InputCount property. /// - /// The number of inputs for the shader. - /// The resulting instance for the InputCount property. - public static PropertyDeclarationSyntax GetSyntax(int inputCount) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - // This code produces a property declaration as follows: - // - // readonly int global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputCount => ; - return - PropertyDeclaration(PredefinedType(Token(SyntaxKind.IntKeyword)), Identifier(nameof(InputCount))) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithExpressionBody(ArrowExpressionClause(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(inputCount)))) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + writer.WriteLine($"readonly int global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputCount => {info.InputTypes.Length};"); } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs index d5597ef5..50c429f4 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs @@ -1,5 +1,4 @@ using System; -using ComputeSharp.D2D1.__Internals; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Helpers; using Microsoft.CodeAnalysis; @@ -7,8 +6,6 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -#pragma warning disable CS0618 - namespace ComputeSharp.D2D1.SourceGenerators; /// @@ -18,112 +15,63 @@ partial class ID2D1ShaderGenerator private static partial class InputDescriptions { /// - /// Creates a instance for the InputDescriptions property. + /// Writes the InputDescriptions property. /// - /// The input descriptions info gathered for the current shader. - /// Any additional instances needed by the generated code, if needed. - /// The resulting instance for the InputDescriptions property. - public static PropertyDeclarationSyntax GetSyntax(EquatableArray inputDescriptions, out MemberDeclarationSyntax[] additionalDataMembers) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - ExpressionSyntax memoryExpression; + writer.WriteLine("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputDescriptions => "); // If there are no input descriptions, just return a default expression. - // Otherwise, declare the shared array and return it from the property. - if (inputDescriptions.Length == 0) + // Otherwise, return the shared array with cached input descriptions. + if (info.InputDescriptions.IsEmpty) { - memoryExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)); - additionalDataMembers = Array.Empty(); + writer.WriteLine("default;"); } else { - memoryExpression = MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("Data"), - IdentifierName(nameof(InputDescriptions))); - - additionalDataMembers = new[] { GetArrayDeclaration(inputDescriptions) }; + writer.WriteLine("Data.InputDescriptions;"); } - - // This code produces a method declaration as follows: - // - // readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputDescriptions => ; - return - PropertyDeclaration( - GenericName(Identifier("global::System.ReadOnlyMemory")) - .AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1InputDescription")), - Identifier(nameof(InputDescriptions))) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithExpressionBody(ArrowExpressionClause(memoryExpression)) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); } /// - /// Gets the array declaration for the given input descriptions. + /// Registers a callback to generate an additional data member, if needed. /// - /// The input descriptions info gathered for the current shader. - /// The array declaration for the given input descriptions. - private static MemberDeclarationSyntax GetArrayDeclaration(EquatableArray inputDescriptions) + /// The input instance with gathered shader info. + /// The registered callbacks to generate additional data members. + public static void RegisterAdditionalDataMemberSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder> callbacks) { - using ImmutableArrayBuilder inputDescriptionExpressions = ImmutableArrayBuilder.Rent(); - - foreach (InputDescription inputDescription in inputDescriptions) + // If there are no input descriptions, there is nothing to di + if (info.ResourceTextureDescriptions.IsEmpty) { - // Create the description expression (excluding level of detail): - // - // new(, ) - ImplicitObjectCreationExpressionSyntax inputDescriptionExpression = - ImplicitObjectCreationExpression() - .AddArgumentListArguments( - Argument(LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(inputDescription.Index))), - Argument( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::ComputeSharp.D2D1.D2D1Filter"), - IdentifierName(inputDescription.Filter.ToString())))); - - // Add the level of detail, if needed: - // - // { LevelOfDetailCount = } - if (inputDescription.LevelOfDetailCount != 0) - { - inputDescriptionExpression = - inputDescriptionExpression - .WithInitializer( - InitializerExpression(SyntaxKind.ObjectInitializerExpression) - .AddExpressions( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - IdentifierName("LevelOfDetailCount"), - LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(inputDescription.LevelOfDetailCount))))); - } - - inputDescriptionExpressions.Add(inputDescriptionExpression); + return; } - // Declare the singleton property to get the memory instance: - // - // /// The singleton array instance. - // public static readonly global::ComputeSharp.D2D1.Interop.D2D1InputDescription[] InputDescriptions = { }; - return - FieldDeclaration( - VariableDeclaration( - ArrayType(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1InputDescription")) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) - .AddVariables( - VariableDeclarator(Identifier(nameof(InputDescriptions))) - .WithInitializer(EqualsValueClause( - InitializerExpression(SyntaxKind.ArrayInitializerExpression) - .AddExpressions(inputDescriptionExpressions.ToArray()))))) - .AddModifiers( - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword), - Token(SyntaxKind.ReadOnlyKeyword)) - .WithLeadingTrivia(Comment("""/// The singleton array instance.""")); + // 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 = """); + + // Initialize all input descriptions + using (writer.WriteBlock()) + { + for (int i = 0; i < info.InputDescriptions.Length; i++) + { + InputDescription description = info.InputDescriptions[i]; + + writer.Write($$"""new global::ComputeSharp.D2D1.Interop.D2D1InputDescription({description.Index}, {description.Filter}) { LevelOfDetailCount = {{description.LevelOfDetailCount}} }"""); + + if (i < info.InputDescriptions.Length - 1) + { + writer.WriteLine(","); + } + } + } + } + + callbacks.Add(Callback); } /// diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs index fe837ca3..4d536efa 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs @@ -1,13 +1,5 @@ -using System; -using System.Collections.Immutable; -using ComputeSharp.D2D1.__Internals; +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; - -#pragma warning disable CS0618 namespace ComputeSharp.D2D1.SourceGenerators; @@ -18,270 +10,111 @@ partial class ID2D1ShaderGenerator partial class InputTypes { /// - /// Creates a instance for the InputTypes property. + /// Writes the InputTypes property. /// - /// The input types for the shader. - /// Any additional instances needed by the generated code, if needed. - /// The resulting instance for the InputTypes property. - public static PropertyDeclarationSyntax GetSyntax(ImmutableArray inputTypes, out TypeDeclarationSyntax[] additionalTypes) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - ExpressionSyntax memoryExpression; + writer.WriteLine("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputTypes => "); - // If there are no inputs, simply return a default expression. - // Otherwise, declare the memory manager and access it. - if (inputTypes.Length == 0) + // If there are no inputs, simply return a default expression. Otherwise, create + // a ReadOnlyMemory instance from the memory manager. + if (info.InputTypes.IsEmpty) { - memoryExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)); - additionalTypes = Array.Empty(); + writer.WriteLine("default;"); } else { - // Create a ReadOnlyMemory instance from the memory manager: - // - // InputTypesMemoryManager.Instance.Memory - memoryExpression = - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("InputTypesMemoryManager"), - IdentifierName("Instance")), - IdentifierName("Memory")); - - additionalTypes = new TypeDeclarationSyntax[] { GetMemoryManagerDeclaration(inputTypes) }; + writer.WriteLine("InputTypesMemoryManager.Instance.Memory;"); } - - // This code produces a method declaration as follows: - // - // readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputTypes => ; - return - PropertyDeclaration( - GenericName(Identifier("global::System.ReadOnlyMemory")) - .AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType")), - Identifier(nameof(InputTypes))) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithExpressionBody(ArrowExpressionClause(memoryExpression)) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); } /// - /// Gets the memory manager declaration for the input type data. + /// Registers a callback to generate an additional type, if needed. /// - /// The input types for the shader. - /// The memory manager declaration for the input type data. - private static TypeDeclarationSyntax GetMemoryManagerDeclaration(ImmutableArray inputTypes) + /// The input instance with gathered shader info. + /// The registered callbacks to generate additional types. + public static void RegisterAdditionalTypeSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder> callbacks) { - // Create the MemoryManager declaration: - // - // /// - // /// A implementation to get the input types. - // /// - // [global::System.CodeDom.Compiler.GeneratedCode("...", "...")] - // [global::System.Diagnostics.DebuggerNonUserCode] - // [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] - // file sealed InputTypesMemoryManager : global::System.Buffers.MemoryManager - // { - // } - TypeDeclarationSyntax typeDeclaration = - ClassDeclaration("InputTypesMemoryManager") - .AddModifiers(Token(SyntaxKind.FileKeyword), Token(SyntaxKind.SealedKeyword)) - .AddBaseListTypes(SimpleBaseType( - GenericName(Identifier("global::System.Buffers.MemoryManager")) - .AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType")))) - .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"))))) - .WithLeadingTrivia( - Comment("/// "), - Comment("""/// A implementation to get the input types."""), - Comment("/// ")); - - using ImmutableArrayBuilder memberDeclarations = ImmutableArrayBuilder.Rent(); - - // Declare the singleton property to get the memory manager: - // - // /// The singleton instance to use. - // public static readonly InputTypesMemoryManager Instance = new(); - memberDeclarations.Add( - FieldDeclaration( - VariableDeclaration(IdentifierName("InputTypesMemoryManager")) - .AddVariables( - VariableDeclarator(Identifier("Instance")) - .WithInitializer(EqualsValueClause(ImplicitObjectCreationExpression())))) - .AddModifiers( - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword), - Token(SyntaxKind.ReadOnlyKeyword)) - .WithLeadingTrivia(Comment("""/// The singleton instance to use."""))); - - using (ImmutableArrayBuilder inputTypeExpressions = ImmutableArrayBuilder.Rent()) + // If there are no inputs, no memory manager is needed + if (info.InputTypes.IsEmpty) { - // Build the sequence of expressions for all input types - foreach (uint inputType in inputTypes) - { - inputTypeExpressions.Add( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType"), - IdentifierName(inputType == 0 ? "Simple" : "Complex"))); - } - - // Construct the RVA span property: - // - // /// The RVA data with the input type info. - // private static global::System.ReadOnlySpan Data => new[] { }; - memberDeclarations.Add( - PropertyDeclaration( - GenericName(Identifier("global::System.ReadOnlySpan")) - .AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType")), - Identifier("Data")) - .AddModifiers(Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.StaticKeyword)) - .WithExpressionBody( - ArrowExpressionClause( - ImplicitArrayCreationExpression( - InitializerExpression( - SyntaxKind.ArrayInitializerExpression, - SeparatedList(inputTypeExpressions.ToArray()))))) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) - .WithLeadingTrivia(Comment("/// The RVA data with the input type info."))); + return; } - // Add the GetSpan() method: - // - // /// - // public override unsafe global::System.Span GetSpan - // { - // return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.InteropServices.MemoryMarshal(Data)), Data.Length); - // } - memberDeclarations.Add( - MethodDeclaration( - GenericName(Identifier("global::System.Span")) - .AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType")), - Identifier("GetSpan")) - .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword), Token(SyntaxKind.UnsafeKeyword)) - .AddBodyStatements( - ReturnStatement( - ImplicitObjectCreationExpression() - .AddArgumentListArguments( - Argument( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.CompilerServices.Unsafe"), - IdentifierName("AsPointer"))) - .AddArgumentListArguments( - Argument( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.InteropServices.MemoryMarshal"), - IdentifierName("GetReference"))) - .AddArgumentListArguments(Argument(IdentifierName("Data")))) - .WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)))), - Argument( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("Data"), - IdentifierName("Length")))))) - .WithLeadingTrivia(Comment("/// "))); + // Declare the InputTypesMemoryManager custom memory manager type + static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer) + { + writer.WriteLine($$"""/// """); + writer.WriteLine($$"""/// A implementation to get the input types."""); + 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 sealed class InputTypesMemoryManager : global::System.Buffers.MemoryManager"""); - // Override the Memory property: - // - // /// - // public override global::System.Memory Memory - // { - // [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - // get => CreateMemory(Data.Length); - // } - memberDeclarations.Add( - PropertyDeclaration( - GenericName(Identifier("global::System.Memory")) - .AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType")), - Identifier("Memory")) - .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword)) - .AddAccessorListAccessors( - AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) - .AddAttributeLists( - AttributeList( - SingletonSeparatedList( - Attribute(IdentifierName("global::System.Runtime.CompilerServices.MethodImpl")) - .AddArgumentListArguments( - AttributeArgument( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.CompilerServices.MethodImplOptions"), - IdentifierName("AggressiveInlining"))))))) - .WithExpressionBody( - ArrowExpressionClause( - InvocationExpression(IdentifierName("CreateMemory")) - .AddArgumentListArguments( - Argument( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("Data"), - IdentifierName("Length")))))) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken))) - .WithLeadingTrivia(Comment("/// "))); + using (writer.WriteBlock()) + { + // Static singleton instance (the object goes in the frozen heap, so there's no static constructor) + writer.WriteLine($$"""/// The singleton instance to use."""); + writer.WriteLine($$"""public static readonly InputTypesMemoryManager Instance = new();"""); - // Add the Pin(int elementIndex) method: - // - // /// - // public override unsafe global::System.Buffers.MemoryHandle Pin(int elementIndex) - // { - // return new(Unsafe.AsPointer(ref Unsafe.AsRef(in Data[elementIndex])), pinnable: this); - // } - memberDeclarations.Add( - MethodDeclaration(IdentifierName("global::System.Buffers.MemoryHandle"), Identifier("Pin")) - .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword), Token(SyntaxKind.UnsafeKeyword)) - .AddParameterListParameters(Parameter(Identifier("elementIndex")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) - .AddBodyStatements( - ReturnStatement( - ImplicitObjectCreationExpression() - .AddArgumentListArguments( - Argument( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.CompilerServices.Unsafe"), - IdentifierName("AsPointer"))) - .AddArgumentListArguments( - Argument( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.CompilerServices.Unsafe"), - IdentifierName("AsRef"))) - .AddArgumentListArguments( - Argument( - ElementAccessExpression(IdentifierName("Data")) - .AddArgumentListArguments(Argument(IdentifierName("elementIndex")))) - .WithRefOrOutKeyword(Token(SyntaxKind.InKeyword)))) - .WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)))), - Argument(ThisExpression()).WithNameColon(NameColon(IdentifierName("pinnable")))))) - .WithLeadingTrivia(Comment("/// "))); + // RVA field + writer.WriteLine(); + writer.WriteLine("/// The RVA data with the input type info."); + writer.WriteLine("private static global::System.ReadOnlySpan Data => new[]"); - // Add the empty Unpin() method - memberDeclarations.Add( - MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier("Unpin")) - .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword)) - .WithBody(Block()) - .WithLeadingTrivia(Comment("/// "))); + // Input types, one per line in the RVA field initializer + using (writer.WriteBlock()) + { + for (int i = 0; i < info.InputTypes.Length; i++) + { + writer.Write("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType."); + writer.Write(info.InputTypes[i] == 0 ? "Simple" : "Complex"); - // Add the empty Dispose(bool disposing) method - memberDeclarations.Add( - MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier("Dispose")) - .AddModifiers(Token(SyntaxKind.ProtectedKeyword), Token(SyntaxKind.OverrideKeyword)) - .AddParameterListParameters( - Parameter(Identifier("disposing")).WithType(PredefinedType(Token(SyntaxKind.BoolKeyword)))) - .WithBody(Block()) - .WithLeadingTrivia(Comment("/// "))); + if (i < info.InputTypes.Length - 1) + { + writer.WriteLine(","); + } + } + } - return typeDeclaration.AddMembers(memberDeclarations.ToArray()); + // Add the remaining members for the memory manager + writer.WriteLine(""" + /// + public override unsafe global::System.Span GetSpan + { + return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.InteropServices.MemoryMarshal(Data)), Data.Length); + } + + /// + public override global::System.Memory Memory + { + [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + get => CreateMemory(Data.Length); + } + + /// + public override unsafe global::System.Buffers.MemoryHandle Pin(int elementIndex) + { + return new(Unsafe.AsPointer(ref Unsafe.AsRef(in Data[elementIndex])), pinnable: this); + } + + /// + public override void Unpin() + { + } + + /// + protected override void Dispose(bool disposing) + { + } + """, isMultiline: true); + } + } + + callbacks.Add(Callback); } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs index 66af8d0a..2c021ad6 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs @@ -1,17 +1,7 @@ -using System; -using System.Globalization; using System.Linq; -using System.Text; -using ComputeSharp.D2D1.__Internals; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Helpers; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Text; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 namespace ComputeSharp.D2D1.SourceGenerators; @@ -22,316 +12,128 @@ partial class ID2D1ShaderGenerator partial class LoadBytecode { /// - /// Creates a instance for the ShaderProfile property. + /// Writes the ShaderProfile property. /// - /// The input shader profile. - /// The resulting instance for the ShaderProfile property. - public static PropertyDeclarationSyntax GetShaderProfileSyntax(D2D1ShaderProfile shaderProfile) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteShaderProfileSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - // This code produces a method declaration as follows: - // - // readonly ComputeSharp.D2D1.D2D1ShaderProfile global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ShaderProfile => ; - return - PropertyDeclaration(IdentifierName("ComputeSharp.D2D1.D2D1ShaderProfile"), Identifier(nameof(ID2D1Shader.ShaderProfile))) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithExpressionBody(ArrowExpressionClause( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::ComputeSharp.D2D1.D2D1ShaderProfile"), - IdentifierName(shaderProfile.ToString(CultureInfo.InvariantCulture))))) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + writer.WriteLine($"readonly ComputeSharp.D2D1.D2D1ShaderProfile global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ShaderProfile => global::ComputeSharp.D2D1.D2D1ShaderProfile.{info.HlslInfoKey.EffectiveShaderProfile};"); } /// - /// Creates a instance for the CompileOptions property. + /// Writes the CompileOptions property. /// - /// The input compile options. - /// The resulting instance for the CompileOptions property. - public static PropertyDeclarationSyntax GetCompileOptionsSyntax(D2D1CompileOptions compileOptions) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteCompileOptionsSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { // Get a formatted representation of the compile options being used - ExpressionSyntax compileOptionsExpression = - ParseExpression( - compileOptions - .ToString(CultureInfo.InvariantCulture) - .Split(',') - .Select(static name => $"global::ComputeSharp.D2D1.D2D1CompileOptions.{name.Trim()}") - .Aggregate("", static (left, right) => left.Length > 0 ? $"{left} | {right}" : right)); + string compileOptionsExpression = + info.HlslInfoKey.EffectiveCompileOptions + .ToString() + .Split(',') + .Select(static name => $"global::ComputeSharp.D2D1.D2D1CompileOptions.{name.Trim()}") + .Aggregate("", static (left, right) => left.Length > 0 ? $"{left} | {right}" : right); - // This code produces a method declaration as follows: - // - // readonly ComputeSharp.D2D1.D2D1CompileOptions global::ComputeSharp.D2D1.__Internals.ID2D1Shader.CompileOptions => ; - return - PropertyDeclaration(IdentifierName("ComputeSharp.D2D1.D2D1CompileOptions"), Identifier(nameof(ID2D1Shader.CompileOptions))) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithExpressionBody(ArrowExpressionClause(compileOptionsExpression)) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + writer.Write($"readonly ComputeSharp.D2D1.D2D1CompileOptions global::ComputeSharp.D2D1.__Internals.ID2D1Shader.CompileOptions => {compileOptionsExpression};"); } /// - /// Creates a instance for the HlslBytecode property. + /// Writes the HlslBytecode property. /// - /// The input bytecode info. - /// An opaque instance to transform the final tree into text. - /// Any additional instances needed by the generated code, if needed. - /// The resulting instance for the HlslBytecode property. - public static PropertyDeclarationSyntax GetHlslBytecodeSyntax( - HlslBytecodeInfo bytecodeInfo, - out Func fixup, - out TypeDeclarationSyntax[] additionalTypes) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteHlslBytecodeSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - ExpressionSyntax memoryExpression; + writer.WriteLine("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ResourceTextureDescriptions => "); - // If there is no bytecode, simply return a default expression. - // Otherwise, declare the memory manager and access it. - if (bytecodeInfo is not HlslBytecodeInfo.Success success) + // If there is no bytecode, just return a default expression. + // Otherwise, return the memory manager backed memory instance. + if (info.HlslInfo is not HlslBytecodeInfo.Success) { - memoryExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)); - fixup = static tree => tree.GetText(Encoding.UTF8); - additionalTypes = Array.Empty(); + writer.WriteLine("default;"); } else { - // Create a ReadOnlyMemory instance from the memory manager: - // - // HlslBytecodeMemoryManager.Instance.Memory - memoryExpression = - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("HlslBytecodeMemoryManager"), - IdentifierName("Instance")), - IdentifierName("Memory")); - - TypeDeclarationSyntax memoryManagerDeclaration = GetMemoryManagerDeclaration(); - string bytecodeLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(success.Bytecode.AsSpan()); - - additionalTypes = new TypeDeclarationSyntax[] { memoryManagerDeclaration }; - fixup = tree => SourceText.From(tree.ToFullString().Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals), Encoding.UTF8); + writer.WriteLine("HlslBytecodeMemoryManager.Instance.Memory;"); } - - // This code produces a method declaration as follows: - // - // readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.HlslBytecode => ; - return - PropertyDeclaration( - GenericName(Identifier("global::System.ReadOnlyMemory")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))), - Identifier(nameof(ID2D1Shader.HlslBytecode))) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithExpressionBody(ArrowExpressionClause(memoryExpression)) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); } /// - /// Gets a instance with the logic to try to get a compiled shader bytecode. + /// Registers a callback to generate an additional type, if needed. /// - /// The instance trying to retrieve the precompiled shader. - private static unsafe TypeDeclarationSyntax GetMemoryManagerDeclaration() + /// The input instance with gathered shader info. + /// The registered callbacks to generate additional types. + public static void RegisterAdditionalTypeSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder> callbacks) { - // Create the MemoryManager declaration: - // - // /// - // /// implementation to get the HLSL bytecode. - // /// - // [global::System.CodeDom.Compiler.GeneratedCode("...", "...")] - // [global::System.Diagnostics.DebuggerNonUserCode] - // [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] - // file sealed HlslBytecodeMemoryManager : global::System.Buffers.MemoryManager - // { - // } - TypeDeclarationSyntax typeDeclaration = - ClassDeclaration("HlslBytecodeMemoryManager") - .AddModifiers(Token(SyntaxKind.FileKeyword), Token(SyntaxKind.SealedKeyword)) - .AddBaseListTypes(SimpleBaseType( - GenericName(Identifier("global::System.Buffers.MemoryManager")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))))) - .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"))))) - .WithLeadingTrivia( - Comment("/// "), - Comment("""/// A implementation to get the HLSL bytecode."""), - Comment("/// ")); + // If there is no bytecode, no memory manager is needed + if (info.HlslInfo is not HlslBytecodeInfo.Success) + { + return; + } - using ImmutableArrayBuilder memberDeclarations = ImmutableArrayBuilder.Rent(); + // Declare the HlslBytecodeMemoryManager custom memory manager type + static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer) + { + writer.WriteLine($$"""/// """); + 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]"""); + writer.WriteLine($$"""[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]"""); + writer.WriteLine($$"""file sealed class HlslBytecodeMemoryManager : global::System.Buffers.MemoryManager"""); - // Declare the singleton property to get the memory manager: - // - // /// The singleton instance to use. - // public static readonly HlslBytecodeMemoryManager Instance = new(); - memberDeclarations.Add( - FieldDeclaration( - VariableDeclaration(IdentifierName("HlslBytecodeMemoryManager")) - .AddVariables( - VariableDeclarator(Identifier("Instance")) - .WithInitializer(EqualsValueClause(ImplicitObjectCreationExpression())))) - .AddModifiers( - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword), - Token(SyntaxKind.ReadOnlyKeyword)) - .WithLeadingTrivia(Comment("""/// The singleton instance to use."""))); + using (writer.WriteBlock()) + { + // Static singleton instance (to avoid the static constructor, just like with the input types) + writer.WriteLine($$"""/// The singleton instance to use."""); + writer.WriteLine($$"""public static readonly HlslBytecodeMemoryManager Instance = new();"""); - // Construct the RVA span property: - // - // /// The RVA data with the HLSL bytecode. - // private static global::System.ReadOnlySpan Data => new byte[] { __EMBEDDED_SHADER_BYTECODE }; - memberDeclarations.Add( - PropertyDeclaration( - GenericName(Identifier("global::System.ReadOnlySpan")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))), - Identifier("Data")) - .AddModifiers(Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.StaticKeyword)) - .WithExpressionBody( - ArrowExpressionClause( - ArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression()))), - InitializerExpression( - SyntaxKind.ArrayInitializerExpression, - SingletonSeparatedList(IdentifierName("__EMBEDDED_SHADER_BYTECODE")))))) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) - .WithLeadingTrivia(Comment("/// The RVA data with the HLSL bytecode."))); + // 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[] { "); - // Override the Memory property: - // - // /// - // public override global::System.Memory Memory - // { - // [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - // get => CreateMemory(Data.Length); - // } - memberDeclarations.Add( - PropertyDeclaration( - GenericName(Identifier("global::System.Memory")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))), - Identifier("Memory")) - .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword)) - .AddAccessorListAccessors( - AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) - .AddAttributeLists( - AttributeList( - SingletonSeparatedList( - Attribute(IdentifierName("global::System.Runtime.CompilerServices.MethodImpl")) - .AddArgumentListArguments( - AttributeArgument( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.CompilerServices.MethodImplOptions"), - IdentifierName("AggressiveInlining"))))))) - .WithExpressionBody( - ArrowExpressionClause( - InvocationExpression(IdentifierName("CreateMemory")) - .AddArgumentListArguments( - Argument( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("Data"), - IdentifierName("Length")))))) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken))) - .WithLeadingTrivia(Comment("/// "))); + SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(((HlslBytecodeInfo.Success)info.HlslInfo).Bytecode.AsSpan(), writer); - // Add the GetSpan() method: - // - // /// - // public override unsafe global::System.Span GetSpan - // { - // return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.InteropServices.MemoryMarshal(Data)), Data.Length); - // } - memberDeclarations.Add( - MethodDeclaration( - GenericName(Identifier("global::System.Span")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))), - Identifier("GetSpan")) - .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword), Token(SyntaxKind.UnsafeKeyword)) - .AddBodyStatements( - ReturnStatement( - ImplicitObjectCreationExpression() - .AddArgumentListArguments( - Argument( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.CompilerServices.Unsafe"), - IdentifierName("AsPointer"))) - .AddArgumentListArguments( - Argument( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.InteropServices.MemoryMarshal"), - IdentifierName("GetReference"))) - .AddArgumentListArguments(Argument(IdentifierName("Data")))) - .WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)))), - Argument( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("Data"), - IdentifierName("Length")))))) - .WithLeadingTrivia(Comment("/// "))); + writer.WriteLine(" };"); - // Add the Pin(int elementIndex) method: - // - // /// - // public override unsafe global::System.Buffers.MemoryHandle Pin(int elementIndex) - // { - // return new(Unsafe.AsPointer(ref Unsafe.AsRef(in Data[elementIndex])), pinnable: this); - // } - memberDeclarations.Add( - MethodDeclaration(IdentifierName("global::System.Buffers.MemoryHandle"), Identifier("Pin")) - .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword), Token(SyntaxKind.UnsafeKeyword)) - .AddParameterListParameters(Parameter(Identifier("elementIndex")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) - .AddBodyStatements( - ReturnStatement( - ImplicitObjectCreationExpression() - .AddArgumentListArguments( - Argument( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.CompilerServices.Unsafe"), - IdentifierName("AsPointer"))) - .AddArgumentListArguments( - Argument( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.CompilerServices.Unsafe"), - IdentifierName("AsRef"))) - .AddArgumentListArguments( - Argument( - ElementAccessExpression(IdentifierName("Data")) - .AddArgumentListArguments(Argument(IdentifierName("elementIndex")))) - .WithRefOrOutKeyword(Token(SyntaxKind.InKeyword)))) - .WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)))), - Argument(ThisExpression()).WithNameColon(NameColon(IdentifierName("pinnable")))))) - .WithLeadingTrivia(Comment("/// "))); + // Add the remaining members for the memory manager + writer.WriteLine(""" + /// + public override unsafe global::System.Span GetSpan + { + return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.InteropServices.MemoryMarshal(Data)), Data.Length); + } - // Add the empty Unpin() method - memberDeclarations.Add( - MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier("Unpin")) - .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword)) - .WithBody(Block()) - .WithLeadingTrivia(Comment("/// "))); + /// + public override global::System.Memory Memory + { + [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + get => CreateMemory(Data.Length); + } - // Add the empty Dispose(bool disposing) method - memberDeclarations.Add( - MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier("Dispose")) - .AddModifiers(Token(SyntaxKind.ProtectedKeyword), Token(SyntaxKind.OverrideKeyword)) - .AddParameterListParameters( - Parameter(Identifier("disposing")).WithType(PredefinedType(Token(SyntaxKind.BoolKeyword)))) - .WithBody(Block()) - .WithLeadingTrivia(Comment("/// "))); + /// + public override unsafe global::System.Buffers.MemoryHandle Pin(int elementIndex) + { + return new(Unsafe.AsPointer(ref Unsafe.AsRef(in Data[elementIndex])), pinnable: this); + } - return typeDeclaration.AddMembers(memberDeclarations.ToArray()); + /// + public override void Unpin() + { + } + + /// + protected override void Dispose(bool disposing) + { + } + """, isMultiline: true); + } + } + + callbacks.Add(Callback); } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs index 413d6342..54e5242e 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs @@ -1,16 +1,6 @@ -using System; -using System.Collections.Immutable; -using ComputeSharp.D2D1.__Internals; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; -using ComputeSharp.SourceGeneration.Models; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 namespace ComputeSharp.D2D1.SourceGenerators; @@ -21,274 +11,126 @@ partial class ID2D1ShaderGenerator partial class LoadDispatchData { /// - /// Creates a instance for the LoadDispatchDataMethod method. + /// Writes the LoadDispatchData method. /// - /// The hiararchy info of the shader type. - /// The description on shader instance fields. - /// The size of the shader constant buffer. - /// Any additional instances needed by the generated code, if needed. - /// The resulting instance for the LoadDispatchDataMethod method. - public static MethodDeclarationSyntax GetSyntax( - HierarchyInfo hierarchyInfo, - EquatableArray fields, - int constantBufferSizeInBytes, - out TypeDeclarationSyntax[] additionalTypes) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - // Declare the mapping constant buffer type, if needed (ie. if the shader has at least one field) - if (fields.Length == 0) - { - additionalTypes = Array.Empty(); - } - else - { - additionalTypes = new[] { GetConstantBufferDeclaration(hierarchyInfo, fields, constantBufferSizeInBytes) }; - } + writer.WriteLine("readonly unsafe void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.LoadDispatchData(ref TLoader loader)"); - // This code produces a method declaration as follows: - // - // readonly unsafe void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.LoadDispatchData(ref TLoader loader) - // { - // - // } - return - MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier(nameof(LoadDispatchData))) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword), Token(SyntaxKind.UnsafeKeyword)) - .AddTypeParameterListParameters(TypeParameter(Identifier("TLoader"))) - .AddParameterListParameters(Parameter(Identifier("loader")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(IdentifierName("TLoader"))) - .WithBody(Block(GetDispatchDataLoadingStatements(fields, constantBufferSizeInBytes))); + using (writer.WriteBlock()) + { + // If there are no fields, just load an empty buffer + if (info.Fields.IsEmpty) + { + writer.WriteLine("loader.LoadConstantBuffer(default);"); + } + else + { + writer.WriteLine("ConstantBuffer buffer;"); + + // Generate loading statements for each captured field + foreach (FieldInfo fieldInfo in info.Fields) + { + switch (fieldInfo) + { + case FieldInfo.Primitive primitive: + + // Assign a primitive value + writer.WriteLine($"buffer.{string.Join("_", primitive.FieldPath)} = this.{string.Join(".", primitive.FieldPath)};"); + break; + + case FieldInfo.NonLinearMatrix matrix: + string fieldPath = string.Join(".", matrix.FieldPath); + string fieldNamePrefix = string.Join("_", matrix.FieldPath); + + // Assign all rows of a given matrix type: + // + // buffer. = this.[0]; + // buffer. = this.[1]; + // ... + // buffer. = this.[N]; + for (int j = 0; j < matrix.Rows; j++) + { + writer.WriteLine($"buffer.{fieldNamePrefix}_{j} = this.{fieldPath}[{j}];"); + } + + break; + } + } + } + } } /// - /// Gets a type definition to map the constant buffer of a given shader type. + /// Registers a callback to generate an additional type, if needed. /// - /// The hiararchy info of the shader type. - /// The array of values for all captured fields. - /// The size of the shader constant buffer. - /// The object for the mapped constant buffer for the current shader type. - private static TypeDeclarationSyntax GetConstantBufferDeclaration(HierarchyInfo hierarchyInfo, ImmutableArray fieldInfos, int constantBufferSizeInBytes) + /// The input instance with gathered shader info. + /// The registered callbacks to generate additional types. + public static void RegisterAdditionalTypeSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder> callbacks) { - string fullyQualifiedTypeName = hierarchyInfo.GetFullyQualifiedTypeName(); - - using ImmutableArrayBuilder fieldDeclarations = ImmutableArrayBuilder.Rent(); - - // Appends a new field declaration for a constant buffer field: - // - // - // [global::System.Runtime.InteropServices.FieldOffset()] - // public ; - void AppendFieldDeclaration( - string comment, - TypeSyntax typeIdentifier, - string identifierName, - int fieldOffset) + // If there are no fields, there is no need for a constant buffer type + if (info.Fields.IsEmpty) { - fieldDeclarations.Add( - FieldDeclaration( - VariableDeclaration(typeIdentifier) - .AddVariables(VariableDeclarator(Identifier(identifierName)))) - .AddAttributeLists(AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("global::System.Runtime.InteropServices.FieldOffset")) - .AddArgumentListArguments(AttributeArgument( - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(fieldOffset))))))) - .AddModifiers(Token(SyntaxKind.PublicKeyword)) - .WithLeadingTrivia(Comment(comment))); + return; } - // Declare fields for every mapped item from the shader layout - foreach (FieldInfo fieldInfo in fieldInfos) + // Declare the ConstantBuffer type + static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer) { - switch (fieldInfo) + string fullyQualifiedTypeName = info.Hierarchy.GetFullyQualifiedTypeName(); + + writer.WriteLine($$"""/// """); + writer.WriteLine($$"""/// A type representing the constant buffer native layout for ."""); + 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($$"""[global::System.Runtime.InteropServices.StructLayout(global::System.Runtime.InteropServices.LayoutKind.Explicit, Size = {{info.ConstantBufferSizeInBytes}})]"""); + writer.WriteLine($$"""file struct ConstantBuffer"""); + + using (writer.WriteBlock()) { - case FieldInfo.Primitive { TypeName: "System.Boolean" } primitive: - - // Append a field as a global::ComputeSharp.Bool value (will use the implicit conversion from bool values) - AppendFieldDeclaration( - comment: $"""/// """, - typeIdentifier: IdentifierName("global::ComputeSharp.Bool"), - identifierName: string.Join("_", primitive.FieldPath), - fieldOffset: primitive.Offset); - break; - case FieldInfo.Primitive primitive: - - // Append primitive fields of other types with their mapped names - AppendFieldDeclaration( - comment: $"""/// """, - typeIdentifier: IdentifierName(HlslKnownTypes.GetMappedName(primitive.TypeName)), - identifierName: string.Join("_", primitive.FieldPath), - fieldOffset: primitive.Offset); - break; - - case FieldInfo.NonLinearMatrix matrix: - string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}"); - string fieldNamePrefix = string.Join("_", matrix.FieldPath); - - // Declare a field for every row of the matrix type - for (int j = 0; j < matrix.Rows; j++) + // Declare fields for every mapped item from the shader layout + for (int i = 0; i < info.Fields.Length; i++) + { + switch (info.Fields[i]) { - AppendFieldDeclaration( - comment: $"""/// Row {j} of .""", - typeIdentifier: IdentifierName(rowTypeName), - identifierName: $"{fieldNamePrefix}_{j}", - fieldOffset: matrix.Offsets[j]); - } + case FieldInfo.Primitive { TypeName: "System.Boolean" } primitive: - break; + // Append a field as a global::ComputeSharp.Bool value (will use the implicit conversion from bool values) + writer.WriteLine($$"""/// """); + writer.WriteLine($$"""[global::System.Runtime.InteropServices.FieldOffset({{primitive.Offset}})]"""); + writer.WriteLine($$"""public global::ComputeSharp.Bool {{string.Join("_", primitive.FieldPath)}};"""); + break; + case FieldInfo.Primitive primitive: + + // Append primitive fields of other types with their mapped names + writer.WriteLine($$"""/// """); + writer.WriteLine($$"""[global::System.Runtime.InteropServices.FieldOffset({{primitive.Offset}})]"""); + writer.WriteLine($$"""public {{HlslKnownTypes.GetMappedName(primitive.TypeName)}} {{string.Join("_", primitive.FieldPath)}};"""); + break; + + case FieldInfo.NonLinearMatrix matrix: + string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}"); + string fieldNamePrefix = string.Join("_", matrix.FieldPath); + + // Declare a field for every row of the matrix type + for (int j = 0; j < matrix.Rows; j++) + { + writer.WriteLine($$"""/// Row {j} of ."""); + writer.WriteLine($$"""[global::System.Runtime.InteropServices.FieldOffset({{matrix.Offsets[j]}})]"""); + writer.WriteLine($$"""public {{rowTypeName}} {{fieldNamePrefix}}_{{j}};"""); + } + + break; + } + } } } - // Create the constant buffer type: - // - // /// - // /// A type representing the constant buffer native layout for . - // /// - // [global::System.CodeDom.Compiler.GeneratedCode("...", "...")] - // [global::System.Diagnostics.DebuggerNonUserCode] - // [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] - // [global::System.Runtime.InteropServices.StructLayout(global::System.Runtime.InteropServices.LayoutKind.Explicit, Size = )] - // file struct ConstantBuffer - // { - // - // } - return - StructDeclaration("ConstantBuffer") - .AddModifiers(Token(SyntaxKind.FileKeyword)) - .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")))), - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("global::System.Runtime.InteropServices.StructLayout")).AddArgumentListArguments( - AttributeArgument(MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::System.Runtime.InteropServices.LayoutKind"), - IdentifierName("Explicit"))), - AttributeArgument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(constantBufferSizeInBytes))) - .WithNameEquals(NameEquals(IdentifierName("Size"))))))) - .AddMembers(fieldDeclarations.ToArray()) - .WithLeadingTrivia( - Comment("/// "), - Comment($"""/// A type representing the constant buffer native layout for ."""), - Comment("/// ")); - } - - /// - /// Gets a sequence of statements to load the dispatch data for a given shader. - /// - /// The array of values for all captured fields. - /// The size of the shader constant buffer. - /// The sequence of instances to load the shader dispatch data. - private static ImmutableArray GetDispatchDataLoadingStatements(ImmutableArray fieldInfos, int constantBufferSizeInBytes) - { - // If there are no fields, just load an empty buffer: - // - // loader.LoadConstantBuffer(default); - if (fieldInfos.IsEmpty) - { - return - ImmutableArray.Create( - ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("loader"), - IdentifierName("LoadConstantBuffer"))) - .AddArgumentListArguments(Argument( - LiteralExpression( - SyntaxKind.DefaultLiteralExpression, - Token(SyntaxKind.DefaultKeyword)))))); - } - - using ImmutableArrayBuilder statements = ImmutableArrayBuilder.Rent(); - - // ConstantBuffer buffer; - statements.Add( - LocalDeclarationStatement( - VariableDeclaration(IdentifierName("ConstantBuffer")) - .AddVariables(VariableDeclarator(Identifier("buffer"))))); - - // Generate loading statements for each captured field - foreach (FieldInfo fieldInfo in fieldInfos) - { - switch (fieldInfo) - { - case FieldInfo.Primitive primitive: - - // Assign a primitive value: - // - // buffer. = this.; - statements.Add( - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("buffer"), - IdentifierName(string.Join("_", primitive.FieldPath))), - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - ThisExpression(), - IdentifierName(string.Join(".", primitive.FieldPath)))))); - break; - - case FieldInfo.NonLinearMatrix matrix: - string fieldPath = string.Join(".", matrix.FieldPath); - string fieldNamePrefix = string.Join("_", matrix.FieldPath); - - // Assign all rows of a given matrix type: - // - // buffer. = this.[0]; - // buffer. = this.[1]; - // ... - // buffer. = this.[N]; - for (int j = 0; j < matrix.Rows; j++) - { - statements.Add( - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("buffer"), - IdentifierName($"{fieldNamePrefix}_{j}")), - ElementAccessExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - ThisExpression(), - IdentifierName(fieldPath))) - .AddArgumentListArguments( - Argument(LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(j))))))); - } - - break; - } - } - - // loader.LoadConstantBuffer(new global::System.ReadOnlySpan(&buffer, sizeof(ConstantBuffer))); - statements.Add( - ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("loader"), - IdentifierName("LoadConstantBuffer"))) - .AddArgumentListArguments(Argument( - ObjectCreationExpression( - GenericName(Identifier("global::System.ReadOnlySpan")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))) - .AddArgumentListArguments( - Argument( - PrefixUnaryExpression( - SyntaxKind.AddressOfExpression, - IdentifierName("buffer"))), - Argument(SizeOfExpression(IdentifierName("ConstantBuffer")))))))); - - return statements.ToImmutable(); + callbacks.Add(Callback); } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateOutputBufferProperties.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateOutputBufferProperties.Syntax.cs index f36ce9ee..8a6400c0 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateOutputBufferProperties.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateOutputBufferProperties.Syntax.cs @@ -1,10 +1,6 @@ using System; -using ComputeSharp.D2D1.__Internals; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 +using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Helpers; namespace ComputeSharp.D2D1.SourceGenerators; @@ -15,73 +11,38 @@ partial class ID2D1ShaderGenerator partial class OutputBuffer { /// - /// Creates a instance for the BufferPrecision property. + /// Writes the BufferPrecision property. /// - /// The buffer precision for the resulting output buffer. - /// The resulting instance for the BufferPrecision property. - public static PropertyDeclarationSyntax GetBufferPrecisionSyntax(D2D1BufferPrecision bufferPrecision) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteBufferPrecisionSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - ExpressionSyntax bufferPrecisionExpression; - - // Set the right expression if the buffer options are valid - if (Enum.IsDefined(typeof(D2D1BufferPrecision), bufferPrecision)) + // Set the right expression if the buffer options are valid. + // If they are not, just return default (the analyzer will emit a diagnostic). + string bufferPrecisionExpression = Enum.IsDefined(typeof(D2D1BufferPrecision), info.BufferPrecision) switch { - bufferPrecisionExpression = - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("ComputeSharp.D2D1.D2D1BufferPrecision"), - IdentifierName(bufferPrecision.ToString())); - } - else - { - // Otherwise just return default (the analyzer will emit a diagnostic) - bufferPrecisionExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)); - } + true => $"global::ComputeSharp.D2D1.D2D1BufferPrecision.{info.BufferPrecision}", + false => "default" + }; - // This code produces a property declaration as follows: - // - // readonly ComputeSharp.D2D1.D2D1BufferPrecision global::ComputeSharp.D2D1.__Internals.ID2D1Shader.BufferPrecision => ; - return - PropertyDeclaration(IdentifierName("ComputeSharp.D2D1.D2D1BufferPrecision"), Identifier("BufferPrecision")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithExpressionBody(ArrowExpressionClause(bufferPrecisionExpression)) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + writer.WriteLine($"readonly ComputeSharp.D2D1.D2D1BufferPrecision global::ComputeSharp.D2D1.__Internals.ID2D1Shader.BufferPrecision => {bufferPrecisionExpression};"); } /// - /// Creates a instance for the ChannelDepth property. + /// Writes the ChannelDepth property. /// - /// The channel depth for the resulting output buffer. - /// The resulting instance for the ChannelDepth property. - public static PropertyDeclarationSyntax GetChannelDepthSyntax(D2D1ChannelDepth channelDepth) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteChannelDepthSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - ExpressionSyntax channelDepthExpression; - // Set the right expression if the buffer options are valid - if (Enum.IsDefined(typeof(D2D1ChannelDepth), channelDepth)) + string channelDepthExpression = Enum.IsDefined(typeof(D2D1ChannelDepth), info.ChannelDepth) switch { - channelDepthExpression = - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("ComputeSharp.D2D1.D2D1ChannelDepth"), - IdentifierName(channelDepth.ToString())); - } - else - { - // Otherwise just return default (the analyzer will emit a diagnostic) - channelDepthExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)); - } + true => $"global::ComputeSharp.D2D1.D2D1ChannelDepth.{info.ChannelDepth}", + false => "default" + }; - // This code produces a property declaration as follows: - // - // readonly ComputeSharp.D2D1.D2D1ChannelDepth global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ChannelDepth => ; - return - PropertyDeclaration(IdentifierName("ComputeSharp.D2D1.D2D1ChannelDepth"), Identifier("ChannelDepth")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithExpressionBody(ArrowExpressionClause(channelDepthExpression)) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + writer.WriteLine($"readonly ComputeSharp.D2D1.D2D1ChannelDepth global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ChannelDepth => {channelDepthExpression};"); } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreatePixelOptionsProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreatePixelOptionsProperty.Syntax.cs index 7dac3342..2c408811 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreatePixelOptionsProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreatePixelOptionsProperty.Syntax.cs @@ -1,9 +1,5 @@ -using ComputeSharp.D2D1.__Internals; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 +using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Helpers; namespace ComputeSharp.D2D1.SourceGenerators; @@ -14,38 +10,20 @@ partial class ID2D1ShaderGenerator partial class PixelOptions { /// - /// Creates a instance for the PixelOptions property. + /// Writes the PixelOptions property. /// - /// The pixel options for the shader. - /// The resulting instance for the PixelOptions property. - public static PropertyDeclarationSyntax GetSyntax(D2D1PixelOptions pixelOptions) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - ExpressionSyntax pixelOptionsExpression; - // Set the right expression if the pixel options are valid - if (pixelOptions is D2D1PixelOptions.None or D2D1PixelOptions.TrivialSampling) + string pixelOptionsExpression = (info.PixelOptions is D2D1PixelOptions.None or D2D1PixelOptions.TrivialSampling) switch { - pixelOptionsExpression = - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("ComputeSharp.D2D1.D2D1PixelOptions"), - IdentifierName(pixelOptions.ToString())); - } - else - { - // Otherwise just return default (the analyzer will emit a diagnostic) - pixelOptionsExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)); - } + true => $"global::ComputeSharp.D2D1.D2D1PixelOptions.{info.PixelOptions}", + false => "default" + }; - // This code produces a property declaration as follows: - // - // readonly ComputeSharp.D2D1.D2D1PixelOptions global::ComputeSharp.D2D1.__Internals.ID2D1Shader.PixelOptions => ; - return - PropertyDeclaration(IdentifierName("ComputeSharp.D2D1.D2D1PixelOptions"), Identifier(nameof(PixelOptions))) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithExpressionBody(ArrowExpressionClause(pixelOptionsExpression)) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + writer.WriteLine($"readonly ComputeSharp.D2D1.D2D1PixelOptions global::ComputeSharp.D2D1.__Internals.ID2D1Shader.PixelOptions => {pixelOptionsExpression};"); } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs index dc3fb916..914f54e9 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs @@ -1,13 +1,5 @@ -using System; -using ComputeSharp.D2D1.__Internals; 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; - -#pragma warning disable CS0618 namespace ComputeSharp.D2D1.SourceGenerators; @@ -18,90 +10,63 @@ partial class ID2D1ShaderGenerator private static partial class ResourceTextureDescriptions { /// - /// Creates a instance for the ResourceTextureDescriptions property. + /// Writes the ResourceTextureDescriptions property. /// - /// The resource texture descriptions info gathered for the current shader. - /// Any additional instances needed by the generated code, if needed. - /// The resulting instance for the ResourceTextureDescriptions property. - public static PropertyDeclarationSyntax GetSyntax(EquatableArray resourceTextureDescriptions, out MemberDeclarationSyntax[] additionalDataMembers) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - ExpressionSyntax memoryExpression; + writer.WriteLine("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ResourceTextureDescriptions => "); // If there are no resource texture descriptions, just return a default expression. - // Otherwise, declare the shared array and return it from the property. - if (resourceTextureDescriptions.Length == 0) + // Otherwise, return a memory instance from the generated static readonly array. + if (info.ResourceTextureDescriptions.IsEmpty) { - memoryExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)); - additionalDataMembers = Array.Empty(); + writer.WriteLine("default;"); } else { - memoryExpression = MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("Data"), - IdentifierName(nameof(ResourceTextureDescriptions))); - - additionalDataMembers = new[] { GetArrayDeclaration(resourceTextureDescriptions) }; + writer.WriteLine("Data.ResourceTextureDescriptions;"); } - - // This code produces a method declaration as follows: - // - // readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ResourceTextureDescriptions => ; - return - PropertyDeclaration( - GenericName(Identifier("global::System.ReadOnlyMemory")) - .AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription")), - Identifier(nameof(ResourceTextureDescriptions))) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithExpressionBody(ArrowExpressionClause(memoryExpression)) - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); } /// - /// Gets the array declaration for the given resource texture descriptions. + /// Registers a callback to generate an additional data member, if needed. /// - /// The resource texture descriptions info gathered for the current shader. - /// The array declaration for the given resource texture descriptions. - private static MemberDeclarationSyntax GetArrayDeclaration(EquatableArray resourceTextureDescriptions) + /// The input instance with gathered shader info. + /// The registered callbacks to generate additional data members. + public static void RegisterAdditionalDataMemberSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder> callbacks) { - using ImmutableArrayBuilder resourceTextureDescriptionExpressions = ImmutableArrayBuilder.Rent(); - - foreach (ResourceTextureDescription resourceTextureDescription in resourceTextureDescriptions) + // If there are no resource texture descriptions, there is nothing to di + if (info.ResourceTextureDescriptions.IsEmpty) { - // Create the description expression: - // - // new(, ) - resourceTextureDescriptionExpressions.Add( - ImplicitObjectCreationExpression() - .AddArgumentListArguments( - Argument(LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(resourceTextureDescription.Index))), - Argument(LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(resourceTextureDescription.Rank))))); + return; } - // Declare the singleton property to get the memory instance: - // - // /// The singleton array instance. - // public static readonly global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription[] ResourceTextureDescriptions = { }; - return - FieldDeclaration( - VariableDeclaration( - ArrayType(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription")) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) - .AddVariables( - VariableDeclarator(Identifier(nameof(ResourceTextureDescriptions))) - .WithInitializer(EqualsValueClause( - InitializerExpression(SyntaxKind.ArrayInitializerExpression) - .AddExpressions(resourceTextureDescriptionExpressions.ToArray()))))) - .AddModifiers( - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword), - Token(SyntaxKind.ReadOnlyKeyword)) - .WithLeadingTrivia(Comment("""/// The singleton array instance.""")); + // Declare the shared array with resource texture descriptions + static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer) + { + writer.WriteLine("""/// The singleton array instance."""); + writer.WriteLine("""public static readonly global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription[] ResourceTextureDescriptions ="""); + + // Initialize all resource texture descriptions + using (writer.WriteBlock()) + { + 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) + { + writer.WriteLine(","); + } + } + } + } + + callbacks.Add(Callback); } } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SyntaxFormattingHelper.cs b/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SyntaxFormattingHelper.cs index da5256a7..d8d0fd01 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SyntaxFormattingHelper.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SyntaxFormattingHelper.cs @@ -30,6 +30,16 @@ internal static class SyntaxFormattingHelper "0xF0", "0xF1", "0xF2", "0xF3", "0xF4", "0xF5", "0xF6", "0xF7", "0xF8", "0xF9", "0xFA", "0xFB", "0xFC", "0xFD", "0xFE", "0xFF" }; + /// + /// Gets an expression representing a single byte. + /// + /// The byte to format. + /// The expression for . + public static string GetByteExpression(byte value) + { + return FormattedBytes[value]; + } + /// /// Writes a formatted expression to initialize a with a given content. /// @@ -58,7 +68,7 @@ internal static class SyntaxFormattingHelper ReadOnlySpan expressions = FormattedBytes.AsSpan(); // First write the first item (which has no leading separator) - expressions[0].AsSpan().CopyTo(span); + expressions[bytecode[0]].AsSpan().CopyTo(span); // Special case: stop early if there's only one element if (bytecode.Length == 1) diff --git a/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs b/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs index 470f6696..2fce1242 100644 --- a/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs +++ b/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs @@ -248,6 +248,14 @@ internal sealed class IndentedTextWriter : IDisposable this.builder.AddRange(content); } + /// + /// A delegate representing a callback to write data into an instance. + /// + /// The type of data to use. + /// The input data to use to write into . + /// The instance to write into. + public delegate void Callback(T value, IndentedTextWriter writer); + /// /// Represents an indented block that needs to be closed. ///