diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems index 549065be..829cb1e5 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems +++ b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems @@ -15,6 +15,7 @@ + diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/Mappings/HlslKnownOperators.cs b/src/ComputeSharp.SourceGeneration.Hlsl/Mappings/HlslKnownOperators.cs new file mode 100644 index 00000000..ee1bda0a --- /dev/null +++ b/src/ComputeSharp.SourceGeneration.Hlsl/Mappings/HlslKnownOperators.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using ComputeSharp.Core.Intrinsics.Attributes; + +namespace ComputeSharp.SourceGeneration.Mappings; + +/// +/// A that contains and maps known HLSL operators names to common .NET methods. +/// +internal static partial class HlslKnownOperators +{ + /// + /// The mapping of supported known operators to HLSL names. + /// + private static readonly IReadOnlyDictionary KnownOperators = BuildKnownOperatorsMap(); + + /// + /// Builds the mapping of supported known operators to HLSL names. + /// + private static IReadOnlyDictionary BuildKnownOperatorsMap() + { + Dictionary knownOperators = new(); + + // Programmatically load mappings for the intrinsic operators on each HLSL primitive type + foreach (var item in + from type in HlslKnownTypes.KnownVectorTypes.Concat(HlslKnownTypes.KnownMatrixTypes) + from method in type.GetMethods(BindingFlags.Static | BindingFlags.Public) + where method.IsSpecialName && method.Name.StartsWith("op_") + let attribute = method.GetCustomAttribute() + where attribute is not null + select (Type: type, Operator: method, IntrinsicName: attribute.Name, attribute.RequiresParametersMatching)) + { + if (!item.RequiresParametersMatching) + { + throw new NotSupportedException("All intrinsic operators must require parameter matching."); + } + + // The key is in the format ".()" + knownOperators.Add( + $"{item.Type.FullName}{Type.Delimiter}{item.Operator.Name}({string.Join(", ", item.Operator.GetParameters().Select(static p => p.ParameterType.Name))})", + item.IntrinsicName); + } + + return knownOperators; + } + + /// + /// Tries to get the mapped HLSL-compatible method name for the input operator name. + /// + /// The input fully qualified operator name. + /// The sequence of type names for the method. + /// The mapped name, if one is found. + /// The HLSL-compatible method name that can be used in an HLSL shader. + public static bool TryGetMappedName(string name, IEnumerable parameterTypeNames, out string? mapped) + { + return KnownOperators.TryGetValue($"{name}({string.Join(", ", parameterTypeNames)})", out mapped); + } +}