From f0f52d46702879a48838f0d7f46dadb2bf6e9e8f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 8 Apr 2022 22:51:14 +0200 Subject: [PATCH] Implement HLSL source generation logic --- ...tor.CreateLoadBytecodeMethod.HlslSource.cs | 453 ++++++++++++++++++ ...nerator.CreateLoadBytecodeMethod.Syntax.cs | 65 +++ .../ID2D1ShaderGenerator.cs | 38 +- .../Models/HlslShaderSourceInfo.cs | 66 +-- 4 files changed, 558 insertions(+), 64 deletions(-) create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.HlslSource.cs create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.HlslSource.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.HlslSource.cs new file mode 100644 index 00000000..f9af6bba --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.HlslSource.cs @@ -0,0 +1,453 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Text; +using ComputeSharp.D2D1Interop.SourceGenerators.Diagnostics; +using ComputeSharp.D2D1Interop.SourceGenerators.Extensions; +using ComputeSharp.D2D1Interop.SourceGenerators.Helpers; +using ComputeSharp.D2D1Interop.SourceGenerators.Mappings; +using ComputeSharp.D2D1Interop.SourceGenerators.SyntaxRewriters; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static ComputeSharp.D2D1Interop.SourceGenerators.Diagnostics.DiagnosticDescriptors; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618, RS1024 + +namespace ComputeSharp.D2D1Interop.SourceGenerators; + +/// +partial class ID2D1ShaderGenerator +{ + /// + /// A helper with all logic to generate the LoadBytecode method. + /// + internal static partial class LoadBytecode + { + /// + /// 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 string GetHlslSource( + Compilation compilation, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + out ImmutableArray diagnostics) + { + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + + // Properties are not supported + DetectAndReportPropertyDeclarations(builder, structDeclarationSymbol); + + // We need to sets to track all discovered custom types and static methods + HashSet discoveredTypes = new(SymbolEqualityComparer.Default); + Dictionary staticMethods = new(SymbolEqualityComparer.Default); + Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); + + // Explore the syntax tree and extract the processed info + var semanticModelProvider = new SemanticModelProvider(compilation); + var valueFields = GetInstanceFields(builder, structDeclarationSymbol, discoveredTypes); + var (entryPoint, processedMethods) = GetProcessedMethods(builder, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, constantDefinitions); + var declaredTypes = GetDeclaredTypes(discoveredTypes); + var definedConstants = GetDefinedConstants(constantDefinitions); + var staticFields = GetStaticFields(builder, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); + + diagnostics = builder.ToImmutable(); + + // Get the HLSL source + return GetHlslSource( + definedConstants, + declaredTypes, + valueFields, + staticFields, + processedMethods, + entryPoint); + } + + /// + /// Gets a sequence of captured fields and their mapped names. + /// + /// The collection of produced instances. + /// The input instance to process. + /// The collection of currently discovered types. + /// A sequence of captured fields in . + private static ImmutableArray<(string Name, string HlslType)> GetInstanceFields( + ImmutableArray.Builder diagnostics, + INamedTypeSymbol structDeclarationSymbol, + ICollection types) + { + ImmutableArray<(string, string)>.Builder values = ImmutableArray.CreateBuilder<(string, string)>(); + + foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) + { + if (fieldSymbol.IsStatic) + { + continue; + } + + // Captured fields must be named type symbols + if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol) + { + diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + + continue; + } + + string metadataName = typeSymbol.GetFullMetadataName(); + string typeName = HlslKnownTypes.GetMappedName(typeSymbol); + + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); + + // Allowed fields must be unmanaged values + 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)); + } + else + { + diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, typeSymbol); + } + } + + return 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 . + 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; + } + + // 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 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. + /// A sequence of processed methods in , and the entry point. + private static (string EntryPoint, ImmutableArray<(string Signature, string Definition)> Methods) GetProcessedMethods( + ImmutableArray.Builder diagnostics, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary staticMethods, + IDictionary constantDefinitions) + { + // 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)>(); + + foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) + { + IMethodSymbol methodDeclarationSymbol = semanticModel.For(methodDeclaration).GetDeclaredSymbol(methodDeclaration)!; + bool isShaderEntryPoint = + methodDeclarationSymbol.Name == nameof(ID2D1PixelShader.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, + diagnostics); + + // Rewrite the method syntax tree + MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia(); + + // Emit the extracted local functions first + foreach (var localFunction in shaderSourceRewriter.LocalFunctions) + { + methods.Add(( + localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString())); + } + + // If the method is the shader entry point, do additional processing + if (isShaderEntryPoint) + { + string entryPointDeclaration = processedMethod.NormalizeWhitespace(eol: "\n").ToFullString(); + string adjustedEntryPointDeclaration = entryPointDeclaration.Replace("float4 Execute()", "D2D_ENTRY(Execute)"); + + entryPoint = adjustedEntryPointDeclaration; + } + else + { + methods.Add(( + processedMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + processedMethod.NormalizeWhitespace(eol: "\n").ToFullString())); + } + } + + // Process static methods as well + foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values) + { + methods.Add(( + staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + staticMethod.NormalizeWhitespace(eol: "\n").ToFullString())); + } + + return (entryPoint!, methods.ToImmutable()); + } + + /// + /// Gets a sequence of discovered constants. + /// + /// The collection of discovered constant definitions. + /// A sequence of discovered constants to declare in the shader. + private static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary constantDefinitions) + { + ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(constantDefinitions.Count); + + foreach (var constant in constantDefinitions) + { + var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); + var constantName = $"__{ownerTypeName}__{constant.Key.Name}"; + + builder.Add((constantName, constant.Value)); + } + + return builder.MoveToImmutable(); + } + + /// + /// Gets the sequence of processed discovered custom types. + /// + /// The sequence of discovered custom types. + /// A sequence of custom type definitions to add to the shader source. + private static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes(IEnumerable types) + { + ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(); + + foreach (var type in HlslKnownTypes.GetCustomTypes(types)) + { + var structType = type.GetFullMetadataName().ToHlslIdentifierName(); + var structDeclaration = StructDeclaration(structType); + + // Declare the fields of the current type + foreach (var field in type.GetMembers().OfType()) + { + if (field.IsStatic) continue; + + INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type; + + // Convert the name to the fully qualified HLSL version + if (!HlslKnownTypes.TryGetMappedName(fieldType.GetFullMetadataName(), out string? mapped)) + { + mapped = fieldType.GetFullMetadataName().ToHlslIdentifierName(); + } + + structDeclaration = structDeclaration.AddMembers( + FieldDeclaration(VariableDeclaration( + IdentifierName(mapped!)).AddVariables( + VariableDeclarator(Identifier(field.Name))))); + } + + // Insert the trailing ; right after the closing bracket (after normalization) + builder.Add(( + structType, + structDeclaration + .NormalizeWhitespace(eol: "\n") + .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) + .ToFullString())); + } + + return builder.ToImmutable(); + } + + /// + /// Finds and reports all declared properties in a shader. + /// + /// The collection of produced instances. + /// The input instance to process. + private static void DetectAndReportPropertyDeclarations(ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol) + { + foreach (var propertySymbol in structDeclarationSymbol.GetMembers().OfType()) + { + diagnostics.Add(DiagnosticDescriptors.PropertyDeclaration, propertySymbol); + } + } + + /// + /// Produces the series of statements to build the current HLSL source. + /// + /// The sequence of defined constants for the shader. + /// The sequence of declared types used by the shader. + /// The sequence of value instance fields for the current shader. + /// The sequence of static fields referenced by the shader. + /// The sequence of processed methods 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 string GetHlslSource( + ImmutableArray<(string Name, string Value)> definedConstants, + ImmutableArray<(string Name, string Definition)> declaredTypes, + ImmutableArray<(string Name, string HlslType)> valueFields, + ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> staticFields, + ImmutableArray<(string Signature, string Definition)> processedMethods, + string executeMethod) + { + StringBuilder hlslBuilder = new(); + + void AppendLF() + { + hlslBuilder.Append('\n'); + } + + void AppendLineAndLF(string text) + { + hlslBuilder.Append(text); + hlslBuilder.Append('\n'); + } + + // Header + AppendLineAndLF("// ================================================"); + AppendLineAndLF("// AUTO GENERATED"); + AppendLineAndLF("// ================================================"); + AppendLineAndLF("// This shader was created by ComputeSharp."); + AppendLineAndLF("// See: https://github.com/Sergio0694/ComputeSharp."); + AppendLF(); + + // Define declarations + foreach (var (name, value) in definedConstants) + { + AppendLineAndLF($"#define {name} {value}"); + } + + // 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); + } + + // Captured variables + AppendLF(); + + // User-defined values + foreach (var (fieldName, fieldType) in valueFields) + { + AppendLineAndLF($"{fieldType} {fieldName};"); + } + + // Forward declarations + foreach (var (forwardDeclaration, _) in processedMethods) + { + AppendLF(); + AppendLineAndLF(forwardDeclaration); + } + + // Captured methods + foreach (var (_, method) in processedMethods) + { + AppendLF(); + AppendLineAndLF(method); + } + + // Entry point + AppendLF(); + AppendLineAndLF(executeMethod); + + return hlslBuilder.ToString(); + } + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs new file mode 100644 index 00000000..2fdd6b5b --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs @@ -0,0 +1,65 @@ +using ComputeSharp.D2D1Interop.__Internals; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618 + +namespace ComputeSharp.D2D1Interop.SourceGenerators; + +/// +partial class ID2D1ShaderGenerator +{ + /// + partial class LoadBytecode + { + /// + /// Creates a instance for the TryGetBytecode method. + /// + /// The input HLSL source. + /// The resulting instance for the BuildHlslString method. + public static MethodDeclarationSyntax GetSyntax(string hlslSource) + { + BlockSyntax block = GetShaderBytecodeBody(hlslSource); + + // This code produces a method declaration as follows: + // + // readonly void global::ComputeSharp.D2D1Interop.__Internals.ID2D1Shader.LoadBytecode(ref TLoader loader, global::ComputeSharp.D2D1Interop.D2D1ShaderProfile? shaderProfile, out string hlslSource) + // { + // + // } + return + MethodDeclaration( + PredefinedType(Token(SyntaxKind.VoidKeyword)), + Identifier("LoadBytecode")) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1Interop.__Internals.{nameof(ID2D1Shader)}"))) + .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) + .AddTypeParameterListParameters(TypeParameter(Identifier("TLoader"))) + .AddParameterListParameters( + Parameter(Identifier("loader")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(IdentifierName("TLoader")), + Parameter(Identifier("shaderProfile")).WithType(NullableType(IdentifierName("global::ComputeSharp.D2D1Interop.D2D1ShaderProfile"))), + Parameter(Identifier("hlslSource")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(PredefinedType(Token(SyntaxKind.StringKeyword)))) + .WithBody(block); + } + + /// + /// Gets a instance with the logic to try to get a compiled shader bytecode. + /// + /// The input HLSL source. + /// The instance trying to retrieve the precompiled shader. + private static unsafe BlockSyntax GetShaderBytecodeBody(string hlslSource) + { + // This code produces a branch as follows: + // + // hlslSource = ; + return + Block(ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + IdentifierName("hlslSource"), + LiteralExpression( + SyntaxKind.StringLiteralExpression, + Literal(hlslSource))))); + } + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.cs index 99dce673..3d048565 100644 --- a/src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.cs @@ -48,7 +48,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator // Get the dispatch data, HLSL source and embedded bytecode info. This info is computed on the // same step as parts are shared in following sub-branches in the incremental generator pipeline. - IncrementalValuesProvider<(Result Dispatch, Result Hlsl, Result ThreadIds)> shaderInfoWithErrors = + IncrementalValuesProvider<(Result Dispatch, Result SourceInfo, Result ThreadIds)> shaderInfoWithErrors = shaderDeclarations .Combine(context.CompilationProvider) .Select(static (item, token) => @@ -68,23 +68,36 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator token.ThrowIfCancellationRequested(); + // Get HLSL source for LoadBytecode() + string hlslSource = LoadBytecode.GetHlslSource( + item.Right, + item.Left.Syntax, + item.Left.Symbol, + out ImmutableArray hlslSourceDiagnostics); + + token.ThrowIfCancellationRequested(); + + HlslShaderSourceInfo sourceInfo = new( + item.Left.Hierarchy, + hlslSource); + // TODO return ( new Result(dispatchDataInfo, dispatchDataDiagnostics), - new Result(null!, ImmutableArray.Empty), + new Result(sourceInfo, ImmutableArray.Empty), new Result(null!, ImmutableArray.Empty)); }); // Output the diagnostics context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, token) => item.Dispatch.Errors)); - context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, token) => item.Hlsl.Errors)); + context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, token) => item.SourceInfo.Errors)); context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, token) => item.ThreadIds.Errors)); // Filter all items to enable caching at a coarse level, and remove diagnostics - IncrementalValuesProvider<(DispatchDataInfo Dispatch, HlslShaderSourceInfo Hlsl, ThreadIdsInfo ThreadIds)> shaderInfo = + IncrementalValuesProvider<(DispatchDataInfo Dispatch, HlslShaderSourceInfo SourceInfo, ThreadIdsInfo ThreadIds)> shaderInfo = shaderInfoWithErrors - .Select(static (item, token) => (item.Dispatch.Value, item.Hlsl.Value, item.ThreadIds.Value)) + .Select(static (item, token) => (item.Dispatch.Value, item.SourceInfo.Value, item.ThreadIds.Value)) .WithComparers(DispatchDataInfo.Comparer.Default, HlslShaderSourceInfo.Comparer.Default, ThreadIdsInfo.Comparer.Default); // Get a filtered sequence to enable caching @@ -101,5 +114,20 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(LoadDispatchData)}", compilationUnit.ToFullString()); }); + + // Get a filtered sequence to enable caching + IncrementalValuesProvider hlslSourceInfo = + shaderInfo + .Select(static (item, token) => item.SourceInfo) + .WithComparer(HlslShaderSourceInfo.Comparer.Default); + + // Generate the LoadBytecode() methods + context.RegisterSourceOutput(hlslSourceInfo, static (context, item) => + { + MethodDeclarationSyntax loadBytecodeMethod = LoadBytecode.GetSyntax(item.HlslSource); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, loadBytecodeMethod, false); + + context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(LoadBytecode)}", compilationUnit.ToFullString()); + }); } } diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/HlslShaderSourceInfo.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/HlslShaderSourceInfo.cs index 59bee7da..aceb8954 100644 --- a/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/HlslShaderSourceInfo.cs +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Models/HlslShaderSourceInfo.cs @@ -1,42 +1,14 @@ using System; using System.Collections.Generic; -using System.Collections.Immutable; -using ComputeSharp.D2D1Interop.SourceGenerators.Extensions; namespace ComputeSharp.D2D1Interop.SourceGenerators.Models; /// /// A model for extracted info on a processed HLSL shader. /// -/// The shader generated header and threadsX count declaration. -/// The threadsY count declaration. -/// The threadsZ count declaration. -/// The define statements, if any. -/// The static fields and declared types, if any. -/// The captured fields, and method forward declarations. -/// The captured method implementations. -/// The shader entry point. -/// The type of the implicit texture type, if any. -/// Whether or not the static sampler is used. -/// The names of declared types. -/// The names of defined constants. -/// The signatures for captured methods. -/// The list of delegate fields. -internal sealed record HlslShaderSourceInfo( - string HeaderAndThreadsX, - string ThreadsY, - string ThreadsZ, - string Defines, - string StaticFieldsAndDeclaredTypes, - string CapturedFieldsAndResourcesAndForwardDeclarations, - string CapturedMethods, - string EntryPoint, - string? ImplicitTextureType, - bool IsSamplerUsed, - ImmutableArray DefinedTypes, - ImmutableArray DefinedConstants, - ImmutableArray MethodSignatures, - ImmutableArray Delegates) +/// The hierarchy data for the shader. +/// The HLSL source. +internal sealed record HlslShaderSourceInfo(HierarchyInfo Hierarchy, string HlslSource) { /// /// An implementation for . @@ -67,20 +39,8 @@ internal sealed record HlslShaderSourceInfo( } return - x.HeaderAndThreadsX == y.HeaderAndThreadsX && - x.ThreadsY == y.ThreadsY && - x.ThreadsZ == y.ThreadsZ && - x.Defines == y.Defines && - x.StaticFieldsAndDeclaredTypes == y.StaticFieldsAndDeclaredTypes && - x.CapturedFieldsAndResourcesAndForwardDeclarations == y.CapturedFieldsAndResourcesAndForwardDeclarations && - x.CapturedMethods == y.CapturedMethods && - x.EntryPoint == y.EntryPoint && - x.ImplicitTextureType == y.ImplicitTextureType && - x.IsSamplerUsed == y.IsSamplerUsed && - x.DefinedTypes.SequenceEqual(y.DefinedTypes) && - x.DefinedConstants.SequenceEqual(y.DefinedTypes) && - x.MethodSignatures.SequenceEqual(y.MethodSignatures) && - x.Delegates.SequenceEqual(y.Delegates); + HierarchyInfo.Comparer.Default.Equals(x.Hierarchy, y.Hierarchy) && + x.HlslSource == y.HlslSource; } /// @@ -88,20 +48,8 @@ internal sealed record HlslShaderSourceInfo( { HashCode hashCode = default; - hashCode.Add(obj.HeaderAndThreadsX); - hashCode.Add(obj.ThreadsY); - hashCode.Add(obj.ThreadsZ); - hashCode.Add(obj.Defines); - hashCode.Add(obj.StaticFieldsAndDeclaredTypes); - hashCode.Add(obj.CapturedFieldsAndResourcesAndForwardDeclarations); - hashCode.Add(obj.CapturedMethods); - hashCode.Add(obj.EntryPoint); - hashCode.Add(obj.ImplicitTextureType); - hashCode.Add(obj.IsSamplerUsed); - hashCode.AddRange(obj.DefinedTypes); - hashCode.AddRange(obj.DefinedConstants); - hashCode.AddRange(obj.MethodSignatures); - hashCode.AddRange(obj.Delegates); + hashCode.Add(HierarchyInfo.Comparer.Default.GetHashCode(obj.Hierarchy)); + hashCode.Add(obj.HlslSource); return hashCode.ToHashCode(); }