Switch BuildHlslString() to incremental

このコミットが含まれているのは:
Sergio Pedri committed 2021-12-08 11:17:04 +01:00
1 親 ad45fc1fc9
コミット 5210c1ecd9
7ファイル変更
+367 -52

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

@@ -0,0 +1,254 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Text;
using ComputeSharp.__Internals;
using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618, RS1024
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
public sealed partial class IShaderGenerator2
{
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.
/// </summary>
/// <param name="hlslSourceInfo">The input <see cref="HlslSourceInfo"/> instance to use.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.</returns>
private static MethodDeclarationSyntax CreateBuildHlslStringMethod(HlslSourceInfo hlslSourceInfo)
{
ImmutableArray<StatementSyntax> 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)
// {
// <BODY>
// }
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));
}
/// <summary>
/// Produces the series of statements to build the current HLSL source.
/// </summary>
/// <param name="hlslSourceInfo">The input <see cref="HlslSourceInfo"/> instance to use.</param>
/// <returns>The series of statements to build the HLSL source to compile to execute the current shader.</returns>
private static ImmutableArray<StatementSyntax> GenerateRenderMethodBody(HlslSourceInfo hlslSourceInfo)
{
ImmutableArray<StatementSyntax>.Builder statements = ImmutableArray.CreateBuilder<StatementSyntax>();
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<string> items)
{
// global::System.Collections.Generic.HashSet<string> <NAME> = 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++;
// <NAME>.Add("<ITEM>");
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 __<DELEGATE_NAME>Attribute = global::ComputeSharp.__Internals.ShaderMethodSourceAttribute.GetForDelegate(<DELEGATE_NAME>, "<DELEGATE_NAME>");
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)
{
// <NAME>.Add("<ITEM>");
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(<SIZE_HINT>);
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();
}
}
@@ -194,14 +194,12 @@ public sealed partial class IShaderGenerator2
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.
/// </summary>
/// <param name="context">The input <see cref="SourceProductionContext"/> instance to use.</param>
/// <param name="shaderInterfaceType">The type of shader interface urrently being processed.</param>
/// <param name="fieldInfos">The array of <see cref="FieldInfo"/> values for all captured fields.</param>
/// <param name="resourceCount">The total number of captured resources in the shader.</param>
/// <param name="root32BitConstantsCount">The total number of needed 32 bit constants in the shader root signature.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.</returns>
private static MethodDeclarationSyntax CreateLoadDispatchDataMethod(
SourceProductionContext context,
Type shaderInterfaceType,
ImmutableArray<FieldInfo> fieldInfos,
int resourceCount,
@@ -228,20 +226,18 @@ public sealed partial class IShaderGenerator2
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, shaderInterfaceType, fieldInfos, resourceCount, root32BitConstantsCount)));
.WithBody(Block(GetDispatchDataLoadingStatements(shaderInterfaceType, fieldInfos, resourceCount, root32BitConstantsCount)));
}
/// <summary>
/// Gets a sequence of statements to load the dispatch data for a given shader.
/// </summary>
/// <param name="context">The current generator context in use.</param>
/// <param name="shaderInterfaceType">The type of shader interface urrently being processed.</param>
/// <param name="fieldInfos">The array of <see cref="FieldInfo"/> values for all captured fields.</param>
/// <param name="resourceCount">The total number of captured resources in the shader.</param>
/// <param name="root32BitConstantsCount">The total number of needed 32 bit constants in the shader root signature.</param>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
private static ImmutableArray<StatementSyntax> GetDispatchDataLoadingStatements(
SourceProductionContext context,
Type shaderInterfaceType,
ImmutableArray<FieldInfo> fieldInfos,
int resourceCount,
@@ -24,14 +24,14 @@ namespace ComputeSharp.SourceGenerators;
public sealed partial class IShaderGenerator2
{
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.
/// Gathers all necessary information on a transpiled HLSL source for a given shader type.
/// </summary>
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> node to process.</param>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for <paramref name="structDeclaration"/>.</param>
/// <param name="diagnostics">The resulting diagnostics from the processing operation.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.</returns>
private static (NonDynamicHlslSourceInfo SourceInfo, string? ImplicitTextureType, bool IsSamplerUsed) GetNonDynamicHlslSourceInfo(
/// <returns>The resulting info on the processed shader.</returns>
private static HlslSourceInfo GetNonDynamicHlslSourceInfo(
Compilation compilation,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
@@ -58,7 +58,8 @@ public sealed partial class IShaderGenerator2
var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) });
var isComputeShader = pixelShaderSymbol is null;
var implicitTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!);
var instanceFields = GetInstanceFields(builder, structDeclarationSymbol, discoveredTypes, isComputeShader);
var nonDelegateInstanceFields = GetInstanceFields(builder, structDeclarationSymbol, discoveredTypes, isComputeShader);
var delegateInstanceFields = GetDelegateFieldNames(structDeclarationSymbol);
var sharedBuffers = GetSharedBuffers(builder, structDeclarationSymbol, discoveredTypes);
var (entryPoint, processedMethods, isSamplerUsed) = GetProcessedMethods(builder, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, constantDefinitions, isComputeShader);
var implicitSamplerField = isSamplerUsed ? ("SamplerState", "__sampler") : default((string, string)?);
@@ -66,11 +67,14 @@ public sealed partial class IShaderGenerator2
var definedConstants = GetDefinedConstants(constantDefinitions);
var staticFields = GetStaticFields(builder, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions);
diagnostics = builder.ToImmutable();
// Get the HLSL source data with the intermediate info
NonDynamicHlslSourceInfo sourceInfo = GetNonDynamicHlslSourceInfo(
return GetNonDynamicHlslSourceInfo(
definedConstants,
declaredTypes,
instanceFields,
nonDelegateInstanceFields,
delegateInstanceFields,
staticFields,
sharedBuffers,
processedMethods,
@@ -78,10 +82,6 @@ public sealed partial class IShaderGenerator2
implicitTextureType,
isSamplerUsed,
entryPoint);
diagnostics = builder.ToImmutable();
return (sourceInfo, implicitTextureType, isSamplerUsed);
}
/// <summary>
@@ -485,6 +485,7 @@ public sealed partial class IShaderGenerator2
/// <param name="definedConstants">The sequence of defined constants for the shader.</param>
/// <param name="declaredTypes">The sequence of declared types used by the shader.</param>
/// <param name="instanceFields">The sequence of instance fields for the current shader.</param>
/// <param name="delegateInstanceFields">The sequence of delegate fields for the current shader.</param>
/// <param name="staticFields">The sequence of static fields referenced by the shader.</param>
/// <param name="sharedBuffers">The sequence of shared buffers declared by the shader.</param>
/// <param name="processedMethods">The sequence of processed methods used by the shader.</param>
@@ -493,10 +494,11 @@ public sealed partial class IShaderGenerator2
/// <param name="isSamplerUsed">Whether the static sampler is used by the shader.</param>
/// <param name="executeMethod">The body of the entry point of the shader.</param>
/// <returns>The series of statements to build the HLSL source to compile to execute the current shader.</returns>
private static NonDynamicHlslSourceInfo GetNonDynamicHlslSourceInfo(
private static HlslSourceInfo GetNonDynamicHlslSourceInfo(
ImmutableArray<(string Name, string Value)> definedConstants,
ImmutableArray<(string Name, string Definition)> declaredTypes,
ImmutableArray<(string MetadataName, string Name, string HlslType)> instanceFields,
ImmutableArray<string> delegateInstanceFields,
ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> staticFields,
ImmutableArray<(string Name, string Type, int? Count)> sharedBuffers,
ImmutableArray<(string Signature, string Definition)> processedMethods,
@@ -703,6 +705,11 @@ public sealed partial class IShaderGenerator2
capturedFieldsAndResourcesAndForwardDeclarations,
capturedMethods,
entryPoint,
processedMethods.Select(static m => m.Signature).ToImmutableArray());
implicitTextureType,
isSamplerUsed,
declaredTypes.Select(static t => t.Name).ToImmutableArray(),
definedConstants.Select(static c => c.Name).ToImmutableArray(),
processedMethods.Select(static m => m.Signature).ToImmutableArray(),
delegateInstanceFields);
}
}
+18 -5
ファイルの表示
@@ -5,6 +5,7 @@ using System.Diagnostics.Contracts;
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;
@@ -104,7 +105,6 @@ public sealed partial class IShaderGenerator2 : IIncrementalGenerator
context.RegisterSourceOutput(dispatchDataInfo.Combine(canUseSkipLocalsInit), static (context, item) =>
{
MethodDeclarationSyntax loadDispatchDataMethod = CreateLoadDispatchDataMethod(
context,
item.Left.Type,
item.Left.FieldInfos,
item.Left.ResourceCount,
@@ -115,24 +115,37 @@ public sealed partial class IShaderGenerator2 : IIncrementalGenerator
});
// Get the HLSL source info
IncrementalValuesProvider<Result<(NonDynamicHlslSourceInfo SourceInfo, string? ImplicitTextureType, bool IsSamplerUsed)>> hlslSourceInfo =
IncrementalValuesProvider<(HierarchyInfo Hierarchy, Result<HlslSourceInfo> Result)> hlslSourceInfoWithErrors =
shaderDeclarations
.Combine(context.CompilationProvider)
.Select(static (item, token) =>
{
(NonDynamicHlslSourceInfo SourceInfo, string? ImplicitTextureType, bool IsSamplerUsed) hlslInfo = GetNonDynamicHlslSourceInfo(
HlslSourceInfo hlslInfo = GetNonDynamicHlslSourceInfo(
item.Right,
item.Left.Syntax,
item.Left.Symbol,
out ImmutableArray<Diagnostic> diagnostics);
return new Result<(NonDynamicHlslSourceInfo, string?, bool)>(hlslInfo, diagnostics);
return (item.Left.Hierarchy, new Result<HlslSourceInfo>(hlslInfo, diagnostics));
});
// Output the diagnostics
context.ReportDiagnostics(hlslSourceInfo.Select(static (item, token) => item.Errors));
context.ReportDiagnostics(hlslSourceInfoWithErrors.Select(static (item, token) => item.Result.Errors));
// Get the filtered sequence to enable caching
IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslSourceInfo SourceInfo)> dynamicSourceInfo =
hlslSourceInfoWithErrors
.Select(static (item, token) => (item.Hierarchy, item.Result.Value))
.WithComparers(HierarchyInfo.Comparer.Default, HlslSourceInfo.Comparer.Default);
// Generate the BuildHlslString() methods
context.RegisterSourceOutput(dynamicSourceInfo.Combine(canUseSkipLocalsInit), static (context, item) =>
{
MethodDeclarationSyntax buildHlslStringMethod = CreateBuildHlslStringMethod(item.Left.SourceInfo);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, buildHlslStringMethod, item.Right);
context.AddSource($"{item.Left.Hierarchy.FilenameHint}.BuildHlslString", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8));
});
}
/// <summary>
+1 -1
ファイルの表示
@@ -68,7 +68,7 @@ public sealed partial class IShaderGenerator : ISourceGenerator
// getDispatchIdMethod,
// loadDispatchDataMethod,
loadDispatchMetadataMethod,
buildHlslStringMethod,
//buildHlslStringMethod,
tryGetBytecodeMethod
};
+38 -15
ファイルの表示
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using ComputeSharp.SourceGenerators.Extensions;
@@ -38,22 +39,44 @@ internal sealed record HierarchyInfo(string FilenameHint, string Namespace, Immu
names.ToImmutable());
}
/// <inheritdoc/>
[Pure]
public bool Equals(HierarchyInfo? other)
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="HierarchyInfo"/>.
/// </summary>
public sealed class Comparer : IEqualityComparer<HierarchyInfo>
{
return
other is not null &&
(ReferenceEquals(this, other) ||
(Namespace == other.Namespace &&
(Names == other.Names ||
Names.AsSpan().SequenceEqual(other.Names.AsSpan()))));
}
/// <summary>
/// The singleton <see cref="Comparer"/> instance.
/// </summary>
public static Comparer Default { get; } = new();
/// <inheritdoc/>
[Pure]
public override int GetHashCode()
{
return HashCode.Combine(Namespace, Names, Names[0]);
/// <inheritdoc/>
public bool Equals(HierarchyInfo? x, HierarchyInfo? y)
{
if (x is null && y is null)
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (ReferenceEquals(x, y))
{
return true;
}
return
x.FilenameHint == y.FilenameHint &&
x.Namespace == y.Namespace &&
x.Names.AsSpan().SequenceEqual(y.Names.AsSpan());
}
/// <inheritdoc/>
public int GetHashCode(HierarchyInfo obj)
{
return HashCode.Combine(obj.Namespace, obj.Names, obj.Names[0]);
}
}
}
@@ -1,11 +1,12 @@
using System;
using ComputeSharp.SourceGenerators.Extensions;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A model for extracted info on a processed HLSL shader, excluding dynamic information.
/// A model for extracted info on a processed HLSL shader.
/// </summary>
/// <param name="HeaderAndThreadsX">The shader generated header and <c>threadsX</c> count declaration.</param>
/// <param name="ThreadsY">The <c>threadsY</c> count declaration.</param>
@@ -15,8 +16,13 @@ namespace ComputeSharp.SourceGenerators.Models;
/// <param name="CapturedFieldsAndResourcesAndForwardDeclarations">The captured fields, and method forward declarations.</param>
/// <param name="CapturedMethods">The captured method implementations.</param>
/// <param name="EntryPoint">The shader entry point.</param>
/// <param name="ImplicitTextureType">The type of the implicit texture type, if any.</param>
/// <param name="IsSamplerUsed">Whether or not the static sampler is used.</param>
/// <param name="DefinedTypes">The names of declared types.</param>
/// <param name="DefinedConstants">The names of defined constants.</param>
/// <param name="MethodSignatures">The signatures for captured methods.</param>
internal sealed record NonDynamicHlslSourceInfo(
/// <param name="Delegates">The list of delegate fields.</param>
internal sealed record HlslSourceInfo(
string HeaderAndThreadsX,
string ThreadsY,
string ThreadsZ,
@@ -25,15 +31,25 @@ internal sealed record NonDynamicHlslSourceInfo(
string CapturedFieldsAndResourcesAndForwardDeclarations,
string CapturedMethods,
string EntryPoint,
ImmutableArray<string> MethodSignatures)
string? ImplicitTextureType,
bool IsSamplerUsed,
ImmutableArray<string> DefinedTypes,
ImmutableArray<string> DefinedConstants,
ImmutableArray<string> MethodSignatures,
ImmutableArray<string> Delegates)
{
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="NonDynamicHlslSourceInfo"/>.
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="HlslSourceInfo"/>.
/// </summary>
public sealed class Comparer : IEqualityComparer<NonDynamicHlslSourceInfo>
public sealed class Comparer : IEqualityComparer<HlslSourceInfo>
{
/// <summary>
/// The singleton <see cref="Comparer"/> instance.
/// </summary>
public static Comparer Default { get; } = new();
/// <inheritdoc/>
public bool Equals(NonDynamicHlslSourceInfo? x, NonDynamicHlslSourceInfo? y)
public bool Equals(HlslSourceInfo? x, HlslSourceInfo? y)
{
if (x is null && y is null)
{
@@ -59,11 +75,16 @@ internal sealed record NonDynamicHlslSourceInfo(
x.CapturedFieldsAndResourcesAndForwardDeclarations == y.CapturedFieldsAndResourcesAndForwardDeclarations &&
x.CapturedMethods == y.CapturedMethods &&
x.EntryPoint == y.EntryPoint &&
x.MethodSignatures.AsSpan().SequenceEqual(y.MethodSignatures.AsSpan());
x.ImplicitTextureType == y.ImplicitTextureType &&
x.IsSamplerUsed == y.IsSamplerUsed &&
x.DefinedTypes.AsSpan().SequenceEqual(y.DefinedTypes.AsSpan()) &&
x.DefinedConstants.AsSpan().SequenceEqual(y.DefinedTypes.AsSpan()) &&
x.MethodSignatures.AsSpan().SequenceEqual(y.MethodSignatures.AsSpan()) &&
x.Delegates.AsSpan().SequenceEqual(y.Delegates.AsSpan());
}
/// <inheritdoc/>
public int GetHashCode(NonDynamicHlslSourceInfo obj)
public int GetHashCode(HlslSourceInfo obj)
{
HashCode hashCode = default;
@@ -75,11 +96,12 @@ internal sealed record NonDynamicHlslSourceInfo(
hashCode.Add(obj.CapturedFieldsAndResourcesAndForwardDeclarations);
hashCode.Add(obj.CapturedMethods);
hashCode.Add(obj.EntryPoint);
foreach (string signature in obj.MethodSignatures)
{
hashCode.Add(signature);
}
hashCode.Add(obj.ImplicitTextureType);
hashCode.Add(obj.IsSamplerUsed);
hashCode.AddRange(obj.DefinedTypes);
hashCode.AddRange(obj.DefinedConstants);
hashCode.AddRange(obj.MethodSignatures);
hashCode.AddRange(obj.Delegates);
return hashCode.ToHashCode();
}