diff --git a/README.md b/README.md index b70760dc..08fb7c30 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,9 @@ If the shader in C# is capturing some local variable, those will be automaticall ✅ `static` properties, same as with fields -✅ `Func` or any delegate with a valid HLSL signature, with the target method being `static` +✅ `Func`s or delegates with a valid HLSL signature, with the target method being `static` + +✅ `Func`s, local methods or delegates with no captured variables ## Advanced usage diff --git a/src/ComputeSharp.Shaders/Extensions/StringExtensions.cs b/src/ComputeSharp.Shaders/Extensions/StringExtensions.cs new file mode 100644 index 00000000..401321a3 --- /dev/null +++ b/src/ComputeSharp.Shaders/Extensions/StringExtensions.cs @@ -0,0 +1,28 @@ +using System; +using System.Diagnostics.Contracts; +using System.Linq; +using System.Text.RegularExpressions; + +namespace ComputeSharp.Shaders.Extensions +{ + /// + /// 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 852dd8b1..77f693d5 100644 --- a/src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs +++ b/src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs @@ -2,6 +2,8 @@ using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; namespace ComputeSharp.Shaders.Extensions { @@ -10,6 +12,23 @@ namespace ComputeSharp.Shaders.Extensions /// internal static class TypeExtensions { + /// + /// Gets whether or not the input represents a + /// + /// 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; + /// /// The mapping of supported known types to display string /// diff --git a/src/ComputeSharp.Shaders/Renderer/Models/Functions/FunctionInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/Functions/FunctionInfo.cs index 3af27abe..387e08e5 100644 --- a/src/ComputeSharp.Shaders/Renderer/Models/Functions/FunctionInfo.cs +++ b/src/ComputeSharp.Shaders/Renderer/Models/Functions/FunctionInfo.cs @@ -7,7 +7,7 @@ namespace ComputeSharp.Shaders.Renderer.Models.Functions /// /// A that contains info on a shader function /// - internal class FunctionInfo + internal sealed class FunctionInfo { /// /// Gets the return type of the current function in the C# source diff --git a/src/ComputeSharp.Shaders/Renderer/Models/Functions/LocalFunctionInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/Functions/LocalFunctionInfo.cs new file mode 100644 index 00000000..4dfd45f9 --- /dev/null +++ b/src/ComputeSharp.Shaders/Renderer/Models/Functions/LocalFunctionInfo.cs @@ -0,0 +1,29 @@ +using System; + +namespace ComputeSharp.Shaders.Renderer.Models.Functions +{ + /// + /// A that contains info on a local shader function + /// + internal sealed class LocalFunctionInfo + { + /// + /// Gets the prototype for the current function + /// + public string FunctionPrototype => FunctionDeclaration.Split(Environment.NewLine)[0]; + + /// + /// Gets the declaration of the current function + /// + public string FunctionDeclaration { get; } + + /// + /// Creates a new instance with the specified parameters + /// + /// The declaration of the current function + public LocalFunctionInfo(string functionDeclaration) + { + FunctionDeclaration = functionDeclaration; + } + } +} diff --git a/src/ComputeSharp.Shaders/Renderer/Models/Functions/ParameterInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/Functions/ParameterInfo.cs index f5cc5172..a424aaf2 100644 --- a/src/ComputeSharp.Shaders/Renderer/Models/Functions/ParameterInfo.cs +++ b/src/ComputeSharp.Shaders/Renderer/Models/Functions/ParameterInfo.cs @@ -8,7 +8,7 @@ namespace ComputeSharp.Shaders.Renderer.Models.Functions /// /// A that contains info on a function parameter /// - internal class ParameterInfo + internal sealed class ParameterInfo { /// /// Gets the modifier to use for the current parameter diff --git a/src/ComputeSharp.Shaders/Renderer/Models/ShaderInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/ShaderInfo.cs index 306dd3f7..fd6e92ed 100644 --- a/src/ComputeSharp.Shaders/Renderer/Models/ShaderInfo.cs +++ b/src/ComputeSharp.Shaders/Renderer/Models/ShaderInfo.cs @@ -51,5 +51,10 @@ namespace ComputeSharp.Shaders.Renderer.Models /// Gets or sets the list of static functions used by the shader /// public IReadOnlyList FunctionsList { get; set; } + + /// + /// Gets or sets the list of local (implicit) functions used by the shader + /// + public IReadOnlyList LocalFunctionsList { get; set; } } } diff --git a/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache b/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache index 189fa50d..62515497 100644 --- a/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache +++ b/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache @@ -38,13 +38,19 @@ cbuffer _{{FieldName}} : register(b{{BufferIndex}}) {{&FieldHlslType}} {{FieldName}} : register(u{{BufferIndex}}); {{/IsReadWriteBuffer}} {{/BuffersList}} +{{#FunctionsList}} {{!Shader private functions}} -{{#FunctionsList}} -// {{FunctionCsharpReturnType}} {{FunctionFullName}}({{FunctionCsharpParameters}}) +// {{FunctionCsharpReturnType}} {{&FunctionFullName}}({{FunctionCsharpParameters}}) {{ReturnType}} {{FunctionName}}({{#ParametersList}}{{ParameterModifier}} {{ParameterType}} {{ParameterName}}{{^IsLastParameter}}, {{/IsLastParameter}}{{/ParametersList}}) {{FunctionBody}} {{/FunctionsList}} +{{#LocalFunctionsList}} + +{{!Shader implicit functions}} +// {{FunctionPrototype}} +{{FunctionDeclaration}} +{{/LocalFunctionsList}} {{!Shader entry point}} // Shader body diff --git a/src/ComputeSharp.Shaders/ShaderRunner.cs b/src/ComputeSharp.Shaders/ShaderRunner.cs index c149e409..038d4b8a 100644 --- a/src/ComputeSharp.Shaders/ShaderRunner.cs +++ b/src/ComputeSharp.Shaders/ShaderRunner.cs @@ -76,7 +76,8 @@ namespace ComputeSharp.Shaders NumThreadsZ = threadsZ, ThreadsIdsVariableName = shaderLoader.ThreadsIdsVariableName, ShaderBody = shaderLoader.MethodBody, - FunctionsList = shaderLoader.FunctionsList + FunctionsList = shaderLoader.FunctionsList, + LocalFunctionsList = shaderLoader.LocalFunctionsList }; string shaderSource = ShaderRenderer.Instance.Render(shaderInfo); diff --git a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs index a6a0b3dc..0a543835 100644 --- a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs +++ b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs @@ -207,9 +207,10 @@ namespace ComputeSharp.Shaders.Translation private string GetSyntaxTreeForStaticMethod(MethodInfo methodInfo) { string - sourceCode = DecompileMethodOrDeclaringType(methodInfo), - prototype = sourceCode.Split(Environment.NewLine)[0], - commentedSourceCode = $"// {methodInfo.Name}{Environment.NewLine}{sourceCode}", + sourceCode = DecompileMethodOrDeclaringType(methodInfo, true), + methodFixedCode = sourceCode.Replace(methodInfo.Name, Regex.Replace(methodInfo.Name, "[<>|]", "_")), + prototype = methodFixedCode.Split(Environment.NewLine)[0], + commentedSourceCode = $"// {methodInfo.Name}{Environment.NewLine}{methodFixedCode}", inFixedSourceCode = Regex.Replace(commentedSourceCode, @"(? public IReadOnlyList FunctionsList => _FunctionsList; + private readonly List _LocalFunctionsList = new List(); + + /// + /// Gets the collection of items for the shader + /// + public IReadOnlyList LocalFunctionsList => _LocalFunctionsList; + /// /// Gets a unique hash code for a given /// @@ -159,8 +166,9 @@ namespace ComputeSharp.Shaders.Translation foreach (FieldInfo fieldInfo in action.Method.DeclaringType.GetFields()) { - if (fieldInfo.FieldType.IsClass && fieldInfo.FieldType.IsGenericType && - fieldInfo.GetValue(action.Target) is Delegate func && func.Method.IsStatic && + if (fieldInfo.FieldType.IsDelegate() && + fieldInfo.GetValue(action.Target) is Delegate func && + (func.Method.IsStatic || func.Method.DeclaringType.IsStatelessDelegateContainer()) && (HlslKnownTypes.IsKnownScalarType(func.Method.ReturnType) || HlslKnownTypes.IsKnownVectorType(func.Method.ReturnType)) && fieldInfo.FieldType.GenericTypeArguments.All(type => HlslKnownTypes.IsKnownScalarType(type) || HlslKnownTypes.IsKnownVectorType(type))) @@ -270,8 +278,9 @@ namespace ComputeSharp.Shaders.Translation LoadFieldInfo(fieldInfo, null, updatedParents); } } - else if (fieldType.IsClass && fieldType.IsGenericType && - memberInfo.GetValue(Action.Target) is Delegate func && func.Method.IsStatic && + else if (fieldType.IsDelegate() && + memberInfo.GetValue(Action.Target) 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))) @@ -293,6 +302,11 @@ namespace ComputeSharp.Shaders.Translation ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel); root = (MethodDeclarationSyntax)syntaxRewriter.Visit(root); + // Extract the implicit local functions + var locals = root.DescendantNodes().OfType().ToArray(); + root = root.RemoveNodes(locals, SyntaxRemoveOptions.KeepNoTrivia); + _LocalFunctionsList.AddRange(locals.Select(local => new LocalFunctionInfo(local.ToFullString().RemoveLeftPadding().Trim(' ', '\r', '\n')))); + // Register the captured static members foreach (var member in syntaxRewriter.StaticMembers) { diff --git a/tests/ComputeSharp.Tests/StaticFunctionsTests.cs b/tests/ComputeSharp.Tests/StaticFunctionsTests.cs index 5a5ad8b7..fbcd1c53 100644 --- a/tests/ComputeSharp.Tests/StaticFunctionsTests.cs +++ b/tests/ComputeSharp.Tests/StaticFunctionsTests.cs @@ -75,5 +75,65 @@ namespace ComputeSharp.Tests Assert.IsTrue(MathF.Abs(result[0] - expected) < 0.0001f); } + + public delegate float Squarer(float x); + + [TestMethod] + public void CustomStaticDelegate() + { + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); + + Squarer square = StaticMethodsContainer.Square; + + Gpu.Default.For(1, id => buffer[0] = square(3)); + + float[] result = buffer.GetData(); + + Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f); + } + + [TestMethod] + public void InlineStatelessDelegate() + { + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); + + Func f = x => x * x; + + Gpu.Default.For(1, id => buffer[0] = f(3)); + + float[] result = buffer.GetData(); + + Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f); + } + + [TestMethod] + public void StatelessLocalFunctionToDelegate() + { + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); + + float Func(float x) => x * x; + + Func f = Func; + + Gpu.Default.For(1, id => buffer[0] = f(3)); + + float[] result = buffer.GetData(); + + Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f); + } + + [TestMethod] + public void StatelessLocalFunction() + { + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); + + float f(float x) => x * x; + + Gpu.Default.For(1, id => buffer[0] = f(3)); + + float[] result = buffer.GetData(); + + Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f); + } } }