Merge pull request #75 from Sergio0694/feature/metaprogramming-support
Initial support for metaprogramming
このコミットが含まれているのは:
21ファイル変更
+425
-97
検索条件に一致するファイルはありません
@@ -5,7 +5,7 @@ namespace ComputeSharp
|
||||
/// <summary>
|
||||
/// An attribute that indicates that a target shader type should get an automatic constructor for all fields.
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)]
|
||||
[AttributeUsage(AttributeTargets.Struct)]
|
||||
public sealed class AutoConstructorAttribute : Attribute
|
||||
{
|
||||
}
|
||||
|
||||
@@ -8,9 +8,9 @@ using System.Reflection;
|
||||
namespace ComputeSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// An attribute that indicates that a target shader type should get an automatic constructor for all fields.
|
||||
/// This attribute is not meant to be directly used by applications using ComputeSharp.
|
||||
/// An attribute that contains info on a processed compute shader that can be executed.
|
||||
/// </summary>
|
||||
/// <remarks>This attribute is not meant to be directly used by applications using ComputeSharp.</remarks>
|
||||
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
[Obsolete("This attribute is meant to be used from the source generator only")]
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
using System;
|
||||
|
||||
namespace ComputeSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// An attribute that indicates that a method will be indirectly used in a compute shader.
|
||||
/// This method is necessary for methods that are captured and used within a given shader
|
||||
/// through a <see cref="Delegate"/> field (of some custom type). In order to be processed
|
||||
/// correctly, wrapped methods need to have this attribute manually applied to them.
|
||||
/// Methods also need to be static, though this can only be tested at runtime.
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Method)]
|
||||
public sealed class ShaderMethodAttribute : Attribute
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Reflection;
|
||||
using ComputeSharp.Core.Extensions;
|
||||
using ComputeSharp.Exceptions;
|
||||
using Microsoft.Toolkit.Diagnostics;
|
||||
|
||||
namespace ComputeSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// An attribute that contains info on a processed shader method that can be executed within a shader.
|
||||
/// Instances of this attribute are generated from method annotated with <see cref="ShaderMethodAttribute"/>.
|
||||
/// </summary>
|
||||
/// <remarks>This attribute is not meant to be directly used by applications using ComputeSharp.</remarks>
|
||||
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
[Obsolete("This attribute is meant to be used from the source generator only")]
|
||||
public sealed class ShaderMethodSourceAttribute : Attribute
|
||||
{
|
||||
/// <summary>
|
||||
/// The identifier for the invoke method, for late binding.
|
||||
/// </summary>
|
||||
internal const string InvokeMethodIdentifier = "__<NAME>__";
|
||||
|
||||
/// <summary>
|
||||
/// The source code for the target entry point method.
|
||||
/// </summary>
|
||||
private readonly string invokeMethod;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ShaderMethodSourceAttribute"/> instance with the specified parameters.
|
||||
/// </summary>
|
||||
/// <param name="methodName">The fully qualified name of the current method.</param>
|
||||
/// <param name="types">The collection of custom types.</param>
|
||||
/// <param name="invokeMethod">The source code for the target entry point method.</param>
|
||||
/// <param name="methods">The collection of processed methods.</param>
|
||||
public ShaderMethodSourceAttribute(string methodName, string[] types, string invokeMethod, string[] methods)
|
||||
{
|
||||
this.invokeMethod = invokeMethod;
|
||||
|
||||
MethodName = methodName;
|
||||
Types = types;
|
||||
Methods = methods;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the fully qualified name of the shader type.
|
||||
/// </summary>
|
||||
internal string MethodName { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the collection of processed custom types.
|
||||
/// </summary>
|
||||
internal IReadOnlyCollection<string> Types { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the collection of processed methods.
|
||||
/// </summary>
|
||||
internal IReadOnlyCollection<string> Methods { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the mapped source code for the current method.
|
||||
/// </summary>
|
||||
/// <param name="name">The name to bind the method to.</param>
|
||||
/// <returns>The mapped source code for the current mehtod.</returns>
|
||||
[Pure]
|
||||
internal string GetMappedInvokeMethod(string name)
|
||||
{
|
||||
return this.invokeMethod.Replace(InvokeMethodIdentifier, name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the associated <see cref="ShaderMethodSourceAttribute"/> instance for a specified type.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The shader type to get the attribute for.</typeparam>
|
||||
/// <returns>The associated <see cref="IComputeShaderSourceAttribute"/> instance for type <typeparamref name="T"/>.</returns>
|
||||
[Pure]
|
||||
internal static ShaderMethodSourceAttribute GetForDelegate(Delegate function)
|
||||
{
|
||||
Guard.IsTrue(function.Method.IsStatic, "Captured delegates need to wrap static methods");
|
||||
|
||||
var attributes = function.Method.DeclaringType.Assembly.GetCustomAttributes<ShaderMethodSourceAttribute>();
|
||||
string methodName = function.Method.GetFullName();
|
||||
|
||||
foreach (var attribute in attributes)
|
||||
{
|
||||
if (attribute.MethodName.Equals(methodName))
|
||||
{
|
||||
return attribute;
|
||||
}
|
||||
}
|
||||
|
||||
return MissingMethodSourceException.Throw(function);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,9 @@ namespace ComputeSharp.Exceptions
|
||||
/// Creates a new <see cref="InvalidExecutionContextException"/> instance
|
||||
/// </summary>
|
||||
/// <param name="name">The name of the caller API</param>
|
||||
internal InvalidExecutionContextException(string name) : base($"The API {name} can only be used from within an HLSL shader") { }
|
||||
internal InvalidExecutionContextException(string name)
|
||||
: base($"The API {name} can only be used from within an HLSL shader.")
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using System;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Text;
|
||||
using ComputeSharp.Core.Extensions;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
|
||||
namespace ComputeSharp.Exceptions
|
||||
{
|
||||
/// <summary>
|
||||
/// A custom <see cref="InvalidOperationException"/> that indicates when an HLSL-only API is called from C#
|
||||
/// </summary>
|
||||
public sealed class MissingMethodSourceException : InvalidOperationException
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MissingMethodSourceException"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="message">The exception message to display.</param>
|
||||
private MissingMethodSourceException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MissingMethodSourceException"/> instance from the specified parameters.
|
||||
/// </summary>
|
||||
/// <param name="method">The target <see cref="Delegate"/> that couldn't be processed.</param>
|
||||
/// <returns>A new <see cref="MissingMethodSourceException"/> instance with a formatted error message.</returns>
|
||||
[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());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Throws a new <see cref="MissingMethodSourceException"/> for a given delegate.
|
||||
/// </summary>
|
||||
/// <param name="method">The target <see cref="Delegate"/> that couldn't be processed.</param>
|
||||
/// <returns>This method always throws and never actually returns anything.</returns>
|
||||
internal static ShaderMethodSourceAttribute Throw(Delegate method)
|
||||
{
|
||||
throw Create(method);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
|
||||
namespace ComputeSharp.Core.Extensions
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that provides extension methods for the <see cref="MethodInfo"/> type.
|
||||
/// </summary>
|
||||
internal static class MethodInfoExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets a fully qualified name for the input method, including parameters.
|
||||
/// </summary>
|
||||
/// <param name="method">The input <see cref="MethodInfo"/> instance.</param>
|
||||
/// <returns>A fully qualified name for <paramref name="method"/>, including parameters.</returns>
|
||||
[Pure]
|
||||
public static string GetFullName(this MethodInfo method)
|
||||
{
|
||||
var parameters = string.Join(", ", method.GetParameters().Select(static p => p.ParameterType.FullName));
|
||||
|
||||
if (method.IsGenericMethod)
|
||||
{
|
||||
var arguments = string.Join(", ", method.GetGenericArguments().Select(static t => t.FullName));
|
||||
|
||||
return $"{method.DeclaringType!.FullName}.{method.Name}<{arguments}>({parameters})";
|
||||
}
|
||||
|
||||
return $"{method.DeclaringType!.FullName}.{method.Name}({parameters})";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -279,9 +279,7 @@ namespace ComputeSharp.Graphics.Buffers.Abstract
|
||||
{
|
||||
if (GraphicsDevice != device)
|
||||
{
|
||||
void Throw() => throw GraphicsDeviceMismatchException.Create(this, device);
|
||||
|
||||
Throw();
|
||||
GraphicsDeviceMismatchException.Throw(this, device);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ using ComputeSharp.Graphics.Buffers.Abstract;
|
||||
namespace ComputeSharp.Exceptions
|
||||
{
|
||||
/// <summary>
|
||||
/// A custom <see cref="Exception"/> that indicates when mismatched devices are being used.
|
||||
/// A custom <see cref="InvalidOperationException"/> that indicates when mismatched devices are being used.
|
||||
/// </summary>
|
||||
public sealed class GraphicsDeviceMismatchException : InvalidOperationException
|
||||
{
|
||||
@@ -28,7 +28,7 @@ namespace ComputeSharp.Exceptions
|
||||
/// <param name="device">The target <see cref="GraphicsDevice"/> instance that was used.</param>
|
||||
/// <returns>A new <see cref="GraphicsDeviceMismatchException"/> instance with a formatted error message.</returns>
|
||||
[Pure]
|
||||
public static GraphicsDeviceMismatchException Create<T>(Buffer<T> buffer, GraphicsDevice device)
|
||||
private static GraphicsDeviceMismatchException Create<T>(Buffer<T> buffer, GraphicsDevice device)
|
||||
where T : unmanaged
|
||||
{
|
||||
StringBuilder builder = new(512);
|
||||
@@ -36,10 +36,23 @@ namespace ComputeSharp.Exceptions
|
||||
builder.AppendLine("Invalid pairing of graphics devices used to run a compute shader and allocate memory buffers.");
|
||||
builder.AppendLine($"The target device to run the compute shader is \"{device}\".");
|
||||
builder.AppendLine($"The buffer of type {buffer.GetType()} was allocated on device \"{buffer.GraphicsDevice}\".");
|
||||
builder.AppendLine("Make sure to always allocate buffers on the same device used to actually run the code that accesses them.");
|
||||
builder.Append("Make sure to always allocate buffers on the same device used to actually run the code that accesses them.");
|
||||
builder.ToString();
|
||||
|
||||
return new(builder.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Throws a new <see cref="GraphicsDeviceMismatchException"/> instance from the specified parameters.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of values in the input buffer.</typeparam>
|
||||
/// <param name="buffer">The input <see cref="Buffer{T}"/> that was used.</param>
|
||||
/// <param name="device">The target <see cref="GraphicsDevice"/> instance that was used.</param>
|
||||
[Pure]
|
||||
internal static void Throw<T>(Buffer<T> buffer, GraphicsDevice device)
|
||||
where T : unmanaged
|
||||
{
|
||||
throw Create(buffer, device);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,17 +5,24 @@ using System.Text;
|
||||
namespace ComputeSharp.Exceptions
|
||||
{
|
||||
/// <summary>
|
||||
/// A custom <see cref="GraphicsDeviceMismatchException"/> that indicates when mismatched devices are being used
|
||||
/// A custom <see cref="Exception"/> type that indicates when a shader compilation with the DXC compiler has failed.
|
||||
/// </summary>
|
||||
public sealed class HlslCompilationException : Exception
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="GraphicsDeviceMismatchException"/> instance
|
||||
/// Creates a new <see cref="HlslCompilationException"/> instance
|
||||
/// </summary>
|
||||
/// <param name="error">The error message produced by the Dxc compiler</param>
|
||||
internal HlslCompilationException(string error) : base(GetExceptionMessage(error)) { }
|
||||
/// <param name="error">The error message produced by the DXC compiler</param>
|
||||
internal HlslCompilationException(string error)
|
||||
: base(GetExceptionMessage(error))
|
||||
{
|
||||
}
|
||||
|
||||
// Gets a proper exception message for a given compilation error
|
||||
/// <summary>
|
||||
/// Gets a formatted exception message for a given compilation error.
|
||||
/// </summary>
|
||||
/// <param name="error">The input compilatin error message from the DXC compiler.</param>
|
||||
/// <returns>A formatted error message for a new <see cref="HlslCompilationException"/> instance.</returns>
|
||||
[Pure]
|
||||
private static string GetExceptionMessage(string error)
|
||||
{
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using System.Reflection.Emit;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Toolkit.Diagnostics;
|
||||
|
||||
namespace System.Reflection.Emit
|
||||
namespace ComputeSharp.Shaders.Extensions
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that provides extension methods for the <see langword="ILGenerator"/> type
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace System
|
||||
{
|
||||
/// <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)}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,53 +1,21 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace System
|
||||
namespace ComputeSharp.Shaders.Extensions
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that provides extension methods for the <see cref="Type"/> type
|
||||
/// A <see langword="class"/> that provides extension methods for the <see cref="Type"/> type.
|
||||
/// </summary>
|
||||
internal static class TypeExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets whether or not the input <see cref="Type"/> represents a <see cref="Delegate"/>
|
||||
/// Gets whether or not the input <see cref="Type"/> represents a <see cref="Delegate"/>.
|
||||
/// </summary>
|
||||
/// <param name="type">The input type to analyze</param>
|
||||
/// <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>
|
||||
/// 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)
|
||||
public static bool IsDelegate(this Type type)
|
||||
{
|
||||
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;
|
||||
return type.IsSubclassOf(typeof(Delegate));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Reflection.Emit;
|
||||
using System.Runtime.CompilerServices;
|
||||
using ComputeSharp.Shaders.Extensions;
|
||||
|
||||
namespace ComputeSharp.Shaders.Translation
|
||||
{
|
||||
|
||||
@@ -8,6 +8,7 @@ using System.Runtime.InteropServices;
|
||||
using ComputeSharp.Core.Interop;
|
||||
using ComputeSharp.Graphics;
|
||||
using ComputeSharp.Graphics.Buffers.Abstract;
|
||||
using ComputeSharp.Shaders.Extensions;
|
||||
using ComputeSharp.Shaders.Mappings;
|
||||
using ComputeSharp.Shaders.Translation.Models;
|
||||
using Microsoft.Toolkit.Diagnostics;
|
||||
|
||||
@@ -56,6 +56,16 @@ namespace ComputeSharp.Shaders.Translation
|
||||
/// </summary>
|
||||
private readonly List<CapturedFieldInfo> fieldsInfo = new();
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="List{T}"/> with the collected methods for the shader.
|
||||
/// </summary>
|
||||
private readonly List<string> methodsInfo = new();
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="List{T}"/> with the collected declared types for the shader.
|
||||
/// </summary>
|
||||
private readonly List<string> declaredTypes = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ShaderLoader{T}"/> instance.
|
||||
/// </summary>
|
||||
@@ -81,10 +91,10 @@ namespace ComputeSharp.Shaders.Translation
|
||||
public IReadOnlyList<CapturedFieldInfo> FieldsInfo => this.fieldsInfo;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public IReadOnlyCollection<string> MethodsInfo { get; private set; }
|
||||
public IReadOnlyCollection<string> MethodsInfo => this.methodsInfo;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public IReadOnlyCollection<string> DeclaredTypes { get; private set; }
|
||||
public IReadOnlyCollection<string> DeclaredTypes => this.declaredTypes;
|
||||
|
||||
/// <summary>
|
||||
/// Loads and processes an input<typeparamref name="T"/> shadeer
|
||||
@@ -178,15 +188,14 @@ namespace ComputeSharp.Shaders.Translation
|
||||
this.capturedFields.Add(fieldInfo);
|
||||
this.fieldsInfo.Add(new CapturedFieldInfo(hlslType, hlslName));
|
||||
}
|
||||
else if (fieldType.IsDelegate() &&
|
||||
fieldInfo.GetValue(shader) 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)))
|
||||
else if (fieldInfo.GetValue(shader) is Delegate { Method: { IsStatic: true } } func)
|
||||
{
|
||||
// Captured static delegates with a return type
|
||||
throw new NotImplementedException();
|
||||
var methodSource = ShaderMethodSourceAttribute.GetForDelegate(func);
|
||||
|
||||
this.declaredTypes.AddRange(methodSource.Types);
|
||||
this.methodsInfo.Add(methodSource.GetMappedInvokeMethod(hlslName));
|
||||
this.methodsInfo.AddRange(methodSource.Methods);
|
||||
}
|
||||
else ThrowHelper.ThrowArgumentException("Invalid captured variable");
|
||||
}
|
||||
@@ -196,9 +205,10 @@ namespace ComputeSharp.Shaders.Translation
|
||||
/// </summary>
|
||||
private void LoadMethodMetadata()
|
||||
{
|
||||
DeclaredTypes = Attribute.Types;
|
||||
EntryPoint = Attribute.ExecuteMethod;
|
||||
MethodsInfo = Attribute.Methods;
|
||||
|
||||
this.methodsInfo.AddRange(Attribute.Methods);
|
||||
this.declaredTypes.AddRange(Attribute.Types);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
@@ -48,10 +49,18 @@ namespace ComputeSharp.SourceGenerators.Extensions
|
||||
/// Gets the full metadata name for a given <see cref="IMethodSymbol"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="symbol">The input <see cref="IMethodSymbol"/> instance.</param>
|
||||
/// <param name="includeParameters">Whether or not to also include parameter types.</param>
|
||||
/// <returns>The full metadata name for <paramref name="symbol"/>.</returns>
|
||||
[Pure]
|
||||
public static string GetFullMetadataName(this IMethodSymbol symbol)
|
||||
public static string GetFullMetadataName(this IMethodSymbol symbol, bool includeParameters = false)
|
||||
{
|
||||
if (includeParameters)
|
||||
{
|
||||
var parameters = string.Join(", ", symbol.Parameters.Select(static p => ((INamedTypeSymbol)p.Type).GetFullMetadataName()));
|
||||
|
||||
return $"{symbol.ToDisplayString(FullyQualifiedWithoutGlobalAndParametersFormat)}({parameters})";
|
||||
}
|
||||
|
||||
return symbol.ToDisplayString(FullyQualifiedWithoutGlobalAndParametersFormat);
|
||||
}
|
||||
|
||||
@@ -70,5 +79,21 @@ namespace ComputeSharp.SourceGenerators.Extensions
|
||||
|
||||
return $"[{nameof(ComputeSharp)}]_[{typeof(TGenerator).Name}]_[{fixedName}]";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a valid filename for a target symbol and generator type.
|
||||
/// </summary>
|
||||
/// <typeparam name="TGenerator">The generator type processing the input symbol.</typeparam>
|
||||
/// <param name="symbol">The symbol being processed.</param>
|
||||
/// <returns>A filename in the form "[ComputeSharp]_[<TGENERATOR>]_[<SYMBOL_FULLNAME>]"</returns>
|
||||
[Pure]
|
||||
public static string GetGeneratedFileName<TGenerator>(this IMethodSymbol symbol)
|
||||
{
|
||||
string
|
||||
metadataName = symbol.GetFullMetadataName(true),
|
||||
fixedName = metadataName.Replace('`', '-').Replace('+', '.');
|
||||
|
||||
return $"[{nameof(ComputeSharp)}]_[{typeof(TGenerator).Name}]_[{fixedName}]";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -111,6 +111,7 @@ namespace ComputeSharp.SourceGenerators
|
||||
foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>())
|
||||
{
|
||||
INamedTypeSymbol typeSymbol = (INamedTypeSymbol)fieldSymbol.Type;
|
||||
|
||||
string typeName = HlslKnownTypes.GetMappedName(typeSymbol);
|
||||
|
||||
_ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
|
||||
@@ -188,7 +189,7 @@ namespace ComputeSharp.SourceGenerators
|
||||
/// </summary>
|
||||
/// <param name="types">The sequence of discovered custom types.</param>
|
||||
/// <returns>A sequence of custom type definitions to add to the shader source.</returns>
|
||||
public static IEnumerable<string> GetProcessedTypes(IEnumerable<INamedTypeSymbol> types)
|
||||
internal static IEnumerable<string> GetProcessedTypes(IEnumerable<INamedTypeSymbol> types)
|
||||
{
|
||||
foreach (var type in HlslKnownTypes.GetCustomTypes(types))
|
||||
{
|
||||
|
||||
@@ -73,8 +73,13 @@ namespace ComputeSharp.SourceGenerators.Mappings
|
||||
/// </summary>
|
||||
/// <param name="typeSymbol">The input type to map.</param>
|
||||
/// <returns>The HLSL-compatible type name that can be used in an HLSL shader.</returns>
|
||||
[Pure]
|
||||
public static string GetMappedName(INamedTypeSymbol typeSymbol)
|
||||
{
|
||||
// Delegate types just return an empty string, as they're not actually
|
||||
// used in the generated shaders, but just mapped to a function at runtime.
|
||||
if (typeSymbol.TypeKind == TypeKind.Delegate) return "";
|
||||
|
||||
string typeName = typeSymbol.GetFullMetadataName();
|
||||
|
||||
// Special case for the structured buffer types
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using ComputeSharp.SourceGenerators.Extensions;
|
||||
using ComputeSharp.SourceGenerators.SyntaxRewriters;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using Microsoft.CodeAnalysis.Text;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
|
||||
namespace ComputeSharp.SourceGenerators
|
||||
{
|
||||
[Generator]
|
||||
public class ShaderMethodSourceGenerator : ISourceGenerator
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public void Initialize(GeneratorInitializationContext context)
|
||||
{
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Execute(GeneratorExecutionContext context)
|
||||
{
|
||||
// Find all the [ShaderMethod] usages and retrieve the target methods
|
||||
ImmutableArray<MethodDeclarationSyntax> methods = (
|
||||
from tree in context.Compilation.SyntaxTrees
|
||||
from attribute in tree.GetRoot().DescendantNodes().OfType<AttributeSyntax>()
|
||||
let symbol = context.Compilation.GetSemanticModel(attribute.SyntaxTree)
|
||||
let typeInfo = symbol.GetTypeInfo(attribute)
|
||||
where typeInfo.Type is { Name: nameof(ShaderMethodAttribute) }
|
||||
select attribute.FirstAncestorOrSelf<MethodDeclarationSyntax>()).ToImmutableArray();
|
||||
|
||||
foreach (MethodDeclarationSyntax methodDeclaration in methods)
|
||||
{
|
||||
SemanticModel semanticModel = context.Compilation.GetSemanticModel(methodDeclaration.SyntaxTree);
|
||||
IMethodSymbol methodDeclarationSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration)!;
|
||||
|
||||
// We need to sets to track all discovered custom types and static methods
|
||||
HashSet<INamedTypeSymbol> discoveredTypes = new(SymbolEqualityComparer.Default);
|
||||
Dictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods = new(SymbolEqualityComparer.Default);
|
||||
|
||||
// Explore the syntax tree and extract the processed info
|
||||
var (invokeMethod, processedMethods) = GetProcessedMethods(methodDeclaration, semanticModel, discoveredTypes, staticMethods);
|
||||
var processedTypes = IComputeShaderSourceGenerator.GetProcessedTypes(discoveredTypes).ToArray();
|
||||
|
||||
// Helper that converts a sequence of strings into an array expression.
|
||||
// That is, this applies the following transformation:
|
||||
// - { "S1", "S2" } => new string[] { "S1", "S2" }
|
||||
static ArrayCreationExpressionSyntax ArrayExpression(IEnumerable<string> values)
|
||||
{
|
||||
return
|
||||
ArrayCreationExpression(
|
||||
ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword)))
|
||||
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
|
||||
.WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression)
|
||||
.AddExpressions(values.Select(static value => LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(value))).ToArray()));
|
||||
}
|
||||
|
||||
// Create the compilation unit with the source attribute
|
||||
var source =
|
||||
CompilationUnit().AddAttributeLists(
|
||||
AttributeList(SingletonSeparatedList(
|
||||
Attribute(IdentifierName(typeof(ShaderMethodSourceAttribute).FullName)).AddArgumentListArguments(
|
||||
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodDeclarationSymbol.GetFullMetadataName(true)))),
|
||||
AttributeArgument(ArrayExpression(processedTypes)),
|
||||
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(invokeMethod))),
|
||||
AttributeArgument(ArrayExpression(processedMethods)))))
|
||||
.WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList()))
|
||||
.WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword))))
|
||||
.NormalizeWhitespace()
|
||||
.ToFullString();
|
||||
|
||||
// Add the method source attribute
|
||||
context.AddSource(methodDeclarationSymbol.GetGeneratedFileName<ShaderMethodSourceAttribute>(), SourceText.From(source, Encoding.UTF8));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a sequence of processed methods from a target method declaration.
|
||||
/// </summary>
|
||||
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> instance for the current method.</param>
|
||||
/// <param name="semanticModel">The <see cref="SemanticModel"/> instance for the method to process.</param>
|
||||
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
|
||||
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
|
||||
/// <returns>A sequence of processed methods in <paramref name="methodDeclaration"/>.</returns>
|
||||
[Pure]
|
||||
private static (string InvokeMethod, IEnumerable<string> Methods) GetProcessedMethods(
|
||||
MethodDeclarationSyntax methodDeclaration,
|
||||
SemanticModel semanticModel,
|
||||
ICollection<INamedTypeSymbol> discoveredTypes,
|
||||
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods)
|
||||
{
|
||||
ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods);
|
||||
|
||||
// Rewrite the method syntax tree
|
||||
var processedMethod = shaderSourceRewriter
|
||||
.Visit(methodDeclaration)!
|
||||
.WithIdentifier(Identifier(ShaderMethodSourceAttribute.InvokeMethodIdentifier))
|
||||
.WithoutTrivia()
|
||||
.NormalizeWhitespace()
|
||||
.ToFullString();
|
||||
|
||||
List<string> methods = new(shaderSourceRewriter.LocalFunctions.Count);
|
||||
|
||||
// Emit the extracted local functions
|
||||
foreach (var localFunction in shaderSourceRewriter.LocalFunctions)
|
||||
{
|
||||
methods.Add(localFunction.Value.NormalizeWhitespace().ToFullString());
|
||||
}
|
||||
|
||||
return (processedMethod, methods);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,7 +162,8 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
|
||||
return
|
||||
((MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!)
|
||||
.WithBlockBody()
|
||||
.WithoutAccessibilityModifiers();
|
||||
.WithoutAccessibilityModifiers()
|
||||
.WithAttributeLists(List<AttributeListSyntax>());
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
@@ -171,6 +172,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
|
||||
var updatedNode =
|
||||
((LocalFunctionStatementSyntax)base.VisitLocalFunctionStatement(node)!)
|
||||
.WithBlockBody()
|
||||
.WithAttributeLists(List<AttributeListSyntax>())
|
||||
.WithIdentifier(Identifier($"__{this.currentMethod!.Identifier.Text}__{node.Identifier.Text}"));
|
||||
|
||||
// HLSL doesn't support local functions, so we first process them as usual and then remove
|
||||
|
||||
新しいイシューから参照
ユーザーをブロックする