Merge pull request #50 from Sergio0694/improvement_member-transformation

Support for static members from class hierarchy
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2019-09-06 14:00:31 +02:00
コミット 2e5a4da7a8
9ファイル変更
+261 -8

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

+6 -1
ファイルの表示
@@ -59,6 +59,8 @@ If the shader in C# is capturing some local variable, those will be automaticall
✅ `Func<T>`s, local methods or delegates with no captured variables
✅ `static` fields and properties with a supported delegate type
## Advanced usage
**ComputeSharp** lets you dispatch compute shaders over thread groups from 1 to 3 dimensions, includes supports for constant and readonly buffers, and more. The shader body can both be declared inline, as a separate `Action<ThreadIds>` or as a local method. Additionally, most of the [HLSL intrinsic functions](https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-intrinsic-functions) are available through the `Hlsl` class. Here is a more advanced sample showcasing all these features.
@@ -71,11 +73,14 @@ float[] y = new float[height * width]; // Result array (assume both had some val
using ReadOnlyBuffer<float> xBuffer = Gpu.Default.AllocateReadOnlyBuffer(x);
using ReadWriteBuffer<float> yBuffer = Gpu.Default.AllocateReadWriteBuffer(y);
static float Sigmoid(float x) => 1 / (1 + Hlsl.Exp(-x));
// Shader body
void Kernel(ThreadIds id)
{
int offset = id.X + id.Y * width;
yBuffer[offset] = Hlsl.Pow(xBuffer[offset], 2);
float pow = Hlsl.Pow(xBuffer[offset], 2);
yBuffer[offset] = Sigmoid(pow);
}
// Run the shader
+1 -1
ファイルの表示
@@ -849,7 +849,7 @@ namespace ComputeSharp
/// <param name="x">The input value</param>
/// <returns>The number of bits</returns>
[Pure]
public static uint CountBits(uint x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(CountBits)}({nameof(Vector4)})");
public static uint CountBits(uint x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(CountBits)}(uint)");
/// <summary>
/// Returns the cross product of two <see cref="Float3"/> values
+77
ファイルの表示
@@ -168,6 +168,83 @@ namespace ComputeSharp.Shaders.Extensions
return node;
}
/// <summary>
/// Checks a <see cref="InvocationExpressionSyntax"/> instance and replaces it to be HLSL compatible, if needed
/// </summary>
/// <param name="node">The input <see cref="InvocationExpressionSyntax"/> to check and modify if needed</param>
/// <param name="declaringType">The <see cref="Type"/> in which the input syntax tree is declared in</param>
/// <param name="variable">The info on parsed static members, if any</param>
/// <param name="method">The info on parsed static methods, if any</param>
/// <returns>A <see cref="SyntaxNode"/> instance that is compatible with HLSL</returns>
[Pure]
public static InvocationExpressionSyntax ReplaceInvocation(this InvocationExpressionSyntax node, Type declaringType, out (string Name, ReadableMember MemberInfo)? variable, out (string Name, MethodInfo MethodInfo)? method)
{
// Set the variable and method to null
variable = null;
method = null;
// Explore the nested classes from bottom to top
if (declaringType.TryFindAncestorMember(node.Expression.ToString(), BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, out var result))
{
// If a static method or delegate is found, track it
string name = $"{result.Value.DeclaringType.Name}_{result.Value.MemberInfo.Name}";
switch (result.Value.MemberInfo)
{
case FieldInfo fieldInfo:
variable = (name, fieldInfo);
break;
case PropertyInfo propertyInfo:
variable = (name, propertyInfo);
break;
case MethodInfo methodInfo:
method = (name, methodInfo);
return SyntaxFactory.InvocationExpression(SyntaxFactory.ParseExpression(name), node.ArgumentList).WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia());
default: throw new InvalidOperationException($"Invalid symbol kind: {result.Value.MemberInfo.GetType()}");
}
// Return the mapped expression
return SyntaxFactory.InvocationExpression(SyntaxFactory.ParseExpression(name), node.ArgumentList).WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia());
}
return node;
}
/// <summary>
/// Checks a <see cref="IdentifierNameSyntax"/> instance and replaces it to be HLSL compatible, if needed
/// </summary>
/// <param name="node">The input <see cref="IdentifierNameSyntax"/> to check and modify if needed</param>
/// <param name="declaringType">The <see cref="Type"/> in which the input syntax tree is declared in</param>
/// <param name="variable">The info on parsed static members, if any</param>
/// <returns>A <see cref="SyntaxNode"/> instance that is compatible with HLSL</returns>
[Pure]
public static IdentifierNameSyntax ReplaceIdentifierName(this IdentifierNameSyntax node, Type declaringType, out (string Name, ReadableMember MemberInfo)? variable)
{
// Set the variable to null
variable = null;
// Explore the nested classes from bottom to top
if (declaringType.TryFindAncestorMember(node.Identifier.ToString(), BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, out var result))
{
// If a static scalar or vector member is found, track it
string name = $"{result.Value.DeclaringType.Name}_{result.Value.MemberInfo.Name}";
switch (result.Value.MemberInfo)
{
case FieldInfo fieldInfo when HlslKnownTypes.IsKnownType(fieldInfo.FieldType):
variable = (name, fieldInfo);
break;
case PropertyInfo propertyInfo when HlslKnownTypes.IsKnownType(propertyInfo.PropertyType):
variable = (name, propertyInfo);
break;
default: return node;
}
// Return the mapped expression
return SyntaxFactory.IdentifierName(name).WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia());
}
return node;
}
/// <summary>
/// Processes a loaded static member, either a field or a property
/// </summary>
+24
ファイルの表示
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
@@ -29,6 +30,29 @@ namespace ComputeSharp.Shaders.Extensions
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsStatelessDelegateContainer(this Type type) => type.GetFields(BindingFlags.Static | BindingFlags.Public).Length > 0;
/// <summary>
/// Tries to find an ancestor member starting from the input <see cref="Type"/>
/// </summary>
/// <param name="type">The input type to start the search from</param>
/// <param name="name">The name of the member to retrieve</param>
/// <param name="bindingAttr">A bitmask comprised of one or more <see cref="BindingFlags"></see> that specify how the search is conducted</param>
/// <returns><see langword="true"/> when a member with the given name is found, <see langword="false"/> otherwise</returns>
public static bool TryFindAncestorMember(this Type type, string name, BindingFlags bindingAttr, [NotNullWhen(true)] out (Type DeclaringType, MemberInfo MemberInfo)? result)
{
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;
}
/// <summary>
/// The mapping of supported known types to display string
/// </summary>
+12
ファイルの表示
@@ -58,6 +58,18 @@ namespace ComputeSharp.Shaders.Mappings
/// </summary>
public static IReadOnlyCollection<Type> HlslMappedVectorTypes => _HlslMappedVectorTypes;
/// <summary>
/// Checks whether or not the input type is a known HLSL-compatible type
/// </summary>
/// <param name="type">The input <see cref="Type"/> instance to check</param>
/// <returns>A <see langword="bool"/> indicating whether the input <see cref="Type"/> is in fact a known HLSL type</returns>
[Pure]
public static bool IsKnownType(Type type) => IsKnownScalarType(type) ||
IsKnownVectorType(type) ||
IsConstantBufferType(type) ||
IsReadOnlyBufferType(type) ||
IsReadWriteBufferType(type);
/// <summary>
/// Checks whether or not the input type is a known scalar type
/// </summary>
+10 -3
ファイルの表示
@@ -299,13 +299,20 @@ namespace ComputeSharp.Shaders.Translation
MethodDecompiler.Instance.GetSyntaxTree(Action.Method, MethodType.Closure, out MethodDeclarationSyntax root, out SemanticModel semanticModel);
// Rewrite the shader method (eg. to fix the type declarations)
ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel);
ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, ShaderType);
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'))));
foreach (var local in locals)
{
string alignedLocal = local.ToFullString().RemoveLeftPadding().Trim(' ', '\r', '\n');
alignedLocal = Regex.Replace(alignedLocal, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value);
alignedLocal = HlslKnownKeywords.GetMappedText(alignedLocal);
_LocalFunctionsList.Add(new LocalFunctionInfo(alignedLocal));
}
// Register the captured static members
foreach (var member in syntaxRewriter.StaticMembers)
@@ -340,7 +347,7 @@ namespace ComputeSharp.Shaders.Translation
MethodDecompiler.Instance.GetSyntaxTree(methodInfo, MethodType.Static, out MethodDeclarationSyntax root, out SemanticModel semanticModel);
// Rewrite the method
ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel);
ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, methodInfo.DeclaringType);
root = (MethodDeclarationSyntax)syntaxRewriter.Visit(root);
// Register the captured static members
+48 -3
ファイルの表示
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Reflection;
using ComputeSharp.Shaders.Extensions;
using ComputeSharp.Shaders.Translation.Models;
@@ -18,11 +19,21 @@ namespace ComputeSharp.Shaders.Translation
/// </summary>
private readonly SemanticModel SemanticModel;
/// <summary>
/// The declaring type that hosts the root from which the current syntax tree is inspected
/// </summary>
private readonly Type DeclaringType;
/// <summary>
/// Creates a new <see cref="ShaderSyntaxRewriter"/> instance with the specified parameters
/// </summary>
/// <param name="semanticModel"></param>
public ShaderSyntaxRewriter(SemanticModel semanticModel) => SemanticModel = semanticModel;
/// <param name="semanticModel">The <see cref="Microsoft.CodeAnalysis.SemanticModel"/> instance to use to rewrite the decompiled code</param>
/// <param name="declaringType">The declaring type that hosts the root from which the current syntax tree is inspected</param>
public ShaderSyntaxRewriter(SemanticModel semanticModel, Type declaringType)
{
SemanticModel = semanticModel;
DeclaringType = declaringType;
}
private readonly Dictionary<string, ReadableMember> _StaticMembers = new Dictionary<string, ReadableMember>();
@@ -38,6 +49,21 @@ namespace ComputeSharp.Shaders.Translation
/// </summary>
public IReadOnlyDictionary<string, MethodInfo> StaticMethods => _StaticMethods;
/// <inheritdoc/>
public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax node)
{
node = (IdentifierNameSyntax)base.VisitIdentifierName(node);
node = node.ReplaceIdentifierName(DeclaringType, out var variable);
// Register the captured member, if any
if (variable.HasValue && !_StaticMembers.ContainsKey(variable.Value.Name))
{
_StaticMembers.Add(variable.Value.Name, variable.Value.MemberInfo);
}
return node;
}
/// <inheritdoc/>
public override SyntaxNode VisitParameter(ParameterSyntax node)
{
@@ -119,6 +145,25 @@ namespace ComputeSharp.Shaders.Translation
return syntaxNode;
}
/// <inheritdoc/>
public override SyntaxNode VisitInvocationExpression(InvocationExpressionSyntax node)
{
node = (InvocationExpressionSyntax)base.VisitInvocationExpression(node);
node = node.ReplaceInvocation(DeclaringType, out var variable, out var method);
// Register the captured members, if any
if (variable.HasValue && !_StaticMembers.ContainsKey(variable.Value.Name))
{
_StaticMembers.Add(variable.Value.Name, variable.Value.MemberInfo);
}
if (method.HasValue && !_StaticMethods.ContainsKey(method.Value.Name))
{
_StaticMethods.Add(method.Value.Name, method.Value.MethodInfo);
}
return node;
}
/// <inheritdoc/>
public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node)
{
+62
ファイルの表示
@@ -135,5 +135,67 @@ namespace ComputeSharp.Tests
Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f);
}
public static float Square(float x) => x * x;
[TestMethod]
public void StaticMethodInSameClass()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
Gpu.Default.For(1, id => buffer[0] = Square(3));
float[] result = buffer.GetData();
Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f);
}
public static Func<float, float> SquareFunc { get; } = x => x * x;
[TestMethod]
public void StaticFunctionInSameClass()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
Gpu.Default.For(1, id => buffer[0] = SquareFunc(3));
float[] result = buffer.GetData();
Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f);
}
[TestMethod]
public void StaticFunctionInExternalClass()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
Gpu.Default.For(1, id => buffer[0] = StaticPropertiesContainer.SquareFunc(3));
float[] result = buffer.GetData();
Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f);
}
[TestMethod]
public void ReadmeSample()
{
float[] buffer = { 3 };
using ReadWriteBuffer<float> xBuffer = Gpu.Default.AllocateReadWriteBuffer(buffer);
static float Sigmoid(float x) => 1 / (1 + Hlsl.Exp(-x));
void Kernel(ThreadIds id)
{
int offset = id.X + id.Y * 1;
float pow = Hlsl.Pow(xBuffer[offset], 2); // 9
xBuffer[offset] = Sigmoid(pow); // 0.9998766
}
Gpu.Default.For(1, Kernel);
float[] result = xBuffer.GetData();
Assert.IsTrue(MathF.Abs(result[0] - 0.9998766f) < 0.0001f);
}
}
}
+21
ファイルの表示
@@ -33,6 +33,11 @@ namespace ComputeSharp.Tests
/// A <see langword="static"/> <see cref="ReadOnlyBuffer{T}"/> property
/// </summary>
public static ReadOnlyBuffer<float> StaticBuffer { get; set; } = Gpu.Default.AllocateReadOnlyBuffer(new[] { 3.14f, 7.77f });
/// <summary>
/// A <see langword="static"/> <see cref="Func{T,TResult}"/> property
/// </summary>
public static Func<float, float> SquareFunc { get; } = x => x * x;
}
[TestClass]
@@ -138,5 +143,21 @@ namespace ComputeSharp.Tests
Assert.IsTrue(MathF.Abs(result[0] - expected[0]) < 0.0001f);
Assert.IsTrue(MathF.Abs(result[1] - expected[1]) < 0.0001f);
}
public static int SomeNumber = 7;
[TestMethod]
public void StaticLocalScalarFieldAssignToBuffer()
{
using ReadWriteBuffer<int> buffer = Gpu.Default.AllocateReadWriteBuffer<int>(1);
Action<ThreadIds> action = id => buffer[0] = SomeNumber;
Gpu.Default.For(1, action);
int[] result = buffer.GetData();
Assert.IsTrue(result[0] == SomeNumber);
}
}
}