Merge pull request #34 from Sergio0694/feature_static-non-public-members

Support for static non public members
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2019-08-20 15:58:16 +02:00
コミット 6be192c2f3
4ファイル変更
+226 -21

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

+1 -1
ファイルの表示
@@ -48,7 +48,7 @@ If the shader in C# is capturing some local variable, those will be automaticall
✅ Local vector types: `System.Numerics.Vector2`, `Vector3`, `Vector4`
✅ `static` fields of both scalar, vector or buffer types (parent class must be `public`)
✅ `static` fields of both scalar, vector or buffer types
✅ `static` properties, same as with fields
+68 -20
ファイルの表示
@@ -65,9 +65,43 @@ namespace ComputeSharp.Shaders.Extensions
return node;
}
// If the input member has no symbol or is not a field, property or method, just return it
if (memberSymbol is null ||
memberSymbol.Kind != SymbolKind.Field &&
// If the input member has no symbol, try to load it manually
if (memberSymbol is null)
{
string expression = node.WithoutTrivia().ToFullString();
int index = expression.LastIndexOf(Type.Delimiter);
string fullname = expression.Substring(0, index);
if (!(AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetType(fullname)).FirstOrDefault(t => t != null) is Type type))
{
// The current node can't possibly represent a field or a property, so just return it
return node;
}
// Try to get the target static field or property, if present
string name = expression.Substring(index + 1, expression.Length - fullname.Length - 1);
MemberInfo[] memberInfos = type.GetMember(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
if (memberInfos.Length == 0) return node;
bool isReadonly;
ReadableMember memberInfo;
switch (memberInfos.First())
{
case FieldInfo fieldInfo:
isReadonly = fieldInfo.IsInitOnly;
memberInfo = fieldInfo;
break;
case PropertyInfo propertyInfo:
isReadonly = !propertyInfo.CanWrite;
memberInfo = propertyInfo;
break;
default: throw new InvalidOperationException($"Invalid symbol kind: {memberInfos.First().GetType()}");
}
// Handle the loaded info
return ProcessStaticMember(node, memberInfo, isReadonly, ref variable);
}
// If the input member is not a field, property or method, just return it
if (memberSymbol.Kind != SymbolKind.Field &&
memberSymbol.Kind != SymbolKind.Property &&
memberSymbol.Kind != SymbolKind.Method)
{
@@ -109,26 +143,40 @@ namespace ComputeSharp.Shaders.Extensions
default: throw new InvalidOperationException($"Invalid symbol kind: {memberSymbol.Kind}");
}
// Constant replacement if the value is a readonly scalar value
if (isReadonly && HlslKnownTypes.IsKnownScalarType(memberInfo.MemberType))
{
LiteralExpressionSyntax expression = memberInfo.GetValue(null) switch
{
true => SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression, SyntaxFactory.Token(SyntaxKind.TrueKeyword)),
false => SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression, SyntaxFactory.Token(SyntaxKind.TrueKeyword)),
IFormattable scalar => SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.ParseToken(scalar.ToString(null, CultureInfo.InvariantCulture))),
_ => throw new InvalidOperationException($"Invalid field of type {memberInfo.MemberType}")
};
return expression.WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia());
}
// Captured member, treat it like any other captured variable in the closure
string name = $"{containingMemberSymbolInfo.Symbol.Name}_{memberInfo.Name}";
variable = (name, memberInfo);
return SyntaxFactory.IdentifierName(name).WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia());
// Handle the loaded info
return ProcessStaticMember(node, memberInfo, isReadonly, ref variable);
}
return node;
}
/// <summary>
/// Processes a loaded static member, either a field or a property
/// </summary>
/// <param name="node">The input <see cref="MemberAccessExpressionSyntax"/> to check and modify if needed</param>
/// <param name="memberInfo">The wrapped member that needs to be processed</param>
/// <param name="isReadonly">Indicates whether or not the target member is readonly</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>
private static SyntaxNode ProcessStaticMember(SyntaxNode node, ReadableMember memberInfo, bool isReadonly, ref (string Name, ReadableMember MemberInfo)? variable)
{
// Constant replacement if the value is a readonly scalar value
if (isReadonly && HlslKnownTypes.IsKnownScalarType(memberInfo.MemberType))
{
LiteralExpressionSyntax expression = memberInfo.GetValue(null) switch
{
true => SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression, SyntaxFactory.Token(SyntaxKind.TrueKeyword)),
false => SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression, SyntaxFactory.Token(SyntaxKind.TrueKeyword)),
IFormattable scalar => SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.ParseToken(scalar.ToString(null, CultureInfo.InvariantCulture))),
_ => throw new InvalidOperationException($"Invalid field of type {memberInfo.MemberType}")
};
return expression.WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia());
}
// Captured member, treat it like any other captured variable in the closure
string name = $"{memberInfo.DeclaringType.Name}_{memberInfo.Name}";
variable = (name, memberInfo);
return SyntaxFactory.IdentifierName(name).WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia());
}
}
}
+14
ファイルの表示
@@ -30,6 +30,20 @@ namespace ComputeSharp.Shaders.Translation.Models
Property = property;
}
/// <summary>
/// Gets the <see cref="Type"/> where the current member is declared in
/// </summary>
public Type DeclaringType
{
get
{
if (Field != null) return Field.DeclaringType;
if (Property != null) return Property.DeclaringType;
throw new InvalidOperationException("Field and property can't both be null at the same time");
}
}
/// <summary>
/// Gets the <see cref="Type"/> of the wrapped member for the current instance
/// </summary>
+143
ファイルの表示
@@ -0,0 +1,143 @@
using System;
using System.Numerics;
using ComputeSharp.Graphics.Buffers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ComputeSharp.Tests
{
/// <summary>
/// A container <see langword="class"/> for static fields to test
/// </summary>
internal sealed class StaticMembersContainer
{
/// <summary>
/// A <see langword="static"/> <see langword="readonly"/> <see langword="float"/> field
/// </summary>
public static readonly float ReadonlyFloat = MathF.PI;
/// <summary>
/// A <see langword="static"/> <see langword="int"/> field
/// </summary>
public static float StaticFloat = MathF.PI;
/// <summary>
/// A <see langword="static"/> <see langword="readonly"/> <see langword="Vector2"/> field
/// </summary>
internal static readonly Vector2 ReadonlyVector2 = new Vector2(3.14f, 7.77f);
/// <summary>
/// A <see langword="static"/> <see langword="Vector2"/> field
/// </summary>
internal static Vector2 StaticVector2 = new Vector2(3.14f, 7.77f);
/// <summary>
/// A <see langword="static"/> <see cref="ReadOnlyBuffer{T}"/> field
/// </summary>
public static ReadOnlyBuffer<float> StaticBuffer = Gpu.Default.AllocateReadOnlyBuffer(new[] { 3.14f, 7.77f });
}
[TestClass]
[TestCategory("StaticFields")]
public class InternalStaticMembersTests
{
[TestMethod]
public void StaticReadonlyScalarFieldAssignToBuffer()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
Action<ThreadIds> action = id => buffer[0] = StaticMembersContainer.ReadonlyFloat;
Gpu.Default.For(1, action);
float[] result = buffer.GetData();
Assert.IsTrue(MathF.Abs(result[0] - StaticMembersContainer.ReadonlyFloat) < 0.0001f);
}
[TestMethod]
public void StaticScalarFieldAssignToBuffer()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
Action<ThreadIds> action = id => buffer[0] = StaticMembersContainer.StaticFloat;
Gpu.Default.For(1, action);
float[] result = buffer.GetData();
Assert.IsTrue(MathF.Abs(result[0] - StaticMembersContainer.StaticFloat) < 0.0001f);
}
[TestMethod]
public void StaticScalarFieldRepeatedAssignToBuffer()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
Action<ThreadIds> action = id => buffer[0] = StaticMembersContainer.StaticFloat + StaticMembersContainer.StaticFloat;
Gpu.Default.For(1, action);
float[] result = buffer.GetData();
Assert.IsTrue(MathF.Abs(result[0] - StaticMembersContainer.StaticFloat * 2) < 0.0001f);
}
[TestMethod]
public void StaticReadonlyVectorFieldAssignToBuffer()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(2);
Action<ThreadIds> action = id =>
{
if (id.X == 0) buffer[0] = StaticMembersContainer.ReadonlyVector2.X;
else buffer[1] = StaticMembersContainer.ReadonlyVector2.Y;
};
Gpu.Default.For(2, action);
float[] result = buffer.GetData();
Assert.IsTrue(MathF.Abs(result[0] - StaticMembersContainer.ReadonlyVector2.X) < 0.0001f);
Assert.IsTrue(MathF.Abs(result[1] - StaticMembersContainer.ReadonlyVector2.Y) < 0.0001f);
}
[TestMethod]
public void StaticVectorFieldAssignToBuffer()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(2);
Action<ThreadIds> action = id =>
{
if (id.X == 0) buffer[0] = StaticMembersContainer.StaticVector2.X;
else buffer[1] = StaticMembersContainer.StaticVector2.Y;
};
Gpu.Default.For(2, action);
float[] result = buffer.GetData();
Assert.IsTrue(MathF.Abs(result[0] - StaticMembersContainer.StaticVector2.X) < 0.0001f);
Assert.IsTrue(MathF.Abs(result[1] - StaticMembersContainer.StaticVector2.Y) < 0.0001f);
}
[TestMethod]
public void StaticReadOnlyBufferFieldAssignToBuffer()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(2);
Action<ThreadIds> action = id =>
{
if (id.X == 0) buffer[0] = StaticMembersContainer.StaticBuffer[0];
else buffer[1] = StaticMembersContainer.StaticBuffer[1];
};
Gpu.Default.For(2, action);
float[] result = buffer.GetData();
float[] expected = StaticMembersContainer.StaticBuffer.GetData();
Assert.IsTrue(MathF.Abs(result[0] - expected[0]) < 0.0001f);
Assert.IsTrue(MathF.Abs(result[1] - expected[1]) < 0.0001f);
}
}
}