using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using ComputeSharp.Core.Intrinsics;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Operations;
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 Dictionary KnownOperators = BuildKnownOperatorsMap();
///
/// Builds the mapping of supported known operators to HLSL names.
///
/// The mapping of supported known operators to HLSL names.
private static Dictionary BuildKnownOperatorsMap()
{
Dictionary knownOperators = [];
// Programmatically load mappings for the intrinsic operators on each HLSL primitive type
foreach ((Type Type, MethodInfo Operator, string IntrinsicName, bool RequiresParametersMatching) item in
from type in HlslKnownTypes.EnumerateKnownVectorTypes().Concat(HlslKnownTypes.EnumerateKnownMatrixTypes())
from method in type.GetMethods(BindingFlags.Static | BindingFlags.Public)
where method.IsSpecialName && method.Name.StartsWith("op_", StringComparison.InvariantCulture)
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;
}
///
/// Checks whether a given operator kind represents a candidate special intrinsic that can handle.
///
/// The input operator kind to check.
/// Whether is a candidate operator for a special intrinsic to rewrite.
public static bool IsCandidateOperator(BinaryOperatorKind operatorKind)
{
return operatorKind is BinaryOperatorKind.Multiply or BinaryOperatorKind.UnsignedRightShift;
}
///
/// 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);
}
}