diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs
index 9538ffb4..57873bd3 100644
--- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs
@@ -1,15 +1,6 @@
-using System;
-using System.Text;
-using ComputeSharp.__Internals;
+using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGenerators.Models;
-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.SourceGenerators;
@@ -20,120 +11,38 @@ partial class IShaderGenerator
partial class LoadBytecode
{
///
- /// Creates a instance for the TryGetBytecode method.
+ /// Writes the LoadBytecode method.
///
- /// The input instance.
- /// An opaque instance to transform the final tree into text.
- /// The resulting instance for the BuildHlslSource method.
- public static MethodDeclarationSyntax GetSyntax(EmbeddedBytecodeInfo bytecodeInfo, out Func fixup)
+ /// The input instance with gathered shader info.
+ /// The instance to write into.
+ public static void WriteSyntax(ShaderInfo info, IndentedTextWriter writer)
{
- BlockSyntax block = GetShaderBytecodeBody(bytecodeInfo, out string? bytecodeLiterals);
+ writer.WriteLine("/// ");
+ writer.WriteGeneratedAttributes(GeneratorName);
+ writer.WriteLine("readonly void global::ComputeSharp.__Internals.IShader.LoadBytecode(ref TLoader loader, int threadsX, int threadsY, int threadsZ)");
- if (bytecodeLiterals is not null)
+ using (writer.WriteBlock())
{
- fixup = tree => SourceText.From(tree.ToFullString().Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals), Encoding.UTF8);
+ // If there is no HLSL bytecode, there's nothing left to do
+ if (info.EmbeddedBytecode.Bytecode.IsEmpty)
+ {
+ return;
+ }
+
+ // Check that the [numthreads] values match
+ writer.WriteLine($"if (threadsX == {info.ThreadIds.X} && threadsY == {info.ThreadIds.Y} && threadsZ == {info.ThreadIds.Z})");
+
+ using (writer.WriteBlock())
+ {
+ writer.Write("global::System.ReadOnlySpan bytecode = new byte[] { ");
+
+ SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(info.EmbeddedBytecode.Bytecode.AsSpan(), writer);
+
+ writer.WriteLine(" };");
+ writer.WriteLine();
+ writer.WriteLine("loader.LoadEmbeddedBytecode(bytecode);");
+ }
}
- else
- {
- fixup = static tree => tree.GetText(Encoding.UTF8);
- }
-
- // This code produces a method declaration as follows:
- //
- // readonly void global::ComputeSharp.__Internals.IShader.LoadBytecode(ref TLoader loader, int threadsX, int threadsY, int threadsZ)
- // {
- //
- // }
- return
- MethodDeclaration(
- PredefinedType(Token(SyntaxKind.VoidKeyword)),
- Identifier("LoadBytecode"))
- .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
- .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
- .AddTypeParameterListParameters(TypeParameter(Identifier("TLoader")))
- .AddParameterListParameters(
- Parameter(Identifier("loader"))
- .AddModifiers(Token(SyntaxKind.RefKeyword))
- .WithType(IdentifierName("TLoader")),
- Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
- Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
- Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))))
- .WithBody(block);
- }
-
- ///
- /// Gets a instance with the logic to try to get a compiled shader bytecode.
- ///
- /// The input instance.
- /// The resulting bytecode literals to insert into the final source code.
- /// The instance trying to retrieve the precompiled shader.
- private static unsafe BlockSyntax GetShaderBytecodeBody(EmbeddedBytecodeInfo bytecodeInfo, out string? bytecodeLiterals)
- {
- if (bytecodeInfo.Bytecode.IsEmpty)
- {
- bytecodeLiterals = null;
-
- // Faulting path
- return Block();
- }
-
- bytecodeLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(bytecodeInfo.Bytecode.AsSpan());
-
- // This code produces a branch as follows:
- //
- // if (threadsX == && threadsY == && threadsZ == )
- // {
- // global::System.ReadOnlySpan bytecode = new byte[] { __EMBEDDED_SHADER_BYTECODE };
- // loader.LoadEmbeddedBytecode(bytecode);
- // }
- //
- // Note that the __EMBEDDED_SHADER_BYTECODE identifier will be replaced after the string
- // is created by the generator. This greatly speeds up the code generation, as it avoids
- // having to create/parse tens of thousands of literal expression nodes for every shader.
- IfStatementSyntax embeddedBranch =
- IfStatement(
- BinaryExpression(
- SyntaxKind.LogicalAndExpression,
- BinaryExpression(
- SyntaxKind.LogicalAndExpression,
- BinaryExpression(
- SyntaxKind.EqualsExpression,
- IdentifierName("threadsX"),
- LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.X))),
- BinaryExpression(
- SyntaxKind.EqualsExpression,
- IdentifierName("threadsY"),
- LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.Y)))),
- BinaryExpression(
- SyntaxKind.EqualsExpression,
- IdentifierName("threadsZ"),
- LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.Z)))),
- Block(
- LocalDeclarationStatement(
- VariableDeclaration(
- GenericName(Identifier("global::System.ReadOnlySpan"))
- .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))))
- .AddVariables(
- VariableDeclarator(Identifier("bytecode"))
- .WithInitializer(
- EqualsValueClause(
- ArrayCreationExpression(
- ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
- .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression()))))
- .WithInitializer(
- InitializerExpression(
- SyntaxKind.ArrayInitializerExpression,
- SingletonSeparatedList(IdentifierName("__EMBEDDED_SHADER_BYTECODE")))))))),
- ExpressionStatement(
- InvocationExpression(
- MemberAccessExpression(
- SyntaxKind.SimpleMemberAccessExpression,
- IdentifierName("loader"),
- IdentifierName("LoadEmbeddedBytecode")))
- .AddArgumentListArguments(Argument(IdentifierName("bytecode"))))));
-
- // If there is no dynamic shader support, add the faulting path after the branch
- return Block(embeddedBranch.WithElse(ElseClause(Block())));
}
}
}
\ No newline at end of file
diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs
index 985f746b..c189e5d0 100644
--- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs
@@ -8,7 +8,6 @@ using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Text;
namespace ComputeSharp.SourceGenerators;
@@ -178,11 +177,19 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
// Generate the TryGetBytecode() methods
context.RegisterSourceOutput(shaderInfoWithErrors, static (context, item) =>
{
- MethodDeclarationSyntax tryGetBytecodeMethod = LoadBytecode.GetSyntax(item.EmbeddedBytecode, out Func fixup);
- CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, tryGetBytecodeMethod, addSkipLocalsInitAttribute: false);
- SourceText text = fixup(compilationUnit);
+ using ImmutableArrayBuilder> declaredMembers = new();
- context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadBytecode)}.g.cs", text);
+ declaredMembers.Add(LoadBytecode.WriteSyntax);
+
+ using IndentedTextWriter writer = new();
+
+ item.Hierarchy.WriteSyntax(
+ state: item,
+ writer: writer,
+ baseTypes: ReadOnlySpan.Empty,
+ memberCallbacks: declaredMembers.WrittenSpan);
+
+ context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadBytecode)}.g.cs", writer.ToString());
});
}
}
\ No newline at end of file