Merge pull request #49 from Sergio0694/feature_non-static-delegates

Added support for stateless delegates and local functions
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2019-09-05 18:29:36 +02:00
コミット 1d708f4e69
12ファイル変更
+178 -13

検索条件に一致するファイルはありません

+3 -1
ファイルの表示
@@ -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<T>` or any delegate with a valid HLSL signature, with the target method being `static`
✅ `Func<T>`s or delegates with a valid HLSL signature, with the target method being `static`
✅ `Func<T>`s, local methods or delegates with no captured variables
## Advanced usage
+28
ファイルの表示
@@ -0,0 +1,28 @@
using System;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text.RegularExpressions;
namespace ComputeSharp.Shaders.Extensions
{
/// <summary>
/// A <see langword="class"/> that provides extension methods for the <see langword="string"/> type
/// </summary>
internal static class StringExtensions
{
/// <summary>
/// Removes the left padding for an input multiline <see langword="string"/>
/// </summary>
/// <param name="text">The input <see langword="string"/> to process</param>
/// <returns>A left-aligned <see langword="string"/> with the same text as the input</returns>
[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)}");
}
}
}
+19
ファイルの表示
@@ -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
/// </summary>
internal static class TypeExtensions
{
/// <summary>
/// Gets whether or not the input <see cref="Type"/> represents a <see cref="Delegate"/>
/// </summary>
/// <param name="type">The input type to analyze</param>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsDelegate(this Type type) => type.IsClass &&
type.IsSubclassOf(typeof(Delegate));
/// <summary>
/// Gets whether or not the input <see cref="Type"/> represents a <see cref="Delegate"/> with no captured variables
/// </summary>
/// <param name="type">The input type to analyze</param>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsStatelessDelegateContainer(this Type type) => type.GetFields(BindingFlags.Static | BindingFlags.Public).Length > 0;
/// <summary>
/// The mapping of supported known types to display string
/// </summary>
+1 -1
ファイルの表示
@@ -7,7 +7,7 @@ namespace ComputeSharp.Shaders.Renderer.Models.Functions
/// <summary>
/// A <see langword="class"/> that contains info on a shader function
/// </summary>
internal class FunctionInfo
internal sealed class FunctionInfo
{
/// <summary>
/// Gets the return type of the current function in the C# source
+29
ファイルの表示
@@ -0,0 +1,29 @@
using System;
namespace ComputeSharp.Shaders.Renderer.Models.Functions
{
/// <summary>
/// A <see langword="class"/> that contains info on a local shader function
/// </summary>
internal sealed class LocalFunctionInfo
{
/// <summary>
/// Gets the prototype for the current function
/// </summary>
public string FunctionPrototype => FunctionDeclaration.Split(Environment.NewLine)[0];
/// <summary>
/// Gets the declaration of the current function
/// </summary>
public string FunctionDeclaration { get; }
/// <summary>
/// Creates a new <see cref="LocalFunctionInfo"/> instance with the specified parameters
/// </summary>
/// <param name="functionDeclaration">The declaration of the current function</param>
public LocalFunctionInfo(string functionDeclaration)
{
FunctionDeclaration = functionDeclaration;
}
}
}
+1 -1
ファイルの表示
@@ -8,7 +8,7 @@ namespace ComputeSharp.Shaders.Renderer.Models.Functions
/// <summary>
/// A <see langword="class"/> that contains info on a function parameter
/// </summary>
internal class ParameterInfo
internal sealed class ParameterInfo
{
/// <summary>
/// Gets the modifier to use for the current parameter
+5
ファイルの表示
@@ -51,5 +51,10 @@ namespace ComputeSharp.Shaders.Renderer.Models
/// Gets or sets the list of static functions used by the shader
/// </summary>
public IReadOnlyList<FunctionInfo> FunctionsList { get; set; }
/// <summary>
/// Gets or sets the list of local (implicit) functions used by the shader
/// </summary>
public IReadOnlyList<LocalFunctionInfo> LocalFunctionsList { get; set; }
}
}
+8 -2
ファイルの表示
@@ -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
+2 -1
ファイルの表示
@@ -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);
+4 -3
ファイルの表示
@@ -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, @"(?<!\w)in ", string.Empty),
outFixedSourceCode = RefactorInlineOutDeclarations(inFixedSourceCode, methodInfo.Name);
+18 -4
ファイルの表示
@@ -148,6 +148,13 @@ namespace ComputeSharp.Shaders.Translation
/// </summary>
public IReadOnlyList<FunctionInfo> FunctionsList => _FunctionsList;
private readonly List<LocalFunctionInfo> _LocalFunctionsList = new List<LocalFunctionInfo>();
/// <summary>
/// Gets the collection of <see cref="LocalFunctionInfo"/> items for the shader
/// </summary>
public IReadOnlyList<LocalFunctionInfo> LocalFunctionsList => _LocalFunctionsList;
/// <summary>
/// Gets a unique hash code for a given <see cref="Action{T}"/>
/// </summary>
@@ -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<LocalFunctionStatementSyntax>().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)
{
+60
ファイルの表示
@@ -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<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(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<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
Func<float, float> 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<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
float Func(float x) => x * x;
Func<float, float> 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<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(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);
}
}
}