diff --git a/src/ComputeSharp.Core/Attributes/AutoConstructorAttribute.cs b/src/ComputeSharp.Core/Attributes/AutoConstructorAttribute.cs
index c5db9978..bd4dc3e7 100644
--- a/src/ComputeSharp.Core/Attributes/AutoConstructorAttribute.cs
+++ b/src/ComputeSharp.Core/Attributes/AutoConstructorAttribute.cs
@@ -5,7 +5,7 @@ namespace ComputeSharp
///
/// An attribute that indicates that a target shader type should get an automatic constructor for all fields.
///
- [AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)]
+ [AttributeUsage(AttributeTargets.Struct)]
public sealed class AutoConstructorAttribute : Attribute
{
}
diff --git a/src/ComputeSharp.Core/Attributes/IComputeShaderSourceAttribute.cs b/src/ComputeSharp.Core/Attributes/IComputeShaderSourceAttribute.cs
index 78a86340..b1db45a8 100644
--- a/src/ComputeSharp.Core/Attributes/IComputeShaderSourceAttribute.cs
+++ b/src/ComputeSharp.Core/Attributes/IComputeShaderSourceAttribute.cs
@@ -8,9 +8,9 @@ using System.Reflection;
namespace ComputeSharp
{
///
- /// An attribute that indicates that a target shader type should get an automatic constructor for all fields.
- /// This attribute is not meant to be directly used by applications using ComputeSharp.
+ /// An attribute that contains info on a processed compute shader that can be executed.
///
+ /// 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")]
diff --git a/src/ComputeSharp.Core/Attributes/ShaderMethodAttribute.cs b/src/ComputeSharp.Core/Attributes/ShaderMethodAttribute.cs
new file mode 100644
index 00000000..9eae4f37
--- /dev/null
+++ b/src/ComputeSharp.Core/Attributes/ShaderMethodAttribute.cs
@@ -0,0 +1,16 @@
+using System;
+
+namespace ComputeSharp
+{
+ ///
+ /// An attribute that indicates that a method will be indirectly used in a compute shader.
+ /// This method is necessary for methods that are captured and used within a given shader
+ /// through a field (of some custom type). In order to be processed
+ /// correctly, wrapped methods need to have this attribute manually applied to them.
+ /// Methods also need to be static, though this can only be tested at runtime.
+ ///
+ [AttributeUsage(AttributeTargets.Method)]
+ public sealed class ShaderMethodAttribute : Attribute
+ {
+ }
+}
\ No newline at end of file
diff --git a/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs b/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs
new file mode 100644
index 00000000..9fd1fbd1
--- /dev/null
+++ b/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs
@@ -0,0 +1,98 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Diagnostics.Contracts;
+using System.Reflection;
+using ComputeSharp.Core.Extensions;
+using ComputeSharp.Exceptions;
+using Microsoft.Toolkit.Diagnostics;
+
+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)
+ {
+ Guard.IsTrue(function.Method.IsStatic, "Captured delegates need to wrap static methods");
+
+ 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);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/ComputeSharp.Core/Exceptions/InvalidExecutionContextException.cs b/src/ComputeSharp.Core/Exceptions/InvalidExecutionContextException.cs
index 00a70c3e..d7401c19 100644
--- a/src/ComputeSharp.Core/Exceptions/InvalidExecutionContextException.cs
+++ b/src/ComputeSharp.Core/Exceptions/InvalidExecutionContextException.cs
@@ -11,6 +11,9 @@ namespace ComputeSharp.Exceptions
/// Creates a new instance
///
/// The name of the caller API
- internal InvalidExecutionContextException(string name) : base($"The API {name} can only be used from within an HLSL shader") { }
+ internal InvalidExecutionContextException(string name)
+ : base($"The API {name} can only be used from within an HLSL shader.")
+ {
+ }
}
}
diff --git a/src/ComputeSharp.Core/Exceptions/MissingMethodSourceException.cs b/src/ComputeSharp.Core/Exceptions/MissingMethodSourceException.cs
new file mode 100644
index 00000000..ddb6232e
--- /dev/null
+++ b/src/ComputeSharp.Core/Exceptions/MissingMethodSourceException.cs
@@ -0,0 +1,52 @@
+using System;
+using System.Diagnostics.Contracts;
+using System.Text;
+using ComputeSharp.Core.Extensions;
+
+#pragma warning disable CS0618
+
+namespace ComputeSharp.Exceptions
+{
+ ///
+ /// A custom that indicates when an HLSL-only API is called from C#
+ ///
+ public sealed class MissingMethodSourceException : InvalidOperationException
+ {
+ ///
+ /// Creates a new instance.
+ ///
+ /// The exception message to display.
+ private MissingMethodSourceException(string message)
+ : base(message)
+ {
+ }
+
+ ///
+ /// Creates a new instance from the specified parameters.
+ ///
+ /// The target that couldn't be processed.
+ /// A new instance with a formatted error message.
+ [Pure]
+ private static MissingMethodSourceException Create(Delegate method)
+ {
+ StringBuilder builder = new(512);
+
+ builder.AppendLine("The processed source for a method captured as a delegate in a shader was not found.");
+ builder.AppendLine($"The delegate was of type {method.GetType()} and it was wrapping the method {method.Method.GetFullName()}.");
+ builder.Append($"Make sure that the target method is annotated with [{nameof(ShaderMethodAttribute)}].");
+ builder.ToString();
+
+ return new(builder.ToString());
+ }
+
+ ///
+ /// Throws a new for a given delegate.
+ ///
+ /// The target that couldn't be processed.
+ /// This method always throws and never actually returns anything.
+ internal static ShaderMethodSourceAttribute Throw(Delegate method)
+ {
+ throw Create(method);
+ }
+ }
+}
diff --git a/src/ComputeSharp.Core/Extensions/MethodInfoExtensions.cs b/src/ComputeSharp.Core/Extensions/MethodInfoExtensions.cs
new file mode 100644
index 00000000..b413e1b3
--- /dev/null
+++ b/src/ComputeSharp.Core/Extensions/MethodInfoExtensions.cs
@@ -0,0 +1,32 @@
+using System.Diagnostics.Contracts;
+using System.Linq;
+using System.Reflection;
+
+namespace ComputeSharp.Core.Extensions
+{
+ ///
+ /// A that provides extension methods for the type.
+ ///
+ internal static class MethodInfoExtensions
+ {
+ ///
+ /// Gets a fully qualified name for the input method, including parameters.
+ ///
+ /// The input instance.
+ /// A fully qualified name for , including parameters.
+ [Pure]
+ public static string GetFullName(this MethodInfo method)
+ {
+ var parameters = string.Join(", ", method.GetParameters().Select(static p => p.ParameterType.FullName));
+
+ if (method.IsGenericMethod)
+ {
+ var arguments = string.Join(", ", method.GetGenericArguments().Select(static t => t.FullName));
+
+ return $"{method.DeclaringType!.FullName}.{method.Name}<{arguments}>({parameters})";
+ }
+
+ return $"{method.DeclaringType!.FullName}.{method.Name}({parameters})";
+ }
+ }
+}
diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/Buffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/Buffer{T}.cs
index 7e9d13cf..e4880443 100644
--- a/src/ComputeSharp.Graphics/Buffers/Abstract/Buffer{T}.cs
+++ b/src/ComputeSharp.Graphics/Buffers/Abstract/Buffer{T}.cs
@@ -279,9 +279,7 @@ namespace ComputeSharp.Graphics.Buffers.Abstract
{
if (GraphicsDevice != device)
{
- void Throw() => throw GraphicsDeviceMismatchException.Create(this, device);
-
- Throw();
+ GraphicsDeviceMismatchException.Throw(this, device);
}
}
}
diff --git a/src/ComputeSharp.Graphics/Exceptions/GraphicsDeviceMismatchException.cs b/src/ComputeSharp.Graphics/Exceptions/GraphicsDeviceMismatchException.cs
index 9fb31b09..fe2c4490 100644
--- a/src/ComputeSharp.Graphics/Exceptions/GraphicsDeviceMismatchException.cs
+++ b/src/ComputeSharp.Graphics/Exceptions/GraphicsDeviceMismatchException.cs
@@ -7,7 +7,7 @@ using ComputeSharp.Graphics.Buffers.Abstract;
namespace ComputeSharp.Exceptions
{
///
- /// A custom that indicates when mismatched devices are being used.
+ /// A custom that indicates when mismatched devices are being used.
///
public sealed class GraphicsDeviceMismatchException : InvalidOperationException
{
@@ -28,7 +28,7 @@ namespace ComputeSharp.Exceptions
/// The target instance that was used.
/// A new instance with a formatted error message.
[Pure]
- public static GraphicsDeviceMismatchException Create(Buffer buffer, GraphicsDevice device)
+ private static GraphicsDeviceMismatchException Create(Buffer buffer, GraphicsDevice device)
where T : unmanaged
{
StringBuilder builder = new(512);
@@ -36,10 +36,23 @@ namespace ComputeSharp.Exceptions
builder.AppendLine("Invalid pairing of graphics devices used to run a compute shader and allocate memory buffers.");
builder.AppendLine($"The target device to run the compute shader is \"{device}\".");
builder.AppendLine($"The buffer of type {buffer.GetType()} was allocated on device \"{buffer.GraphicsDevice}\".");
- builder.AppendLine("Make sure to always allocate buffers on the same device used to actually run the code that accesses them.");
+ builder.Append("Make sure to always allocate buffers on the same device used to actually run the code that accesses them.");
builder.ToString();
return new(builder.ToString());
}
+
+ ///
+ /// Throws a new instance from the specified parameters.
+ ///
+ /// The type of values in the input buffer.
+ /// The input that was used.
+ /// The target instance that was used.
+ [Pure]
+ internal static void Throw(Buffer buffer, GraphicsDevice device)
+ where T : unmanaged
+ {
+ throw Create(buffer, device);
+ }
}
}
\ No newline at end of file
diff --git a/src/ComputeSharp.Shaders/Exceptions/HlslCompilationException.cs b/src/ComputeSharp.Shaders/Exceptions/HlslCompilationException.cs
index 840db2e6..bb94d393 100644
--- a/src/ComputeSharp.Shaders/Exceptions/HlslCompilationException.cs
+++ b/src/ComputeSharp.Shaders/Exceptions/HlslCompilationException.cs
@@ -5,17 +5,24 @@ using System.Text;
namespace ComputeSharp.Exceptions
{
///
- /// A custom that indicates when mismatched devices are being used
+ /// A custom type that indicates when a shader compilation with the DXC compiler has failed.
///
public sealed class HlslCompilationException : Exception
{
///
- /// Creates a new instance
+ /// Creates a new instance
///
- /// The error message produced by the Dxc compiler
- internal HlslCompilationException(string error) : base(GetExceptionMessage(error)) { }
+ /// The error message produced by the DXC compiler
+ internal HlslCompilationException(string error)
+ : base(GetExceptionMessage(error))
+ {
+ }
- // Gets a proper exception message for a given compilation error
+ ///
+ /// Gets a formatted exception message for a given compilation error.
+ ///
+ /// The input compilatin error message from the DXC compiler.
+ /// A formatted error message for a new instance.
[Pure]
private static string GetExceptionMessage(string error)
{
diff --git a/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs b/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs
index 1770ad27..26bfe745 100644
--- a/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs
+++ b/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs
@@ -1,8 +1,11 @@
-using System.Runtime.CompilerServices;
+using System;
+using System.Reflection;
+using System.Reflection.Emit;
+using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.Toolkit.Diagnostics;
-namespace System.Reflection.Emit
+namespace ComputeSharp.Shaders.Extensions
{
///
/// A that provides extension methods for the type
diff --git a/src/ComputeSharp.Shaders/Extensions/StringExtensions.cs b/src/ComputeSharp.Shaders/Extensions/StringExtensions.cs
deleted file mode 100644
index 16f21407..00000000
--- a/src/ComputeSharp.Shaders/Extensions/StringExtensions.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-using System.Diagnostics.Contracts;
-using System.Linq;
-using System.Text.RegularExpressions;
-
-namespace System
-{
- ///
- /// A that provides extension methods for the type
- ///
- internal static class StringExtensions
- {
- ///
- /// Removes the left padding for an input multiline
- ///
- /// The input to process
- /// A left-aligned with the same text as the input
- [Pure]
- public static string RemoveLeftPadding(this string text)
- {
- string[] lines = text.Split(Environment.NewLine);
- int spaces = text.TakeWhile(c => c == ' ').Count();
- Regex regex = new Regex($"^{new string(Enumerable.Repeat(' ', spaces).ToArray())}");
-
- return lines.Aggregate(string.Empty, (result, line) => $"{result}{Environment.NewLine}{regex.Replace(line, string.Empty)}");
- }
- }
-}
diff --git a/src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs b/src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs
index 081a27c0..72771697 100644
--- a/src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs
+++ b/src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs
@@ -1,53 +1,21 @@
-using System.Diagnostics.CodeAnalysis;
+using System;
using System.Diagnostics.Contracts;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-namespace System
+namespace ComputeSharp.Shaders.Extensions
{
///
- /// A that provides extension methods for the type
+ /// A that provides extension methods for the type.
///
internal static class TypeExtensions
{
///
- /// Gets whether or not the input represents a
+ /// Gets whether or not the input represents a .
///
- /// The input type to analyze
+ /// The input type to analyze.
[Pure]
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static bool IsDelegate(this Type type) => type.IsClass &&
- type.IsSubclassOf(typeof(Delegate));
-
- ///
- /// Gets whether or not the input represents a with no captured variables
- ///
- /// The input type to analyze
- [Pure]
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static bool IsStatelessDelegateContainer(this Type type) => type.GetFields(BindingFlags.Static | BindingFlags.Public).Length > 0;
-
- ///
- /// Tries to find an ancestor member starting from the input
- ///
- /// The input type to start the search from
- /// The name of the member to retrieve
- /// A bitmask comprised of one or more that specify how the search is conducted
- /// when a member with the given name is found, otherwise
- public static bool TryFindAncestorMember(this Type type, string name, BindingFlags bindingAttr, [NotNullWhen(true)] out (Type DeclaringType, MemberInfo MemberInfo)? result)
+ public static bool IsDelegate(this Type type)
{
- while ((type = type.DeclaringType!) != null)
- {
- MemberInfo[] memberInfos = type.GetMember(name, bindingAttr);
- if (memberInfos.Length > 0)
- {
- result = (type, memberInfos[0]);
- return true;
- }
- }
-
- result = null;
- return false;
+ return type.IsSubclassOf(typeof(Delegate));
}
}
}
diff --git a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs
index 955ca45e..d4e617f3 100644
--- a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs
+++ b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs
@@ -5,6 +5,7 @@ using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
+using ComputeSharp.Shaders.Extensions;
namespace ComputeSharp.Shaders.Translation
{
diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs
index 781fa8d7..7da9b114 100644
--- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs
+++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs
@@ -8,6 +8,7 @@ using System.Runtime.InteropServices;
using ComputeSharp.Core.Interop;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics.Buffers.Abstract;
+using ComputeSharp.Shaders.Extensions;
using ComputeSharp.Shaders.Mappings;
using ComputeSharp.Shaders.Translation.Models;
using Microsoft.Toolkit.Diagnostics;
diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs
index 347bbcfc..51ad4b88 100644
--- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs
+++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs
@@ -56,6 +56,16 @@ namespace ComputeSharp.Shaders.Translation
///
private readonly List fieldsInfo = new();
+ ///
+ /// The with the collected methods for the shader.
+ ///
+ private readonly List methodsInfo = new();
+
+ ///
+ /// The with the collected declared types for the shader.
+ ///
+ private readonly List declaredTypes = new();
+
///
/// Creates a new instance.
///
@@ -81,10 +91,10 @@ namespace ComputeSharp.Shaders.Translation
public IReadOnlyList FieldsInfo => this.fieldsInfo;
///
- public IReadOnlyCollection MethodsInfo { get; private set; }
+ public IReadOnlyCollection MethodsInfo => this.methodsInfo;
///
- public IReadOnlyCollection DeclaredTypes { get; private set; }
+ public IReadOnlyCollection DeclaredTypes => this.declaredTypes;
///
/// Loads and processes an input shadeer
@@ -178,15 +188,14 @@ namespace ComputeSharp.Shaders.Translation
this.capturedFields.Add(fieldInfo);
this.fieldsInfo.Add(new CapturedFieldInfo(hlslType, hlslName));
}
- else if (fieldType.IsDelegate() &&
- fieldInfo.GetValue(shader) is Delegate func &&
- (func.Method.IsStatic || func.Method.DeclaringType!.IsStatelessDelegateContainer()) &&
- (HlslKnownTypes.IsKnownScalarType(func.Method.ReturnType) || HlslKnownTypes.IsKnownVectorType(func.Method.ReturnType)) &&
- fieldType.GenericTypeArguments.All(type => HlslKnownTypes.IsKnownScalarType(type) ||
- HlslKnownTypes.IsKnownVectorType(type)))
+ else if (fieldInfo.GetValue(shader) is Delegate { Method: { IsStatic: true } } func)
{
// Captured static delegates with a return type
- throw new NotImplementedException();
+ var methodSource = ShaderMethodSourceAttribute.GetForDelegate(func);
+
+ this.declaredTypes.AddRange(methodSource.Types);
+ this.methodsInfo.Add(methodSource.GetMappedInvokeMethod(hlslName));
+ this.methodsInfo.AddRange(methodSource.Methods);
}
else ThrowHelper.ThrowArgumentException("Invalid captured variable");
}
@@ -196,9 +205,10 @@ namespace ComputeSharp.Shaders.Translation
///
private void LoadMethodMetadata()
{
- DeclaredTypes = Attribute.Types;
EntryPoint = Attribute.ExecuteMethod;
- MethodsInfo = Attribute.Methods;
+
+ this.methodsInfo.AddRange(Attribute.Methods);
+ this.declaredTypes.AddRange(Attribute.Types);
}
}
}
diff --git a/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs
index 49f6bb66..392a250c 100644
--- a/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs
+++ b/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs
@@ -1,4 +1,5 @@
using System.Diagnostics.Contracts;
+using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
@@ -48,10 +49,18 @@ namespace ComputeSharp.SourceGenerators.Extensions
/// Gets the full metadata name for a given instance.
///
/// The input instance.
+ /// Whether or not to also include parameter types.
/// The full metadata name for .
[Pure]
- public static string GetFullMetadataName(this IMethodSymbol symbol)
+ public static string GetFullMetadataName(this IMethodSymbol symbol, bool includeParameters = false)
{
+ if (includeParameters)
+ {
+ var parameters = string.Join(", ", symbol.Parameters.Select(static p => ((INamedTypeSymbol)p.Type).GetFullMetadataName()));
+
+ return $"{symbol.ToDisplayString(FullyQualifiedWithoutGlobalAndParametersFormat)}({parameters})";
+ }
+
return symbol.ToDisplayString(FullyQualifiedWithoutGlobalAndParametersFormat);
}
@@ -70,5 +79,21 @@ namespace ComputeSharp.SourceGenerators.Extensions
return $"[{nameof(ComputeSharp)}]_[{typeof(TGenerator).Name}]_[{fixedName}]";
}
+
+ ///
+ /// Gets a valid filename for a target symbol and generator type.
+ ///
+ /// The generator type processing the input symbol.
+ /// The symbol being processed.
+ /// A filename in the form "[ComputeSharp]_[<TGENERATOR>]_[<SYMBOL_FULLNAME>]"
+ [Pure]
+ public static string GetGeneratedFileName(this IMethodSymbol symbol)
+ {
+ string
+ metadataName = symbol.GetFullMetadataName(true),
+ fixedName = metadataName.Replace('`', '-').Replace('+', '.');
+
+ return $"[{nameof(ComputeSharp)}]_[{typeof(TGenerator).Name}]_[{fixedName}]";
+ }
}
}
diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs
index ea60def7..59368f90 100644
--- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs
+++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs
@@ -111,6 +111,7 @@ namespace ComputeSharp.SourceGenerators
foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType())
{
INamedTypeSymbol typeSymbol = (INamedTypeSymbol)fieldSymbol.Type;
+
string typeName = HlslKnownTypes.GetMappedName(typeSymbol);
_ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
@@ -188,7 +189,7 @@ namespace ComputeSharp.SourceGenerators
///
/// The sequence of discovered custom types.
/// A sequence of custom type definitions to add to the shader source.
- public static IEnumerable GetProcessedTypes(IEnumerable types)
+ internal static IEnumerable GetProcessedTypes(IEnumerable types)
{
foreach (var type in HlslKnownTypes.GetCustomTypes(types))
{
diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs
index 6969ffc1..39cfc05a 100644
--- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs
+++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs
@@ -73,8 +73,13 @@ namespace ComputeSharp.SourceGenerators.Mappings
///
/// The input type to map.
/// The HLSL-compatible type name that can be used in an HLSL shader.
+ [Pure]
public static string GetMappedName(INamedTypeSymbol typeSymbol)
{
+ // Delegate types just return an empty string, as they're not actually
+ // used in the generated shaders, but just mapped to a function at runtime.
+ if (typeSymbol.TypeKind == TypeKind.Delegate) return "";
+
string typeName = typeSymbol.GetFullMetadataName();
// Special case for the structured buffer types
diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs
new file mode 100644
index 00000000..277ec2c5
--- /dev/null
+++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs
@@ -0,0 +1,120 @@
+using System.Collections.Generic;
+using System.Collections.Immutable;
+using System.Diagnostics.Contracts;
+using System.Linq;
+using System.Text;
+using ComputeSharp.SourceGenerators.Extensions;
+using ComputeSharp.SourceGenerators.SyntaxRewriters;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.Text;
+using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
+
+#pragma warning disable CS0618
+
+namespace ComputeSharp.SourceGenerators
+{
+ [Generator]
+ public class ShaderMethodSourceGenerator : ISourceGenerator
+ {
+ ///
+ public void Initialize(GeneratorInitializationContext context)
+ {
+ }
+
+ ///
+ public void Execute(GeneratorExecutionContext context)
+ {
+ // Find all the [ShaderMethod] usages and retrieve the target methods
+ ImmutableArray methods = (
+ from tree in context.Compilation.SyntaxTrees
+ from attribute in tree.GetRoot().DescendantNodes().OfType()
+ let symbol = context.Compilation.GetSemanticModel(attribute.SyntaxTree)
+ let typeInfo = symbol.GetTypeInfo(attribute)
+ where typeInfo.Type is { Name: nameof(ShaderMethodAttribute) }
+ select attribute.FirstAncestorOrSelf()).ToImmutableArray();
+
+ foreach (MethodDeclarationSyntax methodDeclaration in methods)
+ {
+ SemanticModel semanticModel = context.Compilation.GetSemanticModel(methodDeclaration.SyntaxTree);
+ IMethodSymbol methodDeclarationSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration)!;
+
+ // We need to sets to track all discovered custom types and static methods
+ HashSet discoveredTypes = new(SymbolEqualityComparer.Default);
+ Dictionary staticMethods = new(SymbolEqualityComparer.Default);
+
+ // Explore the syntax tree and extract the processed info
+ var (invokeMethod, processedMethods) = GetProcessedMethods(methodDeclaration, semanticModel, discoveredTypes, staticMethods);
+ var processedTypes = IComputeShaderSourceGenerator.GetProcessedTypes(discoveredTypes).ToArray();
+
+ // Helper that converts a sequence of strings into an array expression.
+ // That is, this applies the following transformation:
+ // - { "S1", "S2" } => new string[] { "S1", "S2" }
+ static ArrayCreationExpressionSyntax ArrayExpression(IEnumerable values)
+ {
+ return
+ ArrayCreationExpression(
+ ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword)))
+ .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression()))))
+ .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression)
+ .AddExpressions(values.Select(static value => LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(value))).ToArray()));
+ }
+
+ // Create the compilation unit with the source attribute
+ var source =
+ CompilationUnit().AddAttributeLists(
+ AttributeList(SingletonSeparatedList(
+ Attribute(IdentifierName(typeof(ShaderMethodSourceAttribute).FullName)).AddArgumentListArguments(
+ AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodDeclarationSymbol.GetFullMetadataName(true)))),
+ AttributeArgument(ArrayExpression(processedTypes)),
+ AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(invokeMethod))),
+ AttributeArgument(ArrayExpression(processedMethods)))))
+ .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList()))
+ .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword))))
+ .NormalizeWhitespace()
+ .ToFullString();
+
+ // Add the method source attribute
+ context.AddSource(methodDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8));
+ }
+ }
+
+ ///
+ /// Gets a sequence of processed methods from a target method declaration.
+ ///
+ /// The instance for the current method.
+ /// The instance for the method to process.
+ /// The collection of currently discovered types.
+ /// The set of discovered and processed static methods.
+ /// A sequence of processed methods in .
+ [Pure]
+ private static (string InvokeMethod, IEnumerable Methods) GetProcessedMethods(
+ MethodDeclarationSyntax methodDeclaration,
+ SemanticModel semanticModel,
+ ICollection discoveredTypes,
+ IDictionary staticMethods)
+ {
+ ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods);
+
+ // Rewrite the method syntax tree
+ var processedMethod = shaderSourceRewriter
+ .Visit(methodDeclaration)!
+ .WithIdentifier(Identifier(ShaderMethodSourceAttribute.InvokeMethodIdentifier))
+ .WithoutTrivia()
+ .NormalizeWhitespace()
+ .ToFullString();
+
+ List methods = new(shaderSourceRewriter.LocalFunctions.Count);
+
+ // Emit the extracted local functions
+ foreach (var localFunction in shaderSourceRewriter.LocalFunctions)
+ {
+ methods.Add(localFunction.Value.NormalizeWhitespace().ToFullString());
+ }
+
+ return (processedMethod, methods);
+ }
+ }
+}
+
diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs
index 135745fc..5382cafa 100644
--- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs
+++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs
@@ -162,7 +162,8 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
return
((MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!)
.WithBlockBody()
- .WithoutAccessibilityModifiers();
+ .WithoutAccessibilityModifiers()
+ .WithAttributeLists(List());
}
///
@@ -171,6 +172,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
var updatedNode =
((LocalFunctionStatementSyntax)base.VisitLocalFunctionStatement(node)!)
.WithBlockBody()
+ .WithAttributeLists(List())
.WithIdentifier(Identifier($"__{this.currentMethod!.Identifier.Text}__{node.Identifier.Text}"));
// HLSL doesn't support local functions, so we first process them as usual and then remove