diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs
index 061a20e5..b9bdcc22 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs
@@ -1,10 +1,6 @@
-using ComputeSharp.D2D1.__Internals;
+using ComputeSharp.D2D1.SourceGenerators.Models;
+using ComputeSharp.SourceGeneration.Extensions;
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 +11,61 @@ 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("/// ");
+ writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator));
+ 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[]");
+ writer.WriteLine("{");
+ writer.IncreaseIndent();
- // 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)))));
+ // Write the bytes like so:
+ //
+ // b[0], b[1], b[2], b[3],
+ // b[4], b[5],
+ // b[6], b[7],
+ // b[8],
+ // b[9],
+ // b[10],
+ // b[11],
+ // b[12],
+ // b[13],
+ // b[14],
+ // b[15]
+ SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(info.EffectId.AsSpan()[..4], writer);
+ writer.WriteLine(",");
+ SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(info.EffectId.AsSpan()[4..6], writer);
+ writer.WriteLine(",");
+ SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(info.EffectId.AsSpan()[6..8], writer);
+ writer.WriteLine(",");
+ writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[8])},");
+ writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[9])},");
+ writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[10])},");
+ writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[11])},");
+ writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[12])},");
+ writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[13])},");
+ writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[14])},");
+ writer.WriteLine(SyntaxFormattingHelper.GetByteExpression(info.EffectId[15]));
+ writer.DecreaseIndent();
+ writer.WriteLine("};");
- // 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..a5cc487a 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectMetadataProperties.Syntax.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectMetadataProperties.Syntax.cs
@@ -1,9 +1,6 @@
-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.Extensions;
+using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.D2D1.SourceGenerators;
@@ -14,69 +11,66 @@ 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.WriteLine("/// ");
+ writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator));
+ 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..e0b0f645 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateHlslSourceProperty.Syntax.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateHlslSourceProperty.Syntax.cs
@@ -1,11 +1,6 @@
-using ComputeSharp.D2D1.__Internals;
+using ComputeSharp.D2D1.SourceGenerators.Models;
+using ComputeSharp.SourceGeneration.Extensions;
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 +11,20 @@ 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("/// ");
+ writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator));
+ writer.WriteLine("readonly string global::ComputeSharp.D2D1.__Internals.ID2D1Shader.HlslSource =>");
+ writer.IncreaseIndent();
+ writer.WriteLine("\"\"\"");
+ writer.Write(info.HlslInfoKey.HlslSource, isMultiline: true);
+ writer.WriteLine("\"\"\";");
+ writer.DecreaseIndent();
}
}
}
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs
index 6848e527..e51cbcd2 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs
@@ -1,12 +1,6 @@
-using System.Collections.Immutable;
-using ComputeSharp.D2D1.__Internals;
using ComputeSharp.D2D1.SourceGenerators.Models;
+using ComputeSharp.SourceGeneration.Extensions;
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 +11,66 @@ 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("/// ");
+ writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator));
+ 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();
+ writer.WriteLine("ref readonly global::ComputeSharp.D2D1.Generated.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})[{j}] = 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..bbde29e1 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputCountProperty.Syntax.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputCountProperty.Syntax.cs
@@ -1,9 +1,6 @@
-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.Extensions;
+using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.D2D1.SourceGenerators;
@@ -16,21 +13,15 @@ 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("/// ");
+ writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator));
+ 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..f3dbb302 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs
@@ -1,13 +1,8 @@
-using System;
-using ComputeSharp.D2D1.__Internals;
using ComputeSharp.D2D1.SourceGenerators.Models;
+using ComputeSharp.SourceGeneration.Extensions;
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
+#pragma warning disable IDE0053
namespace ComputeSharp.D2D1.SourceGenerators;
@@ -18,155 +13,133 @@ 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("/// ");
+ writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator));
+ writer.Write("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("global::ComputeSharp.D2D1.Generated.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 type, 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 types.
+ /// The using directives needed by the generated code.
+ public static void RegisterAdditionalTypeSyntax(
+ D2D1ShaderInfo info,
+ ImmutableArrayBuilder> callbacks,
+ ImmutableHashSetBuilder usingDirectives)
{
- using ImmutableArrayBuilder inputDescriptionExpressions = ImmutableArrayBuilder.Rent();
-
- foreach (InputDescription inputDescription in inputDescriptions)
+ // If there are no necessary data members, stop here
+ if (info.InputDescriptions.IsEmpty &&
+ 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()))));
+ return;
+ }
- // Add the level of detail, if needed:
- //
- // { LevelOfDetailCount = }
- if (inputDescription.LevelOfDetailCount != 0)
+ usingDirectives.Add("global::System.CodeDom.Compiler");
+ usingDirectives.Add("global::System.Diagnostics");
+ usingDirectives.Add("global::System.Diagnostics.CodeAnalysis");
+
+ AddAdditionalDataMemberUsingDirectives(info, usingDirectives);
+ ResourceTextureDescriptions.AddAdditionalDataMemberUsingDirectives(info, usingDirectives);
+
+ // Declare the additional data type
+ static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer)
+ {
+ writer.WriteLine($$"""/// """);
+ writer.WriteLine($$"""/// A container type for additional data needed by the shader.""");
+ writer.WriteLine($$"""/// """);
+ writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator), useFullyQualifiedTypeNames: false);
+ writer.WriteLine($$"""file static class Data""");
+
+ using (writer.WriteBlock())
{
- inputDescriptionExpression =
- inputDescriptionExpression
- .WithInitializer(
- InitializerExpression(SyntaxKind.ObjectInitializerExpression)
- .AddExpressions(
- AssignmentExpression(
- SyntaxKind.SimpleAssignmentExpression,
- IdentifierName("LevelOfDetailCount"),
- LiteralExpression(
- SyntaxKind.NumericLiteralExpression,
- Literal(inputDescription.LevelOfDetailCount)))));
- }
+ using ImmutableArrayBuilder> dataMembers = ImmutableArrayBuilder>.Rent();
- inputDescriptionExpressions.Add(inputDescriptionExpression);
+ RegisterAdditionalDataMemberSyntax(info, dataMembers);
+ ResourceTextureDescriptions.RegisterAdditionalDataMemberSyntax(info, dataMembers);
+
+ for (int i = 0; i < dataMembers.WrittenSpan.Length; i++)
+ {
+ dataMembers.WrittenSpan[i](info, writer);
+
+ if (i < dataMembers.WrittenSpan.Length - 1)
+ {
+ writer.WriteLine();
+ }
+ }
+ }
}
- // 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."""));
+ callbacks.Add(Callback);
}
///
- /// Gets any type declarations for additional members.
+ /// Adds any using directives for the additional data member, if needed.
///
- /// The additional members that are needed.
- /// Any type declarations for additional members.
- public static TypeDeclarationSyntax[] GetDataTypeDeclarations(MemberDeclarationSyntax[] memberDeclarations)
+ /// The input instance with gathered shader info.
+ /// The using directives needed by the generated code.
+ public static void AddAdditionalDataMemberUsingDirectives(D2D1ShaderInfo info, ImmutableHashSetBuilder usingDirectives)
{
- if (memberDeclarations.Length == 0)
+ if (info.InputDescriptions.IsEmpty)
{
- return Array.Empty();
+ return;
}
- // Create the container type declaration:
- //
- // ///
- // /// A container type for additional data needed by the shader.
- // ///
- // [global::System.CodeDom.Compiler.GeneratedCode("...", "...")]
- // [global::System.Diagnostics.DebuggerNonUserCode]
- // [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
- // file static class Data
- // {
- //
- // }
- TypeDeclarationSyntax dataTypeDeclaration =
- ClassDeclaration("Data")
- .AddModifiers(Token(SyntaxKind.FileKeyword), Token(SyntaxKind.StaticKeyword))
- .AddAttributeLists(
- AttributeList(SingletonSeparatedList(
- Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments(
- AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).FullName))),
- AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).Assembly.GetName().Version.ToString())))))),
- AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))),
- AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))))
- .AddMembers(memberDeclarations)
- .WithLeadingTrivia(
- Comment("/// "),
- Comment("/// A container type for input descriptions."),
- Comment("/// "));
+ usingDirectives.Add("global::ComputeSharp.D2D1");
+ usingDirectives.Add("global::ComputeSharp.D2D1.Interop");
+ }
- return new[] { dataTypeDeclaration };
+ ///
+ /// Registers a callback to generate an additional data member, if needed.
+ ///
+ /// The input instance with gathered shader info.
+ /// The registered callbacks to generate additional data members.
+ public static void RegisterAdditionalDataMemberSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder> callbacks)
+ {
+ // If there are no input descriptions, there is nothing to di
+ if (info.InputDescriptions.IsEmpty)
+ {
+ return;
+ }
+
+ // 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 D2D1InputDescription[] InputDescriptions = """);
+ writer.WriteLine("""{""");
+ writer.IncreaseIndent();
+
+ // Initialize all input descriptions
+ writer.WriteInitializationExpressions(info.InputDescriptions.AsSpan(), static (description, writer) =>
+ {
+ writer.Write($$"""new D2D1InputDescription({{description.Index}}, D2D1Filter.{{description.Filter}}) { LevelOfDetailCount = {{description.LevelOfDetailCount}} }""");
+ });
+
+ writer.DecreaseIndent();
+ writer.WriteLine();
+ writer.WriteLine("};");
+ }
+
+ callbacks.Add(Callback);
}
}
}
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs
index fe837ca3..3f556167 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputTypesProperty.Syntax.cs
@@ -1,13 +1,6 @@
-using System;
-using System.Collections.Immutable;
-using ComputeSharp.D2D1.__Internals;
+using ComputeSharp.D2D1.SourceGenerators.Models;
+using ComputeSharp.SourceGeneration.Extensions;
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 +11,123 @@ 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("/// ");
+ writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator));
+ writer.Write("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("global::ComputeSharp.D2D1.Generated.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.
+ /// The using directives needed by the generated code.
+ public static void RegisterAdditionalTypeSyntax(
+ D2D1ShaderInfo info,
+ ImmutableArrayBuilder> callbacks,
+ ImmutableHashSetBuilder usingDirectives)
{
- // 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("/// ")));
+ usingDirectives.Add("global::System");
+ usingDirectives.Add("global::System.Buffers");
+ usingDirectives.Add("global::System.CodeDom.Compiler");
+ usingDirectives.Add("global::System.Diagnostics");
+ usingDirectives.Add("global::System.Diagnostics.CodeAnalysis");
+ usingDirectives.Add("global::System.Runtime.CompilerServices");
+ usingDirectives.Add("global::System.Runtime.InteropServices");
+ usingDirectives.Add("global::ComputeSharp.D2D1.Interop");
- // 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("/// ")));
+ // 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.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator), useFullyQualifiedTypeNames: false);
+ writer.WriteLine($$"""file sealed class InputTypesMemoryManager : MemoryManager""");
- // 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("/// ")));
+ 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 empty Unpin() method
- memberDeclarations.Add(
- MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier("Unpin"))
- .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword))
- .WithBody(Block())
- .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[]");
+ writer.WriteLine("{");
+ writer.IncreaseIndent();
- // 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("/// ")));
+ // Input types, one per line in the RVA field initializer
+ writer.WriteInitializationExpressions(info.InputTypes.AsSpan(), static (type, writer) =>
+ {
+ writer.Write("D2D1PixelShaderInputType.");
+ writer.Write(type == 0 ? "Simple" : "Complex");
+ });
- return typeDeclaration.AddMembers(memberDeclarations.ToArray());
+ writer.DecreaseIndent();
+ writer.WriteLine();
+ writer.WriteLine("};");
+ writer.WriteLine();
+
+ // Add the remaining members for the memory manager
+ writer.WriteLine("""
+ ///
+ public override unsafe Span GetSpan()
+ {
+ return new(Unsafe.AsPointer(ref MemoryMarshal.GetReference(Data)), Data.Length);
+ }
+
+ ///
+ public override Memory Memory
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => CreateMemory(Data.Length);
+ }
+
+ ///
+ public override unsafe 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..76f2b105 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs
@@ -1,17 +1,8 @@
-using System;
-using System.Globalization;
using System.Linq;
-using System.Text;
-using ComputeSharp.D2D1.__Internals;
using ComputeSharp.D2D1.SourceGenerators.Models;
+using ComputeSharp.SourceGeneration.Extensions;
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 +13,145 @@ 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("/// ");
+ writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator));
+ 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.WriteLine("/// ");
+ writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator));
+ writer.WriteLine($"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("/// ");
+ writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator));
+ writer.Write("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.HlslBytecode => ");
- // 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("global::ComputeSharp.D2D1.Generated.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.
+ /// The using directives needed by the generated code.
+ public static void RegisterAdditionalTypeSyntax(
+ D2D1ShaderInfo info,
+ ImmutableArrayBuilder> callbacks,
+ ImmutableHashSetBuilder usingDirectives)
{
- // 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();
+ usingDirectives.Add("global::System");
+ usingDirectives.Add("global::System.Buffers");
+ usingDirectives.Add("global::System.CodeDom.Compiler");
+ usingDirectives.Add("global::System.Diagnostics");
+ usingDirectives.Add("global::System.Diagnostics.CodeAnalysis");
+ usingDirectives.Add("global::System.Runtime.CompilerServices");
+ usingDirectives.Add("global::System.Runtime.InteropServices");
- // Declare the 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.""")));
+ // 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.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator), useFullyQualifiedTypeNames: false);
+ writer.WriteLine($$"""file sealed class HlslBytecodeMemoryManager : MemoryManager""");
- // 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.")));
+ 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();""");
- // 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("/// ")));
+ // 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 ReadOnlySpan Data => new byte[] { ");
- // 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("/// ")));
+ SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(((HlslBytecodeInfo.Success)info.HlslInfo).Bytecode.AsSpan(), writer);
- // 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("/// ")));
+ writer.WriteLine(" };");
+ writer.WriteLine();
- // 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("/// ")));
+ // Add the remaining members for the memory manager
+ writer.WriteLine("""
+ ///
+ public override unsafe Span GetSpan()
+ {
+ return new(Unsafe.AsPointer(ref MemoryMarshal.GetReference(Data)), 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 Memory Memory
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => CreateMemory(Data.Length);
+ }
- return typeDeclaration.AddMembers(memberDeclarations.ToArray());
+ ///
+ public override unsafe 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.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs
index 413d6342..7ec8edb3 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs
@@ -1,16 +1,7 @@
-using System;
-using System.Collections.Immutable;
-using ComputeSharp.D2D1.__Internals;
using ComputeSharp.D2D1.SourceGenerators.Models;
+using ComputeSharp.SourceGeneration.Extensions;
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 +12,139 @@ 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("/// ");
+ writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator));
+ 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("global::ComputeSharp.D2D1.Generated.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;
+ }
+ }
+
+ writer.WriteLine();
+ writer.WriteLine("loader.LoadConstantBuffer(new global::System.ReadOnlySpan(&buffer, sizeof(global::ComputeSharp.D2D1.Generated.ConstantBuffer)));");
+ }
+ }
}
///
- /// 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.
+ /// The using directives needed by the generated code.
+ public static void RegisterAdditionalTypeSyntax(
+ D2D1ShaderInfo info,
+ ImmutableArrayBuilder> callbacks,
+ ImmutableHashSetBuilder usingDirectives)
{
- 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)
+ usingDirectives.Add("global::System.CodeDom.Compiler");
+ usingDirectives.Add("global::System.Diagnostics");
+ usingDirectives.Add("global::System.Diagnostics.CodeAnalysis");
+ usingDirectives.Add("global::System.Runtime.InteropServices");
+
+ // 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.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator), useFullyQualifiedTypeNames: false);
+ writer.WriteLine($$"""[StructLayout(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
+ writer.WriteLineSeparatedMembers(info.Fields.AsSpan(), (field, writer) =>
+ {
+ switch (field)
{
- 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($$"""[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($$"""[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.WriteLineIf(j > 0);
+ writer.WriteLine($$"""/// Row {j} of .""");
+ writer.WriteLine($$"""[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..ca889f0e 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateOutputBufferProperties.Syntax.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateOutputBufferProperties.Syntax.cs
@@ -1,10 +1,7 @@
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.Extensions;
+using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.D2D1.SourceGenerators;
@@ -15,73 +12,42 @@ 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("/// ");
+ writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator));
+ 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("/// ");
+ writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator));
+ 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..f5207ece 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreatePixelOptionsProperty.Syntax.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreatePixelOptionsProperty.Syntax.cs
@@ -1,9 +1,6 @@
-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.Extensions;
+using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.D2D1.SourceGenerators;
@@ -14,38 +11,22 @@ 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("/// ");
+ writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator));
+ 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..d24e6673 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs
@@ -1,13 +1,8 @@
-using System;
-using ComputeSharp.D2D1.__Internals;
using ComputeSharp.D2D1.SourceGenerators.Models;
+using ComputeSharp.SourceGeneration.Extensions;
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
+#pragma warning disable IDE0053
namespace ComputeSharp.D2D1.SourceGenerators;
@@ -18,90 +13,76 @@ 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("/// ");
+ writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator));
+ writer.Write("readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ResourceTextureDescriptions => ");
// If there are no resource texture descriptions, just return a default expression.
- // Otherwise, 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("global::ComputeSharp.D2D1.Generated.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.
+ /// Adds any using directives for the 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 using directives needed by the generated code.
+ public static void AddAdditionalDataMemberUsingDirectives(D2D1ShaderInfo info, ImmutableHashSetBuilder usingDirectives)
{
- using ImmutableArrayBuilder resourceTextureDescriptionExpressions = ImmutableArrayBuilder.Rent();
-
- foreach (ResourceTextureDescription resourceTextureDescription in resourceTextureDescriptions)
+ 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."""));
+ usingDirectives.Add("global::ComputeSharp.D2D1.Interop");
+ }
+
+ ///
+ /// Registers a callback to generate an additional data member, if needed.
+ ///
+ /// The input instance with gathered shader info.
+ /// The registered callbacks to generate additional data members.
+ public static void RegisterAdditionalDataMemberSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder> callbacks)
+ {
+ // If there are no resource texture descriptions, there is nothing to di
+ if (info.ResourceTextureDescriptions.IsEmpty)
+ {
+ return;
+ }
+
+ // 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 D2D1ResourceTextureDescription[] ResourceTextureDescriptions =""");
+ writer.WriteLine("""{""");
+ writer.IncreaseIndent();
+
+ // Initialize all resource texture descriptions
+ writer.WriteInitializationExpressions(info.ResourceTextureDescriptions.AsSpan(), static (description, writer) =>
+ {
+ writer.Write($"new D2D1ResourceTextureDescription({description.Index}, {description.Rank})");
+ });
+
+ writer.DecreaseIndent();
+ writer.WriteLine();
+ writer.WriteLine("};");
+ }
+
+ callbacks.Add(Callback);
}
}
}
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.Helpers.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.Helpers.cs
index 78ced89a..ff29a0e6 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.Helpers.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.Helpers.cs
@@ -1,10 +1,4 @@
-using System.Collections.Generic;
-using System.Linq;
-using ComputeSharp.SourceGeneration.Models;
using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.D2D1.SourceGenerators;
@@ -34,93 +28,4 @@ partial class ID2D1ShaderGenerator
return false;
}
-
- ///
- /// Creates a instance wrapping the given method.
- ///
- /// The instance for the current type.
- /// The items to insert.
- /// Additional member declarations to also emit, if any.
- /// A object wrapping .
- private static CompilationUnitSyntax GetCompilationUnitFromMembers(
- HierarchyInfo hierarchyInfo,
- (MemberDeclarationSyntax Member, bool SkipLocalsInit)[] memberDeclarations,
- params MemberDeclarationSyntax[] additionalMemberDeclarations)
- {
- // Method attributes
- AttributeListSyntax[] attributes =
- {
- 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.ComponentModel.EditorBrowsable")).AddArgumentListArguments(
- AttributeArgument(ParseExpression("global::System.ComponentModel.EditorBrowsableState.Never"))))),
- AttributeList(SingletonSeparatedList(
- Attribute(IdentifierName("global::System.Obsolete")).AddArgumentListArguments(
- AttributeArgument(LiteralExpression(
- SyntaxKind.StringLiteralExpression,
- Literal("This method is not intended to be used directly by user code"))))))
- };
-
- MemberDeclarationSyntax[] membersToAdd = memberDeclarations.Select(item =>
- {
- MemberDeclarationSyntax memberToAdd = item.Member.AddAttributeLists(attributes);
-
- // Add [SkipLocalsInit] if needed
- if (item.SkipLocalsInit)
- {
- memberToAdd = memberToAdd.AddAttributeLists(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Runtime.CompilerServices.SkipLocalsInit")))));
- }
-
- return memberToAdd;
- }).ToArray();
-
- return hierarchyInfo.GetSyntax(membersToAdd, additionalMemberDeclarations);
- }
-
- ///
- /// Creates a instance wrapping the given method.
- ///
- /// The instance for the current type.
- /// The item to insert.
- /// Whether [SkipLocalsInit] should also be generated.
- /// Additional member declarations to also emit, if any.
- /// A object wrapping .
- private static CompilationUnitSyntax GetCompilationUnitFromMember(
- HierarchyInfo hierarchyInfo,
- MemberDeclarationSyntax memberDeclaration,
- bool skipLocalsInit,
- params MemberDeclarationSyntax[] additionalMemberDeclarations)
- {
- // Method attributes
- List attributes = new()
- {
- 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.ComponentModel.EditorBrowsable")).AddArgumentListArguments(
- AttributeArgument(ParseExpression("global::System.ComponentModel.EditorBrowsableState.Never"))))),
- AttributeList(SingletonSeparatedList(
- Attribute(IdentifierName("global::System.Obsolete")).AddArgumentListArguments(
- AttributeArgument(LiteralExpression(
- SyntaxKind.StringLiteralExpression,
- Literal("This method is not intended to be used directly by user code"))))))
- };
-
- // Add [SkipLocalsInit] if needed
- if (skipLocalsInit)
- {
- attributes.Add(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Runtime.CompilerServices.SkipLocalsInit")))));
- }
-
- return hierarchyInfo.GetSyntax(new MemberDeclarationSyntax[] { memberDeclaration.AddAttributeLists(attributes.ToArray()) }, additionalMemberDeclarations);
- }
}
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs
index 044b2e32..c1a0eb76 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs
@@ -1,4 +1,3 @@
-using System;
using System.Collections.Immutable;
using System.Linq;
using ComputeSharp.D2D1.SourceGenerators.Models;
@@ -8,7 +7,6 @@ using ComputeSharp.SourceGeneration.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Text;
namespace ComputeSharp.D2D1.SourceGenerators;
@@ -196,48 +194,70 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
// Generate the source files, if any
context.RegisterSourceOutput(outputInfo, static (context, item) =>
{
- PropertyDeclarationSyntax effectIdProperty = EffectId.GetSyntax(item.EffectId);
- PropertyDeclarationSyntax effectDisplayNameProperty = EffectMetadata.GetEffectDisplayNameSyntax(item.EffectDisplayName);
- PropertyDeclarationSyntax effectDescriptionProperty = EffectMetadata.GetEffectDescriptionSyntax(item.EffectDescription);
- PropertyDeclarationSyntax effectCategoryProperty = EffectMetadata.GetEffectCategorySyntax(item.EffectCategory);
- PropertyDeclarationSyntax effectAuthorProperty = EffectMetadata.GetEffectAuthorSyntax(item.EffectAuthor);
- PropertyDeclarationSyntax inputCountProperty = InputCount.GetSyntax(item.InputTypes.Length);
- PropertyDeclarationSyntax inputTypesProperty = InputTypes.GetSyntax(item.InputTypes, out TypeDeclarationSyntax[] inputTypesAdditionalTypes);
- PropertyDeclarationSyntax inputDescriptionsProperty = InputDescriptions.GetSyntax(item.InputDescriptions, out MemberDeclarationSyntax[] inputDescriptionsAdditionalDataMembers);
- PropertyDeclarationSyntax resourceTextureDescriptionsProperty = ResourceTextureDescriptions.GetSyntax(item.ResourceTextureDescriptions, out MemberDeclarationSyntax[] resourceTexturesAditionalDataMembers);
- PropertyDeclarationSyntax hlslStringProperty = HlslSource.GetSyntax(item.HlslInfoKey.HlslSource, item.Hierarchy.Hierarchy.Length);
- PropertyDeclarationSyntax hlslBytecodeProperty = LoadBytecode.GetHlslBytecodeSyntax(item.HlslInfo, out Func fixup, out TypeDeclarationSyntax[] hlslBytecodeAdditionalTypes);
- PropertyDeclarationSyntax shaderProfileProperty = LoadBytecode.GetShaderProfileSyntax(item.HlslInfoKey.EffectiveShaderProfile);
- PropertyDeclarationSyntax compileOptionsProperty = LoadBytecode.GetCompileOptionsSyntax(item.HlslInfoKey.EffectiveCompileOptions);
- PropertyDeclarationSyntax bufferPrecisionProperty = OutputBuffer.GetBufferPrecisionSyntax(item.BufferPrecision);
- PropertyDeclarationSyntax channelDepthProperty = OutputBuffer.GetChannelDepthSyntax(item.ChannelDepth);
- PropertyDeclarationSyntax pixelOptionsProperty = PixelOptions.GetSyntax(item.PixelOptions);
+ using ImmutableArrayBuilder> declaredMembers = ImmutableArrayBuilder>.Rent();
- MethodDeclarationSyntax initializeFromDispatchDataMethod = InitializeFromDispatchData.GetSyntax(item.Fields);
- MethodDeclarationSyntax loadDispatchDataMethod = LoadDispatchData.GetSyntax(item.Hierarchy, item.Fields, item.ConstantBufferSizeInBytes, out TypeDeclarationSyntax[] loadDispatchDataAditionalTypes);
+ declaredMembers.Add(EffectId.WriteSyntax);
+ declaredMembers.Add(EffectMetadata.WriteEffectDisplayNameSyntax);
+ declaredMembers.Add(EffectMetadata.WriteEffectDescriptionSyntax);
+ declaredMembers.Add(EffectMetadata.WriteEffectCategorySyntax);
+ declaredMembers.Add(EffectMetadata.WriteEffectAuthorSyntax);
+ declaredMembers.Add(InputCount.WriteSyntax);
+ declaredMembers.Add(InputTypes.WriteSyntax);
+ declaredMembers.Add(InputDescriptions.WriteSyntax);
+ declaredMembers.Add(ResourceTextureDescriptions.WriteSyntax);
+ declaredMembers.Add(PixelOptions.WriteSyntax);
+ declaredMembers.Add(OutputBuffer.WriteBufferPrecisionSyntax);
+ declaredMembers.Add(OutputBuffer.WriteChannelDepthSyntax);
+ declaredMembers.Add(LoadBytecode.WriteShaderProfileSyntax);
+ declaredMembers.Add(LoadBytecode.WriteCompileOptionsSyntax);
+ declaredMembers.Add(HlslSource.WriteSyntax);
+ declaredMembers.Add(LoadBytecode.WriteHlslBytecodeSyntax);
+ declaredMembers.Add(InitializeFromDispatchData.WriteSyntax);
+ declaredMembers.Add(LoadDispatchData.WriteSyntax);
- CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMembers(
- hierarchyInfo: item.Hierarchy,
- memberDeclarations: new (MemberDeclarationSyntax, bool)[]
+ using ImmutableArrayBuilder> additionalTypes = ImmutableArrayBuilder>.Rent();
+ using ImmutableHashSetBuilder usingDirectives = ImmutableHashSetBuilder.Rent();
+
+ LoadDispatchData.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives);
+ InputDescriptions.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives);
+ InputTypes.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives);
+ LoadBytecode.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives);
+
+ using IndentedTextWriter writer = IndentedTextWriter.Rent();
+
+ item.Hierarchy.WriteSyntax(item, writer, declaredMembers.WrittenSpan);
+
+ // If any generated types are needed, they go into a separate namespace
+ // This allows the code to use using directives without any conflicts.
+ if (additionalTypes.Count > 0)
+ {
+ writer.WriteLine();
+ writer.WriteLine("namespace ComputeSharp.D2D1.Generated");
+
+ using (writer.WriteBlock())
{
- (effectIdProperty, false), (effectDisplayNameProperty, false), (effectDescriptionProperty, false), (effectCategoryProperty, false), (effectAuthorProperty, false),
- (inputCountProperty, false), (inputTypesProperty, false), (inputDescriptionsProperty, false), (resourceTextureDescriptionsProperty, false), (hlslStringProperty, false),
- (hlslBytecodeProperty, false), (shaderProfileProperty, false), (compileOptionsProperty, false), (bufferPrecisionProperty, false), (channelDepthProperty, false),
- (pixelOptionsProperty, false), (initializeFromDispatchDataMethod, true), (loadDispatchDataMethod, true)
- },
- additionalMemberDeclarations: new TypeDeclarationSyntax[][]
- {
- loadDispatchDataAditionalTypes,
- InputDescriptions.GetDataTypeDeclarations(new[] { inputDescriptionsAdditionalDataMembers, resourceTexturesAditionalDataMembers }.SelectMany(static members => members).ToArray()),
- inputTypesAdditionalTypes, hlslBytecodeAdditionalTypes
+ // Add the System directives first, in the correct order
+ foreach (string usingDirective in usingDirectives.AsEnumerable().Where(static name => name.StartsWith("global::System")).OrderBy(static name => name))
+ {
+ writer.WriteLine($"using {usingDirective};");
+ }
+
+ // Add the other directives, also sorted in the correct order
+ foreach (string usingDirective in usingDirectives.AsEnumerable().Where(static name => !name.StartsWith("global::System")).OrderBy(static name => name))
+ {
+ writer.WriteLine($"using {usingDirective};");
+ }
+
+ foreach (IndentedTextWriter.Callback callback in additionalTypes.WrittenSpan)
+ {
+ writer.WriteLine();
+
+ callback(item, writer);
+ }
}
- .SelectMany(static types => types)
- .Cast()
- .ToArray());
+ }
- SourceText sourceText = fixup(compilationUnit);
-
- context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.g.cs", sourceText);
+ context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.g.cs", writer.ToString());
});
}
}
\ 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 da489b18..d8d0fd01 100644
--- a/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SyntaxFormattingHelper.cs
+++ b/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SyntaxFormattingHelper.cs
@@ -30,6 +30,68 @@ 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.
+ ///
+ /// The input byte content to serialize.
+ /// The instance to write the expressions to.
+ ///
+ /// This function will write raw byte initialization expressions, such as:
+ /// [1, 2, 3, 4, 5] => 0x01, 0x02, 0x03, 0x04, 0x05.
+ ///
+ public static void WriteByteArrayInitializationExpressions(ReadOnlySpan bytecode, IndentedTextWriter writer)
+ {
+ if (bytecode.Length == 0)
+ {
+ return;
+ }
+
+ // Calculate the buffer size:
+ // - 4 characters per item (eg. "0x00")
+ // - 2 characters between each pair of items (ie. ", ")
+ int length = (bytecode.Length * 4) + ((bytecode.Length - 1) * 2);
+
+ // Reserve the space and get a span into the writer buffer
+ Span span = writer.Advance(length);
+
+ // Cache the value expressions to avoid accessing the static fields multiple times
+ ReadOnlySpan expressions = FormattedBytes.AsSpan();
+
+ // First write the first item (which has no leading separator)
+ expressions[bytecode[0]].AsSpan().CopyTo(span);
+
+ // Special case: stop early if there's only one element
+ if (bytecode.Length == 1)
+ {
+ return;
+ }
+
+ // Advance the span to right past the item we've already written.
+ // This is so that each new item can assume it's starting from 0.
+ span = span.Slice(4);
+
+ // Loop over all remaining items, and add the separator and encoded value.
+ // Then slice the remaining span so following items can repeat the same.
+ foreach (byte b in bytecode.Slice(1))
+ {
+ span[0] = ',';
+ span[1] = ' ';
+ expressions[b].AsSpan().CopyTo(span.Slice(2));
+
+ span = span.Slice(6);
+ }
+ }
+
///
/// Creates a formatted expression to initialize a with a given content.
///
diff --git a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems
index 289de1ea..3a2bf8d3 100644
--- a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems
+++ b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems
@@ -13,6 +13,7 @@
+
@@ -20,7 +21,9 @@
+
+
diff --git a/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs
new file mode 100644
index 00000000..9803e998
--- /dev/null
+++ b/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs
@@ -0,0 +1,96 @@
+using System;
+using ComputeSharp.SourceGeneration.Helpers;
+
+namespace ComputeSharp.SourceGeneration.Extensions;
+
+///
+/// Extension methods for the type.
+///
+internal static class IndentedTextWriterExtensions
+{
+ ///
+ /// Writes the following attributes into a target writer:
+ ///
+ /// [global::System.CodeDom.Compiler.GeneratedCode("...", "...")]
+ /// [global::System.Diagnostics.DebuggerNonUserCode]
+ /// [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
+ ///
+ ///
+ /// The instance to write into.
+ /// The type of the running generator.
+ /// Whether to use fully qualified type names or not.
+ public static void WriteGeneratedAttributes(this IndentedTextWriter writer, Type generatorType, bool useFullyQualifiedTypeNames = true)
+ {
+ if (useFullyQualifiedTypeNames)
+ {
+ writer.WriteLine($$"""[global::System.CodeDom.Compiler.GeneratedCode("{{generatorType.FullName}}", "{{generatorType.Assembly.GetName().Version}}")]""");
+ writer.WriteLine($$"""[global::System.Diagnostics.DebuggerNonUserCode]""");
+ writer.WriteLine($$"""[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]""");
+ }
+ else
+ {
+ writer.WriteLine($$"""[GeneratedCode("{{generatorType.FullName}}", "{{generatorType.Assembly.GetName().Version}}")]""");
+ writer.WriteLine($$"""[DebuggerNonUserCode]""");
+ writer.WriteLine($$"""[ExcludeFromCodeCoverage]""");
+ }
+ }
+
+ ///
+ /// Writes a new line into the target writer depending on an input condition.
+ ///
+ /// The instance to write into.
+ /// The condition to use to decide whether or not to write a new line.
+ public static void WriteLineIf(this IndentedTextWriter writer, bool condition)
+ {
+ if (condition)
+ {
+ writer.WriteLine();
+ }
+ }
+
+ ///
+ /// Writes a series of members separated by one line between each of them.
+ ///
+ /// The type of input items to process.
+ /// The instance to write into.
+ /// The input items to process.
+ /// The instance to invoke for each item.
+ public static void WriteLineSeparatedMembers(
+ this IndentedTextWriter writer,
+ ReadOnlySpan items,
+ IndentedTextWriter.Callback callback)
+ {
+ for (int i = 0; i < items.Length; i++)
+ {
+ if (i > 0)
+ {
+ writer.WriteLine();
+ }
+
+ callback(items[i], writer);
+ }
+ }
+
+ ///
+ /// Writes a series of initialization expressions separated by a comma between each of them.
+ ///
+ /// The type of input items to process.
+ /// The instance to write into.
+ /// The input items to process.
+ /// The instance to invoke for each item.
+ public static void WriteInitializationExpressions(
+ this IndentedTextWriter writer,
+ ReadOnlySpan items,
+ IndentedTextWriter.Callback callback)
+ {
+ for (int i = 0; i < items.Length; i++)
+ {
+ callback(items[i], writer);
+
+ if (i < items.Length - 1)
+ {
+ writer.WriteLine(",");
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs
index 3aa5b62b..aa1d495a 100644
--- a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs
+++ b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs
@@ -60,6 +60,20 @@ internal struct ImmutableArrayBuilder : IDisposable
get => this.writer!.WrittenSpan.Length;
}
+ ///
+ /// Advances the current writer and gets a to the requested memory area.
+ ///
+ /// The requested size to advance by.
+ /// A to the requested memory area.
+ ///
+ /// No other data should be written to the builder while the returned
+ /// is in use, as it could invalidate the memory area wrapped by it, if resizing occurs.
+ ///
+ public readonly Span Advance(int requestedSize)
+ {
+ return this.writer!.Advance(requestedSize);
+ }
+
///
public readonly void Add(T item)
{
@@ -159,6 +173,18 @@ internal struct ImmutableArrayBuilder : IDisposable
get => new(this.array, 0, this.index);
}
+ ///
+ public Span Advance(int requestedSize)
+ {
+ EnsureCapacity(requestedSize);
+
+ Span span = this.array.AsSpan(this.index, requestedSize);
+
+ this.index += requestedSize;
+
+ return span;
+ }
+
///
public void Add(T value)
{
diff --git a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableHashSetBuilder{T}.cs b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableHashSetBuilder{T}.cs
new file mode 100644
index 00000000..f9faaaca
--- /dev/null
+++ b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableHashSetBuilder{T}.cs
@@ -0,0 +1,102 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Collections.Generic;
+using System.Collections.Immutable;
+using System.Linq;
+using System.Runtime.CompilerServices;
+
+namespace ComputeSharp.SourceGeneration.Helpers;
+
+///
+/// A helper type to build hash sets of values with pooled buffers.
+///
+/// The type of items to create hash sets for.
+internal struct ImmutableHashSetBuilder : IDisposable
+{
+ ///
+ /// The shared instance to share objects.
+ ///
+ private static readonly ObjectPool> SharedObjectPool = new(static () => new HashSet());
+
+ ///
+ /// The rented instance to use.
+ ///
+ private HashSet? set;
+
+ ///
+ /// Creates a value with a pooled underlying data writer.
+ ///
+ /// A instance to write data to.
+ public static ImmutableHashSetBuilder Rent()
+ {
+ return new(SharedObjectPool.Allocate());
+ }
+
+ ///
+ /// Creates a new object with the specified parameters.
+ ///
+ /// The target instance to use.
+ private ImmutableHashSetBuilder(HashSet set)
+ {
+ this.set = set;
+ }
+
+ ///
+ /// Gets the number of elements currently written in the current instance.
+ ///
+ public readonly int Count
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get => this.set!.Count;
+ }
+
+ ///
+ public readonly void Add(T item)
+ {
+ _ = this.set!.Add(item);
+ }
+
+ ///
+ /// Gets an instance for the current builder.
+ ///
+ /// An instance for the current builder.
+ ///
+ /// The builder should not be mutated while an enumerator is in use.
+ ///
+ public readonly IEnumerable AsEnumerable()
+ {
+ return this.set!;
+ }
+
+ ///
+ public readonly ImmutableArray ToImmutable()
+ {
+ T[] array = this.set!.ToArray();
+
+ return Unsafe.As>(ref array);
+ }
+
+ ///
+ public readonly T[] ToArray()
+ {
+ return this.set!.ToArray();
+ }
+
+ ///
+ public void Dispose()
+ {
+ HashSet? writer = this.set;
+
+ this.set = null;
+
+ if (writer is not null)
+ {
+ writer.Clear();
+
+ SharedObjectPool.Free(writer);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs b/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs
new file mode 100644
index 00000000..9497cf23
--- /dev/null
+++ b/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs
@@ -0,0 +1,363 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.ComponentModel;
+using System.Runtime.CompilerServices;
+using System.Text;
+
+namespace ComputeSharp.SourceGeneration.Helpers;
+
+///
+/// A helper type to build sequences of values with pooled buffers.
+///
+internal sealed class IndentedTextWriter : IDisposable
+{
+ ///
+ /// The default indentation (4 spaces).
+ ///
+ private const string DefaultIndentation = " ";
+
+ ///
+ /// The default new line ('\n').
+ ///
+ private const char DefaultNewLine = '\n';
+
+ ///
+ /// The instance that text will be written to.
+ ///
+ private ImmutableArrayBuilder builder;
+
+ ///
+ /// The current indentation level.
+ ///
+ private int currentIndentationLevel;
+
+ ///
+ /// The current indentation, as text.
+ ///
+ private string currentIndentation = "";
+
+ ///
+ /// The cached array of available indentations, as text.
+ ///
+ private string[] availableIndentations;
+
+ ///
+ /// Creates an instance with a pooled underlying data writer.
+ ///
+ /// An instance to write data to.
+ public static IndentedTextWriter Rent()
+ {
+ return new(ImmutableArrayBuilder.Rent());
+ }
+
+ ///
+ /// Creates a new object with the specified parameters.
+ ///
+ /// The target instance to use.
+ private IndentedTextWriter(ImmutableArrayBuilder builder)
+ {
+ this.builder = builder;
+ this.currentIndentationLevel = 0;
+ this.currentIndentation = "";
+ this.availableIndentations = new string[4];
+ this.availableIndentations[0] = "";
+
+ for (int i = 1, n = this.availableIndentations.Length; i < n; i++)
+ {
+ this.availableIndentations[i] = this.availableIndentations[i - 1] + DefaultIndentation;
+ }
+ }
+
+ ///
+ /// Advances the current writer and gets a to the requested memory area.
+ ///
+ /// The requested size to advance by.
+ /// A to the requested memory area.
+ ///
+ /// No other data should be written to the writer while the returned
+ /// is in use, as it could invalidate the memory area wrapped by it, if resizing occurs.
+ ///
+ public Span Advance(int requestedSize)
+ {
+ // Add the leading whitespace if needed (same as WriteRawText below)
+ if (this.builder.Count == 0 || this.builder.WrittenSpan[^1] == DefaultNewLine)
+ {
+ this.builder.AddRange(this.currentIndentation.AsSpan());
+ }
+
+ return this.builder.Advance(requestedSize);
+ }
+
+ ///
+ /// Increases the current indentation level.
+ ///
+ public void IncreaseIndent()
+ {
+ this.currentIndentationLevel++;
+
+ if (this.currentIndentationLevel == this.availableIndentations.Length)
+ {
+ Array.Resize(ref this.availableIndentations, this.availableIndentations.Length * 2);
+ }
+
+ // Set both the current indentation and the current position in the indentations
+ // array to the expected indentation for the incremented level (ie. one level more).
+ this.currentIndentation = this.availableIndentations[this.currentIndentationLevel]
+ ??= this.availableIndentations[this.currentIndentationLevel - 1] + DefaultIndentation;
+ }
+
+ ///
+ /// Decreases the current indentation level.
+ ///
+ public void DecreaseIndent()
+ {
+ this.currentIndentationLevel--;
+ this.currentIndentation = this.availableIndentations[this.currentIndentationLevel];
+ }
+
+ ///
+ /// Writes a block to the underlying buffer.
+ ///
+ /// A value to close the open block with.
+ public Block WriteBlock()
+ {
+ WriteLine("{");
+ IncreaseIndent();
+
+ return new(this);
+ }
+
+ ///
+ /// Writes content to the underlying buffer.
+ ///
+ /// The content to write.
+ /// Whether the input content is multiline.
+ public void Write(string content, bool isMultiline = false)
+ {
+ Write(content.AsSpan(), isMultiline);
+ }
+
+ ///
+ /// Writes content to the underlying buffer.
+ ///
+ /// The content to write.
+ /// Whether the input content is multiline.
+ public void Write(ReadOnlySpan content, bool isMultiline = false)
+ {
+ if (isMultiline)
+ {
+ while (content.Length > 0)
+ {
+ int newLineIndex = content.IndexOf(DefaultNewLine);
+
+ if (newLineIndex < 0)
+ {
+ // There are no new lines left, so the content can be written as a single line
+ WriteRawText(content);
+
+ break;
+ }
+ else
+ {
+ // Write the current line
+ WriteRawText(content[..newLineIndex]);
+ WriteLine();
+
+ // Move past the new line character (the result could be an empty span)
+ content = content[(newLineIndex + 1)..];
+ }
+ }
+ }
+ else
+ {
+ WriteRawText(content);
+ }
+ }
+
+ ///
+ /// Writes content to the underlying buffer.
+ ///
+ /// The interpolated string handler with content to write.
+ public void Write([InterpolatedStringHandlerArgument("")] ref WriteInterpolatedStringHandler handler)
+ {
+ _ = this;
+ }
+
+ ///
+ /// Writes a line to the underlying buffer.
+ ///
+ public void WriteLine()
+ {
+ this.builder.Add(DefaultNewLine);
+ }
+
+ ///
+ /// Writes content to the underlying buffer and appends a trailing new line.
+ ///
+ /// The content to write.
+ /// Whether the input content is multiline.
+ public void WriteLine(string content, bool isMultiline = false)
+ {
+ WriteLine(content.AsSpan(), isMultiline);
+ }
+
+ ///
+ /// Writes content to the underlying buffer and appends a trailing new line.
+ ///
+ /// The content to write.
+ /// Whether the input content is multiline.
+ public void WriteLine(ReadOnlySpan content, bool isMultiline = false)
+ {
+ Write(content, isMultiline);
+ WriteLine();
+ }
+
+ ///
+ /// Writes content to the underlying buffer and appends a trailing new line.
+ ///
+ /// The interpolated string handler with content to write.
+ public void WriteLine([InterpolatedStringHandlerArgument("")] ref WriteInterpolatedStringHandler handler)
+ {
+ WriteLine();
+ }
+
+ ///
+ public override string ToString()
+ {
+ return this.builder.ToString();
+ }
+
+ ///
+ public void Dispose()
+ {
+ this.builder.Dispose();
+ }
+
+ ///
+ /// Writes raw text to the underlying buffer, adding leading indentation if needed.
+ ///
+ /// The raw text to write.
+ private void WriteRawText(ReadOnlySpan content)
+ {
+ if (this.builder.Count == 0 || this.builder.WrittenSpan[^1] == DefaultNewLine)
+ {
+ this.builder.AddRange(this.currentIndentation.AsSpan());
+ }
+
+ 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.
+ ///
+ public struct Block : IDisposable
+ {
+ ///
+ /// The instance to write to.
+ ///
+ private IndentedTextWriter? writer;
+
+ ///
+ /// Creates a new instance with the specified parameters.
+ ///
+ /// The input instance to wrap.
+ public Block(IndentedTextWriter writer)
+ {
+ this.writer = writer;
+ }
+
+ ///
+ public void Dispose()
+ {
+ IndentedTextWriter? writer = this.writer;
+
+ this.writer = null;
+
+ if (writer is not null)
+ {
+ writer.DecreaseIndent();
+ writer.WriteLine("}");
+ }
+ }
+ }
+
+ ///
+ /// Provides a handler used by the language compiler to append interpolated strings into instances.
+ ///
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ [InterpolatedStringHandler]
+ public readonly ref struct WriteInterpolatedStringHandler
+ {
+ /// The associated to which to append.
+ private readonly IndentedTextWriter writer;
+
+ /// Creates a handler used to append an interpolated string into a .
+ /// The number of constant characters outside of interpolation expressions in the interpolated string.
+ /// The number of interpolation expressions in the interpolated string.
+ /// The associated to which to append.
+ /// This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly.
+ public WriteInterpolatedStringHandler(int literalLength, int formattedCount, IndentedTextWriter writer)
+ {
+ this.writer = writer;
+ }
+
+ /// Writes the specified string to the handler.
+ /// The string to write.
+ public void AppendLiteral(string value)
+ {
+ this.writer.Write(value);
+ }
+
+ /// Writes the specified value to the handler.
+ /// The value to write.
+ public void AppendFormatted(string? value)
+ {
+ AppendFormatted(value);
+ }
+
+ /// Writes the specified character span to the handler.
+ /// The span to write.
+ public void AppendFormatted(ReadOnlySpan value)
+ {
+ this.writer.Write(value);
+ }
+
+ /// Writes the specified value to the handler.
+ /// The value to write.
+ /// The type of the value to write.
+ public void AppendFormatted(T value)
+ {
+ if (value is not null)
+ {
+ this.writer.Write(value.ToString());
+ }
+ }
+
+ /// Writes the specified value to the handler.
+ /// The value to write.
+ /// The format string.
+ /// The type of the value to write.
+ public void AppendFormatted(T value, string? format)
+ {
+ if (value is IFormattable)
+ {
+ this.writer.Write(((IFormattable)value).ToString(format));
+ }
+ else if (value is not null)
+ {
+ this.writer.Write(value.ToString());
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs b/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs
index 520bd83b..7ab7f352 100644
--- a/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs
+++ b/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs
@@ -42,6 +42,55 @@ internal sealed partial record HierarchyInfo(string FullyQualifiedMetadataName,
hierarchy.ToImmutable());
}
+ ///
+ /// Writes syntax for the current hierarchy into a target writer.
+ ///
+ /// The type of state to pass to callbacks.
+ /// The input state to pass to callbacks.
+ /// The target instance to write text to.
+ /// The callbacks to use to write members into the declared type.
+ public void WriteSyntax(T state, IndentedTextWriter writer, ReadOnlySpan> memberCallbacks)
+ {
+ // Write the generated file header
+ writer.WriteLine("// ");
+ writer.WriteLine("#pragma warning disable");
+ writer.WriteLine();
+
+ // Declare the namespace, if needed
+ if (Namespace.Length > 0)
+ {
+ writer.WriteLine($"namespace {Namespace}");
+ writer.WriteLine("{");
+ writer.IncreaseIndent();
+ }
+
+ // Declare all the opening types until the inner-most one
+ for (int i = Hierarchy.Length - 1; i >= 0; i--)
+ {
+ writer.WriteLine($$"""/// """);
+ writer.WriteLine($$"""partial {{Hierarchy[i].GetTypeKeyword()}} {{Hierarchy[i].QualifiedName}}""");
+ writer.WriteLine($$"""{""");
+ writer.IncreaseIndent();
+ }
+
+ // Generate all nested members
+ writer.WriteLineSeparatedMembers(memberCallbacks, (callback, writer) => callback(state, writer));
+
+ // Close all scopes and reduce the indentation
+ for (int i = 0; i < Hierarchy.Length; i++)
+ {
+ writer.DecreaseIndent();
+ writer.WriteLine("}");
+ }
+
+ // Close the namespace scope as well, if needed
+ if (Namespace.Length > 0)
+ {
+ writer.DecreaseIndent();
+ writer.WriteLine("}");
+ }
+ }
+
///
/// Gets the fully qualified type name for the current instance.
///
diff --git a/src/ComputeSharp.SourceGeneration/Models/TypeInfo.cs b/src/ComputeSharp.SourceGeneration/Models/TypeInfo.cs
index 9341a459..95439d24 100644
--- a/src/ComputeSharp.SourceGeneration/Models/TypeInfo.cs
+++ b/src/ComputeSharp.SourceGeneration/Models/TypeInfo.cs
@@ -13,6 +13,21 @@ namespace ComputeSharp.SourceGeneration.Models;
/// Whether the type is a record type.
internal sealed record TypeInfo(string QualifiedName, TypeKind Kind, bool IsRecord)
{
+ ///
+ /// Gets the keyword for the current type kind.
+ ///
+ /// The keyword for the current type kind.
+ public string GetTypeKeyword()
+ {
+ return Kind switch
+ {
+ TypeKind.Struct => "struct",
+ TypeKind.Interface => "interface",
+ TypeKind.Class when IsRecord => "record",
+ _ => "class"
+ };
+ }
+
///
/// Creates a instance for the current info.
///