Merge pull request #580 from Sergio0694/dev/indented-text-writer

Switch D2D1 generator to use indented text writer
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2023-09-30 14:10:58 +02:00
コミット 8de575ce51
22ファイル変更
+1454 -1539

検索条件に一致するファイルはありません

@@ -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
{
/// <summary>
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>EffectId</c> property.
/// Writes the <c>EffectId</c> property.
/// </summary>
/// <param name="info">The input <see cref="EquatableArray{T}"/> instance with the effect GUID.</param>
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>EffectId</c> property.</returns>
public static PropertyDeclarationSyntax GetSyntax(EquatableArray<byte> info)
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
{
// Prepare the initialization text
string effectIdLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(info.AsSpan());
writer.WriteLine("/// <inheritdoc/>");
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<byte> bytes = new byte[] { <EMBEDDED_EFFECT_ID_BYTES> };
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<byte> bytes = new byte[]");
writer.WriteLine("{");
writer.IncreaseIndent();
// Prepare the return statement:
//
// return
// ref global::System.Runtime.CompilerServices.Unsafe.As<byte, global::System.Guid>(
// 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
// {
// <BYTES_DECLARATION>
// <RETURN_STATEMENT>
// }
// }
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<byte, global::System.Guid>(ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(bytes));");
}
}
}
}
}
@@ -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
{
/// <summary>
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>EffectDisplayName</c> property.
/// Writes the <c>EffectDisplayName</c> property.
/// </summary>
/// <param name="effectDisplayName">The input effect display name value, if available.</param>
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>EffectDisplayName</c> property.</returns>
public static PropertyDeclarationSyntax GetEffectDisplayNameSyntax(string? effectDisplayName)
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteEffectDisplayNameSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
{
return GetEffectMetadataSyntax("EffectDisplayName", effectDisplayName);
WriteEffectMetadataSyntax("EffectDisplayName", info.EffectDisplayName, writer);
}
/// <summary>
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>EffectDescription</c> property.
/// Writes the <c>EffectDescription</c> property.
/// </summary>
/// <param name="effectDescription">The input effect description value, if available.</param>
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>EffectDescription</c> property.</returns>
public static PropertyDeclarationSyntax GetEffectDescriptionSyntax(string? effectDescription)
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteEffectDescriptionSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
{
return GetEffectMetadataSyntax("EffectDescription", effectDescription);
WriteEffectMetadataSyntax("EffectDescription", info.EffectDescription, writer);
}
/// <summary>
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>EffectCategory</c> property.
/// Writes the <c>EffectCategory</c> property.
/// </summary>
/// <param name="effectCategory">The input effect category value, if available.</param>
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>EffectCategory</c> property.</returns>
public static PropertyDeclarationSyntax GetEffectCategorySyntax(string? effectCategory)
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteEffectCategorySyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
{
return GetEffectMetadataSyntax("EffectCategory", effectCategory);
WriteEffectMetadataSyntax("EffectCategory", info.EffectCategory, writer);
}
/// <summary>
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>EffectAuthor</c> property.
/// Writes the <c>EffectAuthor</c> property.
/// </summary>
/// <param name="effectAuthor">The input effect author value, if available.</param>
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>EffectAuthor</c> property.</returns>
public static PropertyDeclarationSyntax GetEffectAuthorSyntax(string? effectAuthor)
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteEffectAuthorSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
{
return GetEffectMetadataSyntax("EffectAuthor", effectAuthor);
WriteEffectMetadataSyntax("EffectAuthor", info.EffectAuthor, writer);
}
/// <summary>
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for a given metadata property.
/// Writes a specified metadata property.
/// </summary>
/// <param name="propertyName">The property name to generate.</param>
/// <param name="metadataValue">The input effect metadata value, if available.</param>
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the given metadata property.</returns>
private static PropertyDeclarationSyntax GetEffectMetadataSyntax(string propertyName, string? metadataValue)
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
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("/// <inheritdoc/>");
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.<PROPERTY_NAME> => <METADATA_VALUE>;
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}\";");
}
}
}
}
@@ -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
{
/// <summary>
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>HlslSource</c> property.
/// Writes the <c>HlslSource</c> property.
/// </summary>
/// <param name="hlslSource">The input HLSL source.</param>
/// <param name="hierarchyDepth">The depth of the hierarchy for this type (used to calculate the right indentation).</param>
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>HlslSource</c> property.</returns>
public static PropertyDeclarationSyntax GetSyntax(string hlslSource, int hierarchyDepth)
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
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 => <HLSL_SOURCE>;
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("/// <inheritdoc/>");
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();
}
}
}
@@ -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
{
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>InitializeFromDispatchData</c> method.
/// Writes the <c>InitializeFromDispatchData</c> method.
/// </summary>
/// <param name="fields">The discovered fields of the current shader.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>InitializeFromDispatchData</c> method.</returns>
public static MethodDeclarationSyntax GetSyntax(EquatableArray<FieldInfo> fields)
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
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<byte> data)
// {
// <BODY>
// }
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("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator));
writer.WriteLine("readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InitializeFromDispatchData(global::System.ReadOnlySpan<byte> data)");
/// <summary>
/// Gets a sequence of statements to initialize a shader from a serialized dispatch data buffer.
/// </summary>
/// <param name="fieldInfos">The array of <see cref="FieldInfo"/> values for all captured fields.</param>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to initialize a shader from the serialized dispatch data buffer.</returns>
private static ImmutableArray<StatementSyntax> GetDispatchDataUnloadingStatements(ImmutableArray<FieldInfo> fieldInfos)
{
// If there are no fields, just return no statements
if (fieldInfos.IsEmpty)
using (writer.WriteBlock())
{
return ImmutableArray<StatementSyntax>.Empty;
}
using ImmutableArrayBuilder<StatementSyntax> statements = ImmutableArrayBuilder<StatementSyntax>.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<byte, ConstantBuffer>(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.<FIELD_PATH>) = buffer.<CONSTANT_BUFFER_PATH>;
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.<FIELD_PATH>)[0] = buffer.<CONSTANT_BUFFER_ROW_0_PATH>;
// global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.<FIELD_PATH>)[1] = buffer.<CONSTANT_BUFFER_ROW_1_PATH>;
// ...
// global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.<FIELD_PATH>)[N] = buffer.<CONSTANT_BUFFER_ROW_N_PATH>;
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<byte, global::ComputeSharp.D2D1.Generated.ConstantBuffer>(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.<FIELD_PATH>)[0] = buffer.<CONSTANT_BUFFER_ROW_0_PATH>;
// global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.<FIELD_PATH>)[1] = buffer.<CONSTANT_BUFFER_ROW_1_PATH>;
// ...
// global::System.Runtime.CompilerServices.Unsafe.AsRef(in this.<FIELD_PATH>)[N] = buffer.<CONSTANT_BUFFER_ROW_N_PATH>;
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();
}
}
}
@@ -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
{
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>InputCount</c> property.
/// Writes the <c>InputCount</c> property.
/// </summary>
/// <param name="inputCount">The number of inputs for the shader.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>InputCount</c> property.</returns>
public static PropertyDeclarationSyntax GetSyntax(int inputCount)
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
{
// This code produces a property declaration as follows:
//
// readonly int global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputCount => <INPUT_COUNT>;
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("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator));
writer.WriteLine($"readonly int global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputCount => {info.InputTypes.Length};");
}
}
}
@@ -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
{
/// <summary>
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>InputDescriptions</c> property.
/// Writes the <c>InputDescriptions</c> property.
/// </summary>
/// <param name="inputDescriptions">The input descriptions info gathered for the current shader.</param>
/// <param name="additionalDataMembers">Any additional <see cref="MemberDeclarationSyntax"/> instances needed by the generated code, if needed.</param>
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>InputDescriptions</c> property.</returns>
public static PropertyDeclarationSyntax GetSyntax(EquatableArray<InputDescription> inputDescriptions, out MemberDeclarationSyntax[] additionalDataMembers)
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
{
ExpressionSyntax memoryExpression;
writer.WriteLine("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator));
writer.Write("readonly global::System.ReadOnlyMemory<global::ComputeSharp.D2D1.Interop.D2D1InputDescription> 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<MemberDeclarationSyntax>();
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.Interop.D2D1InputDescription> global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputDescriptions => <EXPRESSION>;
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));
}
/// <summary>
/// Gets the array declaration for the given input descriptions.
/// Registers a callback to generate an additional type, if needed.
/// </summary>
/// <param name="inputDescriptions">The input descriptions info gathered for the current shader.</param>
/// <returns>The array declaration for the given input descriptions.</returns>
private static MemberDeclarationSyntax GetArrayDeclaration(EquatableArray<InputDescription> inputDescriptions)
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="callbacks">The registered callbacks to generate additional types.</param>
/// <param name="usingDirectives">The using directives needed by the generated code.</param>
public static void RegisterAdditionalTypeSyntax(
D2D1ShaderInfo info,
ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> callbacks,
ImmutableHashSetBuilder<string> usingDirectives)
{
using ImmutableArrayBuilder<ExpressionSyntax> inputDescriptionExpressions = ImmutableArrayBuilder<ExpressionSyntax>.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(<INDEX>, <FILTER>)
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 = <LEVEL_OF_DETAIL_COUNT> }
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($$"""/// <summary>""");
writer.WriteLine($$"""/// A container type for additional data needed by the shader.""");
writer.WriteLine($$"""/// </summary>""");
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<IndentedTextWriter.Callback<D2D1ShaderInfo>> dataMembers = ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>>.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:
//
// /// <summary>The singleton <see cref="global::ComputeSharp.D2D1.Interop.D2D1InputDescription"/> array instance.</summary>
// public static readonly global::ComputeSharp.D2D1.Interop.D2D1InputDescription[] InputDescriptions = { <INPUT_DESCRIPTIONS> };
return
FieldDeclaration(
VariableDeclaration(
ArrayType(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1InputDescription"))
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(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("""/// <summary>The singleton <see cref="global::ComputeSharp.D2D1.Interop.D2D1InputDescription"/> array instance.</summary>"""));
callbacks.Add(Callback);
}
/// <summary>
/// Gets any type declarations for additional members.
/// Adds any using directives for the additional data member, if needed.
/// </summary>
/// <param name="memberDeclarations">The additional members that are needed.</param>
/// <returns>Any type declarations for additional members.</returns>
public static TypeDeclarationSyntax[] GetDataTypeDeclarations(MemberDeclarationSyntax[] memberDeclarations)
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="usingDirectives">The using directives needed by the generated code.</param>
public static void AddAdditionalDataMemberUsingDirectives(D2D1ShaderInfo info, ImmutableHashSetBuilder<string> usingDirectives)
{
if (memberDeclarations.Length == 0)
if (info.InputDescriptions.IsEmpty)
{
return Array.Empty<TypeDeclarationSyntax>();
return;
}
// Create the container type declaration:
//
// /// <summary>
// /// A container type for additional data needed by the shader.
// /// </summary>
// [global::System.CodeDom.Compiler.GeneratedCode("...", "...")]
// [global::System.Diagnostics.DebuggerNonUserCode]
// [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
// file static class Data
// {
// <FIELD_DECLARATION>
// }
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("/// <summary>"),
Comment("/// A container type for input descriptions."),
Comment("/// </summary>"));
usingDirectives.Add("global::ComputeSharp.D2D1");
usingDirectives.Add("global::ComputeSharp.D2D1.Interop");
}
return new[] { dataTypeDeclaration };
/// <summary>
/// Registers a callback to generate an additional data member, if needed.
/// </summary>
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="callbacks">The registered callbacks to generate additional data members.</param>
public static void RegisterAdditionalDataMemberSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> 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("""/// <summary>The singleton <see cref="D2D1InputDescription"/> array instance.</summary>""");
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);
}
}
}
@@ -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
{
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>InputTypes</c> property.
/// Writes the <c>InputTypes</c> property.
/// </summary>
/// <param name="inputTypes">The input types for the shader.</param>
/// <param name="additionalTypes">Any additional <see cref="TypeDeclarationSyntax"/> instances needed by the generated code, if needed.</param>
/// <returns>The resulting <see cref="MemberDeclarationSyntax"/> instance for the <c>InputTypes</c> property.</returns>
public static PropertyDeclarationSyntax GetSyntax(ImmutableArray<uint> inputTypes, out TypeDeclarationSyntax[] additionalTypes)
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
{
ExpressionSyntax memoryExpression;
writer.WriteLine("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator));
writer.Write("readonly global::System.ReadOnlyMemory<global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType> 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<D2D1PixelShaderInputType> instance from the memory manager.
if (info.InputTypes.IsEmpty)
{
memoryExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword));
additionalTypes = Array.Empty<TypeDeclarationSyntax>();
writer.WriteLine("default;");
}
else
{
// Create a ReadOnlyMemory<D2D1PixelShaderInputType> 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.Interop.D2D1PixelShaderInputType> global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputTypes => <MEMORY_EXPRESSION>;
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));
}
/// <summary>
/// Gets the memory manager declaration for the input type data.
/// Registers a callback to generate an additional type, if needed.
/// </summary>
/// <param name="inputTypes">The input types for the shader.</param>
/// <returns>The memory manager declaration for the input type data.</returns>
private static TypeDeclarationSyntax GetMemoryManagerDeclaration(ImmutableArray<uint> inputTypes)
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="callbacks">The registered callbacks to generate additional types.</param>
/// <param name="usingDirectives">The using directives needed by the generated code.</param>
public static void RegisterAdditionalTypeSyntax(
D2D1ShaderInfo info,
ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> callbacks,
ImmutableHashSetBuilder<string> usingDirectives)
{
// Create the MemoryManager<T> declaration:
//
// /// <summary>
// /// A <see cref="global::System.Buffers.MemoryManager{T}"/> implementation to get the input types.
// /// </summary>
// [global::System.CodeDom.Compiler.GeneratedCode("...", "...")]
// [global::System.Diagnostics.DebuggerNonUserCode]
// [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
// file sealed InputTypesMemoryManager : global::System.Buffers.MemoryManager<global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType>
// {
// }
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("/// <summary>"),
Comment("""/// A <see cref="global::System.Buffers.MemoryManager{T}"/> implementation to get the input types."""),
Comment("/// </summary>"));
using ImmutableArrayBuilder<MemberDeclarationSyntax> memberDeclarations = ImmutableArrayBuilder<MemberDeclarationSyntax>.Rent();
// Declare the singleton property to get the memory manager:
//
// /// <summary>The singleton <see cref="InputTypesMemoryManager"/> instance to use.</summary>
// 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("""/// <summary>The singleton <see cref="InputTypesMemoryManager"/> instance to use.</summary>""")));
using (ImmutableArrayBuilder<ExpressionSyntax> inputTypeExpressions = ImmutableArrayBuilder<ExpressionSyntax>.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:
//
// /// <summary>The RVA data with the input type info.</summary>
// private static global::System.ReadOnlySpan<global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType> Data => new[] { <INPUT_TYPES> };
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("/// <summary>The RVA data with the input type info.</summary>")));
return;
}
// Add the GetSpan() method:
//
// /// <inheritdoc/>
// public override unsafe global::System.Span<global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType> 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("/// <inheritdoc/>")));
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<global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType> property:
//
// /// <inheritdoc/>
// public override global::System.Memory<global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType> 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("/// <inheritdoc/>")));
// Declare the InputTypesMemoryManager custom memory manager type
static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer)
{
writer.WriteLine($$"""/// <summary>""");
writer.WriteLine($$"""/// A <see cref="MemoryManager{T}"/> implementation to get the input types.""");
writer.WriteLine($$"""/// </summary>""");
writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator), useFullyQualifiedTypeNames: false);
writer.WriteLine($$"""file sealed class InputTypesMemoryManager : MemoryManager<D2D1PixelShaderInputType>""");
// Add the Pin(int elementIndex) method:
//
// /// <inheritdoc/>
// 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("/// <inheritdoc/>")));
using (writer.WriteBlock())
{
// Static singleton instance (the object goes in the frozen heap, so there's no static constructor)
writer.WriteLine($$"""/// <summary>The singleton <see cref="InputTypesMemoryManager"/> instance to use.</summary>""");
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("/// <inheritdoc/>")));
// RVA field
writer.WriteLine();
writer.WriteLine("/// <summary>The RVA data with the input type info.</summary>");
writer.WriteLine("private static global::System.ReadOnlySpan<D2D1PixelShaderInputType> 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("/// <inheritdoc/>")));
// 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("""
/// <inheritdoc/>
public override unsafe Span<D2D1PixelShaderInputType> GetSpan()
{
return new(Unsafe.AsPointer(ref MemoryMarshal.GetReference(Data)), Data.Length);
}
/// <inheritdoc/>
public override Memory<D2D1PixelShaderInputType> Memory
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => CreateMemory(Data.Length);
}
/// <inheritdoc/>
public override unsafe MemoryHandle Pin(int elementIndex)
{
return new(Unsafe.AsPointer(ref Unsafe.AsRef(in Data[elementIndex])), pinnable: this);
}
/// <inheritdoc/>
public override void Unpin()
{
}
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
}
""", isMultiline: true);
}
}
callbacks.Add(Callback);
}
}
}
@@ -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
{
/// <summary>
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>ShaderProfile</c> property.
/// Writes the <c>ShaderProfile</c> property.
/// </summary>
/// <param name="shaderProfile">The input shader profile.</param>
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>ShaderProfile</c> property.</returns>
public static PropertyDeclarationSyntax GetShaderProfileSyntax(D2D1ShaderProfile shaderProfile)
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
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 => <SHADER_PROFILE>;
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("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator));
writer.WriteLine($"readonly ComputeSharp.D2D1.D2D1ShaderProfile global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ShaderProfile => global::ComputeSharp.D2D1.D2D1ShaderProfile.{info.HlslInfoKey.EffectiveShaderProfile};");
}
/// <summary>
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>CompileOptions</c> property.
/// Writes the <c>CompileOptions</c> property.
/// </summary>
/// <param name="compileOptions">The input compile options.</param>
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>CompileOptions</c> property.</returns>
public static PropertyDeclarationSyntax GetCompileOptionsSyntax(D2D1CompileOptions compileOptions)
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
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 => <COMPILE_OPTIONS_EXPRESSION>;
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("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator));
writer.WriteLine($"readonly ComputeSharp.D2D1.D2D1CompileOptions global::ComputeSharp.D2D1.__Internals.ID2D1Shader.CompileOptions => {compileOptionsExpression};");
}
/// <summary>
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>HlslBytecode</c> property.
/// Writes the <c>HlslBytecode</c> property.
/// </summary>
/// <param name="bytecodeInfo">The input bytecode info.</param>
/// <param name="fixup">An opaque <see cref="Func{TResult}"/> instance to transform the final tree into text.</param>
/// <param name="additionalTypes">Any additional <see cref="TypeDeclarationSyntax"/> instances needed by the generated code, if needed.</param>
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>HlslBytecode</c> property.</returns>
public static PropertyDeclarationSyntax GetHlslBytecodeSyntax(
HlslBytecodeInfo bytecodeInfo,
out Func<SyntaxNode, SourceText> fixup,
out TypeDeclarationSyntax[] additionalTypes)
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteHlslBytecodeSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
{
ExpressionSyntax memoryExpression;
writer.WriteLine("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator));
writer.Write("readonly global::System.ReadOnlyMemory<byte> 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<TypeDeclarationSyntax>();
writer.WriteLine("default;");
}
else
{
// Create a ReadOnlyMemory<byte> 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<byte> global::ComputeSharp.D2D1.__Internals.ID2D1Shader.HlslBytecode => <MEMORY_EXPRESSION>;
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));
}
/// <summary>
/// Gets a <see cref="BlockSyntax"/> instance with the logic to try to get a compiled shader bytecode.
/// Registers a callback to generate an additional type, if needed.
/// </summary>
/// <returns>The <see cref="BlockSyntax"/> instance trying to retrieve the precompiled shader.</returns>
private static unsafe TypeDeclarationSyntax GetMemoryManagerDeclaration()
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="callbacks">The registered callbacks to generate additional types.</param>
/// <param name="usingDirectives">The using directives needed by the generated code.</param>
public static void RegisterAdditionalTypeSyntax(
D2D1ShaderInfo info,
ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> callbacks,
ImmutableHashSetBuilder<string> usingDirectives)
{
// Create the MemoryManager<T> declaration:
//
// /// <summary>
// /// <see cref="global::System.Buffers.MemoryManager{T}"/> implementation to get the HLSL bytecode.
// /// </summary>
// [global::System.CodeDom.Compiler.GeneratedCode("...", "...")]
// [global::System.Diagnostics.DebuggerNonUserCode]
// [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
// file sealed HlslBytecodeMemoryManager : global::System.Buffers.MemoryManager<byte>
// {
// }
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("/// <summary>"),
Comment("""/// A <see cref="global::System.Buffers.MemoryManager{T}"/> implementation to get the HLSL bytecode."""),
Comment("/// </summary>"));
// If there is no bytecode, no memory manager is needed
if (info.HlslInfo is not HlslBytecodeInfo.Success)
{
return;
}
using ImmutableArrayBuilder<MemberDeclarationSyntax> memberDeclarations = ImmutableArrayBuilder<MemberDeclarationSyntax>.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:
//
// /// <summary>The singleton <see cref="HlslBytecodeMemoryManager"/> instance to use.</summary>
// 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("""/// <summary>The singleton <see cref="HlslBytecodeMemoryManager"/> instance to use.</summary>""")));
// Declare the HlslBytecodeMemoryManager custom memory manager type
static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer)
{
writer.WriteLine($$"""/// <summary>""");
writer.WriteLine($$"""/// <see cref="MemoryManager{T}"/> implementation to get the HLSL bytecode.""");
writer.WriteLine($$"""/// </summary>""");
writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator), useFullyQualifiedTypeNames: false);
writer.WriteLine($$"""file sealed class HlslBytecodeMemoryManager : MemoryManager<byte>""");
// Construct the RVA span property:
//
// /// <summary>The RVA data with the HLSL bytecode.</summary>
// private static global::System.ReadOnlySpan<byte> 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<ExpressionSyntax>(OmittedArraySizeExpression()))),
InitializerExpression(
SyntaxKind.ArrayInitializerExpression,
SingletonSeparatedList<ExpressionSyntax>(IdentifierName("__EMBEDDED_SHADER_BYTECODE"))))))
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken))
.WithLeadingTrivia(Comment("/// <summary>The RVA data with the HLSL bytecode.</summary>")));
using (writer.WriteBlock())
{
// Static singleton instance (to avoid the static constructor, just like with the input types)
writer.WriteLine($$"""/// <summary>The singleton <see cref="HlslBytecodeMemoryManager"/> instance to use.</summary>""");
writer.WriteLine($$"""public static readonly HlslBytecodeMemoryManager Instance = new();""");
// Override the Memory<byte> property:
//
// /// <inheritdoc/>
// public override global::System.Memory<byte> 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("/// <inheritdoc/>")));
// RVA field (with the compiled HLSL bytecode, on a single line)
writer.WriteLine();
writer.WriteLine("/// <summary>The RVA data with the HLSL bytecode.</summary>");
writer.Write("private static ReadOnlySpan<byte> Data => new byte[] { ");
// Add the GetSpan() method:
//
// /// <inheritdoc/>
// public override unsafe global::System.Span<byte> 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("/// <inheritdoc/>")));
SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(((HlslBytecodeInfo.Success)info.HlslInfo).Bytecode.AsSpan(), writer);
// Add the Pin(int elementIndex) method:
//
// /// <inheritdoc/>
// 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("/// <inheritdoc/>")));
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("/// <inheritdoc/>")));
// Add the remaining members for the memory manager
writer.WriteLine("""
/// <inheritdoc/>
public override unsafe Span<byte> 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("/// <inheritdoc/>")));
/// <inheritdoc/>
public override Memory<byte> Memory
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => CreateMemory(Data.Length);
}
return typeDeclaration.AddMembers(memberDeclarations.ToArray());
/// <inheritdoc/>
public override unsafe MemoryHandle Pin(int elementIndex)
{
return new(Unsafe.AsPointer(ref Unsafe.AsRef(in Data[elementIndex])), pinnable: this);
}
/// <inheritdoc/>
public override void Unpin()
{
}
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
}
""", isMultiline: true);
}
}
callbacks.Add(Callback);
}
}
}
@@ -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
{
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.
/// Writes the <c>LoadDispatchData</c> method.
/// </summary>
/// <param name="hierarchyInfo">The hiararchy info of the shader type.</param>
/// <param name="fields">The description on shader instance fields.</param>
/// <param name="constantBufferSizeInBytes">The size of the shader constant buffer.</param>
/// <param name="additionalTypes">Any additional <see cref="TypeDeclarationSyntax"/> instances needed by the generated code, if needed.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.</returns>
public static MethodDeclarationSyntax GetSyntax(
HierarchyInfo hierarchyInfo,
EquatableArray<FieldInfo> fields,
int constantBufferSizeInBytes,
out TypeDeclarationSyntax[] additionalTypes)
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
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<TypeDeclarationSyntax>();
}
else
{
additionalTypes = new[] { GetConstantBufferDeclaration(hierarchyInfo, fields, constantBufferSizeInBytes) };
}
writer.WriteLine("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator));
writer.WriteLine("readonly unsafe void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.LoadDispatchData<TLoader>(ref TLoader loader)");
// This code produces a method declaration as follows:
//
// readonly unsafe void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.LoadDispatchData<TLoader>(ref TLoader loader)
// {
// <BODY>
// }
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.<CONSTANT_BUFFER_ROW_0_PATH> = this.<FIELD_PATH>[0];
// buffer.<CONSTANT_BUFFER_ROW_1_PATH> = this.<FIELD_PATH>[1];
// ...
// buffer.<CONSTANT_BUFFER_ROW_N_PATH> = this.<FIELD_PATH>[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<byte>(&buffer, sizeof(global::ComputeSharp.D2D1.Generated.ConstantBuffer)));");
}
}
}
/// <summary>
/// Gets a type definition to map the constant buffer of a given shader type.
/// Registers a callback to generate an additional type, if needed.
/// </summary>
/// <param name="hierarchyInfo">The hiararchy info of the shader type.</param>
/// <param name="fieldInfos">The array of <see cref="FieldInfo"/> values for all captured fields.</param>
/// <param name="constantBufferSizeInBytes">The size of the shader constant buffer.</param>
/// <returns>The <see cref="TypeDeclarationSyntax"/> object for the mapped constant buffer for the current shader type.</returns>
private static TypeDeclarationSyntax GetConstantBufferDeclaration(HierarchyInfo hierarchyInfo, ImmutableArray<FieldInfo> fieldInfos, int constantBufferSizeInBytes)
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="callbacks">The registered callbacks to generate additional types.</param>
/// <param name="usingDirectives">The using directives needed by the generated code.</param>
public static void RegisterAdditionalTypeSyntax(
D2D1ShaderInfo info,
ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> callbacks,
ImmutableHashSetBuilder<string> usingDirectives)
{
string fullyQualifiedTypeName = hierarchyInfo.GetFullyQualifiedTypeName();
using ImmutableArrayBuilder<FieldDeclarationSyntax> fieldDeclarations = ImmutableArrayBuilder<FieldDeclarationSyntax>.Rent();
// Appends a new field declaration for a constant buffer field:
//
// <COMMENT>
// [global::System.Runtime.InteropServices.FieldOffset(<FIELD_OFFSET>)]
// public <FIELD_TYPE> <FIELD_NAME>;
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($$"""/// <summary>""");
writer.WriteLine($$"""/// A type representing the constant buffer native layout for <see cref="{{fullyQualifiedTypeName}}"/>.""");
writer.WriteLine($$"""/// </summary>""");
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: $"""/// <inheritdoc cref="{fullyQualifiedTypeName}.{string.Join(".", primitive.FieldPath)}"/>""",
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: $"""/// <inheritdoc cref="{fullyQualifiedTypeName}.{string.Join(".", primitive.FieldPath)}"/>""",
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: $"""/// <summary>Row {j} of <see cref="{fullyQualifiedTypeName}.{string.Join(".", matrix.FieldPath)}"/>.</summary>""",
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($$"""/// <inheritdoc cref="{{fullyQualifiedTypeName}}.{{string.Join(".", primitive.FieldPath)}}"/>""");
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($$"""/// <inheritdoc cref="{{fullyQualifiedTypeName}}.{{string.Join(".", primitive.FieldPath)}}"/>""");
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($$"""/// <summary>Row {j} of <see cref="{{fullyQualifiedTypeName}}.{{string.Join(".", matrix.FieldPath)}}"/>.</summary>""");
writer.WriteLine($$"""[FieldOffset({{matrix.Offsets[j]}})]""");
writer.WriteLine($$"""public {{rowTypeName}} {{fieldNamePrefix}}_{{j}};""");
}
break;
}
});
}
}
// Create the constant buffer type:
//
// /// <summary>
// /// A type representing the constant buffer native layout for <see cref="<SHADER_TYPE"/>.
// /// </summary>
// [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 = <CONSTANT_BUFFER_SIZE>)]
// file struct ConstantBuffer
// {
// <FIELD_DECLARATIONS>
// }
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("/// <summary>"),
Comment($"""/// A type representing the constant buffer native layout for <see cref="{fullyQualifiedTypeName}"/>."""),
Comment("/// </summary>"));
}
/// <summary>
/// Gets a sequence of statements to load the dispatch data for a given shader.
/// </summary>
/// <param name="fieldInfos">The array of <see cref="FieldInfo"/> values for all captured fields.</param>
/// <param name="constantBufferSizeInBytes">The size of the shader constant buffer.</param>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load the shader dispatch data.</returns>
private static ImmutableArray<StatementSyntax> GetDispatchDataLoadingStatements(ImmutableArray<FieldInfo> fieldInfos, int constantBufferSizeInBytes)
{
// If there are no fields, just load an empty buffer:
//
// loader.LoadConstantBuffer(default);
if (fieldInfos.IsEmpty)
{
return
ImmutableArray.Create<StatementSyntax>(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("loader"),
IdentifierName("LoadConstantBuffer")))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.DefaultLiteralExpression,
Token(SyntaxKind.DefaultKeyword))))));
}
using ImmutableArrayBuilder<StatementSyntax> statements = ImmutableArrayBuilder<StatementSyntax>.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.<CONSTANT_BUFFER_PATH> = this.<FIELD_PATH>;
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.<CONSTANT_BUFFER_ROW_0_PATH> = this.<FIELD_PATH>[0];
// buffer.<CONSTANT_BUFFER_ROW_1_PATH> = this.<FIELD_PATH>[1];
// ...
// buffer.<CONSTANT_BUFFER_ROW_N_PATH> = this.<FIELD_PATH>[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<byte>(&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);
}
}
}
@@ -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
{
/// <summary>
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>BufferPrecision</c> property.
/// Writes the <c>BufferPrecision</c> property.
/// </summary>
/// <param name="bufferPrecision">The buffer precision for the resulting output buffer.</param>
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>BufferPrecision</c> property.</returns>
public static PropertyDeclarationSyntax GetBufferPrecisionSyntax(D2D1BufferPrecision bufferPrecision)
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
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 => <BUFFER_PRECISION>;
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("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator));
writer.WriteLine($"readonly ComputeSharp.D2D1.D2D1BufferPrecision global::ComputeSharp.D2D1.__Internals.ID2D1Shader.BufferPrecision => {bufferPrecisionExpression};");
}
/// <summary>
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>ChannelDepth</c> property.
/// Writes the <c>ChannelDepth</c> property.
/// </summary>
/// <param name="channelDepth">The channel depth for the resulting output buffer.</param>
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>ChannelDepth</c> property.</returns>
public static PropertyDeclarationSyntax GetChannelDepthSyntax(D2D1ChannelDepth channelDepth)
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
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 => <CHANNEL_DEPTH>;
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("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator));
writer.WriteLine($"readonly ComputeSharp.D2D1.D2D1ChannelDepth global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ChannelDepth => {channelDepthExpression};");
}
}
}
@@ -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
{
/// <summary>
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>PixelOptions</c> property.
/// Writes the <c>PixelOptions</c> property.
/// </summary>
/// <param name="pixelOptions">The pixel options for the shader.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>PixelOptions</c> property.</returns>
public static PropertyDeclarationSyntax GetSyntax(D2D1PixelOptions pixelOptions)
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
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 => <PIXEL_OPTIONS>;
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("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator));
writer.WriteLine($"readonly ComputeSharp.D2D1.D2D1PixelOptions global::ComputeSharp.D2D1.__Internals.ID2D1Shader.PixelOptions => {pixelOptionsExpression};");
}
}
}
@@ -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
{
/// <summary>
/// Creates a <see cref="PropertyDeclarationSyntax"/> instance for the <c>ResourceTextureDescriptions</c> property.
/// Writes the <c>ResourceTextureDescriptions</c> property.
/// </summary>
/// <param name="resourceTextureDescriptions">The resource texture descriptions info gathered for the current shader.</param>
/// <param name="additionalDataMembers">Any additional <see cref="MemberDeclarationSyntax"/> instances needed by the generated code, if needed.</param>
/// <returns>The resulting <see cref="PropertyDeclarationSyntax"/> instance for the <c>ResourceTextureDescriptions</c> property.</returns>
public static PropertyDeclarationSyntax GetSyntax(EquatableArray<ResourceTextureDescription> resourceTextureDescriptions, out MemberDeclarationSyntax[] additionalDataMembers)
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
{
ExpressionSyntax memoryExpression;
writer.WriteLine("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(typeof(ID2D1ShaderGenerator));
writer.Write("readonly global::System.ReadOnlyMemory<global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription> 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<MemberDeclarationSyntax>();
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.Interop.D2D1ResourceTextureDescription> global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ResourceTextureDescriptions => <EXPRESSION>;
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));
}
/// <summary>
/// Gets the array declaration for the given resource texture descriptions.
/// Adds any using directives for the additional data member, if needed.
/// </summary>
/// <param name="resourceTextureDescriptions">The resource texture descriptions info gathered for the current shader.</param>
/// <returns>The array declaration for the given resource texture descriptions.</returns>
private static MemberDeclarationSyntax GetArrayDeclaration(EquatableArray<ResourceTextureDescription> resourceTextureDescriptions)
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="usingDirectives">The using directives needed by the generated code.</param>
public static void AddAdditionalDataMemberUsingDirectives(D2D1ShaderInfo info, ImmutableHashSetBuilder<string> usingDirectives)
{
using ImmutableArrayBuilder<ExpressionSyntax> resourceTextureDescriptionExpressions = ImmutableArrayBuilder<ExpressionSyntax>.Rent();
foreach (ResourceTextureDescription resourceTextureDescription in resourceTextureDescriptions)
if (info.ResourceTextureDescriptions.IsEmpty)
{
// Create the description expression:
//
// new(<INDEX>, <RANK>)
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:
//
// /// <summary>The singleton <see cref="global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription"/> array instance.</summary>
// public static readonly global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription[] ResourceTextureDescriptions = { <RESOURCE_TEXTURE_DESCRIPTIONS> };
return
FieldDeclaration(
VariableDeclaration(
ArrayType(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription"))
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(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("""/// <summary>The singleton <see cref="global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription"/> array instance.</summary>"""));
usingDirectives.Add("global::ComputeSharp.D2D1.Interop");
}
/// <summary>
/// Registers a callback to generate an additional data member, if needed.
/// </summary>
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="callbacks">The registered callbacks to generate additional data members.</param>
public static void RegisterAdditionalDataMemberSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> 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("""/// <summary>The singleton <see cref="D2D1ResourceTextureDescription"/> array instance.</summary>""");
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);
}
}
}
-95
ファイルの表示
@@ -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;
}
/// <summary>
/// Creates a <see cref="CompilationUnitSyntax"/> instance wrapping the given method.
/// </summary>
/// <param name="hierarchyInfo">The <see cref="HierarchyInfo"/> instance for the current type.</param>
/// <param name="memberDeclarations">The <see cref="MethodDeclarationSyntax"/> items to insert.</param>
/// <param name="additionalMemberDeclarations">Additional member declarations to also emit, if any.</param>
/// <returns>A <see cref="CompilationUnitSyntax"/> object wrapping <paramref name="memberDeclarations"/>.</returns>
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);
}
/// <summary>
/// Creates a <see cref="CompilationUnitSyntax"/> instance wrapping the given method.
/// </summary>
/// <param name="hierarchyInfo">The <see cref="HierarchyInfo"/> instance for the current type.</param>
/// <param name="memberDeclaration">The <see cref="MemberDeclarationSyntax"/> item to insert.</param>
/// <param name="skipLocalsInit">Whether <c>[SkipLocalsInit]</c> should also be generated.</param>
/// <param name="additionalMemberDeclarations">Additional member declarations to also emit, if any.</param>
/// <returns>A <see cref="CompilationUnitSyntax"/> object wrapping <paramref name="memberDeclaration"/>.</returns>
private static CompilationUnitSyntax GetCompilationUnitFromMember(
HierarchyInfo hierarchyInfo,
MemberDeclarationSyntax memberDeclaration,
bool skipLocalsInit,
params MemberDeclarationSyntax[] additionalMemberDeclarations)
{
// Method attributes
List<AttributeListSyntax> 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);
}
}
+59 -39
ファイルの表示
@@ -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<SyntaxNode, SourceText> 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<IndentedTextWriter.Callback<D2D1ShaderInfo>> declaredMembers = ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>>.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<IndentedTextWriter.Callback<D2D1ShaderInfo>> additionalTypes = ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>>.Rent();
using ImmutableHashSetBuilder<string> usingDirectives = ImmutableHashSetBuilder<string>.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<D2D1ShaderInfo> callback in additionalTypes.WrittenSpan)
{
writer.WriteLine();
callback(item, writer);
}
}
.SelectMany(static types => types)
.Cast<MemberDeclarationSyntax>()
.ToArray());
}
SourceText sourceText = fixup(compilationUnit);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.g.cs", sourceText);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.g.cs", writer.ToString());
});
}
}
+62
ファイルの表示
@@ -30,6 +30,68 @@ internal static class SyntaxFormattingHelper
"0xF0", "0xF1", "0xF2", "0xF3", "0xF4", "0xF5", "0xF6", "0xF7", "0xF8", "0xF9", "0xFA", "0xFB", "0xFC", "0xFD", "0xFE", "0xFF"
};
/// <summary>
/// Gets an expression representing a single byte.
/// </summary>
/// <param name="value">The byte to format.</param>
/// <returns>The expression for <paramref name="value"/>.</returns>
public static string GetByteExpression(byte value)
{
return FormattedBytes[value];
}
/// <summary>
/// Writes a formatted expression to initialize a <see cref="ReadOnlySpan{T}"/> with a given content.
/// </summary>
/// <param name="bytecode">The input byte content to serialize.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write the expressions to.</param>
/// <remarks>
/// This function will write raw byte initialization expressions, such as:
/// <c>[1, 2, 3, 4, 5]</c> => <c>0x01, 0x02, 0x03, 0x04, 0x05</c>.
/// </remarks>
public static void WriteByteArrayInitializationExpressions(ReadOnlySpan<byte> 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<char> span = writer.Advance(length);
// Cache the value expressions to avoid accessing the static fields multiple times
ReadOnlySpan<string> 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);
}
}
/// <summary>
/// Creates a formatted expression to initialize a <see cref="ReadOnlySpan{T}"/> with a given content.
/// </summary>
+3
ファイルの表示
@@ -13,6 +13,7 @@
<Compile Include="$(MSBuildThisFileDirectory)Extensions\CompilationExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\DiagnosticsExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\IMethodSymbolExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\IndentedTextWriterExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\IPropertySymbolExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\IFieldSymbolExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ITypeSymbolExtensions.cs" />
@@ -20,7 +21,9 @@
<Compile Include="$(MSBuildThisFileDirectory)helpers\DynamicCache{TKey,TValue}.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Helpers\EquatableArray{T}.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Helpers\HashCode.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Helpers\ImmutableHashSetBuilder{T}.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Helpers\ImmutableArrayBuilder{T}.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Helpers\IndentedTextWriter.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Helpers\ObjectPool{T}.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Models\DeferredDiagnosticInfo.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Models\DiagnosticInfo.cs" />
+96
ファイルの表示
@@ -0,0 +1,96 @@
using System;
using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.SourceGeneration.Extensions;
/// <summary>
/// Extension methods for the <see cref="IndentedTextWriter"/> type.
/// </summary>
internal static class IndentedTextWriterExtensions
{
/// <summary>
/// Writes the following attributes into a target writer:
/// <code>
/// [global::System.CodeDom.Compiler.GeneratedCode("...", "...")]
/// [global::System.Diagnostics.DebuggerNonUserCode]
/// [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
/// </code>
/// </summary>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
/// <param name="generatorType">The type of the running generator.</param>
/// <param name="useFullyQualifiedTypeNames">Whether to use fully qualified type names or not.</param>
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]""");
}
}
/// <summary>
/// Writes a new line into the target writer depending on an input condition.
/// </summary>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
/// <param name="condition">The condition to use to decide whether or not to write a new line.</param>
public static void WriteLineIf(this IndentedTextWriter writer, bool condition)
{
if (condition)
{
writer.WriteLine();
}
}
/// <summary>
/// Writes a series of members separated by one line between each of them.
/// </summary>
/// <typeparam name="T">The type of input items to process.</typeparam>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
/// <param name="items">The input items to process.</param>
/// <param name="callback">The <see cref="IndentedTextWriter.Callback{T}"/> instance to invoke for each item.</param>
public static void WriteLineSeparatedMembers<T>(
this IndentedTextWriter writer,
ReadOnlySpan<T> items,
IndentedTextWriter.Callback<T> callback)
{
for (int i = 0; i < items.Length; i++)
{
if (i > 0)
{
writer.WriteLine();
}
callback(items[i], writer);
}
}
/// <summary>
/// Writes a series of initialization expressions separated by a comma between each of them.
/// </summary>
/// <typeparam name="T">The type of input items to process.</typeparam>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
/// <param name="items">The input items to process.</param>
/// <param name="callback">The <see cref="IndentedTextWriter.Callback{T}"/> instance to invoke for each item.</param>
public static void WriteInitializationExpressions<T>(
this IndentedTextWriter writer,
ReadOnlySpan<T> items,
IndentedTextWriter.Callback<T> callback)
{
for (int i = 0; i < items.Length; i++)
{
callback(items[i], writer);
if (i < items.Length - 1)
{
writer.WriteLine(",");
}
}
}
}
+26
ファイルの表示
@@ -60,6 +60,20 @@ internal struct ImmutableArrayBuilder<T> : IDisposable
get => this.writer!.WrittenSpan.Length;
}
/// <summary>
/// Advances the current writer and gets a <see cref="Span{T}"/> to the requested memory area.
/// </summary>
/// <param name="requestedSize">The requested size to advance by.</param>
/// <returns>A <see cref="Span{T}"/> to the requested memory area.</returns>
/// <remarks>
/// No other data should be written to the builder while the returned <see cref="Span{T}"/>
/// is in use, as it could invalidate the memory area wrapped by it, if resizing occurs.
/// </remarks>
public readonly Span<T> Advance(int requestedSize)
{
return this.writer!.Advance(requestedSize);
}
/// <inheritdoc cref="ImmutableArray{T}.Builder.Add(T)"/>
public readonly void Add(T item)
{
@@ -159,6 +173,18 @@ internal struct ImmutableArrayBuilder<T> : IDisposable
get => new(this.array, 0, this.index);
}
/// <inheritdoc cref="ImmutableArrayBuilder{T}.Advance"/>
public Span<T> Advance(int requestedSize)
{
EnsureCapacity(requestedSize);
Span<T> span = this.array.AsSpan(this.index, requestedSize);
this.index += requestedSize;
return span;
}
/// <inheritdoc cref="ImmutableArrayBuilder{T}.Add"/>
public void Add(T value)
{
+102
ファイルの表示
@@ -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;
/// <summary>
/// A helper type to build hash sets of values with pooled buffers.
/// </summary>
/// <typeparam name="T">The type of items to create hash sets for.</typeparam>
internal struct ImmutableHashSetBuilder<T> : IDisposable
{
/// <summary>
/// The shared <see cref="ObjectPool{T}"/> instance to share <see cref="HashSet{T}"/> objects.
/// </summary>
private static readonly ObjectPool<HashSet<T>> SharedObjectPool = new(static () => new HashSet<T>());
/// <summary>
/// The rented <see cref="HashSet{T}"/> instance to use.
/// </summary>
private HashSet<T>? set;
/// <summary>
/// Creates a <see cref="ImmutableHashSetBuilder{T}"/> value with a pooled underlying data writer.
/// </summary>
/// <returns>A <see cref="ImmutableHashSetBuilder{T}"/> instance to write data to.</returns>
public static ImmutableHashSetBuilder<T> Rent()
{
return new(SharedObjectPool.Allocate());
}
/// <summary>
/// Creates a new <see cref="ImmutableHashSetBuilder{T}"/> object with the specified parameters.
/// </summary>
/// <param name="set">The target <see cref="HashSet{T}"/> instance to use.</param>
private ImmutableHashSetBuilder(HashSet<T> set)
{
this.set = set;
}
/// <summary>
/// Gets the number of elements currently written in the current instance.
/// </summary>
public readonly int Count
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => this.set!.Count;
}
/// <inheritdoc cref="ImmutableArray{T}.Builder.Add(T)"/>
public readonly void Add(T item)
{
_ = this.set!.Add(item);
}
/// <summary>
/// Gets an <see cref="IEnumerable{T}"/> instance for the current builder.
/// </summary>
/// <returns>An <see cref="IEnumerable{T}"/> instance for the current builder.</returns>
/// <remarks>
/// The builder should not be mutated while an enumerator is in use.
/// </remarks>
public readonly IEnumerable<T> AsEnumerable()
{
return this.set!;
}
/// <inheritdoc cref="ImmutableArray{T}.Builder.ToImmutable"/>
public readonly ImmutableArray<T> ToImmutable()
{
T[] array = this.set!.ToArray();
return Unsafe.As<T[], ImmutableArray<T>>(ref array);
}
/// <inheritdoc cref="ImmutableArray{T}.Builder.ToArray"/>
public readonly T[] ToArray()
{
return this.set!.ToArray();
}
/// <inheritdoc/>
public void Dispose()
{
HashSet<T>? writer = this.set;
this.set = null;
if (writer is not null)
{
writer.Clear();
SharedObjectPool.Free(writer);
}
}
}
+363
ファイルの表示
@@ -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;
/// <summary>
/// A helper type to build sequences of values with pooled buffers.
/// </summary>
internal sealed class IndentedTextWriter : IDisposable
{
/// <summary>
/// The default indentation (4 spaces).
/// </summary>
private const string DefaultIndentation = " ";
/// <summary>
/// The default new line (<c>'\n'</c>).
/// </summary>
private const char DefaultNewLine = '\n';
/// <summary>
/// The <see cref="ImmutableArrayBuilder{T}"/> instance that text will be written to.
/// </summary>
private ImmutableArrayBuilder<char> builder;
/// <summary>
/// The current indentation level.
/// </summary>
private int currentIndentationLevel;
/// <summary>
/// The current indentation, as text.
/// </summary>
private string currentIndentation = "";
/// <summary>
/// The cached array of available indentations, as text.
/// </summary>
private string[] availableIndentations;
/// <summary>
/// Creates an <see cref="IndentedTextWriter"/> instance with a pooled underlying data writer.
/// </summary>
/// <returns>An <see cref="IndentedTextWriter"/> instance to write data to.</returns>
public static IndentedTextWriter Rent()
{
return new(ImmutableArrayBuilder<char>.Rent());
}
/// <summary>
/// Creates a new <see cref="IndentedTextWriter"/> object with the specified parameters.
/// </summary>
/// <param name="builder">The target <see cref="ImmutableArrayBuilder{T}"/> instance to use.</param>
private IndentedTextWriter(ImmutableArrayBuilder<char> 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;
}
}
/// <summary>
/// Advances the current writer and gets a <see cref="Span{T}"/> to the requested memory area.
/// </summary>
/// <param name="requestedSize">The requested size to advance by.</param>
/// <returns>A <see cref="Span{T}"/> to the requested memory area.</returns>
/// <remarks>
/// No other data should be written to the writer while the returned <see cref="Span{T}"/>
/// is in use, as it could invalidate the memory area wrapped by it, if resizing occurs.
/// </remarks>
public Span<char> 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);
}
/// <summary>
/// Increases the current indentation level.
/// </summary>
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;
}
/// <summary>
/// Decreases the current indentation level.
/// </summary>
public void DecreaseIndent()
{
this.currentIndentationLevel--;
this.currentIndentation = this.availableIndentations[this.currentIndentationLevel];
}
/// <summary>
/// Writes a block to the underlying buffer.
/// </summary>
/// <returns>A <see cref="Block"/> value to close the open block with.</returns>
public Block WriteBlock()
{
WriteLine("{");
IncreaseIndent();
return new(this);
}
/// <summary>
/// Writes content to the underlying buffer.
/// </summary>
/// <param name="content">The content to write.</param>
/// <param name="isMultiline">Whether the input content is multiline.</param>
public void Write(string content, bool isMultiline = false)
{
Write(content.AsSpan(), isMultiline);
}
/// <summary>
/// Writes content to the underlying buffer.
/// </summary>
/// <param name="content">The content to write.</param>
/// <param name="isMultiline">Whether the input content is multiline.</param>
public void Write(ReadOnlySpan<char> 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);
}
}
/// <summary>
/// Writes content to the underlying buffer.
/// </summary>
/// <param name="handler">The interpolated string handler with content to write.</param>
public void Write([InterpolatedStringHandlerArgument("")] ref WriteInterpolatedStringHandler handler)
{
_ = this;
}
/// <summary>
/// Writes a line to the underlying buffer.
/// </summary>
public void WriteLine()
{
this.builder.Add(DefaultNewLine);
}
/// <summary>
/// Writes content to the underlying buffer and appends a trailing new line.
/// </summary>
/// <param name="content">The content to write.</param>
/// <param name="isMultiline">Whether the input content is multiline.</param>
public void WriteLine(string content, bool isMultiline = false)
{
WriteLine(content.AsSpan(), isMultiline);
}
/// <summary>
/// Writes content to the underlying buffer and appends a trailing new line.
/// </summary>
/// <param name="content">The content to write.</param>
/// <param name="isMultiline">Whether the input content is multiline.</param>
public void WriteLine(ReadOnlySpan<char> content, bool isMultiline = false)
{
Write(content, isMultiline);
WriteLine();
}
/// <summary>
/// Writes content to the underlying buffer and appends a trailing new line.
/// </summary>
/// <param name="handler">The interpolated string handler with content to write.</param>
public void WriteLine([InterpolatedStringHandlerArgument("")] ref WriteInterpolatedStringHandler handler)
{
WriteLine();
}
/// <inheritdoc/>
public override string ToString()
{
return this.builder.ToString();
}
/// <inheritdoc/>
public void Dispose()
{
this.builder.Dispose();
}
/// <summary>
/// Writes raw text to the underlying buffer, adding leading indentation if needed.
/// </summary>
/// <param name="content">The raw text to write.</param>
private void WriteRawText(ReadOnlySpan<char> content)
{
if (this.builder.Count == 0 || this.builder.WrittenSpan[^1] == DefaultNewLine)
{
this.builder.AddRange(this.currentIndentation.AsSpan());
}
this.builder.AddRange(content);
}
/// <summary>
/// A delegate representing a callback to write data into an <see cref="IndentedTextWriter"/> instance.
/// </summary>
/// <typeparam name="T">The type of data to use.</typeparam>
/// <param name="value">The input data to use to write into <paramref name="writer"/>.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public delegate void Callback<T>(T value, IndentedTextWriter writer);
/// <summary>
/// Represents an indented block that needs to be closed.
/// </summary>
public struct Block : IDisposable
{
/// <summary>
/// The <see cref="IndentedTextWriter"/> instance to write to.
/// </summary>
private IndentedTextWriter? writer;
/// <summary>
/// Creates a new <see cref="Block"/> instance with the specified parameters.
/// </summary>
/// <param name="writer">The input <see cref="IndentedTextWriter"/> instance to wrap.</param>
public Block(IndentedTextWriter writer)
{
this.writer = writer;
}
/// <inheritdoc/>
public void Dispose()
{
IndentedTextWriter? writer = this.writer;
this.writer = null;
if (writer is not null)
{
writer.DecreaseIndent();
writer.WriteLine("}");
}
}
}
/// <summary>
/// Provides a handler used by the language compiler to append interpolated strings into <see cref="IndentedTextWriter"/> instances.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[InterpolatedStringHandler]
public readonly ref struct WriteInterpolatedStringHandler
{
/// <summary>The associated <see cref="IndentedTextWriter"/> to which to append.</summary>
private readonly IndentedTextWriter writer;
/// <summary>Creates a handler used to append an interpolated string into a <see cref="StringBuilder"/>.</summary>
/// <param name="literalLength">The number of constant characters outside of interpolation expressions in the interpolated string.</param>
/// <param name="formattedCount">The number of interpolation expressions in the interpolated string.</param>
/// <param name="writer">The associated <see cref="IndentedTextWriter"/> to which to append.</param>
/// <remarks>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.</remarks>
public WriteInterpolatedStringHandler(int literalLength, int formattedCount, IndentedTextWriter writer)
{
this.writer = writer;
}
/// <summary>Writes the specified string to the handler.</summary>
/// <param name="value">The string to write.</param>
public void AppendLiteral(string value)
{
this.writer.Write(value);
}
/// <summary>Writes the specified value to the handler.</summary>
/// <param name="value">The value to write.</param>
public void AppendFormatted(string? value)
{
AppendFormatted<string?>(value);
}
/// <summary>Writes the specified character span to the handler.</summary>
/// <param name="value">The span to write.</param>
public void AppendFormatted(ReadOnlySpan<char> value)
{
this.writer.Write(value);
}
/// <summary>Writes the specified value to the handler.</summary>
/// <param name="value">The value to write.</param>
/// <typeparam name="T">The type of the value to write.</typeparam>
public void AppendFormatted<T>(T value)
{
if (value is not null)
{
this.writer.Write(value.ToString());
}
}
/// <summary>Writes the specified value to the handler.</summary>
/// <param name="value">The value to write.</param>
/// <param name="format">The format string.</param>
/// <typeparam name="T">The type of the value to write.</typeparam>
public void AppendFormatted<T>(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());
}
}
}
}
+49
ファイルの表示
@@ -42,6 +42,55 @@ internal sealed partial record HierarchyInfo(string FullyQualifiedMetadataName,
hierarchy.ToImmutable());
}
/// <summary>
/// Writes syntax for the current hierarchy into a target writer.
/// </summary>
/// <typeparam name="T">The type of state to pass to callbacks.</typeparam>
/// <param name="state">The input state to pass to callbacks.</param>
/// <param name="writer">The target <see cref="IndentedTextWriter"/> instance to write text to.</param>
/// <param name="memberCallbacks">The callbacks to use to write members into the declared type.</param>
public void WriteSyntax<T>(T state, IndentedTextWriter writer, ReadOnlySpan<IndentedTextWriter.Callback<T>> memberCallbacks)
{
// Write the generated file header
writer.WriteLine("// <auto-generated/>");
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($$"""/// <inheritdoc cref="{{Hierarchy[i].QualifiedName}}"/>""");
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("}");
}
}
/// <summary>
/// Gets the fully qualified type name for the current instance.
/// </summary>
+15
ファイルの表示
@@ -13,6 +13,21 @@ namespace ComputeSharp.SourceGeneration.Models;
/// <param name="IsRecord">Whether the type is a record type.</param>
internal sealed record TypeInfo(string QualifiedName, TypeKind Kind, bool IsRecord)
{
/// <summary>
/// Gets the keyword for the current type kind.
/// </summary>
/// <returns>The keyword for the current type kind.</returns>
public string GetTypeKeyword()
{
return Kind switch
{
TypeKind.Struct => "struct",
TypeKind.Interface => "interface",
TypeKind.Class when IsRecord => "record",
_ => "class"
};
}
/// <summary>
/// Creates a <see cref="TypeDeclarationSyntax"/> instance for the current info.
/// </summary>