diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index 52e8f25f..a621a6da 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -22,7 +22,6 @@ - diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs index 05a12ef3..885fc970 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs @@ -2,6 +2,7 @@ using System.Collections.Immutable; using System.Diagnostics.Contracts; using System.Linq; +using ComputeSharp.__Internals; using ComputeSharp.SourceGenerators.Diagnostics; using ComputeSharp.SourceGenerators.Extensions; using ComputeSharp.SourceGenerators.Helpers; @@ -14,6 +15,8 @@ using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle; +#pragma warning disable CS0618 + namespace ComputeSharp.SourceGenerators { /// @@ -404,7 +407,7 @@ namespace ComputeSharp.SourceGenerators /// /// The sequence of discovered custom types. /// A sequence of custom type definitions to add to the shader source. - internal static IEnumerable GetProcessedTypes(IEnumerable types) + internal static IEnumerable<(string Name, string Definition)> GetProcessedTypes(IEnumerable types) { foreach (var type in HlslKnownTypes.GetCustomTypes(types)) { @@ -430,10 +433,11 @@ namespace ComputeSharp.SourceGenerators // Insert the trailing ; right after the closing bracket (after normalization) yield return - structDeclaration - .NormalizeWhitespace(eol: "\n") - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) - .ToFullString(); + (structType, + structDeclaration + .NormalizeWhitespace(eol: "\n") + .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) + .ToFullString()); } } @@ -468,7 +472,7 @@ namespace ComputeSharp.SourceGenerators private static IEnumerable GenerateRenderMethodBody( IEnumerable<(string Name, string Value)> definedConstants, IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> staticFields, - IEnumerable declaredTypes, + IEnumerable<(string Name, string Definition)> declaredTypes, bool isComputeShader, IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> instanceFields, string? implicitTextureType, @@ -479,6 +483,32 @@ namespace ComputeSharp.SourceGenerators string executeMethod) { List statements = new(); + int capturedDelegates = 0; + + foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields) + { + if (fieldSymbol.Type.TypeKind == TypeKind.Delegate) + { + // ShaderMethodSourceAttribute __Attribute = ShaderMethodSourceAttribute.GetForDelegate(, ""); + statements.Add( + LocalDeclarationStatement(VariableDeclaration(IdentifierName(nameof(ShaderMethodSourceAttribute))) + .AddVariables( + VariableDeclarator(Identifier($"__{fieldName}Attribute")) + .WithInitializer( + EqualsValueClause( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName(nameof(ShaderMethodSourceAttribute)), + IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate)))) + .AddArgumentListArguments( + Argument(IdentifierName(fieldName)), + Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(fieldName))))))))); + + capturedDelegates++; + } + } + int sizeHint = 64; void AppendLF() @@ -554,10 +584,10 @@ namespace ComputeSharp.SourceGenerators } // Declared types - foreach (var type in declaredTypes) + foreach (var (typeName, typeDefinition) in declaredTypes) { AppendLF(); - AppendLineAndLF(type); + AppendLineAndLF(typeDefinition); } // Captured variables @@ -656,13 +686,23 @@ namespace ComputeSharp.SourceGenerators } } + // Captured delegate methods + foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields) + { + if (fieldSymbol.Type.TypeKind == TypeKind.Delegate) + { + AppendLF(); + statements.Add(ParseStatement($"builder.AppendLine(__{fieldName}Attribute.{nameof(ShaderMethodSourceAttribute.GetMappedInvokeMethod)}(\"{fieldName}\"));")); + } + } + // Entry point AppendLF(); AppendLineAndLF("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]"); AppendLineAndLF(executeMethod); // builder = ArrayPoolStringBuilder.Create(); - statements.Insert(0, + statements.Insert(capturedDelegates, ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index c3507627..e3f91e72 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -70,7 +70,7 @@ namespace ComputeSharp.SourceGenerators Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); // Explore the syntax tree and extract the processed info - var (invokeMethod, processedMethods) = GetProcessedMethods(context, methodDeclaration, semanticModel, discoveredTypes, staticMethods, constantDefinitions); + var (invokeMethod, localFunctions) = GetProcessedMethods(context, methodDeclaration, semanticModel, discoveredTypes, staticMethods, constantDefinitions); var processedTypes = IShaderGenerator.GetProcessedTypes(discoveredTypes).ToArray(); var processedConstants = IShaderGenerator.GetProcessedConstants(constantDefinitions); @@ -80,9 +80,9 @@ namespace ComputeSharp.SourceGenerators AttributeList(SingletonSeparatedList( Attribute(IdentifierName(typeof(ShaderMethodSourceAttribute).FullName)).AddArgumentListArguments( AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodDeclarationSymbol.GetFullMetadataName(true)))), - AttributeArgument(ArrayExpression(processedTypes)), + AttributeArgument(NestedArrayExpression(processedTypes)), AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(invokeMethod))), - AttributeArgument(ArrayExpression(processedMethods)), + AttributeArgument(ArrayExpression(localFunctions)), AttributeArgument(NestedArrayExpression(processedConstants))))) .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) diff --git a/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs b/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs index 8d0bbce3..703e9c9a 100644 --- a/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs +++ b/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs @@ -5,7 +5,6 @@ using System.Diagnostics.Contracts; using System.Linq; using System.Reflection; using ComputeSharp.Core.Extensions; -using ComputeSharp.Exceptions; namespace ComputeSharp.__Internals { @@ -37,12 +36,12 @@ namespace ComputeSharp.__Internals /// The source code for the target entry point method. /// The collection of processed methods. /// The collection of discovered constants. - public ShaderMethodSourceAttribute(string methodName, string[] types, string invokeMethod, string[] methods, object[] constants) + public ShaderMethodSourceAttribute(string methodName, object[] types, string invokeMethod, string[] methods, object[] constants) { this.invokeMethod = invokeMethod; MethodName = methodName; - Types = types; + Types = types.Cast().ToDictionary(static c => c[0], static c => c[1]); Methods = methods; Constants = constants.Cast().ToDictionary(static c => c[0], static c => c[1]); } @@ -55,7 +54,7 @@ namespace ComputeSharp.__Internals /// /// Gets the collection of processed custom types. /// - internal IReadOnlyCollection Types { get; } + internal IReadOnlyDictionary Types { get; } /// /// Gets the collection of processed methods. @@ -73,7 +72,7 @@ namespace ComputeSharp.__Internals /// The name to bind the method to. /// The mapped source code for the current mehtod. [Pure] - internal string GetMappedInvokeMethod(string name) + public string GetMappedInvokeMethod(string name) { return this.invokeMethod.Replace(InvokeMethodIdentifier, name); } @@ -82,13 +81,14 @@ namespace ComputeSharp.__Internals /// Gets the associated instance for a specified delegate. /// /// The input instance to get info for. + /// The name of the shader field containing . /// The associated instance for the given delegate. [Pure] - internal static ShaderMethodSourceAttribute GetForDelegate(Delegate function) + public static ShaderMethodSourceAttribute GetForDelegate(Delegate function, string name) { if (!function.Method.IsStatic) { - ThrowArgumentExceptionForNonStaticShader(); + return ThrowArgumentExceptionForNonStaticMethod(name); } var attributes = function.Method.DeclaringType!.Assembly.GetCustomAttributes(); @@ -102,15 +102,25 @@ namespace ComputeSharp.__Internals } } - return MissingMethodSourceException.Throw(function); + return ThrowArgumentExceptionForMissingShaderMethodAttribute(name); } /// /// Throws an when a given is not static. /// - private static void ThrowArgumentExceptionForNonStaticShader() + /// The name of the shader field containing the invalid method. + private static ShaderMethodSourceAttribute ThrowArgumentExceptionForNonStaticMethod(string name) { - throw new ArgumentException("Captured delegates in a shader need to wrap a static method.", "function"); + throw new ArgumentException($"The captured delegate \"{name}\" was wrapping a non static method (only static methods are supported for captured delegates).", name); + } + + /// + /// Throws an when a given doesn't have applied to it. + /// + /// The name of the shader field containing the invalid method. + private static ShaderMethodSourceAttribute ThrowArgumentExceptionForMissingShaderMethodAttribute(string name) + { + throw new ArgumentException($"The captured delegate \"{name}\" was wrapping a method without the [ShaderMethod] attribute applied to it.", name); } } } \ No newline at end of file diff --git a/src/ComputeSharp/Core/Exceptions/MissingMethodSourceException.cs b/src/ComputeSharp/Core/Exceptions/MissingMethodSourceException.cs deleted file mode 100644 index c31a043b..00000000 --- a/src/ComputeSharp/Core/Exceptions/MissingMethodSourceException.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using System.Diagnostics.Contracts; -using System.Text; -using ComputeSharp.__Internals; -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 index b413e1b3..fbff690b 100644 --- a/src/ComputeSharp/Core/Extensions/MethodInfoExtensions.cs +++ b/src/ComputeSharp/Core/Extensions/MethodInfoExtensions.cs @@ -23,10 +23,10 @@ namespace ComputeSharp.Core.Extensions { var arguments = string.Join(", ", method.GetGenericArguments().Select(static t => t.FullName)); - return $"{method.DeclaringType!.FullName}.{method.Name}<{arguments}>({parameters})"; + return $"{method.DeclaringType!.FullName!.Replace('+', '.')}.{method.Name}<{arguments}>({parameters})"; } - return $"{method.DeclaringType!.FullName}.{method.Name}({parameters})"; + return $"{method.DeclaringType!.FullName!.Replace('+', '.')}.{method.Name}({parameters})"; } } } diff --git a/tests/ComputeSharp.Tests/MetaprogrammingTests.cs b/tests/ComputeSharp.Tests/MetaprogrammingTests.cs new file mode 100644 index 00000000..71d5bc4f --- /dev/null +++ b/tests/ComputeSharp.Tests/MetaprogrammingTests.cs @@ -0,0 +1,115 @@ +using System; +using ComputeSharp.Tests.Attributes; +using ComputeSharp.Tests.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +#pragma warning disable IDE0062 + +namespace ComputeSharp.Tests +{ + [TestClass] + [TestCategory("Metaprogramming")] + public partial class MetaprogrammingTests + { + [AutoConstructor] + internal readonly partial struct ActivationWithDelegateShader : IComputeShader + { + public readonly ReadWriteBuffer buffer; + public readonly Func activation; + + public void Execute() + { + buffer[ThreadIds.X] = activation(ThreadIds.X); + } + } + + public static class Activations + { + [ShaderMethod] + public static int Square(int x) => x * x; + + [ShaderMethod] + public static int AddOne(int x) => x + 1; + + // Missing attribute + public static int Identity(int x) => x; + } + + [CombinatorialTestMethod] + [AllDevices] + public unsafe void ActivationWithDelegate(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(100); + + device.Get().For(100, new ActivationWithDelegateShader(buffer, Activations.Square)); + + int[] result = buffer.ToArray(); + + for (int i = 0; i < 100; i++) + { + Assert.AreEqual(result[i], Activations.Square(i)); + } + + device.Get().For(100, new ActivationWithDelegateShader(buffer, Activations.AddOne)); + + result = buffer.ToArray(); + + for (int i = 0; i < 100; i++) + { + Assert.AreEqual(result[i], Activations.AddOne(i)); + } + } + + [CombinatorialTestMethod] + [AllDevices] + [ExpectedException(typeof(ArgumentException))] + public unsafe void DelegateWithMissingAttributeOnMethod(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(100); + + device.Get().For(100, new ActivationWithDelegateShader(buffer, Activations.Identity)); + } + + [CombinatorialTestMethod] + [AllDevices] + [ExpectedException(typeof(ArgumentException))] + public unsafe void DelegateWrappingNonStaticMethod(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(100); + + [ShaderMethod] + int Dummy(int x) => x; + + device.Get().For(100, new ActivationWithDelegateShader(buffer, Dummy)); + } + + [AutoConstructor] + internal readonly partial struct ActivationWithMultipleDelegatesShader : IComputeShader + { + public readonly ReadWriteBuffer buffer; + public readonly Func f1; + public readonly Func f2; + + public void Execute() + { + buffer[ThreadIds.X] = f2(f1(ThreadIds.X)); + } + } + + [CombinatorialTestMethod] + [AllDevices] + public unsafe void ActivationWithMultipleDelegates(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(100); + + device.Get().For(100, new ActivationWithMultipleDelegatesShader(buffer, Activations.Square, Activations.AddOne)); + + int[] result = buffer.ToArray(); + + for (int i = 0; i < 100; i++) + { + Assert.AreEqual(result[i], Activations.AddOne(Activations.Square(i))); + } + } + } +}