diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs index 0a88badb..d777fdc5 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs @@ -42,7 +42,7 @@ partial class ID2D1ShaderGenerator /// /// The array of values for all captured fields. /// The size of the shader constant buffer. - /// The sequence of instances to load shader dispatch data. + /// The sequence of instances to load the shader dispatch data. private static ImmutableArray GetDispatchDataLoadingStatements(ImmutableArray fieldInfos, int constantBufferSizeInBytes) { // If there are no fields, just load an empty buffer diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.Syntax.cs index 8d4ae132..3a568749 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.Syntax.cs @@ -41,7 +41,7 @@ partial class ID2D1ShaderGenerator /// Gets a sequence of statements to load the input descriptions for a given shader. /// /// The array of values for all available input descriptions. - /// The sequence of instances to load shader dispatch data. + /// The sequence of instances to load the input descriptions data. private static ImmutableArray GetInputDescriptionsLoadingStatements(ImmutableArray inputDescriptions) { // If there are no input descriptions available, just load an empty buffer @@ -127,7 +127,7 @@ partial class ID2D1ShaderGenerator AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){offset + 8}))"), - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal((int)inputDescription.LevelOfDetail))))); + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(inputDescription.LevelOfDetail))))); offset += sizeof(int) * 3; } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.Syntax.cs new file mode 100644 index 00000000..82bac704 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.Syntax.cs @@ -0,0 +1,139 @@ +using System.Collections.Immutable; +using ComputeSharp.D2D1.__Internals; +using ComputeSharp.D2D1.SourceGenerators.Models; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618 + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +partial class ID2D1ShaderGenerator +{ + /// + private static partial class LoadResourceTextureDescriptions + { + /// + /// Creates a instance for the LoadResourceTextureDescriptions method. + /// + /// The resource texture descriptions info gathered for the current shader. + /// The resulting instance for the LoadResourceTextureDescriptions method. + public static MethodDeclarationSyntax GetSyntax(ResourceTextureDescriptionsInfo resourceTextureDescriptionsInfo) + { + // This code produces a method declaration as follows: + // + // readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.LoadResourceTextureDescriptions(ref TLoader loader) + // { + // + // } + return + MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier(nameof(LoadResourceTextureDescriptions))) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) + .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) + .AddTypeParameterListParameters(TypeParameter(Identifier("TLoader"))) + .AddParameterListParameters(Parameter(Identifier("loader")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(IdentifierName("TLoader"))) + .WithBody(Block(GetInputDescriptionsLoadingStatements(resourceTextureDescriptionsInfo.ResourceTextureDescriptions))); + } + + /// + /// Gets a sequence of statements to load the resource texture descriptions for a given shader. + /// + /// The array of values for all available resource texture descriptions. + /// The sequence of instances to load the resource texture descriptions data. + private static ImmutableArray GetInputDescriptionsLoadingStatements(ImmutableArray resourceTextureDescriptionsInfo) + { + // If there are no resource texture descriptions available, just load an empty buffer + if (resourceTextureDescriptionsInfo.IsEmpty) + { + // loader.LoadResourceTextureDescriptions(default); + return + ImmutableArray.Create( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("loader"), + IdentifierName("LoadResourceTextureDescriptions"))) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.DefaultLiteralExpression, + Token(SyntaxKind.DefaultKeyword)))))); + } + + ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + + // The size of the buffer with the resource texture descriptions is the number of resurce textures descriptions, + // times the size of each input description, which is a struct containing two int-sized fields (index and rank). + int resourceTextureDescriptionSizeInBytes = resourceTextureDescriptionsInfo.Length * sizeof(int) * 2; + + // global::System.Span data = stackalloc byte[]; + statements.Insert(0, + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("global::System.Span")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("data")) + .WithInitializer(EqualsValueClause( + StackAllocArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) + .AddRankSpecifiers( + ArrayRankSpecifier(SingletonSeparatedList( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(resourceTextureDescriptionSizeInBytes))))))))))); + + // ref byte r0 = ref data[0]; + statements.Insert(1, + LocalDeclarationStatement( + VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("r0")) + .WithInitializer(EqualsValueClause( + RefExpression( + ElementAccessExpression(IdentifierName("data")) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))))))))); + + int offset = 0; + + // Generate loading statements for each resource texture description + foreach (ResourceTextureDescription resourceTextureDescription in resourceTextureDescriptionsInfo) + { + // Write the index of the current resource texture description: + // + // 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){offset}))"), + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal((int)resourceTextureDescription.Index))))); + + // Write the rank of the current resource texture description: + // + // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint) + 4)) = ; + statements.Add(ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){offset + 4}))"), + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal((int)resourceTextureDescription.Rank))))); + + offset += sizeof(int) * 2; + } + + // loader.LoadInputDescriptions(data); + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("loader"), + IdentifierName("LoadResourceTextureDescriptions"))) + .AddArgumentListArguments(Argument(IdentifierName("data"))))); + + return statements.ToImmutable(); + } + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs new file mode 100644 index 00000000..a16d3549 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs @@ -0,0 +1,100 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Mappings; +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +partial class ID2D1ShaderGenerator +{ + /// + /// A helper with all logic to generate the LoadResourceTextureDescriptions method. + /// + private static partial class LoadResourceTextureDescriptions + { + /// + /// Extracts the resource texture descriptions for the current shader. + /// + /// The collection of produced instances. + /// The input instance to process. + /// The number of inputs for the shader. + /// The produced resource texture descriptions for the shader. + public static void GetInfo( + ImmutableArray.Builder diagnostics, + INamedTypeSymbol structDeclarationSymbol, + int inputCount, + out ImmutableArray resourceTextureDescriptions) + { + ImmutableArray<(string Name, uint Index, uint Rank)>.Builder resourceTextureInfos = ImmutableArray.CreateBuilder<(string, uint, uint)>(); + + foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) + { + // Only look for fields of a named type symbol (diagnostics is emitted by the HLSL rewriter if it's not the case). + // We're only looking for instance fields of unmanaged types in this case (as resource textures are structs). + if (fieldSymbol is not { IsStatic: false, Type: INamedTypeSymbol { IsUnmanagedType: true } typeSymbol }) + { + continue; + } + + string metadataName = typeSymbol.GetFullMetadataName(); + + // Check that the field is a resource texture type (if not, it will be processed by the HLSL rewriter too) + if (HlslKnownTypes.IsResourceTextureType(metadataName)) + { + // The type name will be either Texture1D, Texture2D or Texture3D + string typeName = HlslKnownTypes.GetMappedName(typeSymbol); + uint rank = uint.Parse(typeName.Substring(typeName.Length - 2, 1)); + uint index = uint.MaxValue; + + // Get the index from the [D2DResourceTextureIndex] attribute over the field + if (fieldSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DResourceTextureIndexAttribute", out AttributeData? attributeData)) + { + // If the constructor argument isn't available, it means the code is invalid. Just do nothing then, as the + // user will have to fix that to get the code to compile anyway. This way the generator won't crash too. + _ = attributeData!.TryGetConstructorArgument(0, out index); + } + else + { + // If the attribute is missing, emit a diagnostic + // TODO + } + + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); + + resourceTextureInfos.Add((mapping ?? fieldSymbol.Name, index, rank)); + } + } + + // Extract the resource texture descriptions for the rest of the pipeline + resourceTextureDescriptions = resourceTextureInfos.Select(static info => new ResourceTextureDescription(info.Index, info.Rank)).ToImmutableArray(); + + // Validate that the resource texture indices don't overlap with the shader inputs + if (resourceTextureInfos.Any(info => info.Index < inputCount)) + { + // TODO: overlap with textures + + return; + } + + // Validate that no resource texture has an index greater than or equal to 16 + if (resourceTextureInfos.Any(info => info.Index >= 16)) + { + // TODO: diagnostic + + return; + } + + HashSet resourceTextureIndices = new(resourceTextureInfos.Select(info => info.Index)); + + // All input description indices must be unique + if (resourceTextureIndices.Count != resourceTextureInfos.Count) + { + // TODO: diagnostic + } + } + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs index 41f73ce5..cf925966 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -51,9 +51,9 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator .Where(static item => IsD2D1PixelShaderType(item.Left.Symbol, item.Right)) .Select(static (item, token) => (item.Left.Syntax, item.Left.Symbol, HierarchyInfo.From(item.Left.Symbol))); - // Get the dispatch data, input types, 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<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch, InputTypesInfo InputTypes, HlslShaderSourceInfo Source, ImmutableArray Diagnostics)> shaderInfoWithErrors = + // Get the dispatch data, input types, resource texture descriptions, 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<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch, InputTypesInfo InputTypes, ResourceTextureDescriptionsInfo ResourceTextureDescriptions, HlslShaderSourceInfo Source, ImmutableArray Diagnostics)> shaderInfoWithErrors = shaderDeclarations .Combine(context.CompilationProvider) .Select(static (item, token) => @@ -81,6 +81,15 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator InputTypesInfo inputTypesInfo = new(inputTypes); + // Get the resource texture info for LoadResourceTextureDescriptions() + LoadResourceTextureDescriptions.GetInfo( + diagnostics, + item.Left.Symbol, + inputCount, + out ImmutableArray resourceTextureDescriptions); + + ResourceTextureDescriptionsInfo resourceTextureDescriptionsInfo = new(resourceTextureDescriptions); + // Get HLSL source for BuildHlslSource() string hlslSource = BuildHlslSource.GetHlslSource( diagnostics, @@ -111,6 +120,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator item.Left.Hierarchy, dispatchDataInfo, inputTypesInfo, + resourceTextureDescriptionsInfo, sourceInfo, diagnostics.ToImmutableArray()); }); @@ -128,10 +138,10 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.ReportDiagnostics(d2DCompileOptionsAtAssemblyLevelErrors.Select(static (item, token) => item)); // Filter all items to enable caching at a coarse level, and remove diagnostics - IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch, InputTypesInfo InputTypes, HlslShaderSourceInfo Source)> shaderInfo = + IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch, InputTypesInfo InputTypes, ResourceTextureDescriptionsInfo ResourceTextureDescriptions, HlslShaderSourceInfo Source)> shaderInfo = shaderInfoWithErrors - .Select(static (item, token) => (item.Hierarchy, item.Dispatch, item.InputTypes, item.Source)) - .WithComparers(HierarchyInfo.Comparer.Default, DispatchDataInfo.Comparer.Default, InputTypesInfo.Comparer.Default, EqualityComparer.Default); + .Select(static (item, token) => (item.Hierarchy, item.Dispatch, item.InputTypes, item.ResourceTextureDescriptions, item.Source)) + .WithComparers(HierarchyInfo.Comparer.Default, DispatchDataInfo.Comparer.Default, InputTypesInfo.Comparer.Default, ResourceTextureDescriptionsInfo.Comparer.Default, EqualityComparer.Default); // Filter items to enable caching for the input count methods IncrementalValuesProvider<(HierarchyInfo Hierarchy, int InputCount)> inputCountInfo = @@ -163,6 +173,21 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(GetInputType)}", compilationUnit.GetText(Encoding.UTF8)); }); + // Get a filtered sequence to enable caching + IncrementalValuesProvider<(HierarchyInfo Hierarchy, ResourceTextureDescriptionsInfo ResourceTextureDescriptions)> resourceTextureDescriptionsInfo = + shaderInfo + .Select(static (item, token) => (item.Hierarchy, item.ResourceTextureDescriptions)) + .WithComparers(HierarchyInfo.Comparer.Default, ResourceTextureDescriptionsInfo.Comparer.Default); + + // Generate the LoadResourceTextureDescriptions() methods + context.RegisterSourceOutput(resourceTextureDescriptionsInfo.Combine(canUseSkipLocalsInit), static (context, item) => + { + MethodDeclarationSyntax getInputTypeMethod = LoadResourceTextureDescriptions.GetSyntax(item.Left.ResourceTextureDescriptions); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, getInputTypeMethod, canUseSkipLocalsInit: false); + + context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(LoadResourceTextureDescriptions)}", compilationUnit.GetText(Encoding.UTF8)); + }); + // Get a filtered sequence to enable caching IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch)> dispatchDataInfo = shaderInfo diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescription.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescription.cs index 29d20cc9..c92757ab 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescription.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescription.cs @@ -3,7 +3,7 @@ /// /// A model representing an input description for a shader. /// -/// The index of the input resource the description if for. +/// The index of the input resource the description is for. /// The input filter to use. /// The level of detail to use. internal sealed record InputDescription(uint Index, D2D1Filter Filter, int LevelOfDetail); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescriptionsInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescriptionsInfo.cs index 3ac7001b..81869b59 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescriptionsInfo.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescriptionsInfo.cs @@ -8,7 +8,7 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models; /// /// A model representing gathered input descriptions for a shader. /// -/// The input types for a given shader. +/// The input descriptions for a given shader. internal sealed record InputDescriptionsInfo(ImmutableArray InputDescriptions) { /// diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/ResourceTextureDescription.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/ResourceTextureDescription.cs new file mode 100644 index 00000000..63f0d842 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/ResourceTextureDescription.cs @@ -0,0 +1,8 @@ +namespace ComputeSharp.D2D1.SourceGenerators.Models; + +/// +/// A model representing a resource texture description for a shader. +/// +/// The index of the resource texture resource the description is for. +/// The rank of the resource texture. +internal sealed record ResourceTextureDescription(uint Index, uint Rank); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/ResourceTextureDescriptionsInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/ResourceTextureDescriptionsInfo.cs new file mode 100644 index 00000000..b5a174d5 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/ResourceTextureDescriptionsInfo.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Immutable; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; + +namespace ComputeSharp.D2D1.SourceGenerators.Models; + +/// +/// A model representing gathered resource texture descriptions for a shader. +/// +/// The resource textures for the current shader. +internal sealed record ResourceTextureDescriptionsInfo(ImmutableArray ResourceTextureDescriptions) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : Comparer + { + /// + protected override void AddToHashCode(ref HashCode hashCode, ResourceTextureDescriptionsInfo obj) + { + hashCode.AddRange(obj.ResourceTextureDescriptions); + } + + /// + protected override bool AreEqual(ResourceTextureDescriptionsInfo x, ResourceTextureDescriptionsInfo y) + { + return x.ResourceTextureDescriptions.SequenceEqual(y.ResourceTextureDescriptions); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Attributes/D2DResourceIndexAttribute.cs b/src/ComputeSharp.D2D1/Attributes/D2DResourceTextureIndexAttribute.cs similarity index 73% rename from src/ComputeSharp.D2D1/Attributes/D2DResourceIndexAttribute.cs rename to src/ComputeSharp.D2D1/Attributes/D2DResourceTextureIndexAttribute.cs index 637905ab..1bf4938e 100644 --- a/src/ComputeSharp.D2D1/Attributes/D2DResourceIndexAttribute.cs +++ b/src/ComputeSharp.D2D1/Attributes/D2DResourceTextureIndexAttribute.cs @@ -3,20 +3,20 @@ namespace ComputeSharp.D2D1; /// -/// An attribute for resource fields in a D2D1 shader indicating the index of the D2D1 resource. +/// An attribute for resource fields in a D2D1 shader indicating the index of the D2D1 resource texture. /// This is needed to bind an input resource in a shader to the correct input. Using this attribute is mandatory. /// /// /// For more info, see . /// [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)] -public sealed class D2DResourceIndexAttribute : Attribute +public sealed class D2DResourceTextureIndexAttribute : Attribute { /// - /// Creates a new instance of the type with the specified arguments. + /// Creates a new instance of the type with the specified arguments. /// /// The index of the annotated resource field. - public D2DResourceIndexAttribute(int index) + public D2DResourceTextureIndexAttribute(int index) { Index = index; } diff --git a/src/ComputeSharp.SourceGeneration/Extensions/AttributeDataExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/AttributeDataExtensions.cs index 37436b1c..0130f215 100644 --- a/src/ComputeSharp.SourceGeneration/Extensions/AttributeDataExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/AttributeDataExtensions.cs @@ -8,6 +8,29 @@ namespace ComputeSharp.SourceGeneration.Extensions; /// internal static class AttributeDataExtensions { + /// + /// Tries to get a constructor argument at a given index from the input instance. + /// + /// The type of constructor argument to retrieve. + /// The target instance to get the argument from. + /// The index of the argument to try to retrieve. + /// The resulting argument, if it was found. + /// Whether or not an argument of type at position was found. + public static bool TryGetConstructorArgument(this AttributeData attributeData, int index, out T? result) + { + if (attributeData.ConstructorArguments.Length >= index + 1 && + attributeData.ConstructorArguments[index].Value is T argument) + { + result = argument; + + return true; + } + + result = default; + + return false; + } + /// /// Tries to get a given named argument value from an instance, if present. /// diff --git a/src/ComputeSharp.SourceGeneration/Extensions/IncrementalValuesProviderExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/IncrementalValuesProviderExtensions.cs index f7a26034..a338cc34 100644 --- a/src/ComputeSharp.SourceGeneration/Extensions/IncrementalValuesProviderExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/IncrementalValuesProviderExtensions.cs @@ -69,6 +69,32 @@ internal static class IncrementalValuesProviderExtensions return source.WithComparer(new Comparer(comparer1, comparer2, comparer3, comparer4)); } + /// + /// 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 type of fourth items in each tuple. + /// The type of fourth items in each tuple. + /// The input instance. + /// An instance for items. + /// An instance for items. + /// 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, T4, T5)> WithComparers( + this IncrementalValuesProvider<(T1, T2, T3, T4, T5)> source, + IEqualityComparer comparer1, + IEqualityComparer comparer2, + IEqualityComparer comparer3, + IEqualityComparer comparer4, + IEqualityComparer comparer5) + { + return source.WithComparer(new Comparer(comparer1, comparer2, comparer3, comparer4, comparer5)); + } + /// /// An implementation for a value tuple. /// @@ -224,4 +250,74 @@ internal static class IncrementalValuesProviderExtensions this.comparer4.GetHashCode(obj.Item4)); } } + + /// + /// An implementation for a value tuple. + /// + public sealed class Comparer : IEqualityComparer<(T1, T2, T3, T4, T5)> + { + /// + /// The comparer. + /// + private readonly IEqualityComparer comparer1; + + /// + /// The comparer. + /// + private readonly IEqualityComparer comparer2; + + /// + /// The comparer. + /// + private readonly IEqualityComparer comparer3; + + /// + /// The comparer. + /// + private readonly IEqualityComparer comparer4; + + /// + /// The comparer. + /// + private readonly IEqualityComparer comparer5; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The comparer. + /// The comparer. + /// The comparer. + /// The comparer. + /// The comparer. + public Comparer(IEqualityComparer comparer1, IEqualityComparer comparer2, IEqualityComparer comparer3, IEqualityComparer comparer4, IEqualityComparer comparer5) + { + this.comparer1 = comparer1; + this.comparer2 = comparer2; + this.comparer3 = comparer3; + this.comparer4 = comparer4; + this.comparer5 = comparer5; + } + + /// + public bool Equals((T1, T2, T3, T4, T5) x, (T1, T2, T3, T4, T5) y) + { + return + this.comparer1.Equals(x.Item1, y.Item1) && + this.comparer2.Equals(x.Item2, y.Item2) && + this.comparer3.Equals(x.Item3, y.Item3) && + this.comparer4.Equals(x.Item4, y.Item4) && + this.comparer5.Equals(x.Item5, y.Item5); + } + + /// + public int GetHashCode((T1, T2, T3, T4, T5) obj) + { + return HashCode.Combine( + this.comparer1.GetHashCode(obj.Item1), + this.comparer2.GetHashCode(obj.Item2), + this.comparer3.GetHashCode(obj.Item3), + this.comparer4.GetHashCode(obj.Item4), + this.comparer5.GetHashCode(obj.Item5)); + } + } }