Fully enable D2D1 generator to run on indented text writer

このコミットが含まれているのは:
Sergio Pedri committed 2023-09-30 01:34:04 +02:00
1 親 6accd17c9f
コミット 5d859266d8
12ファイル変更
+241 -164

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

@@ -25,42 +25,39 @@ partial class ID2D1ShaderGenerator
using (writer.WriteBlock())
{
writer.WriteLine($"global::System.ReadOnlySpan<byte> bytes = new byte[]");
writer.WriteLine("global::System.ReadOnlySpan<byte> bytes = new byte[]");
writer.WriteLine("{");
writer.IncreaseIndent();
using (writer.WriteBlock())
{
// Write the bytes like so:
//
// b[0], b[1], b[2], b[3],
// b[4], b[5],
// b[6], b[7],
// b[8],
// b[9],
// b[10],
// b[11],
// b[12],
// b[13],
// b[14],
// b[15],
// b[16],
// b[17]
SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(info.EffectId.AsSpan()[..4], writer);
writer.WriteLine(",");
SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(info.EffectId.AsSpan()[4..6], writer);
writer.WriteLine(",");
SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(info.EffectId.AsSpan()[6..8], writer);
writer.WriteLine(",");
writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[8])},");
writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[9])},");
writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[10])},");
writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[11])},");
writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[12])},");
writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[13])},");
writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[14])},");
writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[15])},");
writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[16])},");
writer.WriteLine(SyntaxFormattingHelper.GetByteExpression(info.EffectId[17]));
}
// Write the bytes like so:
//
// b[0], b[1], b[2], b[3],
// b[4], b[5],
// b[6], b[7],
// b[8],
// b[9],
// b[10],
// b[11],
// b[12],
// b[13],
// b[14],
// b[15]
SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(info.EffectId.AsSpan()[..4], writer);
writer.WriteLine(",");
SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(info.EffectId.AsSpan()[4..6], writer);
writer.WriteLine(",");
SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(info.EffectId.AsSpan()[6..8], writer);
writer.WriteLine(",");
writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[8])},");
writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[9])},");
writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[10])},");
writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[11])},");
writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[12])},");
writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[13])},");
writer.WriteLine($"{SyntaxFormattingHelper.GetByteExpression(info.EffectId[14])},");
writer.WriteLine(SyntaxFormattingHelper.GetByteExpression(info.EffectId[15]));
writer.DecreaseIndent();
writer.WriteLine("};");
writer.WriteLine();
writer.WriteLine("return ref global::System.Runtime.CompilerServices.Unsafe.As<byte, global::System.Guid>(ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(bytes));");
@@ -17,9 +17,11 @@ partial class ID2D1ShaderGenerator
public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
{
writer.WriteLine("readonly string global::ComputeSharp.D2D1.__Internals.ID2D1Shader.HlslSource =>");
writer.IncreaseIndent();
writer.WriteLine("\"\"\"");
writer.WriteLine(info.HlslInfoKey.HlslSource, isMultiline: true);
writer.Write(info.HlslInfoKey.HlslSource, isMultiline: true);
writer.WriteLine("\"\"\";");
writer.DecreaseIndent();
}
}
}
@@ -35,6 +35,7 @@ partial class ID2D1ShaderGenerator
}
// Get a reference to the data through the generated native layout type
writer.WriteLine();
writer.WriteLine("ref readonly ConstantBuffer buffer = ref global::System.Runtime.CompilerServices.Unsafe.As<byte, ConstantBuffer>(ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(data));");
// Generate loading statements for each captured field
@@ -1,10 +1,5 @@
using System;
using ComputeSharp.D2D1.SourceGenerators.Models;
using ComputeSharp.SourceGeneration.Helpers;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.D2D1.SourceGenerators;
@@ -21,7 +16,7 @@ partial class ID2D1ShaderGenerator
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
{
writer.WriteLine("readonly global::System.ReadOnlyMemory<global::ComputeSharp.D2D1.Interop.D2D1InputDescription> global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputDescriptions => ");
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, return the shared array with cached input descriptions.
@@ -36,36 +31,44 @@ partial class ID2D1ShaderGenerator
}
/// <summary>
/// Registers a callback to generate an additional data member, if needed.
/// Registers a callback to generate an additional type, 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)
/// <param name="callbacks">The registered callbacks to generate additional types.</param>
public static void RegisterAdditionalTypeSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> callbacks)
{
// If there are no input descriptions, there is nothing to di
if (info.ResourceTextureDescriptions.IsEmpty)
// If there are no necessary data members, stop here
if (info.InputDescriptions.IsEmpty &&
info.ResourceTextureDescriptions.IsEmpty)
{
return;
}
// Declare the shared array with input descriptions
// Declare the additional data type
static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer)
{
writer.WriteLine("""/// <summary>The singleton <see cref="global::ComputeSharp.D2D1.Interop.D2D1InputDescription"/> array instance.</summary>""");
writer.WriteLine("""public static readonly global::ComputeSharp.D2D1.Interop.D2D1InputDescription[] InputDescriptions = """);
writer.WriteLine($$"""/// <summary>""");
writer.WriteLine($$"""/// A container type for additional data needed by the shader.""");
writer.WriteLine($$"""/// </summary>""");
writer.WriteLine($$"""[global::System.CodeDom.Compiler.GeneratedCode("{{typeof(ID2D1ShaderGenerator).FullName}}", "{{typeof(ID2D1ShaderGenerator).Assembly.GetName().Version}}")]""");
writer.WriteLine($$"""[global::System.Diagnostics.DebuggerNonUserCode]""");
writer.WriteLine($$"""[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]""");
writer.WriteLine($$"""file static class Data""");
// Initialize all input descriptions
using (writer.WriteBlock())
{
for (int i = 0; i < info.InputDescriptions.Length; i++)
using ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> dataMembers = ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>>.Rent();
RegisterAdditionalDataMemberSyntax(info, dataMembers);
ResourceTextureDescriptions.RegisterAdditionalDataMemberSyntax(info, dataMembers);
for (int i = 0; i < dataMembers.WrittenSpan.Length; i++)
{
InputDescription description = info.InputDescriptions[i];
dataMembers.WrittenSpan[i](info, writer);
writer.Write($$"""new global::ComputeSharp.D2D1.Interop.D2D1InputDescription({description.Index}, {description.Filter}) { LevelOfDetailCount = {{description.LevelOfDetailCount}} }""");
if (i < info.InputDescriptions.Length - 1)
if (i < dataMembers.WrittenSpan.Length - 1)
{
writer.WriteLine(",");
writer.WriteLine();
}
}
}
@@ -75,46 +78,45 @@ partial class ID2D1ShaderGenerator
}
/// <summary>
/// Gets any type declarations for additional members.
/// Registers a callback to generate an 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="callbacks">The registered callbacks to generate additional data members.</param>
public static void RegisterAdditionalDataMemberSyntax(D2D1ShaderInfo info, ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> callbacks)
{
if (memberDeclarations.Length == 0)
// If there are no input descriptions, there is nothing to di
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>"));
// Declare the shared array with input descriptions
static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer)
{
writer.WriteLine("""/// <summary>The singleton <see cref="global::ComputeSharp.D2D1.Interop.D2D1InputDescription"/> array instance.</summary>""");
writer.WriteLine("""public static readonly global::ComputeSharp.D2D1.Interop.D2D1InputDescription[] InputDescriptions = """);
writer.WriteLine("""{""");
writer.IncreaseIndent();
return new[] { dataTypeDeclaration };
// Initialize all input descriptions
for (int i = 0; i < info.InputDescriptions.Length; i++)
{
InputDescription description = info.InputDescriptions[i];
writer.Write($$"""new global::ComputeSharp.D2D1.Interop.D2D1InputDescription({{description.Index}}, global::ComputeSharp.D2D1.D2D1Filter.{{description.Filter}}) { LevelOfDetailCount = {{description.LevelOfDetailCount}} }""");
if (i < info.InputDescriptions.Length - 1)
{
writer.WriteLine(",");
}
}
writer.DecreaseIndent();
writer.WriteLine();
writer.WriteLine("};");
}
callbacks.Add(Callback);
}
}
}
@@ -16,7 +16,7 @@ partial class ID2D1ShaderGenerator
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
{
writer.WriteLine("readonly global::System.ReadOnlyMemory<global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType> global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputTypes => ");
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, create
// a ReadOnlyMemory<D2D1PixelShaderInputType> instance from the memory manager.
@@ -64,28 +64,32 @@ partial class ID2D1ShaderGenerator
writer.WriteLine();
writer.WriteLine("/// <summary>The RVA data with the input type info.</summary>");
writer.WriteLine("private static global::System.ReadOnlySpan<global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType> Data => new[]");
writer.WriteLine("{");
writer.IncreaseIndent();
// Input types, one per line in the RVA field initializer
using (writer.WriteBlock())
for (int i = 0; i < info.InputTypes.Length; i++)
{
for (int i = 0; i < info.InputTypes.Length; i++)
{
writer.Write("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType.");
writer.Write(info.InputTypes[i] == 0 ? "Simple" : "Complex");
writer.Write("global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType.");
writer.Write(info.InputTypes[i] == 0 ? "Simple" : "Complex");
if (i < info.InputTypes.Length - 1)
{
writer.WriteLine(",");
}
if (i < info.InputTypes.Length - 1)
{
writer.WriteLine(",");
}
}
writer.DecreaseIndent();
writer.WriteLine();
writer.WriteLine("};");
writer.WriteLine();
// Add the remaining members for the memory manager
writer.WriteLine("""
/// <inheritdoc/>
public override unsafe global::System.Span<global::ComputeSharp.D2D1.Interop.D2D1PixelShaderInputType> GetSpan
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);
return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(Data)), Data.Length);
}
/// <inheritdoc/>
@@ -98,7 +102,7 @@ partial class ID2D1ShaderGenerator
/// <inheritdoc/>
public override unsafe global::System.Buffers.MemoryHandle Pin(int elementIndex)
{
return new(Unsafe.AsPointer(ref Unsafe.AsRef(in Data[elementIndex])), pinnable: this);
return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in Data[elementIndex])), pinnable: this);
}
/// <inheritdoc/>
@@ -36,7 +36,7 @@ partial class ID2D1ShaderGenerator
.Select(static name => $"global::ComputeSharp.D2D1.D2D1CompileOptions.{name.Trim()}")
.Aggregate("", static (left, right) => left.Length > 0 ? $"{left} | {right}" : right);
writer.Write($"readonly ComputeSharp.D2D1.D2D1CompileOptions global::ComputeSharp.D2D1.__Internals.ID2D1Shader.CompileOptions => {compileOptionsExpression};");
writer.WriteLine($"readonly ComputeSharp.D2D1.D2D1CompileOptions global::ComputeSharp.D2D1.__Internals.ID2D1Shader.CompileOptions => {compileOptionsExpression};");
}
/// <summary>
@@ -46,7 +46,7 @@ partial class ID2D1ShaderGenerator
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteHlslBytecodeSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
{
writer.WriteLine("readonly global::System.ReadOnlyMemory<global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription> global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ResourceTextureDescriptions => ");
writer.Write("readonly global::System.ReadOnlyMemory<byte> global::ComputeSharp.D2D1.__Internals.ID2D1Shader.HlslBytecode => ");
// If there is no bytecode, just return a default expression.
// Otherwise, return the memory manager backed memory instance.
@@ -77,7 +77,7 @@ partial class ID2D1ShaderGenerator
static void Callback(D2D1ShaderInfo info, IndentedTextWriter writer)
{
writer.WriteLine($$"""/// <summary>""");
writer.WriteLine($$"""<see cref="global::System.Buffers.MemoryManager{T}"/> implementation to get the HLSL bytecode.""");
writer.WriteLine($$"""/// <see cref="global::System.Buffers.MemoryManager{T}"/> implementation to get the HLSL bytecode.""");
writer.WriteLine($$"""/// </summary>""");
writer.WriteLine($$"""[global::System.CodeDom.Compiler.GeneratedCode("{{typeof(ID2D1ShaderGenerator).FullName}}", "{{typeof(ID2D1ShaderGenerator).Assembly.GetName().Version}}")]""");
writer.WriteLine($$"""[global::System.Diagnostics.DebuggerNonUserCode]""");
@@ -93,18 +93,19 @@ partial class ID2D1ShaderGenerator
// RVA field (with the compiled HLSL bytecode, on a single line)
writer.WriteLine();
writer.WriteLine("/// <summary>The RVA data with the HLSL bytecode.</summary>");
writer.Write("private static global::System.ReadOnlySpan<byte> Data => new[] { ");
writer.Write("private static global::System.ReadOnlySpan<byte> Data => new byte[] { ");
SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(((HlslBytecodeInfo.Success)info.HlslInfo).Bytecode.AsSpan(), writer);
writer.WriteLine(" };");
writer.WriteLine();
// Add the remaining members for the memory manager
writer.WriteLine("""
/// <inheritdoc/>
public override unsafe global::System.Span<byte> GetSpan
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);
return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(Data)), Data.Length);
}
/// <inheritdoc/>
@@ -117,7 +118,7 @@ partial class ID2D1ShaderGenerator
/// <inheritdoc/>
public override unsafe global::System.Buffers.MemoryHandle Pin(int elementIndex)
{
return new(Unsafe.AsPointer(ref Unsafe.AsRef(in Data[elementIndex])), pinnable: this);
return new(global::System.Runtime.CompilerServices.Unsafe.AsPointer(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in Data[elementIndex])), pinnable: this);
}
/// <inheritdoc/>
@@ -95,6 +95,11 @@ partial class ID2D1ShaderGenerator
// Declare fields for every mapped item from the shader layout
for (int i = 0; i < info.Fields.Length; i++)
{
if (i > 0)
{
writer.WriteLine();
}
switch (info.Fields[i])
{
case FieldInfo.Primitive { TypeName: "System.Boolean" } primitive:
@@ -16,7 +16,7 @@ partial class ID2D1ShaderGenerator
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer)
{
writer.WriteLine("readonly global::System.ReadOnlyMemory<global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription> global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ResourceTextureDescriptions => ");
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, return a memory instance from the generated static readonly array.
@@ -48,22 +48,25 @@ partial class ID2D1ShaderGenerator
{
writer.WriteLine("""/// <summary>The singleton <see cref="global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription"/> array instance.</summary>""");
writer.WriteLine("""public static readonly global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription[] ResourceTextureDescriptions =""");
writer.WriteLine("""{""");
writer.IncreaseIndent();
// Initialize all resource texture descriptions
using (writer.WriteBlock())
for (int i = 0; i < info.ResourceTextureDescriptions.Length; i++)
{
for (int i = 0; i < info.ResourceTextureDescriptions.Length; i++)
ResourceTextureDescription description = info.ResourceTextureDescriptions[i];
writer.Write($"new global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription({description.Index}, {description.Rank})");
if (i < info.ResourceTextureDescriptions.Length - 1)
{
ResourceTextureDescription description = info.ResourceTextureDescriptions[i];
writer.Write($"new global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription({description.Index}, {description.Rank})");
if (i < info.ResourceTextureDescriptions.Length - 1)
{
writer.WriteLine(",");
}
writer.WriteLine(",");
}
}
writer.DecreaseIndent();
writer.WriteLine();
writer.WriteLine("};");
}
callbacks.Add(Callback);
+36 -40
ファイルの表示
@@ -1,4 +1,3 @@
using System;
using System.Collections.Immutable;
using System.Linq;
using ComputeSharp.D2D1.SourceGenerators.Models;
@@ -8,7 +7,6 @@ using ComputeSharp.SourceGeneration.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace ComputeSharp.D2D1.SourceGenerators;
@@ -196,48 +194,46 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
// Generate the source files, if any
context.RegisterSourceOutput(outputInfo, static (context, item) =>
{
PropertyDeclarationSyntax effectIdProperty = EffectId.GetSyntax(item.EffectId);
PropertyDeclarationSyntax effectDisplayNameProperty = EffectMetadata.GetEffectDisplayNameSyntax(item.EffectDisplayName);
PropertyDeclarationSyntax effectDescriptionProperty = EffectMetadata.GetEffectDescriptionSyntax(item.EffectDescription);
PropertyDeclarationSyntax effectCategoryProperty = EffectMetadata.GetEffectCategorySyntax(item.EffectCategory);
PropertyDeclarationSyntax effectAuthorProperty = EffectMetadata.GetEffectAuthorSyntax(item.EffectAuthor);
PropertyDeclarationSyntax inputCountProperty = InputCount.GetSyntax(item.InputTypes.Length);
PropertyDeclarationSyntax inputTypesProperty = InputTypes.GetSyntax(item.InputTypes, out TypeDeclarationSyntax[] inputTypesAdditionalTypes);
PropertyDeclarationSyntax inputDescriptionsProperty = InputDescriptions.GetSyntax(item.InputDescriptions, out MemberDeclarationSyntax[] inputDescriptionsAdditionalDataMembers);
PropertyDeclarationSyntax resourceTextureDescriptionsProperty = ResourceTextureDescriptions.GetSyntax(item.ResourceTextureDescriptions, out MemberDeclarationSyntax[] resourceTexturesAditionalDataMembers);
PropertyDeclarationSyntax hlslStringProperty = HlslSource.GetSyntax(item.HlslInfoKey.HlslSource, item.Hierarchy.Hierarchy.Length);
PropertyDeclarationSyntax hlslBytecodeProperty = LoadBytecode.GetHlslBytecodeSyntax(item.HlslInfo, out Func<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)[]
{
(effectIdProperty, false), (effectDisplayNameProperty, false), (effectDescriptionProperty, false), (effectCategoryProperty, false), (effectAuthorProperty, false),
(inputCountProperty, false), (inputTypesProperty, false), (inputDescriptionsProperty, false), (resourceTextureDescriptionsProperty, false), (hlslStringProperty, false),
(hlslBytecodeProperty, false), (shaderProfileProperty, false), (compileOptionsProperty, false), (bufferPrecisionProperty, false), (channelDepthProperty, false),
(pixelOptionsProperty, false), (initializeFromDispatchDataMethod, true), (loadDispatchDataMethod, true)
},
additionalMemberDeclarations: new TypeDeclarationSyntax[][]
{
loadDispatchDataAditionalTypes,
InputDescriptions.GetDataTypeDeclarations(new[] { inputDescriptionsAdditionalDataMembers, resourceTexturesAditionalDataMembers }.SelectMany(static members => members).ToArray()),
inputTypesAdditionalTypes, hlslBytecodeAdditionalTypes
}
.SelectMany(static types => types)
.Cast<MemberDeclarationSyntax>()
.ToArray());
using ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> additionalTypes = ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>>.Rent();
SourceText sourceText = fixup(compilationUnit);
LoadDispatchData.RegisterAdditionalTypeSyntax(item, additionalTypes);
InputDescriptions.RegisterAdditionalTypeSyntax(item, additionalTypes);
InputTypes.RegisterAdditionalTypeSyntax(item, additionalTypes);
LoadBytecode.RegisterAdditionalTypeSyntax(item, additionalTypes);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.g.cs", sourceText);
using IndentedTextWriter writer = IndentedTextWriter.Rent();
item.Hierarchy.WriteSyntax(item, writer, declaredMembers.WrittenSpan);
foreach (IndentedTextWriter.Callback<D2D1ShaderInfo> additionalType in additionalTypes.WrittenSpan)
{
writer.WriteLine();
additionalType(item, writer);
}
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.g.cs", writer.ToString());
});
}
}
+4 -2
ファイルの表示
@@ -61,9 +61,8 @@ internal sealed class IndentedTextWriter : IDisposable
{
this.builder = builder;
this.currentIndentationLevel = 0;
this.currentIndentation = DefaultIndentation;
this.currentIndentation = "";
this.availableIndentations = new string[4];
this.availableIndentations[0] = "";
for (int i = 1, n = this.availableIndentations.Length; i < n; i++)
@@ -158,11 +157,14 @@ internal sealed class IndentedTextWriter : IDisposable
{
// There are no new lines left, so the content can be written as a single line
WriteRawText(content);
break;
}
else
{
// Write the current line
WriteRawText(content[..newLineIndex]);
WriteLine();
// Move past the new line character (the result could be an empty span)
content = content[(newLineIndex + 1)..];
+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 file scoped namespace, if needed
if (Namespace.Length > 0)
{
writer.WriteLine($"namespace {Namespace};");
writer.WriteLine();
}
// Declare all the opening types until the inner-most one
for (int i = Hierarchy.Length - 1; i >= 0; i--)
{
writer.WriteLine($$"""/// <inheritdoc cref="{{Hierarchy[i].QualifiedName}}"/>""");
writer.WriteLine($$"""partial {{Hierarchy[i].GetTypeKeyword()}} {{Hierarchy[i].QualifiedName}}""");
writer.WriteLine($$"""{""");
writer.IncreaseIndent();
}
// Generate all nested members
for (int i = 0; i < memberCallbacks.Length; i++)
{
if (i > 0)
{
writer.WriteLine();
}
memberCallbacks[i](state, writer);
}
// Close all scopes and reduce the indentation
for (int i = 0; i < Hierarchy.Length; i++)
{
writer.DecreaseIndent();
writer.WriteLine("}");
}
}
/// <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>