diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.Syntax.cs
new file mode 100644
index 00000000..73116592
--- /dev/null
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.Syntax.cs
@@ -0,0 +1,254 @@
+using System.Collections.Generic;
+using System.Collections.Immutable;
+using System.Text;
+using ComputeSharp.__Internals;
+using ComputeSharp.SourceGenerators.Models;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
+
+#pragma warning disable CS0618, RS1024
+
+namespace ComputeSharp.SourceGenerators;
+
+///
+public sealed partial class IShaderGenerator2
+{
+ ///
+ /// Creates a instance for the BuildHlslString method.
+ ///
+ /// The input instance to use.
+ /// The resulting instance for the BuildHlslString method.
+ private static MethodDeclarationSyntax CreateBuildHlslStringMethod(HlslSourceInfo hlslSourceInfo)
+ {
+ ImmutableArray bodyStatements = GenerateRenderMethodBody(hlslSourceInfo);
+
+ // This code produces a method declaration as follows:
+ //
+ // readonly void global::ComputeSharp.__Internals.IShader.BuildHlslString(ref global::ComputeSharp.__Internals.ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ)
+ // {
+ //
+ // }
+ return
+ MethodDeclaration(
+ PredefinedType(Token(SyntaxKind.VoidKeyword)),
+ Identifier("BuildHlslString"))
+ .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
+ .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
+ .AddParameterListParameters(
+ Parameter(Identifier("builder")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder")),
+ 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(bodyStatements));
+ }
+
+ ///
+ /// Produces the series of statements to build the current HLSL source.
+ ///
+ /// The input instance to use.
+ /// The series of statements to build the HLSL source to compile to execute the current shader.
+ private static ImmutableArray GenerateRenderMethodBody(HlslSourceInfo hlslSourceInfo)
+ {
+ ImmutableArray.Builder statements = ImmutableArray.CreateBuilder();
+ StringBuilder textBuilder = new();
+ int capturedDelegates = 0;
+ int prologueStatements = 0;
+ int sizeHint = 64;
+
+ void AppendLF()
+ {
+ textBuilder.Append('\n');
+ }
+
+ void AppendLine(string text)
+ {
+ textBuilder.Append(text);
+ }
+
+ void AppendParsedStatement(string text)
+ {
+ FlushText();
+
+ statements.Add(ParseStatement(text));
+ }
+
+ void FlushText()
+ {
+ if (textBuilder.Length > 0)
+ {
+ string text = textBuilder.ToString();
+
+ textBuilder.Append(text);
+
+ sizeHint += textBuilder.Length;
+
+ statements.Add(
+ ExpressionStatement(
+ InvocationExpression(
+ MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append")))
+ .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(text))))));
+
+ textBuilder.Clear();
+ }
+ }
+
+ // Declare the hashsets to track imported members and types from delegates, if needed
+ if (!hlslSourceInfo.Delegates.IsEmpty)
+ {
+ void DeclareMapping(int index, string name, IEnumerable items)
+ {
+ // global::System.Collections.Generic.HashSet = new();
+ statements.Insert(index,
+ LocalDeclarationStatement(VariableDeclaration(
+ GenericName(Identifier("global::System.Collections.Generic.HashSet"))
+ .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.StringKeyword))))
+ .AddVariables(
+ VariableDeclarator(Identifier(name))
+ .WithInitializer(EqualsValueClause(ImplicitObjectCreationExpression())))));
+
+ prologueStatements++;
+
+ // .Add("- ");
+ foreach (var item in items)
+ {
+ statements.Add(
+ ExpressionStatement(
+ InvocationExpression(
+ MemberAccessExpression(
+ SyntaxKind.SimpleMemberAccessExpression,
+ IdentifierName(name),
+ IdentifierName("Add")))
+ .AddArgumentListArguments(Argument(
+ LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item))))));
+
+ prologueStatements++;
+ }
+ }
+
+ DeclareMapping(0, "__typeNames", hlslSourceInfo.DefinedTypes);
+ DeclareMapping(1, "__constantNames", hlslSourceInfo.DefinedConstants);
+ DeclareMapping(2, "__methodNames", hlslSourceInfo.MethodSignatures);
+
+ // Go through all existing delegate fields, if any
+ foreach (string fieldName in hlslSourceInfo.Delegates)
+ {
+ // global::ComputeSharp.__Internals.ShaderMethodSourceAttribute __Attribute = global::ComputeSharp.__Internals.ShaderMethodSourceAttribute.GetForDelegate(, "");
+ statements.Add(
+ LocalDeclarationStatement(VariableDeclaration(IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}"))
+ .AddVariables(
+ VariableDeclarator(Identifier($"__{fieldName}Attribute"))
+ .WithInitializer(
+ EqualsValueClause(
+ InvocationExpression(
+ MemberAccessExpression(
+ SyntaxKind.SimpleMemberAccessExpression,
+ IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}"),
+ IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate))))
+ .AddArgumentListArguments(
+ Argument(IdentifierName(fieldName)),
+ Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(fieldName)))))))));
+
+ capturedDelegates++;
+ prologueStatements++;
+ }
+ }
+
+ // Header and thread ids
+ AppendLine(hlslSourceInfo.HeaderAndThreadsX);
+ AppendParsedStatement("builder.Append(threadsX);");
+ AppendLine(hlslSourceInfo.ThreadsY);
+ AppendParsedStatement("builder.Append(threadsY);");
+ AppendLine(hlslSourceInfo.ThreadsZ);
+ AppendParsedStatement("builder.Append(threadsZ);");
+
+ // Define declarations
+ AppendLine(hlslSourceInfo.Defines);
+
+ // Defines from captured delegates
+ foreach (string fieldName in hlslSourceInfo.Delegates)
+ {
+ AppendParsedStatement($"__{fieldName}Attribute.AppendConstants(ref builder, __constantNames);");
+ }
+
+ // Static fields and declared types
+ AppendLine(hlslSourceInfo.StaticFieldsAndDeclaredTypes);
+
+ // Declared types from captured delegates
+ foreach (string fieldName in hlslSourceInfo.Delegates)
+ {
+ AppendParsedStatement($"__{fieldName}Attribute.AppendTypes(ref builder, __typeNames);");
+ }
+
+ // Captured variables
+ AppendLine(hlslSourceInfo.CapturedFieldsAndResourcesAndForwardDeclarations);
+
+ // Forward declarations from captured delegates
+ foreach (string fieldName in hlslSourceInfo.Delegates)
+ {
+ AppendParsedStatement($"__{fieldName}Attribute.AppendForwardDeclarations(ref builder, __methodNames);");
+ }
+
+ // Remove all forward declarations from methods that are embedded into the shader.
+ // This is necessary to avoid duplicate definitions from methods from delegates.
+ if (capturedDelegates > 0)
+ {
+ // .Add("
- ");
+ foreach (string forwardDeclaration in hlslSourceInfo.MethodSignatures)
+ {
+ FlushText();
+
+ statements.Add(
+ ExpressionStatement(
+ InvocationExpression(
+ MemberAccessExpression(
+ SyntaxKind.SimpleMemberAccessExpression,
+ IdentifierName("__methodNames"),
+ IdentifierName("Remove")))
+ .AddArgumentListArguments(Argument(
+ LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(forwardDeclaration))))));
+ }
+ }
+
+ // Captured methods
+ AppendLine(hlslSourceInfo.CapturedMethods);
+
+ // Captured methods from captured delegates
+ foreach (string fieldName in hlslSourceInfo.Delegates)
+ {
+ AppendParsedStatement($"__{fieldName}Attribute.AppendMethods(ref builder, __methodNames);");
+ }
+
+ // Captured delegate methods
+ foreach (string fieldName in hlslSourceInfo.Delegates)
+ {
+ AppendLF();
+ AppendParsedStatement($"__{fieldName}Attribute.AppendMappedInvokeMethod(ref builder, \"{fieldName}\");");
+ AppendLF();
+ }
+
+ // Entry point
+ AppendLine(hlslSourceInfo.EntryPoint);
+
+ FlushText();
+
+ // builder = global::ComputeSharp.__Internals.ArrayPoolStringBuilder.Create();
+ statements.Insert(
+ prologueStatements,
+ ExpressionStatement(
+ AssignmentExpression(
+ SyntaxKind.SimpleAssignmentExpression,
+ IdentifierName("builder"),
+ InvocationExpression(
+ MemberAccessExpression(
+ SyntaxKind.SimpleMemberAccessExpression,
+ IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder"),
+ IdentifierName("Create")))
+ .AddArgumentListArguments(
+ Argument(LiteralExpression(
+ SyntaxKind.NumericLiteralExpression,
+ Literal(sizeHint)))))));
+
+ return statements.ToImmutable();
+ }
+}
diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.cs
index db244bee..e5ecf8c2 100644
--- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.cs
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.cs
@@ -1,10 +1,19 @@
-using System.Collections.Generic;
+using System;
+using System.Collections.Generic;
using System.Collections.Immutable;
+using System.Diagnostics.Contracts;
+using System.Linq;
using System.Text;
-using ComputeSharp.__Internals;
+using ComputeSharp.SourceGenerators.Diagnostics;
+using ComputeSharp.SourceGenerators.Extensions;
+using ComputeSharp.SourceGenerators.Helpers;
+using ComputeSharp.SourceGenerators.Mappings;
using ComputeSharp.SourceGenerators.Models;
+using ComputeSharp.SourceGenerators.SyntaxRewriters;
+using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
+using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618, RS1024
@@ -15,241 +24,703 @@ namespace ComputeSharp.SourceGenerators;
public sealed partial class IShaderGenerator2
{
///
- /// Creates a instance for the BuildHlslString method.
+ /// Gathers all necessary information on a transpiled HLSL source for a given shader type.
///
- /// The input instance to use.
- /// The resulting instance for the BuildHlslString method.
- private static MethodDeclarationSyntax CreateBuildHlslStringMethod(HlslSourceInfo hlslSourceInfo)
+ /// The input object currently in use.
+ /// The node to process.
+ /// The for .
+ /// The resulting diagnostics from the processing operation.
+ /// The resulting info on the processed shader.
+ private static HlslSourceInfo GetNonDynamicHlslSourceInfo(
+ Compilation compilation,
+ StructDeclarationSyntax structDeclaration,
+ INamedTypeSymbol structDeclarationSymbol,
+ out ImmutableArray diagnostics)
{
- ImmutableArray bodyStatements = GenerateRenderMethodBody(hlslSourceInfo);
+ ImmutableArray.Builder builder = ImmutableArray.CreateBuilder();
- // This code produces a method declaration as follows:
- //
- // readonly void global::ComputeSharp.__Internals.IShader.BuildHlslString(ref global::ComputeSharp.__Internals.ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ)
- // {
- //
- // }
- return
- MethodDeclaration(
- PredefinedType(Token(SyntaxKind.VoidKeyword)),
- Identifier("BuildHlslString"))
- .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
- .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
- .AddParameterListParameters(
- Parameter(Identifier("builder")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder")),
- 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(bodyStatements));
+ // Properties are not supported
+ DetectAndReportPropertyDeclarations(builder, structDeclarationSymbol);
+
+ // We need to sets to track all discovered custom types and static methods
+ HashSet discoveredTypes = new(SymbolEqualityComparer.Default);
+ Dictionary staticMethods = new(SymbolEqualityComparer.Default);
+ Dictionary constantDefinitions = new(SymbolEqualityComparer.Default);
+
+ // A given type can only represent a single shader type
+ if (structDeclarationSymbol.AllInterfaces.Count(static interfaceSymbol => interfaceSymbol is { Name: nameof(IComputeShader) } or { IsGenericType: true, Name: nameof(IPixelShader) }) > 1)
+ {
+ builder.Add(MultipleShaderTypesImplemented, structDeclarationSymbol, structDeclarationSymbol);
+ }
+
+ // Explore the syntax tree and extract the processed info
+ var semanticModelProvider = new SemanticModelProvider(compilation);
+ var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) });
+ var isComputeShader = pixelShaderSymbol is null;
+ var implicitTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!);
+ var (resourceFields, valueFields) = GetInstanceFields(builder, structDeclarationSymbol, discoveredTypes, isComputeShader);
+ var delegateInstanceFields = GetDelegateFieldNames(structDeclarationSymbol);
+ var sharedBuffers = GetSharedBuffers(builder, structDeclarationSymbol, discoveredTypes);
+ var (entryPoint, processedMethods, isSamplerUsed) = GetProcessedMethods(builder, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, constantDefinitions, isComputeShader);
+ var implicitSamplerField = isSamplerUsed ? ("SamplerState", "__sampler") : default((string, string)?);
+ var declaredTypes = GetDeclaredTypes(discoveredTypes);
+ var definedConstants = GetDefinedConstants(constantDefinitions);
+ var staticFields = GetStaticFields(builder, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions);
+
+ diagnostics = builder.ToImmutable();
+
+ // Get the HLSL source data with the intermediate info
+ return GetNonDynamicHlslSourceInfo(
+ definedConstants,
+ declaredTypes,
+ resourceFields,
+ valueFields,
+ delegateInstanceFields,
+ staticFields,
+ sharedBuffers,
+ processedMethods,
+ isComputeShader,
+ implicitTextureType,
+ isSamplerUsed,
+ entryPoint);
+ }
+
+ ///
+ /// Gets a sequence of captured fields and their mapped names.
+ ///
+ /// The collection of produced instances.
+ /// The input instance to process.
+ /// The collection of currently discovered types.
+ /// Indicates whether or not represents a compute shader.
+ /// A sequence of captured fields in .
+ [Pure]
+ private static (
+ ImmutableArray<(string MetadataName, string Name, string HlslType)>,
+ ImmutableArray<(string Name, string HlslType)>)
+ GetInstanceFields(
+ ImmutableArray.Builder diagnostics,
+ INamedTypeSymbol structDeclarationSymbol,
+ ICollection types,
+ bool isComputeShader)
+ {
+ ImmutableArray<(string, string, string)>.Builder resources = ImmutableArray.CreateBuilder<(string, string, string)>();
+ ImmutableArray<(string, string)>.Builder values = ImmutableArray.CreateBuilder<(string, string)>();
+ bool hlslResourceFound = false;
+
+ foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType())
+ {
+ if (fieldSymbol.IsStatic)
+ {
+ continue;
+ }
+
+ AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) });
+
+ // Group shared fields must be static
+ if (attribute is not null)
+ {
+ diagnostics.Add(InvalidGroupSharedFieldDeclaration, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name);
+ }
+
+ // Captured fields must be named type symbols
+ if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol)
+ {
+ diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
+
+ continue;
+ }
+
+ string metadataName = typeSymbol.GetFullMetadataName();
+ string typeName = HlslKnownTypes.GetMappedName(typeSymbol);
+
+ _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
+
+ // Allowed fields must be either resources, unmanaged values or delegates
+ if (HlslKnownTypes.IsTypedResourceType(metadataName))
+ {
+ hlslResourceFound = true;
+
+ // Track the type of items in the current buffer
+ if (HlslKnownTypes.IsStructuredBufferType(metadataName))
+ {
+ types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]);
+ }
+
+ // Add the current mapping for the name (if the name used a reserved keyword)
+ resources.Add((metadataName, mapping ?? fieldSymbol.Name, typeName));
+ }
+ else if (!typeSymbol.IsUnmanagedType &&
+ typeSymbol.TypeKind != TypeKind.Delegate)
+ {
+ // Shaders can only capture valid HLSL resource types or unmanaged types
+ diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, typeSymbol);
+
+ continue;
+ }
+ else if (typeSymbol.IsUnmanagedType)
+ {
+ // Track the type if it's a custom struct
+ if (!HlslKnownTypes.IsKnownHlslType(metadataName))
+ {
+ types.Add(typeSymbol);
+ }
+
+ values.Add((mapping ?? fieldSymbol.Name, typeName));
+ }
+ }
+
+ // If the shader is a compute one (so no implicit output texture), it has to contain at least one resource
+ if (!hlslResourceFound && isComputeShader)
+ {
+ diagnostics.Add(MissingShaderResources, structDeclarationSymbol, structDeclarationSymbol);
+ }
+
+ return (resources.ToImmutable(), values.ToImmutable());
+ }
+
+ ///
+ /// Gets a sequence of shader static fields and their mapped names.
+ ///
+ /// The collection of produced instances.
+ /// The instance for the type to process.
+ /// The instance for the current type.
+ /// The type symbol for the shader type.
+ /// The collection of currently discovered types.
+ /// The collection of discovered constant definitions.
+ /// A sequence of static constant fields in .
+ [Pure]
+ private static ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields(
+ ImmutableArray.Builder diagnostics,
+ SemanticModelProvider semanticModel,
+ StructDeclarationSyntax structDeclaration,
+ INamedTypeSymbol structDeclarationSymbol,
+ ICollection discoveredTypes,
+ IDictionary constantDefinitions)
+ {
+ ImmutableArray<(string, string, string?)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, string?)>();
+
+ foreach (var fieldDeclaration in structDeclaration.Members.OfType())
+ {
+ foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables)
+ {
+ IFieldSymbol fieldSymbol = (IFieldSymbol)semanticModel.For(variableDeclarator).GetDeclaredSymbol(variableDeclarator)!;
+
+ if (!fieldSymbol.IsStatic || fieldSymbol.IsConst)
+ {
+ continue;
+ }
+
+ AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) });
+
+ if (attribute is not null)
+ {
+ continue;
+ }
+
+ // Constant properties must be of a primitive, vector or matrix type
+ if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol ||
+ !HlslKnownTypes.IsKnownHlslType(typeSymbol.GetFullMetadataName()))
+ {
+ diagnostics.Add(InvalidShaderStaticFieldType, variableDeclarator, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
+
+ continue;
+ }
+
+ _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
+
+ string typeDeclaration = fieldSymbol.IsReadOnly switch
+ {
+ true => $"static const {HlslKnownTypes.GetMappedName(typeSymbol)}",
+ false => $"static {HlslKnownTypes.GetMappedName(typeSymbol)}"
+ };
+
+ StaticFieldRewriter2 staticFieldRewriter = new(
+ semanticModel,
+ discoveredTypes,
+ constantDefinitions,
+ diagnostics);
+
+ string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace(eol: "\n").ToFullString();
+
+ builder.Add((mapping ?? fieldSymbol.Name, typeDeclaration, assignment));
+ }
+ }
+
+ return builder.ToImmutable();
+ }
+
+ ///
+ /// Gets a sequence of captured members and their mapped names.
+ ///
+ /// The collection of produced instances.
+ /// The input instance to process.
+ /// The collection of currently discovered types.
+ /// A sequence of captured members in .
+ [Pure]
+ private static ImmutableArray<(string Name, string Type, int? Count)> GetSharedBuffers(
+ ImmutableArray.Builder diagnostics,
+ INamedTypeSymbol structDeclarationSymbol,
+ ICollection types)
+ {
+ ImmutableArray<(string, string, int?)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, int?)>();
+
+ foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType())
+ {
+ if (!fieldSymbol.IsStatic)
+ {
+ continue;
+ }
+
+ AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) });
+
+ if (attribute is null)
+ {
+ continue;
+ }
+
+ if (fieldSymbol.Type is not IArrayTypeSymbol typeSymbol)
+ {
+ diagnostics.Add(InvalidGroupSharedFieldType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
+
+ continue;
+ }
+
+ if (!typeSymbol.ElementType.IsUnmanagedType)
+ {
+ diagnostics.Add(InvalidGroupSharedFieldElementType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
+
+ continue;
+ }
+
+ int? bufferSize = (int?)attribute.ConstructorArguments.FirstOrDefault().Value;
+
+ string typeName = HlslKnownTypes.GetMappedElementName(typeSymbol);
+
+ _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
+
+ builder.Add((mapping ?? fieldSymbol.Name, typeName, bufferSize));
+
+ types.Add((INamedTypeSymbol)typeSymbol.ElementType);
+ }
+
+ return builder.ToImmutable();
+ }
+
+ ///
+ /// Gets a sequence of processed methods declared within a given type.
+ ///
+ /// The collection of produced instances.
+ /// The type symbol for the shader type.
+ /// The instance for the current type.
+ /// The instance for the type to process.
+ /// The collection of currently discovered types.
+ /// The set of discovered and processed static methods.
+ /// The collection of discovered constant definitions.
+ /// Indicates whether or not represents a compute shader.
+ /// A sequence of processed methods in , and the entry point.
+ [Pure]
+ private static (string EntryPoint, ImmutableArray<(string Signature, string Definition)> Methods, bool IsSamplerUser) GetProcessedMethods(
+ ImmutableArray.Builder diagnostics,
+ StructDeclarationSyntax structDeclaration,
+ INamedTypeSymbol structDeclarationSymbol,
+ SemanticModelProvider semanticModel,
+ ICollection discoveredTypes,
+ IDictionary staticMethods,
+ IDictionary constantDefinitions,
+ bool isComputeShader)
+ {
+ // Find all declared methods in the type
+ ImmutableArray methodDeclarations = (
+ from syntaxNode in structDeclaration.DescendantNodes()
+ where syntaxNode.IsKind(SyntaxKind.MethodDeclaration)
+ select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray();
+
+ string? entryPoint = null;
+ ImmutableArray<(string, string)>.Builder methods = ImmutableArray.CreateBuilder<(string, string)>();
+ bool isSamplerUsed = false;
+
+ foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations)
+ {
+ IMethodSymbol methodDeclarationSymbol = semanticModel.For(methodDeclaration).GetDeclaredSymbol(methodDeclaration)!;
+ bool isShaderEntryPoint =
+ (isComputeShader &&
+ methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) &&
+ methodDeclarationSymbol.ReturnsVoid &&
+ methodDeclarationSymbol.TypeParameters.Length == 0 &&
+ methodDeclarationSymbol.Parameters.Length == 0) ||
+ (!isComputeShader &&
+ methodDeclarationSymbol.Name == nameof(IPixelShader.Execute) &&
+ methodDeclarationSymbol.ReturnType is not null && // TODO: match for pixel type
+ methodDeclarationSymbol.TypeParameters.Length == 0 &&
+ methodDeclarationSymbol.Parameters.Length == 0);
+
+ // Create the source rewriter for the current method
+ ShaderSourceRewriter2 shaderSourceRewriter = new(
+ structDeclarationSymbol,
+ semanticModel,
+ discoveredTypes,
+ staticMethods,
+ constantDefinitions,
+ diagnostics,
+ isShaderEntryPoint);
+
+ // Rewrite the method syntax tree
+ MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia();
+
+ // Track the implicit sampler, if used
+ isSamplerUsed = isSamplerUsed || shaderSourceRewriter.IsSamplerUsed;
+
+ // Emit the extracted local functions first
+ foreach (var localFunction in shaderSourceRewriter.LocalFunctions)
+ {
+ methods.Add((
+ localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
+ localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString()));
+ }
+
+ // If the method is the shader entry point, do additional processing
+ if (isShaderEntryPoint)
+ {
+ processedMethod = isComputeShader switch
+ {
+ true => new ExecuteMethodRewriter2.Compute(shaderSourceRewriter).Visit(processedMethod)!,
+ false => new ExecuteMethodRewriter2.Pixel(shaderSourceRewriter).Visit(processedMethod)!
+ };
+
+ entryPoint = processedMethod.NormalizeWhitespace(eol: "\n").ToFullString();
+ }
+ else
+ {
+ methods.Add((
+ processedMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
+ processedMethod.NormalizeWhitespace(eol: "\n").ToFullString()));
+ }
+ }
+
+ // Process static methods as well
+ foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values)
+ {
+ methods.Add((
+ staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
+ staticMethod.NormalizeWhitespace(eol: "\n").ToFullString()));
+ }
+
+ return (entryPoint!, methods.ToImmutable(), isSamplerUsed);
+ }
+
+ ///
+ /// Gets a sequence of discovered constants.
+ ///
+ /// The collection of discovered constant definitions.
+ /// A sequence of discovered constants to declare in the shader.
+ [Pure]
+ internal static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary constantDefinitions)
+ {
+ ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(constantDefinitions.Count);
+
+ foreach (var constant in constantDefinitions)
+ {
+ var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName();
+ var constantName = $"__{ownerTypeName}__{constant.Key.Name}";
+
+ builder.Add((constantName, constant.Value));
+ }
+
+ return builder.MoveToImmutable();
+ }
+
+ ///
+ /// Gets the sequence of processed discovered custom types.
+ ///
+ /// The sequence of discovered custom types.
+ /// A sequence of custom type definitions to add to the shader source.
+ internal static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes(IEnumerable types)
+ {
+ ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>();
+
+ foreach (var type in HlslKnownTypes.GetCustomTypes(types))
+ {
+ var structType = type.GetFullMetadataName().ToHlslIdentifierName();
+ var structDeclaration = StructDeclaration(structType);
+
+ // Declare the fields of the current type
+ foreach (var field in type.GetMembers().OfType())
+ {
+ if (field.IsStatic) continue;
+
+ INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type;
+
+ // Convert the name to the fully qualified HLSL version
+ if (!HlslKnownTypes.TryGetMappedName(fieldType.GetFullMetadataName(), out string? mapped))
+ {
+ mapped = fieldType.GetFullMetadataName().ToHlslIdentifierName();
+ }
+
+ structDeclaration = structDeclaration.AddMembers(
+ FieldDeclaration(VariableDeclaration(
+ IdentifierName(mapped!)).AddVariables(
+ VariableDeclarator(Identifier(field.Name)))));
+ }
+
+ // Insert the trailing ; right after the closing bracket (after normalization)
+ builder.Add((
+ structType,
+ structDeclaration
+ .NormalizeWhitespace(eol: "\n")
+ .WithSemicolonToken(Token(SyntaxKind.SemicolonToken))
+ .ToFullString()));
+ }
+
+ return builder.ToImmutable();
+ }
+
+ ///
+ /// Finds and reports all declared properties in a shader.
+ ///
+ /// The collection of produced instances.
+ /// The input instance to process.
+ private static void DetectAndReportPropertyDeclarations(ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol)
+ {
+ foreach (var propertySymbol in structDeclarationSymbol.GetMembers().OfType())
+ {
+ diagnostics.Add(DiagnosticDescriptors.PropertyDeclaration, propertySymbol);
+ }
}
///
/// Produces the series of statements to build the current HLSL source.
///
- /// The input instance to use.
+ /// The sequence of defined constants for the shader.
+ /// The sequence of declared types used by the shader.
+ /// The sequence of resource instance fields for the current shader.
+ /// The sequence of value instance fields for the current shader.
+ /// The sequence of delegate fields for the current shader.
+ /// The sequence of static fields referenced by the shader.
+ /// The sequence of shared buffers declared by the shader.
+ /// The sequence of processed methods used by the shader.
+ /// Whether or not the current shader type is a compute shader.
+ /// The type of the implicit target texture, if present.
+ /// Whether the static sampler is used by the shader.
+ /// The body of the entry point of the shader.
/// The series of statements to build the HLSL source to compile to execute the current shader.
- private static ImmutableArray GenerateRenderMethodBody(HlslSourceInfo hlslSourceInfo)
+ private static HlslSourceInfo GetNonDynamicHlslSourceInfo(
+ ImmutableArray<(string Name, string Value)> definedConstants,
+ ImmutableArray<(string Name, string Definition)> declaredTypes,
+ ImmutableArray<(string MetadataName, string Name, string HlslType)> resourceFields,
+ ImmutableArray<(string Name, string HlslType)> valueFields,
+ ImmutableArray delegateInstanceFields,
+ ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> staticFields,
+ ImmutableArray<(string Name, string Type, int? Count)> sharedBuffers,
+ ImmutableArray<(string Signature, string Definition)> processedMethods,
+ bool isComputeShader,
+ string? implicitTextureType,
+ bool isSamplerUsed,
+
+ string executeMethod)
{
- ImmutableArray.Builder statements = ImmutableArray.CreateBuilder();
- StringBuilder textBuilder = new();
- int capturedDelegates = 0;
- int prologueStatements = 0;
- int sizeHint = 64;
+ StringBuilder hlslBuilder = new();
void AppendLF()
{
- textBuilder.Append('\n');
+ hlslBuilder.Append('\n');
}
void AppendLine(string text)
{
- textBuilder.Append(text);
+ hlslBuilder.Append(text);
}
- void AppendParsedStatement(string text)
+ void AppendLineAndLF(string text)
{
- FlushText();
-
- statements.Add(ParseStatement(text));
+ hlslBuilder.Append(text);
+ hlslBuilder.Append('\n');
}
- void FlushText()
+ void AppendCharacterAndLF(char c)
{
- if (textBuilder.Length > 0)
- {
- string text = textBuilder.ToString();
-
- textBuilder.Append(text);
-
- sizeHint += textBuilder.Length;
-
- statements.Add(
- ExpressionStatement(
- InvocationExpression(
- MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append")))
- .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(text))))));
-
- textBuilder.Clear();
- }
+ hlslBuilder.Append(c);
+ hlslBuilder.Append('\n');
}
- // Declare the hashsets to track imported members and types from delegates, if needed
- if (!hlslSourceInfo.Delegates.IsEmpty)
+ string FlushText()
{
- void DeclareMapping(int index, string name, IEnumerable items)
- {
- // global::System.Collections.Generic.HashSet = new();
- statements.Insert(index,
- LocalDeclarationStatement(VariableDeclaration(
- GenericName(Identifier("global::System.Collections.Generic.HashSet"))
- .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.StringKeyword))))
- .AddVariables(
- VariableDeclarator(Identifier(name))
- .WithInitializer(EqualsValueClause(ImplicitObjectCreationExpression())))));
+ string text = hlslBuilder.ToString();
- prologueStatements++;
+ hlslBuilder.Clear();
- // .Add("
- ");
- foreach (var item in items)
- {
- statements.Add(
- ExpressionStatement(
- InvocationExpression(
- MemberAccessExpression(
- SyntaxKind.SimpleMemberAccessExpression,
- IdentifierName(name),
- IdentifierName("Add")))
- .AddArgumentListArguments(Argument(
- LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item))))));
-
- prologueStatements++;
- }
- }
-
- DeclareMapping(0, "__typeNames", hlslSourceInfo.DefinedTypes);
- DeclareMapping(1, "__constantNames", hlslSourceInfo.DefinedConstants);
- DeclareMapping(2, "__methodNames", hlslSourceInfo.MethodSignatures);
-
- // Go through all existing delegate fields, if any
- foreach (string fieldName in hlslSourceInfo.Delegates)
- {
- // global::ComputeSharp.__Internals.ShaderMethodSourceAttribute __Attribute = global::ComputeSharp.__Internals.ShaderMethodSourceAttribute.GetForDelegate(, "");
- statements.Add(
- LocalDeclarationStatement(VariableDeclaration(IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}"))
- .AddVariables(
- VariableDeclarator(Identifier($"__{fieldName}Attribute"))
- .WithInitializer(
- EqualsValueClause(
- InvocationExpression(
- MemberAccessExpression(
- SyntaxKind.SimpleMemberAccessExpression,
- IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}"),
- IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate))))
- .AddArgumentListArguments(
- Argument(IdentifierName(fieldName)),
- Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(fieldName)))))))));
-
- capturedDelegates++;
- prologueStatements++;
- }
+ return text;
}
- // Header and thread ids
- AppendLine(hlslSourceInfo.HeaderAndThreadsX);
- AppendParsedStatement("builder.Append(threadsX);");
- AppendLine(hlslSourceInfo.ThreadsY);
- AppendParsedStatement("builder.Append(threadsY);");
- AppendLine(hlslSourceInfo.ThreadsZ);
- AppendParsedStatement("builder.Append(threadsZ);");
+ // Header
+ AppendLineAndLF("// ================================================");
+ AppendLineAndLF("// AUTO GENERATED");
+ AppendLineAndLF("// ================================================");
+ AppendLineAndLF("// This shader was created by ComputeSharp.");
+ AppendLineAndLF("// See: https://github.com/Sergio0694/ComputeSharp.");
+
+ // Group size constants
+ AppendLF();
+ AppendLine("#define __GroupSize__get_X ");
+
+ string headerAndThreadsX = FlushText();
+
+ AppendLF();
+ AppendLine("#define __GroupSize__get_Y ");
+
+ string threadsY = FlushText();
+
+ AppendLF();
+ AppendLine("#define __GroupSize__get_Z ");
+
+ string threadsZ = FlushText();
+
+ AppendLF();
// Define declarations
- AppendLine(hlslSourceInfo.Defines);
-
- // Defines from captured delegates
- foreach (string fieldName in hlslSourceInfo.Delegates)
+ foreach (var (name, value) in definedConstants)
{
- AppendParsedStatement($"__{fieldName}Attribute.AppendConstants(ref builder, __constantNames);");
+ AppendLineAndLF($"#define {name} {value}");
}
- // Static fields and declared types
- AppendLine(hlslSourceInfo.StaticFieldsAndDeclaredTypes);
+ string defines = FlushText();
- // Declared types from captured delegates
- foreach (string fieldName in hlslSourceInfo.Delegates)
+ // Static fields
+ if (staticFields.Any())
{
- AppendParsedStatement($"__{fieldName}Attribute.AppendTypes(ref builder, __typeNames);");
- }
+ AppendLF();
- // Captured variables
- AppendLine(hlslSourceInfo.CapturedFieldsAndResourcesAndForwardDeclarations);
-
- // Forward declarations from captured delegates
- foreach (string fieldName in hlslSourceInfo.Delegates)
- {
- AppendParsedStatement($"__{fieldName}Attribute.AppendForwardDeclarations(ref builder, __methodNames);");
- }
-
- // Remove all forward declarations from methods that are embedded into the shader.
- // This is necessary to avoid duplicate definitions from methods from delegates.
- if (capturedDelegates > 0)
- {
- // .Add("
- ");
- foreach (string forwardDeclaration in hlslSourceInfo.MethodSignatures)
+ foreach (var field in staticFields)
{
- FlushText();
-
- statements.Add(
- ExpressionStatement(
- InvocationExpression(
- MemberAccessExpression(
- SyntaxKind.SimpleMemberAccessExpression,
- IdentifierName("__methodNames"),
- IdentifierName("Remove")))
- .AddArgumentListArguments(Argument(
- LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(forwardDeclaration))))));
+ if (field.Assignment is string assignment)
+ {
+ AppendLineAndLF($"{field.TypeDeclaration} {field.Name} = {assignment};");
+ }
+ else
+ {
+ AppendLineAndLF($"{field.TypeDeclaration} {field.Name};");
+ }
}
}
+ // Declared types
+ foreach (var (_, typeDefinition) in declaredTypes)
+ {
+ AppendLF();
+ AppendLineAndLF(typeDefinition);
+ }
+
+ string staticFieldsAndDeclaredTypes = FlushText();
+
+ // Captured variables
+ AppendLF();
+ AppendLineAndLF("cbuffer _ : register(b0)");
+ AppendCharacterAndLF('{');
+ AppendLineAndLF(" uint __x;");
+ AppendLineAndLF(" uint __y;");
+
+ if (isComputeShader)
+ {
+ AppendLineAndLF(" uint __z;");
+ }
+
+ // User-defined values
+ foreach (var (fieldName, fieldType) in valueFields)
+ {
+ AppendLineAndLF($" {fieldType} {fieldName};");
+ }
+
+ AppendCharacterAndLF('}');
+
+ int constantBuffersCount = 1;
+ int readOnlyBuffersCount = 0;
+ int readWriteBuffersCount = 0;
+
+ // Optional implicit texture field
+ if (!isComputeShader)
+ {
+ AppendLF();
+ AppendLineAndLF($"{implicitTextureType} __outputTexture : register(u{readWriteBuffersCount++});");
+ }
+
+ // Optional sampler field
+ if (isSamplerUsed)
+ {
+ AppendLF();
+ AppendLineAndLF("SamplerState __sampler : register(s);");
+ }
+
+ // Resources
+ foreach (var (metadataName, fieldName, fieldType) in resourceFields)
+ {
+ if (HlslKnownTypes.IsConstantBufferType(metadataName))
+ {
+ AppendLF();
+ AppendLineAndLF($"cbuffer _{fieldName} : register(b{constantBuffersCount++})");
+ AppendCharacterAndLF('{');
+ AppendLineAndLF($" {fieldType} {fieldName}[2];");
+ AppendCharacterAndLF('}');
+ }
+ else if (HlslKnownTypes.IsReadOnlyTypedResourceType(metadataName))
+ {
+ AppendLF();
+ AppendLineAndLF($"{fieldType} {fieldName} : register(t{readOnlyBuffersCount++});");
+ }
+ else if (HlslKnownTypes.IsReadWriteTypedResourceType(metadataName))
+ {
+ AppendLF();
+ AppendLineAndLF($"{fieldType} {fieldName} : register(u{readWriteBuffersCount++});");
+ }
+ }
+
+ // Shared buffers
+ foreach (var (bufferName, bufferType, bufferCount) in sharedBuffers)
+ {
+ object count = (object?)bufferCount ?? "threadsX * threadsY * threadsZ";
+
+ AppendLF();
+ AppendLineAndLF($"groupshared {bufferType} {bufferName} [{count}];");
+ }
+
+ // Forward declarations
+ foreach (var (forwardDeclaration, _) in processedMethods)
+ {
+ AppendLF();
+ AppendLineAndLF(forwardDeclaration);
+ }
+
+ string capturedFieldsAndResourcesAndForwardDeclarations = FlushText();
+
// Captured methods
- AppendLine(hlslSourceInfo.CapturedMethods);
-
- // Captured methods from captured delegates
- foreach (string fieldName in hlslSourceInfo.Delegates)
- {
- AppendParsedStatement($"__{fieldName}Attribute.AppendMethods(ref builder, __methodNames);");
- }
-
- // Captured delegate methods
- foreach (string fieldName in hlslSourceInfo.Delegates)
+ foreach (var (_, method) in processedMethods)
{
AppendLF();
- AppendParsedStatement($"__{fieldName}Attribute.AppendMappedInvokeMethod(ref builder, \"{fieldName}\");");
- AppendLF();
+ AppendLineAndLF(method);
}
+ string capturedMethods = FlushText();
+
// Entry point
- AppendLine(hlslSourceInfo.EntryPoint);
+ AppendLF();
+ AppendLineAndLF("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]");
+ AppendLineAndLF(executeMethod);
- FlushText();
+ string entryPoint = FlushText();
- // builder = global::ComputeSharp.__Internals.ArrayPoolStringBuilder.Create();
- statements.Insert(
- prologueStatements,
- ExpressionStatement(
- AssignmentExpression(
- SyntaxKind.SimpleAssignmentExpression,
- IdentifierName("builder"),
- InvocationExpression(
- MemberAccessExpression(
- SyntaxKind.SimpleMemberAccessExpression,
- IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder"),
- IdentifierName("Create")))
- .AddArgumentListArguments(
- Argument(LiteralExpression(
- SyntaxKind.NumericLiteralExpression,
- Literal(sizeHint)))))));
-
- return statements.ToImmutable();
+ return new(
+ headerAndThreadsX,
+ threadsY,
+ threadsZ,
+ defines,
+ staticFieldsAndDeclaredTypes,
+ capturedFieldsAndResourcesAndForwardDeclarations,
+ capturedMethods,
+ entryPoint,
+ implicitTextureType,
+ isSamplerUsed,
+ declaredTypes.Select(static t => t.Name).ToImmutableArray(),
+ definedConstants.Select(static c => c.Name).ToImmutableArray(),
+ processedMethods.Select(static m => m.Signature).ToImmutableArray(),
+ delegateInstanceFields);
}
///
diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.Syntax.cs
new file mode 100644
index 00000000..fe0e9a61
--- /dev/null
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.Syntax.cs
@@ -0,0 +1,94 @@
+using System.Collections.Generic;
+using System.Collections.Immutable;
+using System.Diagnostics.Contracts;
+using ComputeSharp.__Internals;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
+
+#pragma warning disable CS0618
+
+namespace ComputeSharp.SourceGenerators;
+
+///
+public sealed partial class IShaderGenerator2
+{
+ ///
+ /// Creates a instance for the GetDispatchId method.
+ ///
+ ///The names of all instance fields within the current shader type.
+ /// The resulting instance for the GetDispatchId method.
+ private static MethodDeclarationSyntax CreateGetDispatchIdMethod(ImmutableArray delegateFieldNames)
+ {
+ // This code produces a method declaration as follows:
+ //
+ // readonly int global::ComputeSharp.__Internals.IShader.GetDispatchId()
+ // {
+ //
+ // }
+ return
+ MethodDeclaration(
+ PredefinedType(Token(SyntaxKind.IntKeyword)),
+ Identifier("GetDispatchId"))
+ .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
+ .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
+ .WithBody(GetShaderHashCodeBody(delegateFieldNames));
+ }
+
+ ///
+ /// Gets a instance with the logic to compute the hashcode of a given shader type.
+ ///
+ /// The names of all instance fields within the current shader type.
+ /// The instance to hash the input shader.
+ [Pure]
+ private static BlockSyntax GetShaderHashCodeBody(ImmutableArray delegateFieldNames)
+ {
+ if (delegateFieldNames.Length == 0)
+ {
+ // return 0;
+ return
+ Block(ReturnStatement(
+ LiteralExpression(
+ SyntaxKind.NumericLiteralExpression,
+ Literal(0))));
+ }
+
+ List blockStatements = new(4);
+
+ // global::System.HashCode hashCode = default;
+ blockStatements.Add(LocalDeclarationStatement(
+ VariableDeclaration(IdentifierName("global::System.HashCode"))
+ .AddVariables(
+ VariableDeclarator(Identifier("hashCode"))
+ .WithInitializer(EqualsValueClause(
+ LiteralExpression(
+ SyntaxKind.DefaultLiteralExpression,
+ Token(SyntaxKind.DefaultKeyword)))))));
+
+ foreach (string fieldName in delegateFieldNames)
+ {
+ // hashCode.Add(delegateField.Method);
+ blockStatements.Add(ExpressionStatement(
+ InvocationExpression(
+ MemberAccessExpression(
+ SyntaxKind.SimpleMemberAccessExpression,
+ IdentifierName("hashCode"),
+ IdentifierName("Add")))
+ .AddArgumentListArguments(Argument(
+ MemberAccessExpression(
+ SyntaxKind.SimpleMemberAccessExpression,
+ IdentifierName(fieldName),
+ IdentifierName("Method"))))));
+ }
+
+ // return hashCode.ToHashCode();
+ blockStatements.Add(ReturnStatement(
+ InvocationExpression(
+ MemberAccessExpression(
+ SyntaxKind.SimpleMemberAccessExpression,
+ IdentifierName("hashCode"),
+ IdentifierName("ToHashCode")))));
+
+ return Block(blockStatements);
+ }
+}
diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.cs
index 93f92739..9ea1324f 100644
--- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.cs
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.cs
@@ -1,14 +1,7 @@
-using System.Collections.Generic;
-using System.Collections.Immutable;
+using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using System.Linq;
-using ComputeSharp.__Internals;
using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
-
-#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators;
@@ -31,83 +24,4 @@ public sealed partial class IShaderGenerator2
.Select(static member => member.Name)
.ToImmutableArray();
}
-
- ///
- /// Creates a instance for the GetDispatchId method.
- ///
- ///The names of all instance fields within the current shader type.
- /// The resulting instance for the GetDispatchId method.
- private static MethodDeclarationSyntax CreateGetDispatchIdMethod(ImmutableArray delegateFieldNames)
- {
- // This code produces a method declaration as follows:
- //
- // readonly int global::ComputeSharp.__Internals.IShader.GetDispatchId()
- // {
- //
- // }
- return
- MethodDeclaration(
- PredefinedType(Token(SyntaxKind.IntKeyword)),
- Identifier("GetDispatchId"))
- .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
- .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
- .WithBody(GetShaderHashCodeBody(delegateFieldNames));
- }
-
- ///
- /// Gets a instance with the logic to compute the hashcode of a given shader type.
- ///
- /// The names of all instance fields within the current shader type.
- /// The instance to hash the input shader.
- [Pure]
- private static BlockSyntax GetShaderHashCodeBody(ImmutableArray delegateFieldNames)
- {
- if (delegateFieldNames.Length == 0)
- {
- // return 0;
- return
- Block(ReturnStatement(
- LiteralExpression(
- SyntaxKind.NumericLiteralExpression,
- Literal(0))));
- }
-
- List blockStatements = new(4);
-
- // global::System.HashCode hashCode = default;
- blockStatements.Add(LocalDeclarationStatement(
- VariableDeclaration(IdentifierName("global::System.HashCode"))
- .AddVariables(
- VariableDeclarator(Identifier("hashCode"))
- .WithInitializer(EqualsValueClause(
- LiteralExpression(
- SyntaxKind.DefaultLiteralExpression,
- Token(SyntaxKind.DefaultKeyword)))))));
-
- foreach (string fieldName in delegateFieldNames)
- {
- // hashCode.Add(delegateField.Method);
- blockStatements.Add(ExpressionStatement(
- InvocationExpression(
- MemberAccessExpression(
- SyntaxKind.SimpleMemberAccessExpression,
- IdentifierName("hashCode"),
- IdentifierName("Add")))
- .AddArgumentListArguments(Argument(
- MemberAccessExpression(
- SyntaxKind.SimpleMemberAccessExpression,
- IdentifierName(fieldName),
- IdentifierName("Method"))))));
- }
-
- // return hashCode.ToHashCode();
- blockStatements.Add(ReturnStatement(
- InvocationExpression(
- MemberAccessExpression(
- SyntaxKind.SimpleMemberAccessExpression,
- IdentifierName("hashCode"),
- IdentifierName("ToHashCode")))));
-
- return Block(blockStatements);
- }
}
diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.Syntax.cs
new file mode 100644
index 00000000..65e63abb
--- /dev/null
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.Syntax.cs
@@ -0,0 +1,245 @@
+using System;
+using System.Collections.Immutable;
+using ComputeSharp.__Internals;
+using ComputeSharp.SourceGenerators.Models;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
+
+#pragma warning disable CS0618
+
+namespace ComputeSharp.SourceGenerators;
+
+///
+public sealed partial class IShaderGenerator2
+{
+ ///
+ /// Creates a instance for the LoadDispatchDataMethod method.
+ ///
+ /// The type of shader interface urrently being processed.
+ /// The array of values for all captured fields.
+ /// The total number of captured resources in the shader.
+ /// The total number of needed 32 bit constants in the shader root signature.
+ /// The resulting instance for the LoadDispatchDataMethod method.
+ private static MethodDeclarationSyntax CreateLoadDispatchDataMethod(
+ Type shaderInterfaceType,
+ ImmutableArray fieldInfos,
+ int resourceCount,
+ int root32BitConstantsCount)
+ {
+ // This code produces a method declaration as follows:
+ //
+ // readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchData(ref TDataLoader loader, global::ComputeSharp.GraphicsDevice device, int x, int y, int z)
+ // {
+ //
+ // }
+ return
+ MethodDeclaration(
+ PredefinedType(Token(SyntaxKind.VoidKeyword)),
+ Identifier("LoadDispatchData"))
+ .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
+ .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
+ .AddTypeParameterListParameters(TypeParameter(Identifier("TDataLoader")))
+ .AddParameterListParameters(
+ Parameter(Identifier("loader"))
+ .AddModifiers(Token(SyntaxKind.RefKeyword))
+ .WithType(IdentifierName("TDataLoader")),
+ Parameter(Identifier("device")).WithType(IdentifierName("global::ComputeSharp.GraphicsDevice")),
+ Parameter(Identifier("x")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
+ Parameter(Identifier("y")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
+ Parameter(Identifier("z")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))))
+ .WithBody(Block(GetDispatchDataLoadingStatements(shaderInterfaceType, fieldInfos, resourceCount, root32BitConstantsCount)));
+ }
+
+ ///
+ /// Gets a sequence of statements to load the dispatch data for a given shader.
+ ///
+ /// The type of shader interface urrently being processed.
+ /// The array of values for all captured fields.
+ /// The total number of captured resources in the shader.
+ /// The total number of needed 32 bit constants in the shader root signature.
+ /// The sequence of instances to load shader dispatch data.
+ private static ImmutableArray GetDispatchDataLoadingStatements(
+ Type shaderInterfaceType,
+ ImmutableArray fieldInfos,
+ int resourceCount,
+ int root32BitConstantsCount)
+ {
+ ImmutableArray.Builder statements = ImmutableArray.CreateBuilder();
+ bool isComputeShader = shaderInterfaceType == typeof(IComputeShader);
+
+ // Append the statements for the dispatch ranges:
+ //
+ // span0[0] = (uint)x;
+ // span0[1] = (uint)y;
+ // span0[2] = (uint)z;
+ statements.Add(
+ ExpressionStatement(
+ AssignmentExpression(
+ SyntaxKind.SimpleAssignmentExpression,
+ ElementAccessExpression(IdentifierName("span0"))
+ .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))),
+ CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("x")))));
+
+ statements.Add(
+ ExpressionStatement(
+ AssignmentExpression(
+ SyntaxKind.SimpleAssignmentExpression,
+ ElementAccessExpression(IdentifierName("span0"))
+ .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1)))),
+ CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("y")))));
+
+ // If the shader is a compute shader, also track the bounds on the Z axis
+ if (isComputeShader)
+ {
+ statements.Add(
+ ExpressionStatement(
+ AssignmentExpression(
+ SyntaxKind.SimpleAssignmentExpression,
+ ElementAccessExpression(IdentifierName("span0"))
+ .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(2)))),
+ CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("z")))));
+ }
+
+ // Generate loading statements for each captured field
+ foreach (FieldInfo fieldInfo in fieldInfos)
+ {
+ switch (fieldInfo)
+ {
+ case FieldInfo.Resource resource:
+
+ // Validate the resource and get a handle for it. This will generate:
+ //
+ // global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, ) =
+ // global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(, device);
+ statements.Add(ExpressionStatement(
+ AssignmentExpression(
+ SyntaxKind.SimpleAssignmentExpression,
+ ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resource.Offset})"),
+ ParseExpression($"global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({resource.FieldName}, device)"))));
+ break;
+ case FieldInfo.Primitive primitive:
+
+ // Read a primitive value and serialize it into the target buffer. This will generate:
+ //
+ // global::System.Runtime.CompilerServices.Unsafe.As>(
+ // ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint))) =
+ statements.Add(ExpressionStatement(
+ AssignmentExpression(
+ SyntaxKind.SimpleAssignmentExpression,
+ ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){primitive.Offset}))"),
+ ParseExpression($"{string.Join(".", primitive.FieldPath)}"))));
+ break;
+
+ case FieldInfo.NonLinearMatrix matrix:
+ string rowTypeName = $"global::ComputeSharp.{matrix.ElementName}{matrix.Columns}";
+ string rowLocalName = $"__{string.Join("_", matrix.FieldPath)}__row0";
+
+ // Declare a local to index into individual rows. This will generate:
+ //
+ // ref = ref global::System.Runtime.CompilerServices.Unsafe.As, >(
+ // ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in ));
+ statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in {string.Join(".", matrix.FieldPath)}));"));
+
+ // Generate the loading code for each individual row, with proper alignment.
+ // This will result in the following (assuming Float2x3 m):
+ //
+ // ref global::ComputeSharp.Float3 __m__row0 = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m));
+ // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) =, global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0);
+ // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 1);
+ for (int j = 0; j < matrix.Rows; j++)
+ {
+ statements.Add(ExpressionStatement(
+ AssignmentExpression(
+ SyntaxKind.SimpleAssignmentExpression,
+ ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){matrix.Offsets[j]}))"),
+ ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j})"))));
+ }
+ break;
+ }
+ }
+
+ // global::System.Span span0 = stackalloc uint[];
+ statements.Insert(0,
+ LocalDeclarationStatement(
+ VariableDeclaration(
+ GenericName(Identifier("global::System.Span"))
+ .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.UIntKeyword))))
+ .AddVariables(
+ VariableDeclarator(Identifier("span0"))
+ .WithInitializer(EqualsValueClause(
+ StackAllocArrayCreationExpression(
+ ArrayType(PredefinedType(Token(SyntaxKind.UIntKeyword)))
+ .AddRankSpecifiers(
+ ArrayRankSpecifier(SingletonSeparatedList(
+ LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(root32BitConstantsCount)))))))))));
+
+ // ref uint r0 = ref span0[0];
+ statements.Insert(1,
+ LocalDeclarationStatement(
+ VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.UIntKeyword))))
+ .AddVariables(
+ VariableDeclarator(Identifier("r0"))
+ .WithInitializer(EqualsValueClause(
+ RefExpression(
+ ElementAccessExpression(IdentifierName("span0"))
+ .AddArgumentListArguments(Argument(
+ LiteralExpression(
+ SyntaxKind.NumericLiteralExpression,
+ Literal(0))))))))));
+
+ // loader.LoadCapturedValues(span0);
+ statements.Add(
+ ExpressionStatement(
+ InvocationExpression(
+ MemberAccessExpression(
+ SyntaxKind.SimpleMemberAccessExpression,
+ IdentifierName("loader"),
+ IdentifierName("LoadCapturedValues")))
+ .AddArgumentListArguments(Argument(IdentifierName("span0")))));
+
+ if (resourceCount > 0)
+ {
+ // global::System.Span span1 = stackalloc ulong[];
+ statements.Insert(1,
+ LocalDeclarationStatement(
+ VariableDeclaration(
+ GenericName(Identifier("global::System.Span"))
+ .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ULongKeyword))))
+ .AddVariables(
+ VariableDeclarator(Identifier("span1"))
+ .WithInitializer(EqualsValueClause(
+ StackAllocArrayCreationExpression(
+ ArrayType(PredefinedType(Token(SyntaxKind.ULongKeyword)))
+ .AddRankSpecifiers(
+ ArrayRankSpecifier(SingletonSeparatedList(
+ LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(resourceCount)))))))))));
+
+ // ref ulong r1 = ref span1[0];
+ statements.Insert(3,
+ LocalDeclarationStatement(
+ VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ULongKeyword))))
+ .AddVariables(
+ VariableDeclarator(Identifier("r1"))
+ .WithInitializer(EqualsValueClause(
+ RefExpression(
+ ElementAccessExpression(IdentifierName("span1"))
+ .AddArgumentListArguments(Argument(
+ LiteralExpression(
+ SyntaxKind.NumericLiteralExpression,
+ Literal(0))))))))));
+
+ // loader.LoadCapturedResources(span1);
+ statements.Add(
+ ExpressionStatement(
+ InvocationExpression(
+ MemberAccessExpression(
+ SyntaxKind.SimpleMemberAccessExpression,
+ IdentifierName("loader"),
+ IdentifierName("LoadCapturedResources")))
+ .AddArgumentListArguments(Argument(IdentifierName("span1")))));
+ }
+
+ return statements.ToImmutable();
+ }
+}
diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs
index 5624caa2..579581de 100644
--- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs
@@ -3,19 +3,13 @@ using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Runtime.CompilerServices;
-using ComputeSharp.__Internals;
using ComputeSharp.Core.Helpers;
using ComputeSharp.SourceGenerators.Diagnostics;
using ComputeSharp.SourceGenerators.Extensions;
using ComputeSharp.SourceGenerators.Mappings;
using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
-using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
-
-#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators;
@@ -190,234 +184,4 @@ public sealed partial class IShaderGenerator2
return new FieldInfo.Primitive(fieldPath, typeName, startingRawDataOffset);
}
}
-
- ///
- /// Creates a instance for the LoadDispatchDataMethod method.
- ///
- /// The type of shader interface urrently being processed.
- /// The array of values for all captured fields.
- /// The total number of captured resources in the shader.
- /// The total number of needed 32 bit constants in the shader root signature.
- /// The resulting instance for the LoadDispatchDataMethod method.
- private static MethodDeclarationSyntax CreateLoadDispatchDataMethod(
- Type shaderInterfaceType,
- ImmutableArray fieldInfos,
- int resourceCount,
- int root32BitConstantsCount)
- {
- // This code produces a method declaration as follows:
- //
- // readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchData(ref TDataLoader loader, global::ComputeSharp.GraphicsDevice device, int x, int y, int z)
- // {
- //
- // }
- return
- MethodDeclaration(
- PredefinedType(Token(SyntaxKind.VoidKeyword)),
- Identifier("LoadDispatchData"))
- .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
- .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
- .AddTypeParameterListParameters(TypeParameter(Identifier("TDataLoader")))
- .AddParameterListParameters(
- Parameter(Identifier("loader"))
- .AddModifiers(Token(SyntaxKind.RefKeyword))
- .WithType(IdentifierName("TDataLoader")),
- Parameter(Identifier("device")).WithType(IdentifierName("global::ComputeSharp.GraphicsDevice")),
- Parameter(Identifier("x")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
- Parameter(Identifier("y")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
- Parameter(Identifier("z")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))))
- .WithBody(Block(GetDispatchDataLoadingStatements(shaderInterfaceType, fieldInfos, resourceCount, root32BitConstantsCount)));
- }
-
- ///
- /// Gets a sequence of statements to load the dispatch data for a given shader.
- ///
- /// The type of shader interface urrently being processed.
- /// The array of values for all captured fields.
- /// The total number of captured resources in the shader.
- /// The total number of needed 32 bit constants in the shader root signature.
- /// The sequence of instances to load shader dispatch data.
- private static ImmutableArray GetDispatchDataLoadingStatements(
- Type shaderInterfaceType,
- ImmutableArray fieldInfos,
- int resourceCount,
- int root32BitConstantsCount)
- {
- ImmutableArray.Builder statements = ImmutableArray.CreateBuilder();
- bool isComputeShader = shaderInterfaceType == typeof(IComputeShader);
-
- // Append the statements for the dispatch ranges:
- //
- // span0[0] = (uint)x;
- // span0[1] = (uint)y;
- // span0[2] = (uint)z;
- statements.Add(
- ExpressionStatement(
- AssignmentExpression(
- SyntaxKind.SimpleAssignmentExpression,
- ElementAccessExpression(IdentifierName("span0"))
- .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))),
- CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("x")))));
-
- statements.Add(
- ExpressionStatement(
- AssignmentExpression(
- SyntaxKind.SimpleAssignmentExpression,
- ElementAccessExpression(IdentifierName("span0"))
- .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1)))),
- CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("y")))));
-
- // If the shader is a compute shader, also track the bounds on the Z axis
- if (isComputeShader)
- {
- statements.Add(
- ExpressionStatement(
- AssignmentExpression(
- SyntaxKind.SimpleAssignmentExpression,
- ElementAccessExpression(IdentifierName("span0"))
- .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(2)))),
- CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("z")))));
- }
-
- // Generate loading statements for each captured field
- foreach (FieldInfo fieldInfo in fieldInfos)
- {
- switch (fieldInfo)
- {
- case FieldInfo.Resource resource:
-
- // Validate the resource and get a handle for it. This will generate:
- //
- // global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, ) =
- // global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(, device);
- statements.Add(ExpressionStatement(
- AssignmentExpression(
- SyntaxKind.SimpleAssignmentExpression,
- ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resource.Offset})"),
- ParseExpression($"global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({resource.FieldName}, device)"))));
- break;
- case FieldInfo.Primitive primitive:
-
- // Read a primitive value and serialize it into the target buffer. This will generate:
- //
- // global::System.Runtime.CompilerServices.Unsafe.As>(
- // ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint))) =
- statements.Add(ExpressionStatement(
- AssignmentExpression(
- SyntaxKind.SimpleAssignmentExpression,
- ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){primitive.Offset}))"),
- ParseExpression($"{string.Join(".", primitive.FieldPath)}"))));
- break;
-
- case FieldInfo.NonLinearMatrix matrix:
- string rowTypeName = $"global::ComputeSharp.{matrix.ElementName}{matrix.Columns}";
- string rowLocalName = $"__{string.Join("_", matrix.FieldPath)}__row0";
-
- // Declare a local to index into individual rows. This will generate:
- //
- // ref = ref global::System.Runtime.CompilerServices.Unsafe.As, >(
- // ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in ));
- statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in {string.Join(".", matrix.FieldPath)}));"));
-
- // Generate the loading code for each individual row, with proper alignment.
- // This will result in the following (assuming Float2x3 m):
- //
- // ref global::ComputeSharp.Float3 __m__row0 = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m));
- // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) =, global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0);
- // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 1);
- for (int j = 0; j < matrix.Rows; j++)
- {
- statements.Add(ExpressionStatement(
- AssignmentExpression(
- SyntaxKind.SimpleAssignmentExpression,
- ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){matrix.Offsets[j]}))"),
- ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j})"))));
- }
- break;
- }
- }
-
- // global::System.Span span0 = stackalloc uint[];
- statements.Insert(0,
- LocalDeclarationStatement(
- VariableDeclaration(
- GenericName(Identifier("global::System.Span"))
- .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.UIntKeyword))))
- .AddVariables(
- VariableDeclarator(Identifier("span0"))
- .WithInitializer(EqualsValueClause(
- StackAllocArrayCreationExpression(
- ArrayType(PredefinedType(Token(SyntaxKind.UIntKeyword)))
- .AddRankSpecifiers(
- ArrayRankSpecifier(SingletonSeparatedList(
- LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(root32BitConstantsCount)))))))))));
-
- // ref uint r0 = ref span0[0];
- statements.Insert(1,
- LocalDeclarationStatement(
- VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.UIntKeyword))))
- .AddVariables(
- VariableDeclarator(Identifier("r0"))
- .WithInitializer(EqualsValueClause(
- RefExpression(
- ElementAccessExpression(IdentifierName("span0"))
- .AddArgumentListArguments(Argument(
- LiteralExpression(
- SyntaxKind.NumericLiteralExpression,
- Literal(0))))))))));
-
- // loader.LoadCapturedValues(span0);
- statements.Add(
- ExpressionStatement(
- InvocationExpression(
- MemberAccessExpression(
- SyntaxKind.SimpleMemberAccessExpression,
- IdentifierName("loader"),
- IdentifierName("LoadCapturedValues")))
- .AddArgumentListArguments(Argument(IdentifierName("span0")))));
-
- if (resourceCount > 0)
- {
- // global::System.Span span1 = stackalloc ulong[];
- statements.Insert(1,
- LocalDeclarationStatement(
- VariableDeclaration(
- GenericName(Identifier("global::System.Span"))
- .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ULongKeyword))))
- .AddVariables(
- VariableDeclarator(Identifier("span1"))
- .WithInitializer(EqualsValueClause(
- StackAllocArrayCreationExpression(
- ArrayType(PredefinedType(Token(SyntaxKind.ULongKeyword)))
- .AddRankSpecifiers(
- ArrayRankSpecifier(SingletonSeparatedList(
- LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(resourceCount)))))))))));
-
- // ref ulong r1 = ref span1[0];
- statements.Insert(3,
- LocalDeclarationStatement(
- VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ULongKeyword))))
- .AddVariables(
- VariableDeclarator(Identifier("r1"))
- .WithInitializer(EqualsValueClause(
- RefExpression(
- ElementAccessExpression(IdentifierName("span1"))
- .AddArgumentListArguments(Argument(
- LiteralExpression(
- SyntaxKind.NumericLiteralExpression,
- Literal(0))))))))));
-
- // loader.LoadCapturedResources(span1);
- statements.Add(
- ExpressionStatement(
- InvocationExpression(
- MemberAccessExpression(
- SyntaxKind.SimpleMemberAccessExpression,
- IdentifierName("loader"),
- IdentifierName("LoadCapturedResources")))
- .AddArgumentListArguments(Argument(IdentifierName("span1")))));
- }
-
- return statements.ToImmutable();
- }
}
diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.Syntax.cs
new file mode 100644
index 00000000..d5ad9351
--- /dev/null
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.Syntax.cs
@@ -0,0 +1,132 @@
+using System;
+using System.Collections.Immutable;
+using ComputeSharp.__Internals;
+using ComputeSharp.SourceGenerators.Models;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
+
+#pragma warning disable CS0618
+
+namespace ComputeSharp.SourceGenerators;
+
+///
+public sealed partial class IShaderGenerator2
+{
+ ///
+ /// Creates a instance for the LoadDispatchMetadata method.
+ ///
+ /// The dispatch metadata for the current shader..
+ /// The resulting instance for the LoadDispatchMetadata method.
+ private static MethodDeclarationSyntax CreateLoadDispatchMetadataMethod(DispatchMetadataInfo metadataInfo)
+ {
+ // This code produces a method declaration as follows:
+ //
+ // readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchMetadata(ref TMetadataLoader loader, out global::System.IntPtr result)
+ // {
+ //
+ // }
+ return
+ MethodDeclaration(
+ PredefinedType(Token(SyntaxKind.VoidKeyword)),
+ Identifier("LoadDispatchMetadata"))
+ .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
+ .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
+ .AddTypeParameterListParameters(TypeParameter(Identifier("TMetadataLoader")))
+ .AddParameterListParameters(
+ Parameter(Identifier("loader"))
+ .AddModifiers(Token(SyntaxKind.RefKeyword))
+ .WithType(IdentifierName("TMetadataLoader")),
+ Parameter(Identifier("result"))
+ .AddModifiers(Token(SyntaxKind.OutKeyword))
+ .WithType(IdentifierName($"global::System.{typeof(IntPtr).Name}")))
+ .WithBody(Block(GetDispatchMetadataLoadingStatements(metadataInfo)));
+ }
+
+ ///
+ /// Gets a sequence of statements to load the dispatch metadata for a given shader type.
+ ///
+ /// The dispatch metadata for the current shader..
+ /// The sequence of instances to load shader dispatch data.
+ private static ImmutableArray GetDispatchMetadataLoadingStatements(DispatchMetadataInfo metadataInfo)
+ {
+ ImmutableArray.Builder statements = ImmutableArray.CreateBuilder();
+
+ // global::System.Span span0 = stackalloc byte[5];
+ statements.Add(
+ LocalDeclarationStatement(
+ VariableDeclaration(
+ GenericName(Identifier("global::System.Span"))
+ .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))))
+ .AddVariables(
+ VariableDeclarator(Identifier("span0"))
+ .WithInitializer(EqualsValueClause(
+ StackAllocArrayCreationExpression(
+ ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
+ .AddRankSpecifiers(
+ ArrayRankSpecifier(SingletonSeparatedList(
+ LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(5)))))))))));
+
+ // Compute the total number of resources
+ int totalResourcesCount = metadataInfo.ResourceDescriptors.Length;
+
+ // Span span1 = stackalloc global::ComputeSharp.__Internals.ResourceDescriptor[];
+ statements.Add(
+ LocalDeclarationStatement(
+ VariableDeclaration(
+ GenericName(Identifier("global::System.Span"))
+ .AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor")))
+ .AddVariables(
+ VariableDeclarator(Identifier("span1"))
+ .WithInitializer(EqualsValueClause(
+ StackAllocArrayCreationExpression(
+ ArrayType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor"))
+ .AddRankSpecifiers(
+ ArrayRankSpecifier(SingletonSeparatedList(
+ LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(totalResourcesCount)))))))))));
+
+ // ref byte r0 = ref span0[0];
+ statements.Add(
+ LocalDeclarationStatement(
+ VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword))))
+ .AddVariables(
+ VariableDeclarator(Identifier("r0"))
+ .WithInitializer(EqualsValueClause(
+ RefExpression(
+ ElementAccessExpression(IdentifierName("span0"))
+ .AddArgumentListArguments(Argument(
+ LiteralExpression(
+ SyntaxKind.NumericLiteralExpression,
+ Literal(0))))))))));
+
+ // ref global::ComputeSharp.__Internals.ResourceDescriptor r1 = ref span1[0];
+ statements.Add(
+ LocalDeclarationStatement(
+ VariableDeclaration(RefType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor")))
+ .AddVariables(
+ VariableDeclarator(Identifier("r1"))
+ .WithInitializer(EqualsValueClause(
+ RefExpression(
+ ElementAccessExpression(IdentifierName("span1"))
+ .AddArgumentListArguments(Argument(
+ LiteralExpression(
+ SyntaxKind.NumericLiteralExpression,
+ Literal(0))))))))));
+
+ // Serialized shader metadata
+ statements.Add(ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 0), {metadataInfo.Root32BitConstantCount});"));
+ statements.Add(ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 4), {metadataInfo.IsSamplerUsed.ToString().ToLowerInvariant()});"));
+
+
+ // Populate the sequence of resource descriptors
+ foreach (ResourceDescriptor descriptor in metadataInfo.ResourceDescriptors)
+ {
+ statements.Add(ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create({descriptor.TypeId}, {descriptor.RegisterOffset}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {descriptor.Offset}));"));
+ }
+
+ // Invoke the value delegate to create the opaque root signature handle
+ statements.Add(ParseStatement("loader.LoadMetadataHandle(span0, span1, out result);"));
+
+ return statements.ToImmutable();
+ }
+}
diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.cs
index 06531460..6e671a19 100644
--- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.cs
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.cs
@@ -1,13 +1,6 @@
-using System;
-using System.Collections.Immutable;
-using ComputeSharp.__Internals;
+using System.Collections.Immutable;
using ComputeSharp.SourceGenerators.Mappings;
using ComputeSharp.SourceGenerators.Models;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
-
-#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators;
@@ -62,121 +55,4 @@ public sealed partial class IShaderGenerator2
isSamplerUsed,
descriptors.ToImmutable());
}
-
- ///
- /// Creates a instance for the LoadDispatchMetadata method.
- ///
- /// The dispatch metadata for the current shader..
- /// The resulting instance for the LoadDispatchMetadata method.
- private static MethodDeclarationSyntax CreateLoadDispatchMetadataMethod(DispatchMetadataInfo metadataInfo)
- {
- // This code produces a method declaration as follows:
- //
- // readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchMetadata(ref TMetadataLoader loader, out global::System.IntPtr result)
- // {
- //
- // }
- return
- MethodDeclaration(
- PredefinedType(Token(SyntaxKind.VoidKeyword)),
- Identifier("LoadDispatchMetadata"))
- .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
- .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
- .AddTypeParameterListParameters(TypeParameter(Identifier("TMetadataLoader")))
- .AddParameterListParameters(
- Parameter(Identifier("loader"))
- .AddModifiers(Token(SyntaxKind.RefKeyword))
- .WithType(IdentifierName("TMetadataLoader")),
- Parameter(Identifier("result"))
- .AddModifiers(Token(SyntaxKind.OutKeyword))
- .WithType(IdentifierName($"global::System.{typeof(IntPtr).Name}")))
- .WithBody(Block(GetDispatchMetadataLoadingStatements(metadataInfo)));
- }
-
- ///
- /// Gets a sequence of statements to load the dispatch metadata for a given shader type.
- ///
- /// The dispatch metadata for the current shader..
- /// The sequence of instances to load shader dispatch data.
- private static ImmutableArray GetDispatchMetadataLoadingStatements(DispatchMetadataInfo metadataInfo)
- {
- ImmutableArray.Builder statements = ImmutableArray.CreateBuilder();
-
- // global::System.Span span0 = stackalloc byte[5];
- statements.Add(
- LocalDeclarationStatement(
- VariableDeclaration(
- GenericName(Identifier("global::System.Span"))
- .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))))
- .AddVariables(
- VariableDeclarator(Identifier("span0"))
- .WithInitializer(EqualsValueClause(
- StackAllocArrayCreationExpression(
- ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
- .AddRankSpecifiers(
- ArrayRankSpecifier(SingletonSeparatedList(
- LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(5)))))))))));
-
- // Compute the total number of resources
- int totalResourcesCount = metadataInfo.ResourceDescriptors.Length;
-
- // Span span1 = stackalloc global::ComputeSharp.__Internals.ResourceDescriptor[];
- statements.Add(
- LocalDeclarationStatement(
- VariableDeclaration(
- GenericName(Identifier("global::System.Span"))
- .AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor")))
- .AddVariables(
- VariableDeclarator(Identifier("span1"))
- .WithInitializer(EqualsValueClause(
- StackAllocArrayCreationExpression(
- ArrayType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor"))
- .AddRankSpecifiers(
- ArrayRankSpecifier(SingletonSeparatedList(
- LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(totalResourcesCount)))))))))));
-
- // ref byte r0 = ref span0[0];
- statements.Add(
- LocalDeclarationStatement(
- VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword))))
- .AddVariables(
- VariableDeclarator(Identifier("r0"))
- .WithInitializer(EqualsValueClause(
- RefExpression(
- ElementAccessExpression(IdentifierName("span0"))
- .AddArgumentListArguments(Argument(
- LiteralExpression(
- SyntaxKind.NumericLiteralExpression,
- Literal(0))))))))));
-
- // ref global::ComputeSharp.__Internals.ResourceDescriptor r1 = ref span1[0];
- statements.Add(
- LocalDeclarationStatement(
- VariableDeclaration(RefType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor")))
- .AddVariables(
- VariableDeclarator(Identifier("r1"))
- .WithInitializer(EqualsValueClause(
- RefExpression(
- ElementAccessExpression(IdentifierName("span1"))
- .AddArgumentListArguments(Argument(
- LiteralExpression(
- SyntaxKind.NumericLiteralExpression,
- Literal(0))))))))));
-
- // Serialized shader metadata
- statements.Add(ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 0), {metadataInfo.Root32BitConstantCount});"));
- statements.Add(ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 4), {metadataInfo.IsSamplerUsed.ToString().ToLowerInvariant()});"));
-
-
- // Populate the sequence of resource descriptors
- foreach (ResourceDescriptor descriptor in metadataInfo.ResourceDescriptors)
- {
- statements.Add(ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create({descriptor.TypeId}, {descriptor.RegisterOffset}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {descriptor.Offset}));"));
- }
-
- // Invoke the value delegate to create the opaque root signature handle
- statements.Add(ParseStatement("loader.LoadMetadataHandle(span0, span1, out result);"));
-
- return statements.ToImmutable();
- }
}
diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.Syntax.cs
new file mode 100644
index 00000000..a4917459
--- /dev/null
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.Syntax.cs
@@ -0,0 +1,187 @@
+using System;
+using System.Diagnostics.Contracts;
+using ComputeSharp.__Internals;
+using ComputeSharp.SourceGenerators.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.SourceGenerators;
+
+///
+public sealed partial class IShaderGenerator2
+{
+ ///
+ /// Creates a instance for the TryGetBytecode method.
+ ///
+ /// The input instance.
+ /// An opaque instance to transform the final tree into text.
+ /// The resulting instance for the BuildHlslString method.
+ private static MethodDeclarationSyntax CreateTryGetBytecodeMethod(EmbeddedBytecodeInfo bytecodeInfo, out Func fixup)
+ {
+ BlockSyntax block = GetShaderBytecodeBody(bytecodeInfo, out string? bytecodeLiterals);
+
+ if (bytecodeLiterals is not null)
+ {
+ fixup = tree => tree.ToFullString().Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals);
+ }
+ else
+ {
+ fixup = static tree => tree.ToFullString();
+ }
+
+ // This code produces a method declaration as follows:
+ //
+ // readonly int global::ComputeSharp.__Internals.IShader.TryGetBytecode(int threadsX, int threadsY, int threadsZ, out ReadOnlySpan bytecode)
+ // {
+ //
+ // }
+ return
+ MethodDeclaration(
+ PredefinedType(Token(SyntaxKind.BoolKeyword)),
+ Identifier("TryGetBytecode"))
+ .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
+ .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
+ .AddParameterListParameters(
+ Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
+ Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
+ Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
+ Parameter(Identifier("bytecode")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("global::System.ReadOnlySpan")))
+ .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.
+ [Pure]
+ private static unsafe BlockSyntax GetShaderBytecodeBody(EmbeddedBytecodeInfo bytecodeInfo, out string? bytecodeLiterals)
+ {
+ if (bytecodeInfo.Bytecode.IsEmpty)
+ {
+ bytecodeLiterals = null;
+
+ // This code produces a method declaration as follows:
+ //
+ // bytecode = default;
+ //
+ // return false;
+ return
+ Block(
+ ExpressionStatement(
+ AssignmentExpression(
+ SyntaxKind.SimpleAssignmentExpression,
+ IdentifierName("bytecode"),
+ LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))),
+ ReturnStatement(
+ LiteralExpression(
+ SyntaxKind.FalseLiteralExpression)));
+ }
+
+ bytecodeLiterals = BuildShaderBytecodeExpressionString(bytecodeInfo.Bytecode.AsSpan());
+
+ // This code produces a method declaration as follows:
+ //
+ // if (threadsX == && threadsY == && threadsZ == )
+ // {
+ // bytecode = new byte[] { __EMBEDDED_SHADER_BYTECODE };
+ //
+ // return true;
+ // }
+ //
+ // bytecode = default;
+ //
+ // return false;
+ //
+ // 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.
+ return
+ Block(
+ 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(
+ ExpressionStatement(
+ AssignmentExpression(
+ SyntaxKind.SimpleAssignmentExpression,
+ IdentifierName("bytecode"),
+ ArrayCreationExpression(
+ ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
+ .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression()))))
+ .WithInitializer(
+ InitializerExpression(
+ SyntaxKind.ArrayInitializerExpression,
+ SingletonSeparatedList(IdentifierName("__EMBEDDED_SHADER_BYTECODE")))))),
+ ReturnStatement(LiteralExpression(SyntaxKind.TrueLiteralExpression)))),
+ ExpressionStatement(
+ AssignmentExpression(
+ SyntaxKind.SimpleAssignmentExpression,
+ IdentifierName("bytecode"),
+ LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))),
+ ReturnStatement(LiteralExpression(SyntaxKind.FalseLiteralExpression)));
+ }
+
+ ///
+ /// A mapping of precomputed literals for all values.
+ ///
+ private static readonly string[] formattedBytes =
+ {
+ "0x00", "0x01", "0x02", "0x03", "0x04", "0x05", "0x06", "0x07", "0x08", "0x09", "0x0A", "0x0B", "0x0C", "0x0D", "0x0E", "0x0F",
+ "0x10", "0x11", "0x12", "0x13", "0x14", "0x15", "0x16", "0x17", "0x18", "0x19", "0x1A", "0x1B", "0x1C", "0x1D", "0x1E", "0x1F",
+ "0x20", "0x21", "0x22", "0x23", "0x24", "0x25", "0x26", "0x27", "0x28", "0x29", "0x2A", "0x2B", "0x2C", "0x2D", "0x2E", "0x2F",
+ "0x30", "0x31", "0x32", "0x33", "0x34", "0x35", "0x36", "0x37", "0x38", "0x39", "0x3A", "0x3B", "0x3C", "0x3D", "0x3E", "0x3F",
+ "0x40", "0x41", "0x42", "0x43", "0x44", "0x45", "0x46", "0x47", "0x48", "0x49", "0x4A", "0x4B", "0x4C", "0x4D", "0x4E", "0x4F",
+ "0x50", "0x51", "0x52", "0x53", "0x54", "0x55", "0x56", "0x57", "0x58", "0x59", "0x5A", "0x5B", "0x5C", "0x5D", "0x5E", "0x5F",
+ "0x60", "0x61", "0x62", "0x63", "0x64", "0x65", "0x66", "0x67", "0x68", "0x69", "0x6A", "0x6B", "0x6C", "0x6D", "0x6E", "0x6F",
+ "0x70", "0x71", "0x72", "0x73", "0x74", "0x75", "0x76", "0x77", "0x78", "0x79", "0x7A", "0x7B", "0x7C", "0x7D", "0x7E", "0x7F",
+ "0x80", "0x81", "0x82", "0x83", "0x84", "0x85", "0x86", "0x87", "0x88", "0x89", "0x8A", "0x8B", "0x8C", "0x8D", "0x8E", "0x8F",
+ "0x90", "0x91", "0x92", "0x93", "0x94", "0x95", "0x96", "0x97", "0x98", "0x99", "0x9A", "0x9B", "0x9C", "0x9D", "0x9E", "0x9F",
+ "0xA0", "0xA1", "0xA2", "0xA3", "0xA4", "0xA5", "0xA6", "0xA7", "0xA8", "0xA9", "0xAA", "0xAB", "0xAC", "0xAD", "0xAE", "0xAF",
+ "0xB0", "0xB1", "0xB2", "0xB3", "0xB4", "0xB5", "0xB6", "0xB7", "0xB8", "0xB9", "0xBA", "0xBB", "0xBC", "0xBD", "0xBE", "0xBF",
+ "0xC0", "0xC1", "0xC2", "0xC3", "0xC4", "0xC5", "0xC6", "0xC7", "0xC8", "0xC9", "0xCA", "0xCB", "0xCC", "0xCD", "0xCE", "0xCF",
+ "0xD0", "0xD1", "0xD2", "0xD3", "0xD4", "0xD5", "0xD6", "0xD7", "0xD8", "0xD9", "0xDA", "0xDB", "0xDC", "0xDD", "0xDE", "0xDF",
+ "0xE0", "0xE1", "0xE2", "0xE3", "0xE4", "0xE5", "0xE6", "0xE7", "0xE8", "0xE9", "0xEA", "0xEB", "0xEC", "0xED", "0xEE", "0xEF",
+ "0xF0", "0xF1", "0xF2", "0xF3", "0xF4", "0xF5", "0xF6", "0xF7", "0xF8", "0xF9", "0xFA", "0xFB", "0xFC", "0xFD", "0xFE", "0xFF"
+ };
+
+ ///
+ /// Creates a formatted expression to initialize a with a given shader data.
+ ///
+ /// The input shader bytecode to serialize.
+ /// A formatted with the serialized data.
+ private static string BuildShaderBytecodeExpressionString(ReadOnlySpan bytecode)
+ {
+ //The estimation is 4 characters per byte (up to "255" in hex), plus ", " to separate sequential values
+ using ArrayPoolStringBuilder builder = ArrayPoolStringBuilder.Create(bytecode.Length * 6);
+
+ builder.Append(formattedBytes[bytecode[0]]);
+
+ foreach (byte b in bytecode.Slice(1))
+ {
+ builder.Append(", ");
+ builder.Append(formattedBytes[b]);
+ }
+
+ return builder.WrittenSpan.ToString();
+ }
+}
diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.cs
index 7cc33038..8d2c1170 100644
--- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.cs
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.cs
@@ -7,20 +7,15 @@ using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
-using ComputeSharp.__Internals;
using ComputeSharp.Exceptions;
using ComputeSharp.Shaders.Translation;
using ComputeSharp.SourceGenerators.Diagnostics;
using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
-using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
-
-#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators;
@@ -220,175 +215,4 @@ public sealed partial class IShaderGenerator2
areDxcLibrariesLoaded = true;
}
-
- ///
- /// Creates a instance for the TryGetBytecode method.
- ///
- /// The input instance.
- /// An opaque instance to transform the final tree into text.
- /// The resulting instance for the BuildHlslString method.
- private static MethodDeclarationSyntax CreateTryGetBytecodeMethod(EmbeddedBytecodeInfo bytecodeInfo, out Func fixup)
- {
- BlockSyntax block = GetShaderBytecodeBody(bytecodeInfo, out string? bytecodeLiterals);
-
- if (bytecodeLiterals is not null)
- {
- fixup = tree => tree.ToFullString().Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals);
- }
- else
- {
- fixup = static tree => tree.ToFullString();
- }
-
- // This code produces a method declaration as follows:
- //
- // readonly int global::ComputeSharp.__Internals.IShader.TryGetBytecode(int threadsX, int threadsY, int threadsZ, out ReadOnlySpan bytecode)
- // {
- //
- // }
- return
- MethodDeclaration(
- PredefinedType(Token(SyntaxKind.BoolKeyword)),
- Identifier("TryGetBytecode"))
- .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
- .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
- .AddParameterListParameters(
- Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
- Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
- Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
- Parameter(Identifier("bytecode")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("global::System.ReadOnlySpan")))
- .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.
- [Pure]
- private static unsafe BlockSyntax GetShaderBytecodeBody(EmbeddedBytecodeInfo bytecodeInfo, out string? bytecodeLiterals)
- {
- if (bytecodeInfo.Bytecode.IsEmpty)
- {
- bytecodeLiterals = null;
-
- // This code produces a method declaration as follows:
- //
- // bytecode = default;
- //
- // return false;
- return
- Block(
- ExpressionStatement(
- AssignmentExpression(
- SyntaxKind.SimpleAssignmentExpression,
- IdentifierName("bytecode"),
- LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))),
- ReturnStatement(
- LiteralExpression(
- SyntaxKind.FalseLiteralExpression)));
- }
-
- bytecodeLiterals = BuildShaderBytecodeExpressionString(bytecodeInfo.Bytecode.AsSpan());
-
- // This code produces a method declaration as follows:
- //
- // if (threadsX == && threadsY == && threadsZ == )
- // {
- // bytecode = new byte[] { __EMBEDDED_SHADER_BYTECODE };
- //
- // return true;
- // }
- //
- // bytecode = default;
- //
- // return false;
- //
- // 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.
- return
- Block(
- 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(
- ExpressionStatement(
- AssignmentExpression(
- SyntaxKind.SimpleAssignmentExpression,
- IdentifierName("bytecode"),
- ArrayCreationExpression(
- ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
- .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression()))))
- .WithInitializer(
- InitializerExpression(
- SyntaxKind.ArrayInitializerExpression,
- SingletonSeparatedList(IdentifierName("__EMBEDDED_SHADER_BYTECODE")))))),
- ReturnStatement(LiteralExpression(SyntaxKind.TrueLiteralExpression)))),
- ExpressionStatement(
- AssignmentExpression(
- SyntaxKind.SimpleAssignmentExpression,
- IdentifierName("bytecode"),
- LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))),
- ReturnStatement(LiteralExpression(SyntaxKind.FalseLiteralExpression)));
- }
-
- ///
- /// A mapping of precomputed literals for all values.
- ///
- private static readonly string[] formattedBytes =
- {
- "0x00", "0x01", "0x02", "0x03", "0x04", "0x05", "0x06", "0x07", "0x08", "0x09", "0x0A", "0x0B", "0x0C", "0x0D", "0x0E", "0x0F",
- "0x10", "0x11", "0x12", "0x13", "0x14", "0x15", "0x16", "0x17", "0x18", "0x19", "0x1A", "0x1B", "0x1C", "0x1D", "0x1E", "0x1F",
- "0x20", "0x21", "0x22", "0x23", "0x24", "0x25", "0x26", "0x27", "0x28", "0x29", "0x2A", "0x2B", "0x2C", "0x2D", "0x2E", "0x2F",
- "0x30", "0x31", "0x32", "0x33", "0x34", "0x35", "0x36", "0x37", "0x38", "0x39", "0x3A", "0x3B", "0x3C", "0x3D", "0x3E", "0x3F",
- "0x40", "0x41", "0x42", "0x43", "0x44", "0x45", "0x46", "0x47", "0x48", "0x49", "0x4A", "0x4B", "0x4C", "0x4D", "0x4E", "0x4F",
- "0x50", "0x51", "0x52", "0x53", "0x54", "0x55", "0x56", "0x57", "0x58", "0x59", "0x5A", "0x5B", "0x5C", "0x5D", "0x5E", "0x5F",
- "0x60", "0x61", "0x62", "0x63", "0x64", "0x65", "0x66", "0x67", "0x68", "0x69", "0x6A", "0x6B", "0x6C", "0x6D", "0x6E", "0x6F",
- "0x70", "0x71", "0x72", "0x73", "0x74", "0x75", "0x76", "0x77", "0x78", "0x79", "0x7A", "0x7B", "0x7C", "0x7D", "0x7E", "0x7F",
- "0x80", "0x81", "0x82", "0x83", "0x84", "0x85", "0x86", "0x87", "0x88", "0x89", "0x8A", "0x8B", "0x8C", "0x8D", "0x8E", "0x8F",
- "0x90", "0x91", "0x92", "0x93", "0x94", "0x95", "0x96", "0x97", "0x98", "0x99", "0x9A", "0x9B", "0x9C", "0x9D", "0x9E", "0x9F",
- "0xA0", "0xA1", "0xA2", "0xA3", "0xA4", "0xA5", "0xA6", "0xA7", "0xA8", "0xA9", "0xAA", "0xAB", "0xAC", "0xAD", "0xAE", "0xAF",
- "0xB0", "0xB1", "0xB2", "0xB3", "0xB4", "0xB5", "0xB6", "0xB7", "0xB8", "0xB9", "0xBA", "0xBB", "0xBC", "0xBD", "0xBE", "0xBF",
- "0xC0", "0xC1", "0xC2", "0xC3", "0xC4", "0xC5", "0xC6", "0xC7", "0xC8", "0xC9", "0xCA", "0xCB", "0xCC", "0xCD", "0xCE", "0xCF",
- "0xD0", "0xD1", "0xD2", "0xD3", "0xD4", "0xD5", "0xD6", "0xD7", "0xD8", "0xD9", "0xDA", "0xDB", "0xDC", "0xDD", "0xDE", "0xDF",
- "0xE0", "0xE1", "0xE2", "0xE3", "0xE4", "0xE5", "0xE6", "0xE7", "0xE8", "0xE9", "0xEA", "0xEB", "0xEC", "0xED", "0xEE", "0xEF",
- "0xF0", "0xF1", "0xF2", "0xF3", "0xF4", "0xF5", "0xF6", "0xF7", "0xF8", "0xF9", "0xFA", "0xFB", "0xFC", "0xFD", "0xFE", "0xFF"
- };
-
- ///
- /// Creates a formatted expression to initialize a with a given shader data.
- ///
- /// The input shader bytecode to serialize.
- /// A formatted with the serialized data.
- private static string BuildShaderBytecodeExpressionString(ReadOnlySpan bytecode)
- {
- //The estimation is 4 characters per byte (up to "255" in hex), plus ", " to separate sequential values
- using ArrayPoolStringBuilder builder = ArrayPoolStringBuilder.Create(bytecode.Length * 6);
-
- builder.Append(formattedBytes[bytecode[0]]);
-
- foreach (byte b in bytecode.Slice(1))
- {
- builder.Append(", ");
- builder.Append(formattedBytes[b]);
- }
-
- return builder.WrittenSpan.ToString();
- }
}
diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.GetNonDynamicHlslSourceInfo.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.GetNonDynamicHlslSourceInfo.cs
deleted file mode 100644
index 5f153721..00000000
--- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.GetNonDynamicHlslSourceInfo.cs
+++ /dev/null
@@ -1,725 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Diagnostics.Contracts;
-using System.Linq;
-using System.Text;
-using ComputeSharp.SourceGenerators.Diagnostics;
-using ComputeSharp.SourceGenerators.Extensions;
-using ComputeSharp.SourceGenerators.Helpers;
-using ComputeSharp.SourceGenerators.Mappings;
-using ComputeSharp.SourceGenerators.Models;
-using ComputeSharp.SourceGenerators.SyntaxRewriters;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
-using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
-
-#pragma warning disable CS0618, RS1024
-
-namespace ComputeSharp.SourceGenerators;
-
-///
-public sealed partial class IShaderGenerator2
-{
- ///
- /// Gathers all necessary information on a transpiled HLSL source for a given shader type.
- ///
- /// The input object currently in use.
- /// The node to process.
- /// The for .
- /// The resulting diagnostics from the processing operation.
- /// The resulting info on the processed shader.
- private static HlslSourceInfo GetNonDynamicHlslSourceInfo(
- Compilation compilation,
- StructDeclarationSyntax structDeclaration,
- INamedTypeSymbol structDeclarationSymbol,
- out ImmutableArray diagnostics)
- {
- ImmutableArray.Builder builder = ImmutableArray.CreateBuilder();
-
- // Properties are not supported
- DetectAndReportPropertyDeclarations(builder, structDeclarationSymbol);
-
- // We need to sets to track all discovered custom types and static methods
- HashSet discoveredTypes = new(SymbolEqualityComparer.Default);
- Dictionary staticMethods = new(SymbolEqualityComparer.Default);
- Dictionary constantDefinitions = new(SymbolEqualityComparer.Default);
-
- // A given type can only represent a single shader type
- if (structDeclarationSymbol.AllInterfaces.Count(static interfaceSymbol => interfaceSymbol is { Name: nameof(IComputeShader) } or { IsGenericType: true, Name: nameof(IPixelShader) }) > 1)
- {
- builder.Add(MultipleShaderTypesImplemented, structDeclarationSymbol, structDeclarationSymbol);
- }
-
- // Explore the syntax tree and extract the processed info
- var semanticModelProvider = new SemanticModelProvider(compilation);
- var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) });
- var isComputeShader = pixelShaderSymbol is null;
- var implicitTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!);
- var (resourceFields, valueFields) = GetInstanceFields(builder, structDeclarationSymbol, discoveredTypes, isComputeShader);
- var delegateInstanceFields = GetDelegateFieldNames(structDeclarationSymbol);
- var sharedBuffers = GetSharedBuffers(builder, structDeclarationSymbol, discoveredTypes);
- var (entryPoint, processedMethods, isSamplerUsed) = GetProcessedMethods(builder, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, constantDefinitions, isComputeShader);
- var implicitSamplerField = isSamplerUsed ? ("SamplerState", "__sampler") : default((string, string)?);
- var declaredTypes = GetDeclaredTypes(discoveredTypes);
- var definedConstants = GetDefinedConstants(constantDefinitions);
- var staticFields = GetStaticFields(builder, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions);
-
- diagnostics = builder.ToImmutable();
-
- // Get the HLSL source data with the intermediate info
- return GetNonDynamicHlslSourceInfo(
- definedConstants,
- declaredTypes,
- resourceFields,
- valueFields,
- delegateInstanceFields,
- staticFields,
- sharedBuffers,
- processedMethods,
- isComputeShader,
- implicitTextureType,
- isSamplerUsed,
- entryPoint);
- }
-
- ///
- /// Gets a sequence of captured fields and their mapped names.
- ///
- /// The collection of produced instances.
- /// The input instance to process.
- /// The collection of currently discovered types.
- /// Indicates whether or not represents a compute shader.
- /// A sequence of captured fields in .
- [Pure]
- private static (
- ImmutableArray<(string MetadataName, string Name, string HlslType)>,
- ImmutableArray<(string Name, string HlslType)>)
- GetInstanceFields(
- ImmutableArray.Builder diagnostics,
- INamedTypeSymbol structDeclarationSymbol,
- ICollection types,
- bool isComputeShader)
- {
- ImmutableArray<(string, string, string)>.Builder resources = ImmutableArray.CreateBuilder<(string, string, string)>();
- ImmutableArray<(string, string)>.Builder values = ImmutableArray.CreateBuilder<(string, string)>();
- bool hlslResourceFound = false;
-
- foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType())
- {
- if (fieldSymbol.IsStatic)
- {
- continue;
- }
-
- AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) });
-
- // Group shared fields must be static
- if (attribute is not null)
- {
- diagnostics.Add(InvalidGroupSharedFieldDeclaration, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name);
- }
-
- // Captured fields must be named type symbols
- if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol)
- {
- diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
-
- continue;
- }
-
- string metadataName = typeSymbol.GetFullMetadataName();
- string typeName = HlslKnownTypes.GetMappedName(typeSymbol);
-
- _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
-
- // Allowed fields must be either resources, unmanaged values or delegates
- if (HlslKnownTypes.IsTypedResourceType(metadataName))
- {
- hlslResourceFound = true;
-
- // Track the type of items in the current buffer
- if (HlslKnownTypes.IsStructuredBufferType(metadataName))
- {
- types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]);
- }
-
- // Add the current mapping for the name (if the name used a reserved keyword)
- resources.Add((metadataName, mapping ?? fieldSymbol.Name, typeName));
- }
- else if (!typeSymbol.IsUnmanagedType &&
- typeSymbol.TypeKind != TypeKind.Delegate)
- {
- // Shaders can only capture valid HLSL resource types or unmanaged types
- diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, typeSymbol);
-
- continue;
- }
- else if (typeSymbol.IsUnmanagedType)
- {
- // Track the type if it's a custom struct
- if (!HlslKnownTypes.IsKnownHlslType(metadataName))
- {
- types.Add(typeSymbol);
- }
-
- values.Add((mapping ?? fieldSymbol.Name, typeName));
- }
- }
-
- // If the shader is a compute one (so no implicit output texture), it has to contain at least one resource
- if (!hlslResourceFound && isComputeShader)
- {
- diagnostics.Add(MissingShaderResources, structDeclarationSymbol, structDeclarationSymbol);
- }
-
- return (resources.ToImmutable(), values.ToImmutable());
- }
-
- ///
- /// Gets a sequence of shader static fields and their mapped names.
- ///
- /// The collection of produced instances.
- /// The instance for the type to process.
- /// The instance for the current type.
- /// The type symbol for the shader type.
- /// The collection of currently discovered types.
- /// The collection of discovered constant definitions.
- /// A sequence of static constant fields in .
- [Pure]
- private static ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields(
- ImmutableArray.Builder diagnostics,
- SemanticModelProvider semanticModel,
- StructDeclarationSyntax structDeclaration,
- INamedTypeSymbol structDeclarationSymbol,
- ICollection discoveredTypes,
- IDictionary constantDefinitions)
- {
- ImmutableArray<(string, string, string?)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, string?)>();
-
- foreach (var fieldDeclaration in structDeclaration.Members.OfType())
- {
- foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables)
- {
- IFieldSymbol fieldSymbol = (IFieldSymbol)semanticModel.For(variableDeclarator).GetDeclaredSymbol(variableDeclarator)!;
-
- if (!fieldSymbol.IsStatic || fieldSymbol.IsConst)
- {
- continue;
- }
-
- AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) });
-
- if (attribute is not null)
- {
- continue;
- }
-
- // Constant properties must be of a primitive, vector or matrix type
- if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol ||
- !HlslKnownTypes.IsKnownHlslType(typeSymbol.GetFullMetadataName()))
- {
- diagnostics.Add(InvalidShaderStaticFieldType, variableDeclarator, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
-
- continue;
- }
-
- _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
-
- string typeDeclaration = fieldSymbol.IsReadOnly switch
- {
- true => $"static const {HlslKnownTypes.GetMappedName(typeSymbol)}",
- false => $"static {HlslKnownTypes.GetMappedName(typeSymbol)}"
- };
-
- StaticFieldRewriter2 staticFieldRewriter = new(
- semanticModel,
- discoveredTypes,
- constantDefinitions,
- diagnostics);
-
- string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace(eol: "\n").ToFullString();
-
- builder.Add((mapping ?? fieldSymbol.Name, typeDeclaration, assignment));
- }
- }
-
- return builder.ToImmutable();
- }
-
- ///
- /// Gets a sequence of captured members and their mapped names.
- ///
- /// The collection of produced instances.
- /// The input instance to process.
- /// The collection of currently discovered types.
- /// A sequence of captured members in .
- [Pure]
- private static ImmutableArray<(string Name, string Type, int? Count)> GetSharedBuffers(
- ImmutableArray.Builder diagnostics,
- INamedTypeSymbol structDeclarationSymbol,
- ICollection types)
- {
- ImmutableArray<(string, string, int?)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, int?)>();
-
- foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType())
- {
- if (!fieldSymbol.IsStatic)
- {
- continue;
- }
-
- AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) });
-
- if (attribute is null)
- {
- continue;
- }
-
- if (fieldSymbol.Type is not IArrayTypeSymbol typeSymbol)
- {
- diagnostics.Add(InvalidGroupSharedFieldType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
-
- continue;
- }
-
- if (!typeSymbol.ElementType.IsUnmanagedType)
- {
- diagnostics.Add(InvalidGroupSharedFieldElementType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
-
- continue;
- }
-
- int? bufferSize = (int?)attribute.ConstructorArguments.FirstOrDefault().Value;
-
- string typeName = HlslKnownTypes.GetMappedElementName(typeSymbol);
-
- _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
-
- builder.Add((mapping ?? fieldSymbol.Name, typeName, bufferSize));
-
- types.Add((INamedTypeSymbol)typeSymbol.ElementType);
- }
-
- return builder.ToImmutable();
- }
-
- ///
- /// Gets a sequence of processed methods declared within a given type.
- ///
- /// The collection of produced instances.
- /// The type symbol for the shader type.
- /// The instance for the current type.
- /// The instance for the type to process.
- /// The collection of currently discovered types.
- /// The set of discovered and processed static methods.
- /// The collection of discovered constant definitions.
- /// Indicates whether or not represents a compute shader.
- /// A sequence of processed methods in , and the entry point.
- [Pure]
- private static (string EntryPoint, ImmutableArray<(string Signature, string Definition)> Methods, bool IsSamplerUser) GetProcessedMethods(
- ImmutableArray.Builder diagnostics,
- StructDeclarationSyntax structDeclaration,
- INamedTypeSymbol structDeclarationSymbol,
- SemanticModelProvider semanticModel,
- ICollection discoveredTypes,
- IDictionary staticMethods,
- IDictionary constantDefinitions,
- bool isComputeShader)
- {
- // Find all declared methods in the type
- ImmutableArray methodDeclarations = (
- from syntaxNode in structDeclaration.DescendantNodes()
- where syntaxNode.IsKind(SyntaxKind.MethodDeclaration)
- select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray();
-
- string? entryPoint = null;
- ImmutableArray<(string, string)>.Builder methods = ImmutableArray.CreateBuilder<(string, string)>();
- bool isSamplerUsed = false;
-
- foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations)
- {
- IMethodSymbol methodDeclarationSymbol = semanticModel.For(methodDeclaration).GetDeclaredSymbol(methodDeclaration)!;
- bool isShaderEntryPoint =
- (isComputeShader &&
- methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) &&
- methodDeclarationSymbol.ReturnsVoid &&
- methodDeclarationSymbol.TypeParameters.Length == 0 &&
- methodDeclarationSymbol.Parameters.Length == 0) ||
- (!isComputeShader &&
- methodDeclarationSymbol.Name == nameof(IPixelShader.Execute) &&
- methodDeclarationSymbol.ReturnType is not null && // TODO: match for pixel type
- methodDeclarationSymbol.TypeParameters.Length == 0 &&
- methodDeclarationSymbol.Parameters.Length == 0);
-
- // Create the source rewriter for the current method
- ShaderSourceRewriter2 shaderSourceRewriter = new(
- structDeclarationSymbol,
- semanticModel,
- discoveredTypes,
- staticMethods,
- constantDefinitions,
- diagnostics,
- isShaderEntryPoint);
-
- // Rewrite the method syntax tree
- MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia();
-
- // Track the implicit sampler, if used
- isSamplerUsed = isSamplerUsed || shaderSourceRewriter.IsSamplerUsed;
-
- // Emit the extracted local functions first
- foreach (var localFunction in shaderSourceRewriter.LocalFunctions)
- {
- methods.Add((
- localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
- localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString()));
- }
-
- // If the method is the shader entry point, do additional processing
- if (isShaderEntryPoint)
- {
- processedMethod = isComputeShader switch
- {
- true => new ExecuteMethodRewriter2.Compute(shaderSourceRewriter).Visit(processedMethod)!,
- false => new ExecuteMethodRewriter2.Pixel(shaderSourceRewriter).Visit(processedMethod)!
- };
-
- entryPoint = processedMethod.NormalizeWhitespace(eol: "\n").ToFullString();
- }
- else
- {
- methods.Add((
- processedMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
- processedMethod.NormalizeWhitespace(eol: "\n").ToFullString()));
- }
- }
-
- // Process static methods as well
- foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values)
- {
- methods.Add((
- staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
- staticMethod.NormalizeWhitespace(eol: "\n").ToFullString()));
- }
-
- return (entryPoint!, methods.ToImmutable(), isSamplerUsed);
- }
-
- ///
- /// Gets a sequence of discovered constants.
- ///
- /// The collection of discovered constant definitions.
- /// A sequence of discovered constants to declare in the shader.
- [Pure]
- internal static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary constantDefinitions)
- {
- ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(constantDefinitions.Count);
-
- foreach (var constant in constantDefinitions)
- {
- var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName();
- var constantName = $"__{ownerTypeName}__{constant.Key.Name}";
-
- builder.Add((constantName, constant.Value));
- }
-
- return builder.MoveToImmutable();
- }
-
- ///
- /// Gets the sequence of processed discovered custom types.
- ///
- /// The sequence of discovered custom types.
- /// A sequence of custom type definitions to add to the shader source.
- internal static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes(IEnumerable types)
- {
- ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>();
-
- foreach (var type in HlslKnownTypes.GetCustomTypes(types))
- {
- var structType = type.GetFullMetadataName().ToHlslIdentifierName();
- var structDeclaration = StructDeclaration(structType);
-
- // Declare the fields of the current type
- foreach (var field in type.GetMembers().OfType())
- {
- if (field.IsStatic) continue;
-
- INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type;
-
- // Convert the name to the fully qualified HLSL version
- if (!HlslKnownTypes.TryGetMappedName(fieldType.GetFullMetadataName(), out string? mapped))
- {
- mapped = fieldType.GetFullMetadataName().ToHlslIdentifierName();
- }
-
- structDeclaration = structDeclaration.AddMembers(
- FieldDeclaration(VariableDeclaration(
- IdentifierName(mapped!)).AddVariables(
- VariableDeclarator(Identifier(field.Name)))));
- }
-
- // Insert the trailing ; right after the closing bracket (after normalization)
- builder.Add((
- structType,
- structDeclaration
- .NormalizeWhitespace(eol: "\n")
- .WithSemicolonToken(Token(SyntaxKind.SemicolonToken))
- .ToFullString()));
- }
-
- return builder.ToImmutable();
- }
-
- ///
- /// Finds and reports all declared properties in a shader.
- ///
- /// The collection of produced instances.
- /// The input instance to process.
- private static void DetectAndReportPropertyDeclarations(ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol)
- {
- foreach (var propertySymbol in structDeclarationSymbol.GetMembers().OfType())
- {
- diagnostics.Add(DiagnosticDescriptors.PropertyDeclaration, propertySymbol);
- }
- }
-
- ///
- /// Produces the series of statements to build the current HLSL source.
- ///
- /// The sequence of defined constants for the shader.
- /// The sequence of declared types used by the shader.
- /// The sequence of resource instance fields for the current shader.
- /// The sequence of value instance fields for the current shader.
- /// The sequence of delegate fields for the current shader.
- /// The sequence of static fields referenced by the shader.
- /// The sequence of shared buffers declared by the shader.
- /// The sequence of processed methods used by the shader.
- /// Whether or not the current shader type is a compute shader.
- /// The type of the implicit target texture, if present.
- /// Whether the static sampler is used by the shader.
- /// The body of the entry point of the shader.
- /// The series of statements to build the HLSL source to compile to execute the current shader.
- private static HlslSourceInfo GetNonDynamicHlslSourceInfo(
- ImmutableArray<(string Name, string Value)> definedConstants,
- ImmutableArray<(string Name, string Definition)> declaredTypes,
- ImmutableArray<(string MetadataName, string Name, string HlslType)> resourceFields,
- ImmutableArray<(string Name, string HlslType)> valueFields,
- ImmutableArray delegateInstanceFields,
- ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> staticFields,
- ImmutableArray<(string Name, string Type, int? Count)> sharedBuffers,
- ImmutableArray<(string Signature, string Definition)> processedMethods,
- bool isComputeShader,
- string? implicitTextureType,
- bool isSamplerUsed,
-
- string executeMethod)
- {
- StringBuilder hlslBuilder = new();
-
- void AppendLF()
- {
- hlslBuilder.Append('\n');
- }
-
- void AppendLine(string text)
- {
- hlslBuilder.Append(text);
- }
-
- void AppendLineAndLF(string text)
- {
- hlslBuilder.Append(text);
- hlslBuilder.Append('\n');
- }
-
- void AppendCharacterAndLF(char c)
- {
- hlslBuilder.Append(c);
- hlslBuilder.Append('\n');
- }
-
- string FlushText()
- {
- string text = hlslBuilder.ToString();
-
- hlslBuilder.Clear();
-
- return text;
- }
-
- // Header
- AppendLineAndLF("// ================================================");
- AppendLineAndLF("// AUTO GENERATED");
- AppendLineAndLF("// ================================================");
- AppendLineAndLF("// This shader was created by ComputeSharp.");
- AppendLineAndLF("// See: https://github.com/Sergio0694/ComputeSharp.");
-
- // Group size constants
- AppendLF();
- AppendLine("#define __GroupSize__get_X ");
-
- string headerAndThreadsX = FlushText();
-
- AppendLF();
- AppendLine("#define __GroupSize__get_Y ");
-
- string threadsY = FlushText();
-
- AppendLF();
- AppendLine("#define __GroupSize__get_Z ");
-
- string threadsZ = FlushText();
-
- AppendLF();
-
- // Define declarations
- foreach (var (name, value) in definedConstants)
- {
- AppendLineAndLF($"#define {name} {value}");
- }
-
- string defines = FlushText();
-
- // Static fields
- if (staticFields.Any())
- {
- AppendLF();
-
- foreach (var field in staticFields)
- {
- if (field.Assignment is string assignment)
- {
- AppendLineAndLF($"{field.TypeDeclaration} {field.Name} = {assignment};");
- }
- else
- {
- AppendLineAndLF($"{field.TypeDeclaration} {field.Name};");
- }
- }
- }
-
- // Declared types
- foreach (var (_, typeDefinition) in declaredTypes)
- {
- AppendLF();
- AppendLineAndLF(typeDefinition);
- }
-
- string staticFieldsAndDeclaredTypes = FlushText();
-
- // Captured variables
- AppendLF();
- AppendLineAndLF("cbuffer _ : register(b0)");
- AppendCharacterAndLF('{');
- AppendLineAndLF(" uint __x;");
- AppendLineAndLF(" uint __y;");
-
- if (isComputeShader)
- {
- AppendLineAndLF(" uint __z;");
- }
-
- // User-defined values
- foreach (var (fieldName, fieldType) in valueFields)
- {
- AppendLineAndLF($" {fieldType} {fieldName};");
- }
-
- AppendCharacterAndLF('}');
-
- int constantBuffersCount = 1;
- int readOnlyBuffersCount = 0;
- int readWriteBuffersCount = 0;
-
- // Optional implicit texture field
- if (!isComputeShader)
- {
- AppendLF();
- AppendLineAndLF($"{implicitTextureType} __outputTexture : register(u{readWriteBuffersCount++});");
- }
-
- // Optional sampler field
- if (isSamplerUsed)
- {
- AppendLF();
- AppendLineAndLF("SamplerState __sampler : register(s);");
- }
-
- // Resources
- foreach (var (metadataName, fieldName, fieldType) in resourceFields)
- {
- if (HlslKnownTypes.IsConstantBufferType(metadataName))
- {
- AppendLF();
- AppendLineAndLF($"cbuffer _{fieldName} : register(b{constantBuffersCount++})");
- AppendCharacterAndLF('{');
- AppendLineAndLF($" {fieldType} {fieldName}[2];");
- AppendCharacterAndLF('}');
- }
- else if (HlslKnownTypes.IsReadOnlyTypedResourceType(metadataName))
- {
- AppendLF();
- AppendLineAndLF($"{fieldType} {fieldName} : register(t{readOnlyBuffersCount++});");
- }
- else if (HlslKnownTypes.IsReadWriteTypedResourceType(metadataName))
- {
- AppendLF();
- AppendLineAndLF($"{fieldType} {fieldName} : register(u{readWriteBuffersCount++});");
- }
- }
-
- // Shared buffers
- foreach (var (bufferName, bufferType, bufferCount) in sharedBuffers)
- {
- object count = (object?)bufferCount ?? "threadsX * threadsY * threadsZ";
-
- AppendLF();
- AppendLineAndLF($"groupshared {bufferType} {bufferName} [{count}];");
- }
-
- // Forward declarations
- foreach (var (forwardDeclaration, _) in processedMethods)
- {
- AppendLF();
- AppendLineAndLF(forwardDeclaration);
- }
-
- string capturedFieldsAndResourcesAndForwardDeclarations = FlushText();
-
- // Captured methods
- foreach (var (_, method) in processedMethods)
- {
- AppendLF();
- AppendLineAndLF(method);
- }
-
- string capturedMethods = FlushText();
-
- // Entry point
- AppendLF();
- AppendLineAndLF("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]");
- AppendLineAndLF(executeMethod);
-
- string entryPoint = FlushText();
-
- return new(
- headerAndThreadsX,
- threadsY,
- threadsZ,
- defines,
- staticFieldsAndDeclaredTypes,
- capturedFieldsAndResourcesAndForwardDeclarations,
- capturedMethods,
- entryPoint,
- implicitTextureType,
- isSamplerUsed,
- declaredTypes.Select(static t => t.Name).ToImmutableArray(),
- definedConstants.Select(static c => c.Name).ToImmutableArray(),
- processedMethods.Select(static m => m.Signature).ToImmutableArray(),
- delegateInstanceFields);
- }
-}