diff --git a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md
index 9507ad4e..74fadd53 100644
--- a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md
+++ b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md
@@ -43,16 +43,13 @@ CMPS0033 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentatio
CMPS0034 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0035 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0036 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
-CMPS0037 | ComputeSharp.SourceGenerators.AutoConstructorGenerator | Warning | AutoConstructorGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
-CMPS0040 | ComputeSharp.SourceGenerators.IShaderGenerator | Warning | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
-CMPS0041 | ComputeSharp.SourceGenerators.ShaderMethodSourceGenerator | Warning | ShaderMethodSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0037 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0038 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0039 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0040 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0041 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0042 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0043 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0044 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0045 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0046 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
-CMPS0047 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
-CMPS0048 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
-CMPS0049 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
-CMPS0050 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
-CMPS0051 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
diff --git a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.SyntaxReceiver.cs b/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.SyntaxReceiver.cs
deleted file mode 100644
index 478303bb..00000000
--- a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.SyntaxReceiver.cs
+++ /dev/null
@@ -1,54 +0,0 @@
-using System.Collections.Generic;
-using System.Linq;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-
-namespace ComputeSharp.SourceGenerators;
-
-///
-public sealed partial class AutoConstructorGenerator
-{
- ///
- /// An that selects candidate nodes to process.
- ///
- private sealed class SyntaxReceiver : ISyntaxContextReceiver
- {
- ///
- /// The list of info gathered during exploration.
- ///
- private readonly List- gatheredInfo = new();
-
- ///
- /// Gets the collection of gathered info to process.
- ///
- public IReadOnlyCollection
- GatheredInfo => this.gatheredInfo;
-
- ///
- public void OnVisitSyntaxNode(GeneratorSyntaxContext context)
- {
- if (context.Node is StructDeclarationSyntax { AttributeLists: { Count: > 0 } } structDeclaration &&
- context.SemanticModel.GetDeclaredSymbol(structDeclaration) is INamedTypeSymbol structSymbol &&
- context.SemanticModel.Compilation.GetTypeByMetadataName(typeof(AutoConstructorAttribute).FullName) is INamedTypeSymbol attributeSymbol &&
- structSymbol.GetAttributes().FirstOrDefault(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, attributeSymbol)) is AttributeData attributeData &&
- attributeData.ApplicationSyntaxReference is SyntaxReference syntaxReference &&
- syntaxReference.GetSyntax() is AttributeSyntax attributeSyntax)
- {
- this.gatheredInfo.Add(new Item(structDeclaration, structSymbol, attributeSyntax, attributeData));
- }
- }
-
- ///
- /// A model for a group of item representing a discovered type to process.
- ///
- /// The instance for the target struct declaration.
- /// The instance for .
- /// The instance for the target attribute over .
- /// The instance for .
- public sealed record Item(
- StructDeclarationSyntax StructDeclaration,
- INamedTypeSymbol StructSymbol,
- AttributeSyntax AttributeSyntax,
- AttributeData AttributeData);
- }
-}
diff --git a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs b/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs
index 1aac7f97..f04c3e04 100644
--- a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs
+++ b/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs
@@ -1,111 +1,151 @@
-using System.Collections.Immutable;
+using System.Collections.Generic;
+using System.Collections.Immutable;
using System.Linq;
using System.Text;
-using ComputeSharp.SourceGenerators.Diagnostics;
using ComputeSharp.SourceGenerators.Extensions;
+using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
-using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
-using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle;
namespace ComputeSharp.SourceGenerators;
///
/// A source generator creating constructors for types annotated with .
///
-[Generator]
-public sealed partial class AutoConstructorGenerator : ISourceGenerator
+[Generator(LanguageNames.CSharp)]
+public sealed partial class AutoConstructorGenerator : IIncrementalGenerator
{
///
- public void Initialize(GeneratorInitializationContext context)
+ public void Initialize(IncrementalGeneratorInitializationContext context)
{
- context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver());
- }
+ // Get all declared struct symbols with the [AutoConstructor] attribute
+ IncrementalValuesProvider structDeclarations =
+ context.SyntaxProvider
+ .CreateSyntaxProvider(
+ static (node, token) => node is StructDeclarationSyntax structDeclaration,
+ static (context, token) => (INamedTypeSymbol?)context.SemanticModel.GetDeclaredSymbol(context.Node, token))
+ .Where(static symbol => symbol is not null &&
+ symbol.GetAttributes().Any(static a => a.AttributeClass?.ToDisplayString() == typeof(AutoConstructorAttribute).FullName))!;
- ///
- public void Execute(GeneratorExecutionContext context)
- {
- // Get the syntax receiver with the candidate nodes
- if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver)
- {
- return;
- }
+ // Get the type hierarchy and fields info
+ IncrementalValuesProvider<(HierarchyInfo Left, ImmutableArray Right)> constructorInfo =
+ structDeclarations
+ .Select(static (item, token) => (Hierarchy: HierarchyInfo.From(item), Parameters: Ctor.GetData(item)))
+ .Where(static item => !item.Parameters.IsEmpty)
+ .WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer.Default.ForImmutableArray());
- foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo)
+ // Generate the constructors
+ context.RegisterSourceOutput(constructorInfo, static (context, item) =>
{
- try
- {
- OnExecute(context, item.StructDeclaration, item.StructSymbol);
- }
- catch
- {
- context.ReportDiagnostic(AutoConstructorGeneratorError, item.AttributeSyntax, item.StructSymbol);
- }
- }
+ CompilationUnitSyntax compilationUnit = Ctor.GetSyntax(item.Left, item.Right);
+
+ context.AddSource($"{item.Left.FilenameHint}.Ctor", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8));
+ });
}
///
- /// Processes a given target type.
+ /// A helper with all logic to generate the constructor declarations.
///
- /// The input instance to use.
- /// The node to process.
- /// The for .
- private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol)
+ private static class Ctor
{
- // Extract the info on the type to process
- var namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces));
- var structName = structDeclaration.Identifier.Text;
- var structModifiers = structDeclaration.Modifiers;
- var fields = (
- from fieldSymbol in structDeclarationSymbol.GetMembers().OfType()
- where !fieldSymbol.IsConst && !fieldSymbol.IsStatic && !fieldSymbol.IsFixedSizeBuffer
- let typeName = fieldSymbol.Type!.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)
- let fieldFullType = ParseTypeName(typeName)
- select (Type: fieldFullType, Identifier: Identifier(fieldSymbol.Name))).ToImmutableArray();
-
- // Create the constructor declaration for the type. This will
- // produce a constructor with simple initialization of all variables:
- //
- // public MyType(Foo a, Bar b, Baz c, ...)
- // {
- // this.a = a;
- // this.b = b;
- // this.c = c;
- // ...
- // }
- var structDeclarationSyntax =
- StructDeclaration(structName).WithModifiers(structModifiers).AddMembers(
- ConstructorDeclaration(structName)
- .AddModifiers(Token(SyntaxKind.PublicKeyword))
- .AddParameterListParameters(fields.Select(field => Parameter(field.Identifier).WithType(field.Type)).ToArray())
- .AddBodyStatements(fields.Select(field => ParseStatement($"this.{field.Identifier} = {field.Identifier};")).ToArray()));
-
- TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax;
-
- // Add all parent types in ascending order, if any
- foreach (var parentType in structDeclaration.Ancestors().OfType())
+ ///
+ /// Gets the sequence of items for all fields in the input type.
+ ///
+ /// The being inspected.
+ /// The sequence of items for all fields in .
+ public static ImmutableArray GetData(INamedTypeSymbol structDeclarationSymbol)
{
- typeDeclarationSyntax = parentType
- .WithMembers(SingletonList(typeDeclarationSyntax))
- .WithConstraintClauses(List())
- .WithBaseList(null)
- .WithAttributeLists(List())
- .WithoutTrivia();
+ return (
+ from fieldSymbol in structDeclarationSymbol.GetMembers().OfType()
+ where fieldSymbol is { IsConst: false, IsStatic: false, IsFixedSizeBuffer: false }
+ let typeName = fieldSymbol.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)
+ select new ParameterInfo(typeName, fieldSymbol.Name)).ToImmutableArray();
}
- // Create the compilation unit with the namespace and target member.
- // From this, we can finally generate the source code to output.
- var source =
- CompilationUnit().AddMembers(
- FileScopedNamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax)
- .WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList())))
- .NormalizeWhitespace(eol: "\n")
- .ToFullString();
+ ///
+ /// Gets the instance for a given type and sequence of parameters.
+ ///
+ /// The type hierarchy info.
+ /// The sequence of parameters to initialize.
+ /// A instance for a specified type.
+ public static CompilationUnitSyntax GetSyntax(HierarchyInfo hierarchyInfo, ImmutableArray parameters)
+ {
+ // Create the constructor declaration for the type. This will
+ // produce a constructor with simple initialization of all variables:
+ //
+ // public MyType(Foo a, Bar b, Baz c, ...)
+ // {
+ // this.a = a;
+ // this.b = b;
+ // this.c = c;
+ // ...
+ // }
+ ConstructorDeclarationSyntax constructorDeclaration =
+ ConstructorDeclaration(hierarchyInfo.Names[0])
+ .AddModifiers(Token(SyntaxKind.PublicKeyword))
+ .AddParameterListParameters(parameters.Select(field => Parameter(Identifier(field.Name)).WithType(IdentifierName(field.Type))).ToArray())
+ .AddBodyStatements(parameters.Select(field => ParseStatement($"this.{field.Name} = {field.Name};")).ToArray());
- // Add the partial type
- context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8));
+ // Add the unsafe modifier, if needed
+ if (parameters.Any(static param => param.Type.Contains("*")))
+ {
+ constructorDeclaration = constructorDeclaration.AddModifiers(Token(SyntaxKind.UnsafeKeyword));
+ }
+
+ // Constructor attributes
+ AttributeListSyntax[] attributes =
+ {
+ AttributeList(SingletonSeparatedList(
+ Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments(
+ AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(AutoConstructorGenerator).FullName))),
+ AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(AutoConstructorGenerator).Assembly.GetName().Version.ToString())))))),
+ AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))),
+ AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage"))))
+ };
+
+ // Create the partial shader type declaration with the given method implementation.
+ // This code produces a struct declaration as follows:
+ //
+ // partial struct
+ // {
+ //
+ // }
+ StructDeclarationSyntax structDeclarationSyntax =
+ StructDeclaration(hierarchyInfo.Names[0])
+ .AddModifiers(Token(SyntaxKind.PartialKeyword))
+ .AddMembers(constructorDeclaration.AddAttributeLists(attributes));
+
+ TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax;
+
+ // Add all parent types in ascending order, if any
+ foreach (string parentType in hierarchyInfo.Names.AsSpan().Slice(1))
+ {
+ typeDeclarationSyntax =
+ ClassDeclaration(parentType)
+ .AddModifiers(Token(SyntaxKind.PartialKeyword))
+ .AddMembers(typeDeclarationSyntax);
+ }
+
+ // Create the compilation unit with disabled warnings, target namespace and generated type.
+ // This will produce code as follows:
+ //
+ // #pragma warning disable
+ //
+ // namespace ;
+ //
+ //
+ return
+ CompilationUnit().AddMembers(
+ FileScopedNamespaceDeclaration(IdentifierName(hierarchyInfo.Namespace))
+ .AddMembers(typeDeclarationSyntax)
+ .WithNamespaceKeyword(Token(TriviaList(
+ Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))),
+ SyntaxKind.NamespaceKeyword,
+ TriviaList())))
+ .NormalizeWhitespace(eol: "\n");
+ }
}
}
diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs
index 1e5cf347..7f11ded0 100644
--- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs
+++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs
@@ -496,59 +496,11 @@ internal static class DiagnosticDescriptors
description: "String literal expressions cannot be used in a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
- ///
- /// Gets a for an internal error in .
- ///
- /// Format: "The generator AutoConstructorGenerator failed to execute on type {0}, and its constructor might not be available".
- ///
- ///
- public static readonly DiagnosticDescriptor AutoConstructorGeneratorError = new(
- id: "CMPS0037",
- title: $"Internal error for {nameof(AutoConstructorGenerator)}",
- messageFormat: $"The generator {nameof(AutoConstructorGenerator)} failed to execute on type {{0}}, and its constructor might not be available",
- category: typeof(AutoConstructorGenerator).FullName,
- defaultSeverity: DiagnosticSeverity.Warning,
- isEnabledByDefault: true,
- description: $"The {nameof(AutoConstructorGenerator)} generator encountered an error while processing a type, and its constructor might not be available. Please report this issue at https://github.com/Sergio0694/ComputeSharp/issues.",
- helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
-
- ///
- /// Gets a for an internal error in .
- ///
- /// Format: "The generator IShaderGenerator failed to execute on type {0}, and trying to use that shader might result in a runtime crash".
- ///
- ///
- public static readonly DiagnosticDescriptor IShaderGeneratorError = new(
- id: "CMPS0040",
- title: $"Internal error for {nameof(IShaderGenerator)}",
- messageFormat: $"The generator {nameof(IShaderGenerator)} failed to execute on type {{0}}, and trying to use that shader might result in a runtime crash",
- category: typeof(IShaderGenerator).FullName,
- defaultSeverity: DiagnosticSeverity.Warning,
- isEnabledByDefault: true,
- description: $"The {nameof(IShaderGenerator)} generator encountered an error while processing a type, and trying to use that shader might result in a runtime crash. Please report this issue at https://github.com/Sergio0694/ComputeSharp/issues.",
- helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
-
- ///
- /// Gets a for an internal error in .
- ///
- /// Format: "The generator ShaderMethodSourceGenerator failed to execute on method {0}, and using it in a shader might result in a runtime crash".
- ///
- ///
- public static readonly DiagnosticDescriptor ShaderMethodSourceGeneratorError = new(
- id: "CMPS0041",
- title: $"Internal error for {nameof(ShaderMethodSourceGenerator)}",
- messageFormat: $"The generator {nameof(ShaderMethodSourceGenerator)} failed to execute on method {{0}}, and using it in a shader might result in a runtime crash",
- category: typeof(ShaderMethodSourceGenerator).FullName,
- defaultSeverity: DiagnosticSeverity.Warning,
- isEnabledByDefault: true,
- description: $"The {nameof(ShaderMethodSourceGenerator)} generator encountered an error while processing a method, and using it in a shader might result in a runtime crash. Please report this issue at https://github.com/Sergio0694/ComputeSharp/issues.",
- helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
-
///
/// Gets a for an incorrect matrix swizzling property argument.
///
public static readonly DiagnosticDescriptor NonConstantMatrixSwizzledIndex = new(
- id: "CMPS0042",
+ id: "CMPS0037",
title: "Non constant matrix swizzled property argument",
messageFormat: "The arguments in a swizzled indexer for a matrix type must be compile-time constants",
category: typeof(ShaderMethodSourceGenerator).FullName,
@@ -564,7 +516,7 @@ internal static class DiagnosticDescriptors
///
///
public static readonly DiagnosticDescriptor InvalidShaderStaticFieldType = new(
- id: "CMPS0043",
+ id: "CMPS0038",
title: "Invalid shader static field type",
messageFormat: "The compute shader of type {0} contains a static field \"{1}\" of an invalid type {2} (only primitive, vector and matrix types are supported)",
category: typeof(IComputeShader).FullName,
@@ -577,7 +529,7 @@ internal static class DiagnosticDescriptors
/// Gets a for an invalid usage.
///
public static readonly DiagnosticDescriptor InvalidDispatchSizeUsage = new(
- id: "CMPS0044",
+ id: "CMPS0039",
title: "Invalid DispatchSize usage",
messageFormat: "The DispatchSize type can only be used within the main body of a compute shader",
category: typeof(IComputeShader).FullName,
@@ -590,7 +542,7 @@ internal static class DiagnosticDescriptors
/// Gets a for a property declaration.
///
public static readonly DiagnosticDescriptor PropertyDeclaration = new(
- id: "CMPS0045",
+ id: "CMPS0040",
title: "Property declaration",
messageFormat: "Property declarations cannot be used in a compute shader",
category: typeof(IComputeShader).FullName,
@@ -606,7 +558,7 @@ internal static class DiagnosticDescriptors
///
///
public static readonly DiagnosticDescriptor ShaderDispatchDataSizeExceeded = new(
- id: "CMPS0046",
+ id: "CMPS0041",
title: "Shader dispatch data size exceeded",
messageFormat: "The compute shader of type {0} has exceeded the maximum allowed size for captured values and resources",
category: typeof(IComputeShader).FullName,
@@ -622,7 +574,7 @@ internal static class DiagnosticDescriptors
///
///
public static readonly DiagnosticDescriptor MultipleShaderTypesImplemented = new(
- id: "CMPS0047",
+ id: "CMPS0042",
title: "Multiple shader implementations for type declaration",
messageFormat: $"The shader of type {{0}} cannot implement more than one shader interface",
category: typeof(IShaderGenerator).FullName,
@@ -638,7 +590,7 @@ internal static class DiagnosticDescriptors
///
///
public static readonly DiagnosticDescriptor EmbeddedBytecodeWithDynamicShader = new(
- id: "CMPS0048",
+ id: "CMPS0043",
title: "Embedded bytecode for dynamic shader",
messageFormat: $"The shader of type {{0}} cannot be precompiled, as it is dynamic (it captures delegate fields)",
category: typeof(IShaderGenerator).FullName,
@@ -654,7 +606,7 @@ internal static class DiagnosticDescriptors
///
///
public static readonly DiagnosticDescriptor InvalidEmbeddedBytecodeThreadIds = new(
- id: "CMPS0049",
+ id: "CMPS0044",
title: "Invalid thread ids for shader with embedded bytecode",
messageFormat: $"The shader of type {{0}} is annotated with invalid thread ids values ({{1}}, {{2}}, {{3}})",
category: typeof(IShaderGenerator).FullName,
@@ -670,7 +622,7 @@ internal static class DiagnosticDescriptors
///
///
public static readonly DiagnosticDescriptor EmbeddedBytecodeFailedWithWin32Exception = new(
- id: "CMPS0050",
+ id: "CMPS0045",
title: "Embedded bytecode compilation failed due to Win32 exception",
messageFormat: $"The shader of type {{0}} failed to compile due to a Win32 exception (HRESULT: {{1:X8}}, Message: \"{{2}}\")",
category: typeof(IShaderGenerator).FullName,
@@ -686,7 +638,7 @@ internal static class DiagnosticDescriptors
///
///
public static readonly DiagnosticDescriptor EmbeddedBytecodeFailedWithHlslCompilationException = new(
- id: "CMPS0051",
+ id: "CMPS0046",
title: "Embedded bytecode compilation failed due to an HLSL compiler error",
messageFormat: $"The shader of type {{0}} failed to compile due to an HLSL compiler error (Message: \"{{1}}\")",
category: typeof(IShaderGenerator).FullName,
diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs
index a5894cd6..8584bee1 100644
--- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs
+++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs
@@ -1,4 +1,5 @@
-using System.Linq;
+using System.Collections.Immutable;
+using System.Linq;
using Microsoft.CodeAnalysis;
namespace ComputeSharp.SourceGenerators.Diagnostics;
@@ -39,4 +40,52 @@ internal static class DiagnosticsExtensions
{
context.ReportDiagnostic(Diagnostic.Create(descriptor, node.GetLocation(), args));
}
+
+ ///
+ /// Adds a new diagnostics to the target builder.
+ ///
+ /// The collection of produced instances.
+ /// The input for the diagnostics to create.
+ /// The source to attach the diagnostics to.
+ /// The optional arguments for the formatted message to include.
+ public static void Add(
+ this ImmutableArray.Builder diagnostics,
+ DiagnosticDescriptor descriptor,
+ ISymbol symbol,
+ params object[] args)
+ {
+ diagnostics.Add(Diagnostic.Create(descriptor, symbol.Locations.FirstOrDefault(), args));
+ }
+
+ ///
+ /// Adds a new diagnostics to the target builder.
+ ///
+ /// The collection of produced instances.
+ /// The input for the diagnostics to create.
+ /// The source to attach the diagnostics to.
+ /// The optional arguments for the formatted message to include.
+ public static void Add(
+ this ImmutableArray.Builder diagnostics,
+ DiagnosticDescriptor descriptor,
+ SyntaxNode node,
+ params object[] args)
+ {
+ diagnostics.Add(Diagnostic.Create(descriptor, node.GetLocation(), args));
+ }
+
+ ///
+ /// Registers an output node into an to output diagnostics.
+ ///
+ /// The input instance.
+ /// The input sequence of diagnostics.
+ public static void ReportDiagnostics(this IncrementalGeneratorInitializationContext context, IncrementalValuesProvider> diagnostics)
+ {
+ context.RegisterSourceOutput(diagnostics, static (context, diagnostics) =>
+ {
+ foreach (Diagnostic diagnostic in diagnostics)
+ {
+ context.ReportDiagnostic(diagnostic);
+ }
+ });
+ }
}
diff --git a/src/ComputeSharp.SourceGenerators/Extensions/HashCodeExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/HashCodeExtensions.cs
new file mode 100644
index 00000000..7d486566
--- /dev/null
+++ b/src/ComputeSharp.SourceGenerators/Extensions/HashCodeExtensions.cs
@@ -0,0 +1,40 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.Immutable;
+
+namespace ComputeSharp.SourceGenerators.Extensions;
+
+///
+/// Extension methods for .
+///
+internal static class HashCodeExtensions
+{
+ ///
+ /// Adds all items from a given instance to an hashcode.
+ ///
+ /// The type of items to hash.
+ /// The target instance.
+ /// The input items to hash.
+ public static void AddRange(this ref HashCode hashCode, ImmutableArray items)
+ {
+ foreach (T item in items)
+ {
+ hashCode.Add(item);
+ }
+ }
+
+ ///
+ /// Adds all items from a given instance to an hashcode.
+ ///
+ /// The type of items to hash.
+ /// The target instance.
+ /// A comparer to get hashcodes for items.
+ /// The input items to hash.
+ public static void AddRange(this ref HashCode hashCode, ImmutableArray items, IEqualityComparer comparer)
+ {
+ foreach (T item in items)
+ {
+ hashCode.Add(item, comparer);
+ }
+ }
+}
diff --git a/src/ComputeSharp.SourceGenerators/Extensions/IEqualityComparerExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/IEqualityComparerExtensions.cs
new file mode 100644
index 00000000..306d8c11
--- /dev/null
+++ b/src/ComputeSharp.SourceGenerators/Extensions/IEqualityComparerExtensions.cs
@@ -0,0 +1,59 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.Immutable;
+
+namespace ComputeSharp.SourceGenerators.Extensions;
+
+///
+/// Extension methods for .
+///
+internal static class IEqualityComparerExtensions
+{
+ ///
+ /// Gets an for an sequence.
+ ///
+ /// The type of items to compare.
+ /// The compare for individual items.
+ public static IEqualityComparer> ForImmutableArray(this IEqualityComparer comparer)
+ {
+ return new Comparer(comparer);
+ }
+
+ ///
+ /// An implementation for an value.
+ ///
+ public sealed class Comparer : IEqualityComparer>
+ {
+ ///
+ /// The comparer.
+ ///
+ private readonly IEqualityComparer comparer;
+
+ ///
+ /// Creates a new instance with the specified parameters.
+ ///
+ /// The comparer.
+ public Comparer(IEqualityComparer comparer)
+ {
+ this.comparer = comparer;
+ }
+
+ ///
+ public bool Equals(ImmutableArray x, ImmutableArray y)
+ {
+ return
+ x == y ||
+ x.SequenceEqual(y, this.comparer);
+ }
+
+ ///
+ public int GetHashCode(ImmutableArray obj)
+ {
+ HashCode hashCode = default;
+
+ hashCode.AddRange(obj, this.comparer);
+
+ return hashCode.ToHashCode();
+ }
+ }
+}
diff --git a/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs
index aade5e79..dac1c8f9 100644
--- a/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs
+++ b/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs
@@ -116,17 +116,6 @@ internal static class ISymbolExtensions
return symbol.GetFullMetadataName().Replace('`', '-').Replace('+', '.');
}
- ///
- /// Gets a valid filename for a target symbol and generator type.
- ///
- /// The symbol being processed.
- /// A filename in the form "<SYMBOL_FULLNAME>"
- [Pure]
- public static string GetGeneratedFileName(this IMethodSymbol symbol)
- {
- return symbol.GetFullMetadataName(true).Replace('`', '-').Replace('+', '.');
- }
-
///
/// Tracks an instance and returns an HLSL compatible object.
///
diff --git a/src/ComputeSharp.SourceGenerators/Extensions/ImmutableArrayExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/ImmutableArrayExtensions.cs
new file mode 100644
index 00000000..e4100441
--- /dev/null
+++ b/src/ComputeSharp.SourceGenerators/Extensions/ImmutableArrayExtensions.cs
@@ -0,0 +1,50 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.Immutable;
+
+namespace ComputeSharp.SourceGenerators.Extensions;
+
+///
+/// Extension methods for .
+///
+internal static class ImmutableArrayExtensions
+{
+ ///
+ /// Compares two sequences for equality.
+ ///
+ /// The items to compare.
+ /// The left sequence of items.
+ /// The right sequence of items.
+ /// Whether or not equals .
+ public static bool SequenceEqual(this ImmutableArray left, ImmutableArray right)
+ where T : IEquatable
+ {
+ return left.AsSpan().SequenceEqual(right.AsSpan());
+ }
+
+ ///
+ /// Compares two sequences for equality.
+ ///
+ /// The items to compare.
+ /// The left sequence of items.
+ /// The right sequence of items.
+ /// The instance used to compare items.
+ /// Whether or not equals .
+ public static bool SequenceEqual(this ImmutableArray left, ImmutableArray right, IEqualityComparer comparer)
+ {
+ if (left.Length != right.Length)
+ {
+ return false;
+ }
+
+ for (int i = 0; i < left.Length; i++)
+ {
+ if (!comparer.Equals(left[i], right[i]))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+}
diff --git a/src/ComputeSharp.SourceGenerators/Extensions/IncrementalValuesProviderExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/IncrementalValuesProviderExtensions.cs
new file mode 100644
index 00000000..bdcd5290
--- /dev/null
+++ b/src/ComputeSharp.SourceGenerators/Extensions/IncrementalValuesProviderExtensions.cs
@@ -0,0 +1,143 @@
+using System;
+using System.Collections.Generic;
+using Microsoft.CodeAnalysis;
+
+namespace ComputeSharp.SourceGenerators.Extensions;
+
+///
+/// Extension methods for .
+///
+internal static class IncrementalValuesProviderExtensions
+{
+ ///
+ /// Creates a new instance with a gven pair of comparers.
+ ///
+ /// The type of left items in each tuple.
+ /// The type of right items in each tuple.
+ /// The input instance.
+ /// An instance for items.
+ /// An instance for items.
+ /// An with the specified comparers applied to each item.
+ public static IncrementalValuesProvider<(TLeft Left, TRight Right)> WithComparers(
+ this IncrementalValuesProvider<(TLeft Left, TRight Right)> source,
+ IEqualityComparer comparerLeft,
+ IEqualityComparer comparerRight)
+ {
+ return source.WithComparer(new Comparer(comparerLeft, comparerRight));
+ }
+
+ ///
+ /// Creates a new instance with a gven pair of comparers.
+ ///
+ /// The type of first items in each tuple.
+ /// The type of second items in each tuple.
+ /// The type of third items in each tuple.
+ /// The input instance.
+ /// An instance for items.
+ /// An instance for items.
+ /// An instance for items.
+ /// An with the specified comparers applied to each item.
+ public static IncrementalValuesProvider<(T1, T2, T3)> WithComparers(
+ this IncrementalValuesProvider<(T1, T2, T3)> source,
+ IEqualityComparer comparer1,
+ IEqualityComparer comparer2,
+ IEqualityComparer comparer3)
+ {
+ return source.WithComparer(new Comparer(comparer1, comparer2, comparer3));
+ }
+
+ ///
+ /// An implementation for a value tuple.
+ ///
+ public sealed class Comparer : IEqualityComparer<(TLeft Left, TRight Right)>
+ {
+ ///
+ /// The comparer.
+ ///
+ private readonly IEqualityComparer comparerLeft;
+
+ ///
+ /// The comparer.
+ ///
+ private readonly IEqualityComparer comparerRight;
+
+ ///
+ /// Creates a new instance with the specified parameters.
+ ///
+ /// The comparer.
+ /// The comparer.
+ public Comparer(IEqualityComparer comparerLeft, IEqualityComparer comparerRight)
+ {
+ this.comparerLeft = comparerLeft;
+ this.comparerRight = comparerRight;
+ }
+
+ ///
+ public bool Equals((TLeft Left, TRight Right) x, (TLeft Left, TRight Right) y)
+ {
+ return
+ this.comparerLeft.Equals(x.Left, y.Left) &&
+ this.comparerRight.Equals(x.Right, y.Right);
+ }
+
+ ///
+ public int GetHashCode((TLeft Left, TRight Right) obj)
+ {
+ return HashCode.Combine(
+ this.comparerLeft.GetHashCode(obj.Left),
+ this.comparerRight.GetHashCode(obj.Right));
+ }
+ }
+
+ ///
+ /// An implementation for a value tuple.
+ ///
+ public sealed class Comparer : IEqualityComparer<(T1, T2, T3)>
+ {
+ ///
+ /// The comparer.
+ ///
+ private readonly IEqualityComparer comparer1;
+
+ ///
+ /// The comparer.
+ ///
+ private readonly IEqualityComparer comparer2;
+
+ ///
+ /// The comparer.
+ ///
+ private readonly IEqualityComparer comparer3;
+
+ ///
+ /// Creates a new instance with the specified parameters.
+ ///
+ /// The comparer.
+ /// The comparer.
+ /// The comparer.
+ public Comparer(IEqualityComparer comparer1, IEqualityComparer comparer2, IEqualityComparer comparer3)
+ {
+ this.comparer1 = comparer1;
+ this.comparer2 = comparer2;
+ this.comparer3 = comparer3;
+ }
+
+ ///
+ public bool Equals((T1, T2, T3) x, (T1, T2, T3) y)
+ {
+ return
+ this.comparer1.Equals(x.Item1, y.Item1) &&
+ this.comparer2.Equals(x.Item2, y.Item2) &&
+ this.comparer3.Equals(x.Item3, y.Item3);
+ }
+
+ ///
+ public int GetHashCode((T1, T2, T3) obj)
+ {
+ return HashCode.Combine(
+ this.comparer1.GetHashCode(obj.Item1),
+ this.comparer2.GetHashCode(obj.Item2),
+ this.comparer3.GetHashCode(obj.Item3));
+ }
+ }
+}
diff --git a/src/ComputeSharp.SourceGenerators/GlobalUsingDirectivesGenerator.cs b/src/ComputeSharp.SourceGenerators/GlobalUsingDirectivesGenerator.cs
index 020d0056..53d86891 100644
--- a/src/ComputeSharp.SourceGenerators/GlobalUsingDirectivesGenerator.cs
+++ b/src/ComputeSharp.SourceGenerators/GlobalUsingDirectivesGenerator.cs
@@ -9,13 +9,13 @@ namespace ComputeSharp.SourceGenerators;
///
/// A source generator to create global using directives for the HLSL primitive types.
///
-[Generator]
-public sealed class GlobalUsingDirectivesGenerator : ISourceGenerator
+[Generator(LanguageNames.CSharp)]
+public sealed class GlobalUsingDirectivesGenerator : IIncrementalGenerator
{
///
- public void Initialize(GeneratorInitializationContext context)
+ public void Initialize(IncrementalGeneratorInitializationContext context)
{
- context.RegisterForPostInitialization(static context =>
+ context.RegisterPostInitializationOutput(static context =>
{
const string filename = "ComputeSharp.SourceGenerators.EmbeddedResources.GlobalUsingDirectives.cs";
@@ -27,9 +27,4 @@ public sealed class GlobalUsingDirectivesGenerator : ISourceGenerator
context.AddSource("GlobalUsingDirectives.cs", SourceText.From(globalUsingDirectives, Encoding.UTF8));
});
}
-
- ///
- public void Execute(GeneratorExecutionContext context)
- {
- }
}
diff --git a/src/ComputeSharp.SourceGenerators/Helpers/HashCode.cs b/src/ComputeSharp.SourceGenerators/Helpers/HashCode.cs
index 1861ee67..94ea71f0 100644
--- a/src/ComputeSharp.SourceGenerators/Helpers/HashCode.cs
+++ b/src/ComputeSharp.SourceGenerators/Helpers/HashCode.cs
@@ -1,10 +1,181 @@
-namespace System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security.Cryptography;
+
+#pragma warning disable CS0809
+
+namespace System;
///
/// A polyfill type that mirrors some methods from on .NET 6.
///
internal struct HashCode
{
+ private const uint Prime1 = 2654435761U;
+ private const uint Prime2 = 2246822519U;
+ private const uint Prime3 = 3266489917U;
+ private const uint Prime4 = 668265263U;
+ private const uint Prime5 = 374761393U;
+
+ private static readonly uint seed = GenerateGlobalSeed();
+
+ private uint v1, v2, v3, v4;
+ private uint queue1, queue2, queue3;
+ private uint length;
+
+ ///
+ /// Initializes the default seed.
+ ///
+ /// A random seed.
+ private static unsafe uint GenerateGlobalSeed()
+ {
+ byte[] bytes = new byte[4];
+
+ RandomNumberGenerator.Create().GetBytes(bytes);
+
+ return BitConverter.ToUInt32(bytes, 0);
+ }
+
+ ///
+ /// Combines a value into a hash code.
+ ///
+ /// The type of the value to combine into the hash code.
+ /// The value to combine into the hash code.
+ /// The hash code that represents the value.
+ public static int Combine(T1 value)
+ {
+ uint hc1 = (uint)(value?.GetHashCode() ?? 0);
+ uint hash = MixEmptyState();
+
+ hash += 4;
+ hash = QueueRound(hash, hc1);
+ hash = MixFinal(hash);
+
+ return (int)hash;
+ }
+
+ ///
+ /// Combines two values into a hash code.
+ ///
+ /// The type of the first value to combine into the hash code.
+ /// The type of the second value to combine into the hash code.
+ /// The first value to combine into the hash code.
+ /// The second value to combine into the hash code.
+ /// The hash code that represents the values.
+ public static int Combine(T1 value1, T2 value2)
+ {
+ uint hc1 = (uint)(value1?.GetHashCode() ?? 0);
+ uint hc2 = (uint)(value2?.GetHashCode() ?? 0);
+ uint hash = MixEmptyState();
+
+ hash += 8;
+ hash = QueueRound(hash, hc1);
+ hash = QueueRound(hash, hc2);
+ hash = MixFinal(hash);
+
+ return (int)hash;
+ }
+
+ ///
+ /// Combines three values into a hash code.
+ ///
+ /// The type of the first value to combine into the hash code.
+ /// The type of the second value to combine into the hash code.
+ /// The type of the third value to combine into the hash code.
+ /// The first value to combine into the hash code.
+ /// The second value to combine into the hash code.
+ /// The third value to combine into the hash code.
+ /// The hash code that represents the values.
+ public static int Combine(T1 value1, T2 value2, T3 value3)
+ {
+ uint hc1 = (uint)(value1?.GetHashCode() ?? 0);
+ uint hc2 = (uint)(value2?.GetHashCode() ?? 0);
+ uint hc3 = (uint)(value3?.GetHashCode() ?? 0);
+ uint hash = MixEmptyState();
+
+ hash += 12;
+ hash = QueueRound(hash, hc1);
+ hash = QueueRound(hash, hc2);
+ hash = QueueRound(hash, hc3);
+ hash = MixFinal(hash);
+
+ return (int)hash;
+ }
+
+ ///
+ /// Combines four values into a hash code.
+ ///
+ /// The type of the first value to combine into the hash code.
+ /// The type of the second value to combine into the hash code.
+ /// The type of the third value to combine into the hash code.
+ /// The type of the fourth value to combine into the hash code.
+ /// The first value to combine into the hash code.
+ /// The second value to combine into the hash code.
+ /// The third value to combine into the hash code.
+ /// The fourth value to combine into the hash code.
+ /// The hash code that represents the values.
+ public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4)
+ {
+ uint hc1 = (uint)(value1?.GetHashCode() ?? 0);
+ uint hc2 = (uint)(value2?.GetHashCode() ?? 0);
+ uint hc3 = (uint)(value3?.GetHashCode() ?? 0);
+ uint hc4 = (uint)(value4?.GetHashCode() ?? 0);
+
+ Initialize(out uint v1, out uint v2, out uint v3, out uint v4);
+
+ v1 = Round(v1, hc1);
+ v2 = Round(v2, hc2);
+ v3 = Round(v3, hc3);
+ v4 = Round(v4, hc4);
+
+ uint hash = MixState(v1, v2, v3, v4);
+
+ hash += 16;
+ hash = MixFinal(hash);
+
+ return (int)hash;
+ }
+
+ ///
+ /// Combines five values into a hash code.
+ ///
+ /// The type of the first value to combine into the hash code.
+ /// The type of the second value to combine into the hash code.
+ /// The type of the third value to combine into the hash code.
+ /// The type of the fourth value to combine into the hash code.
+ /// The type of the fifth value to combine into the hash code.
+ /// The first value to combine into the hash code.
+ /// The second value to combine into the hash code.
+ /// The third value to combine into the hash code.
+ /// The fourth value to combine into the hash code.
+ /// The fifth value to combine into the hash code.
+ /// The hash code that represents the values.
+ public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5)
+ {
+ uint hc1 = (uint)(value1?.GetHashCode() ?? 0);
+ uint hc2 = (uint)(value2?.GetHashCode() ?? 0);
+ uint hc3 = (uint)(value3?.GetHashCode() ?? 0);
+ uint hc4 = (uint)(value4?.GetHashCode() ?? 0);
+ uint hc5 = (uint)(value5?.GetHashCode() ?? 0);
+
+ Initialize(out uint v1, out uint v2, out uint v3, out uint v4);
+
+ v1 = Round(v1, hc1);
+ v2 = Round(v2, hc2);
+ v3 = Round(v3, hc3);
+ v4 = Round(v4, hc4);
+
+ uint hash = MixState(v1, v2, v3, v4);
+
+ hash += 20;
+ hash = QueueRound(hash, hc5);
+ hash = MixFinal(hash);
+
+ return (int)hash;
+ }
+
///
/// Combines six values into a hash code.
///
@@ -20,28 +191,303 @@ internal struct HashCode
/// The fourth value to combine into the hash code.
/// The fifth value to combine into the hash code.
/// The sixth value to combine into the hash code.
- /// The hash code that represents the six values.
+ /// The hash code that represents the values.
public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6)
{
- throw new NotSupportedException();
+ uint hc1 = (uint)(value1?.GetHashCode() ?? 0);
+ uint hc2 = (uint)(value2?.GetHashCode() ?? 0);
+ uint hc3 = (uint)(value3?.GetHashCode() ?? 0);
+ uint hc4 = (uint)(value4?.GetHashCode() ?? 0);
+ uint hc5 = (uint)(value5?.GetHashCode() ?? 0);
+ uint hc6 = (uint)(value6?.GetHashCode() ?? 0);
+
+ Initialize(out uint v1, out uint v2, out uint v3, out uint v4);
+
+ v1 = Round(v1, hc1);
+ v2 = Round(v2, hc2);
+ v3 = Round(v3, hc3);
+ v4 = Round(v4, hc4);
+
+ uint hash = MixState(v1, v2, v3, v4);
+
+ hash += 24;
+ hash = QueueRound(hash, hc5);
+ hash = QueueRound(hash, hc6);
+ hash = MixFinal(hash);
+
+ return (int)hash;
}
///
- /// Adds a single value to the hash code.
+ /// Combines seven values into a hash code.
///
- /// The type of the value to add to the hash code.
- /// The value to add to the hash code.
+ /// The type of the first value to combine into the hash code.
+ /// The type of the second value to combine into the hash code.
+ /// The type of the third value to combine into the hash code.
+ /// The type of the fourth value to combine into the hash code.
+ /// The type of the fifth value to combine into the hash code.
+ /// The type of the sixth value to combine into the hash code.
+ /// The type of the seventh value to combine into the hash code.
+ /// The first value to combine into the hash code.
+ /// The second value to combine into the hash code.
+ /// The third value to combine into the hash code.
+ /// The fourth value to combine into the hash code.
+ /// The fifth value to combine into the hash code.
+ /// The sixth value to combine into the hash code.
+ /// The seventh value to combine into the hash code.
+ /// The hash code that represents the values.
+ public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6, T7 value7)
+ {
+ uint hc1 = (uint)(value1?.GetHashCode() ?? 0);
+ uint hc2 = (uint)(value2?.GetHashCode() ?? 0);
+ uint hc3 = (uint)(value3?.GetHashCode() ?? 0);
+ uint hc4 = (uint)(value4?.GetHashCode() ?? 0);
+ uint hc5 = (uint)(value5?.GetHashCode() ?? 0);
+ uint hc6 = (uint)(value6?.GetHashCode() ?? 0);
+ uint hc7 = (uint)(value7?.GetHashCode() ?? 0);
+
+ Initialize(out uint v1, out uint v2, out uint v3, out uint v4);
+
+ v1 = Round(v1, hc1);
+ v2 = Round(v2, hc2);
+ v3 = Round(v3, hc3);
+ v4 = Round(v4, hc4);
+
+ uint hash = MixState(v1, v2, v3, v4);
+
+ hash += 28;
+ hash = QueueRound(hash, hc5);
+ hash = QueueRound(hash, hc6);
+ hash = QueueRound(hash, hc7);
+ hash = MixFinal(hash);
+
+ return (int)hash;
+ }
+
+ ///
+ /// Combines eight values into a hash code.
+ ///
+ /// The type of the first value to combine into the hash code.
+ /// The type of the second value to combine into the hash code.
+ /// The type of the third value to combine into the hash code.
+ /// The type of the fourth value to combine into the hash code.
+ /// The type of the fifth value to combine into the hash code.
+ /// The type of the sixth value to combine into the hash code.
+ /// The type of the seventh value to combine into the hash code.
+ /// The type of the eigth value to combine into the hash code.
+ /// The first value to combine into the hash code.
+ /// The second value to combine into the hash code.
+ /// The third value to combine into the hash code.
+ /// The fourth value to combine into the hash code.
+ /// The fifth value to combine into the hash code.
+ /// The sixth value to combine into the hash code.
+ /// The seventh value to combine into the hash code.
+ /// The eigth value to combine into the hash code.
+ /// The hash code that represents the values.
+ public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6, T7 value7, T8 value8)
+ {
+ uint hc1 = (uint)(value1?.GetHashCode() ?? 0);
+ uint hc2 = (uint)(value2?.GetHashCode() ?? 0);
+ uint hc3 = (uint)(value3?.GetHashCode() ?? 0);
+ uint hc4 = (uint)(value4?.GetHashCode() ?? 0);
+ uint hc5 = (uint)(value5?.GetHashCode() ?? 0);
+ uint hc6 = (uint)(value6?.GetHashCode() ?? 0);
+ uint hc7 = (uint)(value7?.GetHashCode() ?? 0);
+ uint hc8 = (uint)(value8?.GetHashCode() ?? 0);
+
+ Initialize(out uint v1, out uint v2, out uint v3, out uint v4);
+
+ v1 = Round(v1, hc1);
+ v2 = Round(v2, hc2);
+ v3 = Round(v3, hc3);
+ v4 = Round(v4, hc4);
+
+ v1 = Round(v1, hc5);
+ v2 = Round(v2, hc6);
+ v3 = Round(v3, hc7);
+ v4 = Round(v4, hc8);
+
+ uint hash = MixState(v1, v2, v3, v4);
+
+ hash += 32;
+ hash = MixFinal(hash);
+
+ return (int)hash;
+ }
+
+ ///
+ /// Adds a single value to the current hash.
+ ///
+ /// The type of the value to add into the hash code.
+ /// The value to add into the hash code.
public void Add(T value)
{
- throw new NotSupportedException();
+ Add(value?.GetHashCode() ?? 0);
}
///
- /// Calculates the final hash code after consecutive invocations.
+ /// Adds a single value to the current hash.
///
- /// The calculated hash code.
+ /// The type of the value to add into the hash code.
+ /// The value to add into the hash code.
+ /// The instance to use.
+ public void Add(T value, IEqualityComparer? comparer)
+ {
+ Add(value is null ? 0 : (comparer?.GetHashCode(value) ?? value.GetHashCode()));
+ }
+
+ ///
+ /// Adds a span of bytes to the hash code.
+ ///
+ /// The span.
+ public void AddBytes(ReadOnlySpan value)
+ {
+ ref byte pos = ref MemoryMarshal.GetReference(value);
+ ref byte end = ref Unsafe.Add(ref pos, value.Length);
+
+ while ((nint)Unsafe.ByteOffset(ref pos, ref end) >= sizeof(int))
+ {
+ Add(Unsafe.ReadUnaligned(ref pos));
+ pos = ref Unsafe.Add(ref pos, sizeof(int));
+ }
+
+ while (Unsafe.IsAddressLessThan(ref pos, ref end))
+ {
+ Add((int)pos);
+ pos = ref Unsafe.Add(ref pos, 1);
+ }
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private static void Initialize(out uint v1, out uint v2, out uint v3, out uint v4)
+ {
+ v1 = seed + Prime1 + Prime2;
+ v2 = seed + Prime2;
+ v3 = seed;
+ v4 = seed - Prime1;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private static uint Round(uint hash, uint input)
+ {
+ return RotateLeft(hash + input * Prime2, 13) * Prime1;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private static uint QueueRound(uint hash, uint queuedValue)
+ {
+ return RotateLeft(hash + queuedValue * Prime3, 17) * Prime4;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private static uint MixState(uint v1, uint v2, uint v3, uint v4)
+ {
+ return RotateLeft(v1, 1) + RotateLeft(v2, 7) + RotateLeft(v3, 12) + RotateLeft(v4, 18);
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private static uint MixEmptyState()
+ {
+ return seed + Prime5;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private static uint MixFinal(uint hash)
+ {
+ hash ^= hash >> 15;
+ hash *= Prime2;
+ hash ^= hash >> 13;
+ hash *= Prime3;
+ hash ^= hash >> 16;
+
+ return hash;
+ }
+
+ private void Add(int value)
+ {
+ uint val = (uint)value;
+ uint previousLength = length++;
+ uint position = previousLength % 4;
+
+ if (position == 0)
+ {
+ queue1 = val;
+ }
+ else if (position == 1)
+ {
+ queue2 = val;
+ }
+ else if (position == 2)
+ {
+ queue3 = val;
+ }
+ else
+ {
+ if (previousLength == 3)
+ {
+ Initialize(out v1, out v2, out v3, out v4);
+ }
+
+ v1 = Round(v1, queue1);
+ v2 = Round(v2, queue2);
+ v3 = Round(v3, queue3);
+ v4 = Round(v4, val);
+ }
+ }
+
+ ///
+ /// Gets the resulting hashcode from the current instance.
+ ///
+ /// The resulting hashcode from the current instance.
public int ToHashCode()
{
- throw new NotSupportedException();
+ uint length = this.length;
+ uint position = length % 4;
+ uint hash = length < 4 ? MixEmptyState() : MixState(v1, v2, v3, v4);
+
+ hash += length * 4;
+
+ if (position > 0)
+ {
+ hash = QueueRound(hash, queue1);
+
+ if (position > 1)
+ {
+ hash = QueueRound(hash, queue2);
+
+ if (position > 2)
+ {
+ hash = QueueRound(hash, queue3);
+ }
+ }
+ }
+
+ hash = MixFinal(hash);
+
+ return (int)hash;
+ }
+
+ ///
+ [Obsolete("HashCode is a mutable struct and should not be compared with other HashCodes. Use ToHashCode to retrieve the computed hash code.", error: true)]
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override int GetHashCode() => throw new NotSupportedException();
+
+ ///
+ [Obsolete("HashCode is a mutable struct and should not be compared with other HashCodes.", error: true)]
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override bool Equals(object? obj) => throw new NotSupportedException();
+
+ ///
+ /// Rotates the specified value left by the specified number of bits.
+ /// Similar in behavior to the x86 instruction ROL.
+ ///
+ /// The value to rotate.
+ /// The number of bits to rotate by.
+ /// Any value outside the range [0..31] is treated as congruent mod 32.
+ /// The rotated value.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private static uint RotateLeft(uint value, int offset)
+ {
+ return (value << offset) | (value >> (32 - offset));
}
}
\ No newline at end of file
diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.Syntax.cs
new file mode 100644
index 00000000..5b4e860a
--- /dev/null
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.Syntax.cs
@@ -0,0 +1,258 @@
+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 IShaderGenerator
+{
+ ///
+ internal static partial class BuildHlslString
+ {
+ ///
+ /// Creates a instance for the BuildHlslString method.
+ ///
+ /// The input instance to use.
+ /// The resulting instance for the BuildHlslString method.
+ public static MethodDeclarationSyntax GetSyntax(HlslShaderSourceInfo 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(HlslShaderSourceInfo 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.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs
index 94d6bf45..d329491e 100644
--- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs
@@ -1,20 +1,20 @@
-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;
-using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle;
#pragma warning disable CS0618, RS1024
@@ -23,812 +23,727 @@ namespace ComputeSharp.SourceGenerators;
///
public sealed partial class IShaderGenerator
{
- ///
- private static partial MethodDeclarationSyntax CreateBuildHlslStringMethod(
- GeneratorExecutionContext context,
- StructDeclarationSyntax structDeclaration,
- INamedTypeSymbol structDeclarationSymbol,
- out string? implicitTextureType,
- out bool isSamplerUsed,
- out string hlslSource)
- {
- // Properties are not supported
- DetectAndReportPropertyDeclarations(context, 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)
- {
- context.ReportDiagnostic(MultipleShaderTypesImplemented, structDeclarationSymbol, structDeclarationSymbol);
- }
-
- // Explore the syntax tree and extract the processed info
- var semanticModel = new SemanticModelProvider(context.Compilation);
- var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) });
- var isComputeShader = pixelShaderSymbol is null;
- var pixelShaderTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!);
- var processedMembers = GetProcessedFields(context, structDeclarationSymbol, discoveredTypes, isComputeShader).ToArray();
- var sharedBuffers = GetGroupSharedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray();
- var (entryPoint, processedMethods, accessesStaticSampler) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions, isComputeShader);
- var implicitSamplerField = accessesStaticSampler ? ("SamplerState", "__sampler") : default((string, string)?);
- var processedTypes = GetProcessedTypes(discoveredTypes).ToArray();
- var processedConstants = GetProcessedConstants(constantDefinitions);
- var staticFields = GetStaticFields(context, semanticModel, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions);
- string namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces));
- string structName = structDeclaration.Identifier.Text;
- SyntaxTokenList structModifiers = structDeclaration.Modifiers;
- IEnumerable bodyStatements = GenerateRenderMethodBody(
- processedConstants,
- staticFields,
- processedTypes,
- isComputeShader,
- processedMembers,
- pixelShaderTextureType,
- accessesStaticSampler,
- sharedBuffers,
- processedMethods,
- entryPoint,
- out hlslSource);
-
- implicitTextureType = pixelShaderTextureType;
- isSamplerUsed = accessesStaticSampler;
-
- // 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));
- }
-
///
- /// Gets a sequence of captured fields and their mapped names.
+ /// A helper with all logic to generate the BuildHlslString method.
///
- /// The current generator context in use.
- /// 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 IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> GetProcessedFields(
- GeneratorExecutionContext context,
- INamedTypeSymbol structDeclarationSymbol,
- ICollection types,
- bool isComputeShader)
+ internal static partial class BuildHlslString
{
- bool hlslResourceFound = false;
-
- foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType())
+ ///
+ /// 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.
+ public static HlslShaderSourceInfo GetInfo(
+ Compilation compilation,
+ StructDeclarationSyntax structDeclaration,
+ INamedTypeSymbol structDeclarationSymbol,
+ out ImmutableArray diagnostics)
{
- if (fieldSymbol.IsStatic) continue;
+ ImmutableArray.Builder builder = ImmutableArray.CreateBuilder();
- AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) });
+ // Properties are not supported
+ DetectAndReportPropertyDeclarations(builder, structDeclarationSymbol);
- // Group shared fields must be static
- if (attribute is not null)
+ // 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)
{
- context.ReportDiagnostic(InvalidGroupSharedFieldDeclaration, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name);
+ builder.Add(MultipleShaderTypesImplemented, structDeclarationSymbol, structDeclarationSymbol);
}
- // Captured fields must be named type symbols
- if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol)
- {
- context.ReportDiagnostic(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
+ // 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 = GetDispatchId.GetInfo(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);
- continue;
- }
+ diagnostics = builder.ToImmutable();
- string metadataName = typeSymbol.GetFullMetadataName();
-
- // 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]);
- }
- }
- else if (!typeSymbol.IsUnmanagedType &&
- typeSymbol.TypeKind != TypeKind.Delegate)
- {
- // Shaders can only capture valid HLSL resource types or unmanaged types
- context.ReportDiagnostic(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, typeSymbol);
-
- continue;
- }
- else if (typeSymbol.IsUnmanagedType &&
- !HlslKnownTypes.IsKnownHlslType(metadataName))
- {
- // Track the type if it's a custom struct
- types.Add(typeSymbol);
- }
-
- string typeName = HlslKnownTypes.GetMappedName(typeSymbol);
-
- _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
-
- // Yield back the current mapping for the name (if the name used a reserved keyword)
- yield return (fieldSymbol, mapping ?? fieldSymbol.Name, typeName);
+ // Get the HLSL source data with the intermediate info
+ return GetHlslSourceInfo(
+ definedConstants,
+ declaredTypes,
+ resourceFields,
+ valueFields,
+ delegateInstanceFields,
+ staticFields,
+ sharedBuffers,
+ processedMethods,
+ isComputeShader,
+ implicitTextureType,
+ isSamplerUsed,
+ entryPoint);
}
- // If the shader is a compute one (so no implicit output texture), it has to contain at least one resource
- if (!hlslResourceFound && isComputeShader)
+ ///
+ /// 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)
{
- context.ReportDiagnostic(MissingShaderResources, structDeclarationSymbol, structDeclarationSymbol);
- }
- }
+ ImmutableArray<(string, string, string)>.Builder resources = ImmutableArray.CreateBuilder<(string, string, string)>();
+ ImmutableArray<(string, string)>.Builder values = ImmutableArray.CreateBuilder<(string, string)>();
+ bool hlslResourceFound = false;
- ///
- /// Gets a sequence of shader static fields and their mapped names.
- ///
- /// The current generator context in use.
- /// 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 IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields(
- GeneratorExecutionContext context,
- SemanticModelProvider semanticModel,
- StructDeclarationSyntax structDeclaration,
- INamedTypeSymbol structDeclarationSymbol,
- ICollection discoveredTypes,
- IDictionary constantDefinitions)
- {
- foreach (var fieldDeclaration in structDeclaration.Members.OfType())
- {
- foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables)
+ foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType())
{
- IFieldSymbol fieldSymbol = (IFieldSymbol)semanticModel.For(variableDeclarator).GetDeclaredSymbol(variableDeclarator)!;
-
- if (!fieldSymbol.IsStatic || fieldSymbol.IsConst)
+ if (fieldSymbol.IsStatic)
{
continue;
}
- AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) });
+ AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass?.ToDisplayString() == typeof(GroupSharedAttribute).FullName);
- 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()))
+ // Group shared fields must be static
+ if (attribute is not null)
{
- context.ReportDiagnostic(InvalidShaderStaticFieldType, variableDeclarator, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
+ 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);
- string typeDeclaration = fieldSymbol.IsReadOnly switch
+ // Allowed fields must be either resources, unmanaged values or delegates
+ if (HlslKnownTypes.IsTypedResourceType(metadataName))
{
- true => $"static const {HlslKnownTypes.GetMappedName(typeSymbol)}",
- false => $"static {HlslKnownTypes.GetMappedName(typeSymbol)}"
- };
+ hlslResourceFound = true;
- StaticFieldRewriter staticFieldRewriter = new(
+ // 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?.ToDisplayString() == typeof(GroupSharedAttribute).FullName);
+
+ 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)}"
+ };
+
+ StaticFieldRewriter 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?.ToDisplayString() == typeof(GroupSharedAttribute).FullName);
+
+ 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
+ ShaderSourceRewriter shaderSourceRewriter = new(
+ structDeclarationSymbol,
semanticModel,
discoveredTypes,
+ staticMethods,
constantDefinitions,
- context);
+ diagnostics,
+ isShaderEntryPoint);
- string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace(eol: "\n").ToFullString();
+ // Rewrite the method syntax tree
+ MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia();
- yield return (mapping ?? fieldSymbol.Name, typeDeclaration, assignment);
- }
- }
- }
+ // Track the implicit sampler, if used
+ isSamplerUsed = isSamplerUsed || shaderSourceRewriter.IsSamplerUsed;
- ///
- /// Gets a sequence of captured members and their mapped names.
- ///
- /// The current generator context in use.
- /// The input instance to process.
- /// The collection of currently discovered types.
- /// A sequence of captured members in .
- [Pure]
- private static IEnumerable<(string Name, string Type, int? Count)> GetGroupSharedMembers(
- GeneratorExecutionContext context,
- INamedTypeSymbol structDeclarationSymbol,
- ICollection types)
- {
- 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)
- {
- context.ReportDiagnostic(InvalidGroupSharedFieldType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
-
- continue;
- }
-
- if (!typeSymbol.ElementType.IsUnmanagedType)
- {
- context.ReportDiagnostic(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);
-
- yield return (mapping ?? fieldSymbol.Name, typeName, bufferSize);
-
- types.Add((INamedTypeSymbol)typeSymbol.ElementType);
- }
- }
-
- ///
- /// Gets a sequence of processed methods declared within a given type.
- ///
- /// The current generator context in use.
- /// 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, IEnumerable<(string Signature, string Definition)> ProcessedMethods, bool IsSamplerUser) GetProcessedMethods(
- GeneratorExecutionContext context,
- 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;
- List<(string, string)> processedMethods = new();
- 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
- ShaderSourceRewriter shaderSourceRewriter = new(
- structDeclarationSymbol,
- semanticModel,
- discoveredTypes,
- staticMethods,
- constantDefinitions,
- context,
- 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)
- {
- processedMethods.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
+ // Emit the extracted local functions first
+ foreach (var localFunction in shaderSourceRewriter.LocalFunctions)
{
- true => new ExecuteMethodRewriter.Compute(shaderSourceRewriter).Visit(processedMethod)!,
- false => new ExecuteMethodRewriter.Pixel(shaderSourceRewriter).Visit(processedMethod)!
- };
-
- entryPoint = processedMethod.NormalizeWhitespace(eol: "\n").ToFullString();
- }
- else
- {
- processedMethods.Add((
- processedMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
- processedMethod.NormalizeWhitespace(eol: "\n").ToFullString()));
- }
- }
-
- // Process static methods as well
- foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values)
- {
- processedMethods.Add((
- staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
- staticMethod.NormalizeWhitespace(eol: "\n").ToFullString()));
- }
-
- return (entryPoint!, processedMethods, 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 IEnumerable<(string Name, string Value)> GetProcessedConstants(IReadOnlyDictionary constantDefinitions)
- {
- foreach (var constant in constantDefinitions)
- {
- var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName();
- var constantName = $"__{ownerTypeName}__{constant.Key.Name}";
-
- yield return (constantName, constant.Value);
- }
- }
-
- ///
- /// 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 IEnumerable<(string Name, string Definition)> GetProcessedTypes(IEnumerable types)
- {
- 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();
+ methods.Add((
+ localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
+ localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString()));
}
- structDeclaration = structDeclaration.AddMembers(
- FieldDeclaration(VariableDeclaration(
- IdentifierName(mapped!)).AddVariables(
- VariableDeclarator(Identifier(field.Name)))));
- }
-
- // Insert the trailing ; right after the closing bracket (after normalization)
- yield return
- (structType,
- structDeclaration
- .NormalizeWhitespace(eol: "\n")
- .WithSemicolonToken(Token(SyntaxKind.SemicolonToken))
- .ToFullString());
- }
- }
-
- ///
- /// Finds and reports all declared properties in a shader.
- ///
- /// The current generator context in use.
- /// The input instance to process.
- private static void DetectAndReportPropertyDeclarations(GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol)
- {
- foreach (var propertySymbol in structDeclarationSymbol.GetMembers().OfType())
- {
- context.ReportDiagnostic(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 static fields referenced by the shader.
- /// The sequence of declared types used by the shader.
- /// Whether or not the current shader is a compute shader (or a pixel shader).
- /// The sequence of instance fields for the current shader.
- /// The type of the implicit target texture, if present.
- /// Whether the static sampler is used by the shader.
- /// The sequence of shared buffers declared by the shader.
- /// The sequence of processed methods used by the shader.
- /// The body of the entry point of the shader.
- /// The generated HLSL source code (ignoring captured delegates, if present).
- /// The series of statements to build the HLSL source to compile to execute the current shader.
- private static IEnumerable GenerateRenderMethodBody(
- IEnumerable<(string Name, string Value)> definedConstants,
- IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> staticFields,
- IEnumerable<(string Name, string Definition)> declaredTypes,
- bool isComputeShader,
- IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> instanceFields,
- string? implicitTextureType,
- bool isSamplerUsed,
- IEnumerable<(string Name, string Type, int? Count)> sharedBuffers,
- IEnumerable<(string Signature, string Definition)> processedMethods,
- string executeMethod,
- out string hlslSource)
- {
- List statements = new();
- StringBuilder chunkedTextBuilder = new();
- StringBuilder aggregateTextBuilder = new();
- int capturedDelegates = 0;
- int prologueStatements = 0;
- int sizeHint = 64;
-
- void AppendLF()
- {
- chunkedTextBuilder.Append('\n');
- }
-
- void AppendLine(string text)
- {
- chunkedTextBuilder.Append(text);
- }
-
- void AppendLineAndLF(string text)
- {
- chunkedTextBuilder.Append(text);
- chunkedTextBuilder.Append('\n');
- }
-
- void AppendCharacterAndLF(char c)
- {
- chunkedTextBuilder.Append(c);
- chunkedTextBuilder.Append('\n');
- }
-
- void AppendThreadNumIdentifier(string name)
- {
- aggregateTextBuilder.Append(name);
- }
-
- void AppendParsedStatement(string text)
- {
- FlushText();
-
- statements.Add(ParseStatement(text));
- }
-
- void FlushText()
- {
- if (chunkedTextBuilder.Length > 0)
- {
- string chunkedText = chunkedTextBuilder.ToString();
-
- aggregateTextBuilder.Append(chunkedText);
-
- sizeHint += chunkedTextBuilder.Length;
-
- statements.Add(
- ExpressionStatement(
- InvocationExpression(
- MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append")))
- .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(chunkedText))))));
-
- chunkedTextBuilder.Clear();
- }
- }
-
- // Declare the hashsets to track imported members and types from delegates, if needed
- if (instanceFields.Any(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate))
- {
- 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)
+ // If the method is the shader entry point, do additional processing
+ if (isShaderEntryPoint)
{
- statements.Add(
- ExpressionStatement(
- InvocationExpression(
- MemberAccessExpression(
- SyntaxKind.SimpleMemberAccessExpression,
- IdentifierName(name),
- IdentifierName("Add")))
- .AddArgumentListArguments(Argument(
- LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item))))));
+ processedMethod = isComputeShader switch
+ {
+ true => new ExecuteMethodRewriter.Compute(shaderSourceRewriter).Visit(processedMethod)!,
+ false => new ExecuteMethodRewriter.Pixel(shaderSourceRewriter).Visit(processedMethod)!
+ };
- prologueStatements++;
- }
- }
-
- DeclareMapping(0, "__typeNames", declaredTypes.Select(static t => t.Name));
- DeclareMapping(1, "__constantNames", definedConstants.Select(static t => t.Name));
- DeclareMapping(2, "__methodNames", processedMethods.Select(static t => t.Signature));
-
- // Go through all existing delegate fields, if any
- foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate))
- {
- // 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
- 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 ");
- AppendParsedStatement("builder.Append(threadsX);");
- AppendThreadNumIdentifier("");
- AppendLF();
- AppendLine("#define __GroupSize__get_Y ");
- AppendParsedStatement("builder.Append(threadsY);");
- AppendThreadNumIdentifier("");
- AppendLF();
- AppendLine("#define __GroupSize__get_Z ");
- AppendParsedStatement("builder.Append(threadsZ);");
- AppendThreadNumIdentifier("");
- AppendLF();
-
- // Define declarations
- foreach (var (name, value) in definedConstants)
- {
- AppendLineAndLF($"#define {name} {value}");
- }
-
- // Defines from captured delegates
- foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate))
- {
- AppendParsedStatement($"__{fieldName}Attribute.AppendConstants(ref builder, __constantNames);");
- }
-
- // Static fields
- if (staticFields.Any())
- {
- AppendLF();
-
- foreach (var field in staticFields)
- {
- if (field.Assignment is string assignment)
- {
- AppendLineAndLF($"{field.TypeDeclaration} {field.Name} = {assignment};");
+ entryPoint = processedMethod.NormalizeWhitespace(eol: "\n").ToFullString();
}
else
{
- AppendLineAndLF($"{field.TypeDeclaration} {field.Name};");
+ methods.Add((
+ processedMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
+ processedMethod.NormalizeWhitespace(eol: "\n").ToFullString()));
}
}
- }
- // Declared types
- foreach (var (_, typeDefinition) in declaredTypes)
- {
- AppendLF();
- AppendLineAndLF(typeDefinition);
- }
-
- // Declared types from captured delegates
- foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate))
- {
- AppendParsedStatement($"__{fieldName}Attribute.AppendTypes(ref builder, __typeNames);");
- }
-
- // Captured variables
- AppendLF();
- AppendLineAndLF("cbuffer _ : register(b0)");
- AppendCharacterAndLF('{');
- AppendLineAndLF(" uint __x;");
- AppendLineAndLF(" uint __y;");
-
- if (isComputeShader)
- {
- AppendLineAndLF(" uint __z;");
- }
-
- // User-defined values
- foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields.Where(static t => t.Symbol.Type.IsUnmanagedType))
- {
- 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 (fieldSymbol, fieldName, fieldType) in instanceFields)
- {
- string metadataName = fieldSymbol.Type.GetFullMetadataName();
-
- if (HlslKnownTypes.IsConstantBufferType(metadataName))
+ // Process static methods as well
+ foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values)
{
- AppendLF();
- AppendLineAndLF($"cbuffer _{fieldName} : register(b{constantBuffersCount++})");
- AppendCharacterAndLF('{');
- AppendLineAndLF($" {fieldType} {fieldName}[2];");
- AppendCharacterAndLF('}');
+ methods.Add((
+ staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
+ staticMethod.NormalizeWhitespace(eol: "\n").ToFullString()));
}
- else if (HlslKnownTypes.IsReadOnlyTypedResourceType(metadataName))
+
+ 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)
{
- AppendLF();
- AppendLineAndLF($"{fieldType} {fieldName} : register(t{readOnlyBuffersCount++});");
+ var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName();
+ var constantName = $"__{ownerTypeName}__{constant.Key.Name}";
+
+ builder.Add((constantName, constant.Value));
}
- else if (HlslKnownTypes.IsTypedResourceType(metadataName))
+
+ 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))
{
- AppendLF();
- AppendLineAndLF($"{fieldType} {fieldName} : register(u{readWriteBuffersCount++});");
+ 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);
}
}
- // Shared buffers
- foreach (var (bufferName, bufferType, bufferCount) in sharedBuffers)
+ ///
+ /// 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 HlslShaderSourceInfo GetHlslSourceInfo(
+ 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)
{
- object count = (object?)bufferCount ?? "threadsX * threadsY * threadsZ";
+ 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();
- AppendLineAndLF($"groupshared {bufferType} {bufferName} [{count}];");
- }
+ AppendLine("#define __GroupSize__get_Y ");
+
+ string threadsY = FlushText();
- // Forward declarations
- foreach (var (forwardDeclaration, _) in processedMethods)
- {
AppendLF();
- AppendLineAndLF(forwardDeclaration);
- }
+ AppendLine("#define __GroupSize__get_Z ");
- // Forward declarations from captured delegates
- foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate))
- {
- AppendParsedStatement($"__{fieldName}Attribute.AppendForwardDeclarations(ref builder, __methodNames);");
- }
+ string threadsZ = FlushText();
- // 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("
- ");
+ 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 ?? "__GroupSize__get_X * __GroupSize__get_Y * __GroupSize__get_Z";
+
+ AppendLF();
+ AppendLineAndLF($"groupshared {bufferType} {bufferName} [{count}];");
+ }
+
+ // Forward declarations
foreach (var (forwardDeclaration, _) in processedMethods)
{
- FlushText();
-
- statements.Add(
- ExpressionStatement(
- InvocationExpression(
- MemberAccessExpression(
- SyntaxKind.SimpleMemberAccessExpression,
- IdentifierName("__methodNames"),
- IdentifierName("Remove")))
- .AddArgumentListArguments(Argument(
- LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(forwardDeclaration))))));
+ AppendLF();
+ AppendLineAndLF(forwardDeclaration);
}
- }
- // Captured methods
- foreach (var (_, method) in processedMethods)
- {
+ string capturedFieldsAndResourcesAndForwardDeclarations = FlushText();
+
+ // Captured methods
+ foreach (var (_, method) in processedMethods)
+ {
+ AppendLF();
+ AppendLineAndLF(method);
+ }
+
+ string capturedMethods = FlushText();
+
+ // Entry point
AppendLF();
- AppendLineAndLF(method);
+ 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);
}
- // Captured methods from captured delegates
- foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate))
+ ///
+ /// Produces the non dynamic HLSL source (concatenating all generated HLSL source chunks).
+ ///
+ /// The input instance to use.
+ /// The non dynamic HLSL source code.
+ public static string GetNonDynamicHlslSource(HlslShaderSourceInfo hlslSourceInfo)
{
- AppendParsedStatement($"__{fieldName}Attribute.AppendMethods(ref builder, __methodNames);");
+ return
+ hlslSourceInfo.HeaderAndThreadsX + "" +
+ hlslSourceInfo.ThreadsY + "" +
+ hlslSourceInfo.ThreadsZ + "" +
+ hlslSourceInfo.Defines +
+ hlslSourceInfo.StaticFieldsAndDeclaredTypes +
+ hlslSourceInfo.CapturedFieldsAndResourcesAndForwardDeclarations +
+ hlslSourceInfo.CapturedMethods +
+ hlslSourceInfo.EntryPoint;
}
-
- // Captured delegate methods
- foreach (var (fieldSymbol, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate))
- {
- AppendLF();
- AppendParsedStatement($"__{fieldName}Attribute.AppendMappedInvokeMethod(ref builder, \"{fieldName}\");");
- AppendLF();
- }
-
- // Entry point
- AppendLF();
- AppendLineAndLF("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]");
- AppendLineAndLF(executeMethod);
-
- 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)))))));
-
- hlslSource = aggregateTextBuilder.ToString();
-
- return statements;
}
}
diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs
new file mode 100644
index 00000000..273bf081
--- /dev/null
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs
@@ -0,0 +1,98 @@
+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 IShaderGenerator
+{
+ ///
+ private static partial class GetDispatchId
+ {
+ ///
+ /// 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.
+ public static MethodDeclarationSyntax GetSyntax(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.CreateGetDispatchIdMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs
index 1e8a3eae..65b64877 100644
--- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs
@@ -1,101 +1,33 @@
-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;
///
public sealed partial class IShaderGenerator
{
- ///
- private static partial MethodDeclarationSyntax CreateGetDispatchIdMethod(INamedTypeSymbol structDeclarationSymbol, out bool isDynamicShader)
- {
- // 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(structDeclarationSymbol, out isDynamicShader));
- }
-
///
- /// Gets a instance with the logic to compute the hashcode of a given shader type.
+ /// A helper with all logic to generate the GetDispatchId method.
///
- /// The input instance to process.
- /// Indicates whether or not the shader is dynamic (ie. captures delegates).
- /// The instance to hash the input shader.
- [Pure]
- private static BlockSyntax GetShaderHashCodeBody(INamedTypeSymbol structDeclarationSymbol, out bool isDynamicShader)
+ private static partial class GetDispatchId
{
- var delegateFields = structDeclarationSymbol
- .GetMembers()
- .OfType()
- .Where(static m => m.Type is INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false })
- .ToImmutableArray();
-
- isDynamicShader = delegateFields.Length > 0;
-
- if (delegateFields.Length == 0)
+ ///
+ /// Extracts the names of all instance fields of a type.
+ ///
+ /// The input instance to process.
+ /// The names of all instance fields within .
+ [Pure]
+ public static ImmutableArray GetInfo(INamedTypeSymbol structDeclarationSymbol)
{
- // return 0;
return
- Block(ReturnStatement(
- LiteralExpression(
- SyntaxKind.NumericLiteralExpression,
- Literal(0))));
+ structDeclarationSymbol
+ .GetMembers()
+ .OfType()
+ .Where(static member => member.Type is INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false })
+ .Select(static member => member.Name)
+ .ToImmutableArray();
}
-
- 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 (IFieldSymbol fieldSymbol in delegateFields)
- {
- // hashCode.Add(delegateField.Method);
- blockStatements.Add(ExpressionStatement(
- InvocationExpression(
- MemberAccessExpression(
- SyntaxKind.SimpleMemberAccessExpression,
- IdentifierName("hashCode"),
- IdentifierName("Add")))
- .AddArgumentListArguments(Argument(
- MemberAccessExpression(
- SyntaxKind.SimpleMemberAccessExpression,
- IdentifierName(fieldSymbol.Name),
- 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.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs
new file mode 100644
index 00000000..e834356d
--- /dev/null
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs
@@ -0,0 +1,249 @@
+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 IShaderGenerator
+{
+ ///
+ private static partial class LoadDispatchData
+ {
+ ///
+ /// 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.
+ public static MethodDeclarationSyntax GetSyntax(
+ 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.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs
index a6288e93..813722bf 100644
--- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs
@@ -1,335 +1,193 @@
using System;
using System.Collections.Generic;
+using System.Collections.Immutable;
using System.Linq;
-using ComputeSharp.__Internals;
+using System.Runtime.CompilerServices;
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;
///
public sealed partial class IShaderGenerator
{
- ///
- private static partial MethodDeclarationSyntax CreateLoadDispatchDataMethod(
- GeneratorExecutionContext context,
- INamedTypeSymbol structDeclarationSymbol,
- out IReadOnlyCollection discoveredResources,
- out 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(context, structDeclarationSymbol, out discoveredResources, out root32BitConstantsCount)));
- }
-
///
- /// Gets a sequence of statements to load the dispatch data for a given shader.
+ /// A helper with all logic to generate the LoadDispatchData method.
///
- /// The current generator context in use.
- /// The input instance to process.
- /// The collection of discovered resources in the current shader type.
- /// The total number of 32 bit root constants being loaded for the current shader type.
- /// The sequence of instances to load shader dispatch data.
- private static IEnumerable GetDispatchDataLoadingStatements(GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol, out IReadOnlyCollection discoveredResources, out int root32BitConstantsCount)
+ private static partial class LoadDispatchData
{
- List statements = new();
- List resources = new();
-
- discoveredResources = resources;
-
- var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) });
- var isComputeShader = pixelShaderSymbol is null;
- int resourceOffset = 0;
- int rawDataOffset = sizeof(int) * (isComputeShader ? 3 : 2);
-
- // 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 (isComputeShader)
+ ///
+ /// Explores a given type hierarchy and generates statements to load fields.
+ ///
+ /// The current shader type being explored.
+ /// The type of shader interface urrently being processed.
+ /// The total number of captured resources in the shader.
+ /// The total number of needed 32 bit constants in the shader root signature.
+ /// The resulting diagnostics from the processing operation.
+ /// The sequence of instances for all captured resources and values.
+ public static ImmutableArray GetInfo(
+ ITypeSymbol structDeclarationSymbol,
+ Type shaderInterfaceType,
+ out int resourceCount,
+ out int root32BitConstantCount,
+ out ImmutableArray diagnostics)
{
- statements.Add(
- ExpressionStatement(
- AssignmentExpression(
- SyntaxKind.SimpleAssignmentExpression,
- ElementAccessExpression(IdentifierName("span0"))
- .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(2)))),
- CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("z")))));
+ // Helper method that uses boxes instead of ref-s (illegal in enumerators)
+ static IEnumerable GetCapturedFieldInfos(
+ ITypeSymbol currentTypeSymbol,
+ ImmutableArray fieldPath,
+ StrongBox resourceOffset,
+ StrongBox rawDataOffset)
+ {
+ bool isFirstField = true;
+
+ foreach (
+ IFieldSymbol fieldSymbol in
+ from fieldSymbol in currentTypeSymbol.GetMembers().OfType()
+ where fieldSymbol.Type is INamedTypeSymbol { IsStatic: false } &&
+ !fieldSymbol.IsConst && !fieldSymbol.IsStatic &&
+ !fieldSymbol.IsFixedSizeBuffer
+ select fieldSymbol)
+ {
+ string fieldName = fieldSymbol.Name;
+ string typeName = fieldSymbol.Type.GetFullMetadataName();
+
+ // Disambiguates the name of target fields against the current input parameters
+ if (fieldName is "loader" or "device" or "x" or "y" or "z")
+ {
+ fieldName = $"this.{fieldName}";
+ }
+
+ // The first item in each nested struct needs to be aligned to 16 bytes
+ if (isFirstField && fieldPath.Length > 0)
+ {
+ rawDataOffset.Value = AlignmentHelper.Pad(rawDataOffset.Value, 16);
+
+ isFirstField = false;
+ }
+
+ if (HlslKnownTypes.IsTypedResourceType(typeName))
+ {
+ yield return new FieldInfo.Resource(fieldName, typeName, resourceOffset.Value++);
+ }
+ else if (HlslKnownTypes.IsKnownHlslType(typeName))
+ {
+ yield return GetHlslKnownTypeFieldInfo(fieldPath.Add(fieldName), typeName, ref rawDataOffset.Value);
+ }
+ else if (fieldSymbol.Type.IsUnmanagedType)
+ {
+ // Custom struct type defined by the user
+ foreach (var fieldInfo in GetCapturedFieldInfos(fieldSymbol.Type, fieldPath.Add(fieldName), resourceOffset, rawDataOffset))
+ {
+ yield return fieldInfo;
+ }
+ }
+ }
+ }
+
+ ImmutableArray.Builder builder = ImmutableArray.CreateBuilder();
+
+ // Setup the resource and byte offsets for tracking. Pixel shaders have only two
+ // implicitly captured int values, as they're always dispatched over a 2D texture.
+ bool isComputeShader = shaderInterfaceType == typeof(IComputeShader);
+ int initialRawDataOffset = sizeof(int) * (isComputeShader ? 3 : 2);
+ StrongBox resourceOffsetAsBox = new();
+ StrongBox rawDataOffsetAsBox = new(initialRawDataOffset);
+
+ // Traverse all shader fields and gather info, and update the tracking offsets
+ ImmutableArray fieldInfos = GetCapturedFieldInfos(
+ structDeclarationSymbol,
+ ImmutableArray.Empty,
+ resourceOffsetAsBox,
+ rawDataOffsetAsBox).ToImmutableArray();
+
+ resourceCount = resourceOffsetAsBox.Value;
+
+ // After all the captured fields have been processed, ansure the reported byte size for
+ // the local variables is padded to a multiple of a 32 bit value. This is necessary to
+ // enable loading all the dispatch data after reinterpreting it to a sequence of values
+ // of size 32 bits (via SetComputeRoot32BitConstants), without reading out of bounds.
+ root32BitConstantCount = AlignmentHelper.Pad(rawDataOffsetAsBox.Value, sizeof(int)) / sizeof(int);
+
+ // A shader root signature has a maximum size of 64 DWORDs, so 256 bytes.
+ // Loaded values in the root signature have the following costs:
+ // - Root constants cost 1 DWORD each, since they are 32-bit values.
+ // - Descriptor tables cost 1 DWORD each.
+ // - Root descriptors (64-bit GPU virtual addresses) cost 2 DWORDs each.
+ // So here we check whether the current signature respects that constraint,
+ // and emit a build error otherwise. For more info on this, see the docs here:
+ // https://docs.microsoft.com/windows/win32/direct3d12/root-signature-limits.
+ int rootSignatureDwordSize = root32BitConstantCount + resourceCount;
+
+ if (rootSignatureDwordSize > 64)
+ {
+ builder.Add(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol);
+ }
+
+ diagnostics = builder.ToImmutable();
+
+ return fieldInfos;
}
- // Append the statements to load all fields (both resources and other captured values)
- AppendFields(structDeclarationSymbol, Array.Empty(), ref resourceOffset, ref rawDataOffset, resources, statements);
-
- // After all the captured fields have been processed, ansure the reported byte size for
- // the local variables is padded to a multiple of a 32 bit value. This is necessary to
- // enable loading all the dispatch data after reinterpreting it to a sequence of values
- // of size 32 bits (via SetComputeRoot32BitConstants), without reading out of bounds.
- rawDataOffset = AlignmentHelper.Pad(rawDataOffset, sizeof(int));
- root32BitConstantsCount = rawDataOffset / sizeof(int);
-
- // A shader root signature has a maximum size of 64 DWORDs, so 256 bytes.
- // Loaded values in the root signature have the following costs:
- // - Root constants cost 1 DWORD each, since they are 32-bit values.
- // - Descriptor tables cost 1 DWORD each.
- // - Root descriptors (64-bit GPU virtual addresses) cost 2 DWORDs each.
- // So here we check whether the current signature respects that constraint,
- // and emit a build error otherwise. For more info on this, see the docs here:
- // https://docs.microsoft.com/windows/win32/direct3d12/root-signature-limits.
- int rootSignatureDwordSize = root32BitConstantsCount + resourceOffset;
-
- if (rootSignatureDwordSize > 64)
+ ///
+ /// Gets info on a given captured HLSL primitive type (either a scalar, a vector or a matrix).
+ ///
+ /// The current path of the field with respect to the shader instance.
+ /// The type name currently being read.
+ /// The current offset within the loaded data buffer.
+ private static FieldInfo GetHlslKnownTypeFieldInfo(
+ ImmutableArray fieldPath,
+ string typeName,
+ ref int rawDataOffset)
{
- context.ReportDiagnostic(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol);
- }
+ // For scalar, vector and linear matrix types, serialize the value normally.
+ // Only the initial alignment needs to be considered, while data is packed.
+ var (fieldSize, fieldPack) = HlslKnownSizes.GetTypeInfo(typeName);
- // 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 (resourceOffset > 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(resourceOffset)))))))))));
-
- // 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;
- }
-
- ///
- /// Explores a given type hierarchy and generates statements to load fields.
- ///
- /// The current type being explored.
- /// The current path of the field with respect to the shader instance.
- /// The current offset in the root table of loaded resources.
- /// The current offset within the loaded data buffer.
- /// The target list of resources in the current shader type.
- /// The target list of statements being generated.
- private static void AppendFields(ITypeSymbol currentTypeSymbol, IReadOnlyCollection fieldPath, ref int resourceOffset, ref int rawDataOffset, ICollection resources, ICollection statements)
- {
- bool isFirstField = true;
-
- foreach (
- IFieldSymbol fieldSymbol in
- from fieldSymbol in currentTypeSymbol.GetMembers().OfType()
- where fieldSymbol.Type is INamedTypeSymbol { IsStatic: false } &&
- !fieldSymbol.IsConst && !fieldSymbol.IsStatic && !fieldSymbol.IsFixedSizeBuffer
- select fieldSymbol)
- {
- string fieldName = fieldSymbol.Name;
- string typeName = fieldSymbol.Type.GetFullMetadataName();
-
- // Disambiguates the name of target fields against the current input parameters
- if (fieldName is "loader" or "device" or "x" or "y" or "z")
+ // Check if the current type is a matrix type with more than one row. In this
+ // case, each row is aligned as if it was a separate array, so the start of
+ // each row needs to be at a multiple of 16 bytes (a float4 register).
+ if (HlslKnownTypes.IsNonLinearMatrixType(typeName, out string? elementName, out int rows, out int columns))
{
- fieldName = $"this.{fieldName}";
- }
+ ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(rows);
- // The first item in each nested struct needs to be aligned to 16 bytes
- if (isFirstField && fieldPath.Count > 0)
+ for (int j = 0; j < rows; j++)
+ {
+ int startingRawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
+
+ builder.Add(startingRawDataOffset);
+
+ rawDataOffset = startingRawDataOffset + fieldPack * columns;
+ }
+
+ return new FieldInfo.NonLinearMatrix(
+ fieldPath,
+ typeName,
+ elementName!,
+ rows,
+ columns,
+ builder.MoveToImmutable());
+ }
+ else
{
- rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
+ // Calculate the right offset with 16-bytes padding (HLSL constant buffer).
+ // Since we're in a constant buffer, we need to both pad the starting offset
+ // to be aligned to the packing size of the type, and also to align the initial
+ // offset to ensure that values do not cross 16 bytes boundaries either.
+ int startingRawDataOffset = AlignmentHelper.AlignToBoundary(
+ AlignmentHelper.Pad(rawDataOffset, fieldPack),
+ fieldSize,
+ 16);
- isFirstField = false;
+ rawDataOffset = startingRawDataOffset + fieldSize;
+
+ return new FieldInfo.Primitive(fieldPath, typeName, startingRawDataOffset);
}
-
- if (HlslKnownTypes.IsTypedResourceType(typeName))
- {
- resources.Add(typeName);
-
- statements.Add(ExpressionStatement(
- AssignmentExpression(
- SyntaxKind.SimpleAssignmentExpression,
- ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resourceOffset++})"),
- ParseExpression($"global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({fieldName}, device)"))));
- }
- else if (HlslKnownTypes.IsKnownHlslType(typeName))
- {
- AppendHlslKnownTypeField(fieldPath.Concat(new[] { fieldName }), typeName, ref rawDataOffset, statements);
- }
- else if (fieldSymbol.Type.IsUnmanagedType)
- {
- // Custom struct type defined by the user
- AppendFields(fieldSymbol.Type, fieldPath.Concat(new[] { fieldName }).ToArray(), ref resourceOffset, ref rawDataOffset, resources, statements);
- }
- }
- }
-
- ///
- /// Generates a loading statement for a known HLSL primitive type field (scalar, vector or matrix).
- ///
- /// The current path of the field with respect to the shader instance.
- /// The type name currently being read.
- /// The current offset within the loaded data buffer.
- /// The target list of statements being generated.
- private static void AppendHlslKnownTypeField(IEnumerable fieldPath, string typeName, ref int rawDataOffset, ICollection statements)
- {
- // For scalar, vector and linear matrix types, serialize the value normally.
- // Only the initial alignment needs to be considered, while data is packed.
- var (fieldSize, fieldPack) = HlslKnownSizes.GetTypeInfo(typeName);
-
- // Check if the current type is a matrix type with more than one row. In this
- // case, each row is aligned as if it was a separate array, so the start of
- // each row needs to be at a multiple of 16 bytes (a float4 register).
- if (HlslKnownTypes.IsNonLinearMatrixType(typeName, out string? elementName, out int rows, out int columns))
- {
- string rowTypeName = $"global::ComputeSharp.{elementName}{columns}";
- string rowLocalName = $"__{string.Join("_", fieldPath)}__row0";
-
- statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in {string.Join(".", 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 < rows; j++)
- {
- rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
-
- statements.Add(ExpressionStatement(
- AssignmentExpression(
- SyntaxKind.SimpleAssignmentExpression,
- ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){rawDataOffset}))"),
- ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j})"))));
-
- rawDataOffset += fieldPack * columns;
- }
- }
- else
- {
- // Calculate the right offset with 16-bytes padding (HLSL constant buffer).
- // Since we're in a constant buffer, we need to both pad the starting offset
- // to be aligned to the packing size of the type, and also to align the initial
- // offset to ensure that values do not cross 16 bytes boundaries either.
- rawDataOffset = AlignmentHelper.AlignToBoundary(
- AlignmentHelper.Pad(rawDataOffset, fieldPack),
- fieldSize,
- 16);
-
- statements.Add(ExpressionStatement(
- AssignmentExpression(
- SyntaxKind.SimpleAssignmentExpression,
- ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){rawDataOffset}))"),
- ParseExpression($"{string.Join(".", fieldPath)}"))));
-
- rawDataOffset += fieldSize;
}
}
}
diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs
new file mode 100644
index 00000000..a886d33e
--- /dev/null
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs
@@ -0,0 +1,136 @@
+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 IShaderGenerator
+{
+ ///
+ private static partial class LoadDispatchMetadata
+ {
+ ///
+ /// Creates a instance for the LoadDispatchMetadata method.
+ ///
+ /// The dispatch metadata for the current shader..
+ /// The resulting instance for the LoadDispatchMetadata method.
+ public static MethodDeclarationSyntax GetSyntax(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.CreateLoadDispatchMetadataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs
index 391416d0..5132b5d0 100644
--- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs
@@ -1,156 +1,64 @@
-using System;
-using System.Collections.Generic;
-using ComputeSharp.__Internals;
+using System.Collections.Immutable;
using ComputeSharp.SourceGenerators.Mappings;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
-
-#pragma warning disable CS0618
+using ComputeSharp.SourceGenerators.Models;
namespace ComputeSharp.SourceGenerators;
///
public sealed partial class IShaderGenerator
{
- ///
- private static partial MethodDeclarationSyntax CreateLoadDispatchMetadataMethod(
- string? implicitTextureType,
- IReadOnlyCollection discoveredResources,
- int root32BitConstantsCount,
- bool isSamplerUsed)
- {
- // 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(implicitTextureType, discoveredResources, root32BitConstantsCount, isSamplerUsed)));
- }
-
///