using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.Contracts; using System.Reflection; using ComputeSharp.Core.Extensions; using ComputeSharp.Exceptions; namespace ComputeSharp { /// /// An attribute that contains info on a processed shader method that can be executed within a shader. /// Instances of this attribute are generated from method annotated with . /// /// This attribute is not meant to be directly used by applications using ComputeSharp. [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This attribute is meant to be used from the source generator only")] public sealed class ShaderMethodSourceAttribute : Attribute { /// /// The identifier for the invoke method, for late binding. /// internal const string InvokeMethodIdentifier = "____"; /// /// The source code for the target entry point method. /// private readonly string invokeMethod; /// /// Creates a new instance with the specified parameters. /// /// The fully qualified name of the current method. /// The collection of custom types. /// The source code for the target entry point method. /// The collection of processed methods. public ShaderMethodSourceAttribute(string methodName, string[] types, string invokeMethod, string[] methods) { this.invokeMethod = invokeMethod; MethodName = methodName; Types = types; Methods = methods; } /// /// Gets the fully qualified name of the shader type. /// internal string MethodName { get; } /// /// Gets the collection of processed custom types. /// internal IReadOnlyCollection Types { get; } /// /// Gets the collection of processed methods. /// internal IReadOnlyCollection Methods { get; } /// /// Gets the mapped source code for the current method. /// /// The name to bind the method to. /// The mapped source code for the current mehtod. [Pure] internal string GetMappedInvokeMethod(string name) { return this.invokeMethod.Replace(InvokeMethodIdentifier, name); } /// /// Gets the associated instance for a specified type. /// /// The shader type to get the attribute for. /// The associated instance for type . [Pure] internal static ShaderMethodSourceAttribute GetForDelegate(Delegate function) { if (!function.Method.IsStatic) { ThrowArgumentExceptionForNonStaticShader(); } var attributes = function.Method.DeclaringType!.Assembly.GetCustomAttributes(); string methodName = function.Method.GetFullName(); foreach (var attribute in attributes) { if (attribute.MethodName.Equals(methodName)) { return attribute; } } return MissingMethodSourceException.Throw(function); } /// /// Throws an when a given is not static. /// private static void ThrowArgumentExceptionForNonStaticShader() { throw new ArgumentException("Captured delegates in a shader need to wrap a static method.", "function"); } } }