Remove [ShaderMethod] support and infrastructure
このコミットが含まれているのは:
1 親
2e020a1524
コミット
249c708466
10ファイル変更
+2
-531
検索条件に一致するファイルはありません
@@ -1,39 +0,0 @@
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace ComputeSharp.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>
|
||||
public static string GetFullyQualifiedName(this MethodInfo method)
|
||||
{
|
||||
string parameters = string.Join(", ", method.GetParameters().Select(static p => p.ParameterType.FullName));
|
||||
|
||||
// Fixup the method name for static local functions in global statements. This only needs to
|
||||
// be done when the method is in a type with fully qualified name "Program", as that's the only
|
||||
// case where it might happen. If the declaring type has a name, it can't be that for sure.
|
||||
(string declaringType, string methodName) = (method.DeclaringType!.FullName!, method.Name) switch
|
||||
{
|
||||
("Program", var name) => ("Program", Regex.Replace(name, @"<<Main>\$>g__(\w+)\|\d+_\d+", static m => m.Groups[1].Value)),
|
||||
(var type, var name) => (type, name)
|
||||
};
|
||||
|
||||
if (method.IsGenericMethod)
|
||||
{
|
||||
string arguments = string.Join(", ", method.GetGenericArguments().Select(static t => t.FullName));
|
||||
|
||||
return $"{declaringType}.{methodName}<{arguments}>({parameters})";
|
||||
}
|
||||
|
||||
return $"{declaringType}.{methodName}({parameters})";
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
|
||||
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, AllowMultiple = false)]
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
[Obsolete(
|
||||
"This API (and shader metaprogramming in general) is being removed in a future version of ComputeSharp. " +
|
||||
"If you're relying on this functionality, consider manually implementing different shader variants. " +
|
||||
"It is possible to still reuse code by moving it to helper methods that are used by multiple shaders.")]
|
||||
public sealed class ShaderMethodAttribute : Attribute
|
||||
{
|
||||
}
|
||||
-93
@@ -1,93 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace ComputeSharp.__Internals;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class ShaderMethodSourceAttribute : Attribute
|
||||
{
|
||||
/// <summary>
|
||||
/// Appends the mapped source code for the current method.
|
||||
/// </summary>
|
||||
/// <param name="builder">The target <see cref="ArrayPoolStringBuilder"/> instance to write to.</param>
|
||||
/// <param name="mapping">The mapping of already discovered constant names.</param>
|
||||
public void AppendConstants(ref ArrayPoolStringBuilder builder, HashSet<string> mapping)
|
||||
{
|
||||
foreach (KeyValuePair<string, string> constant in this.constants)
|
||||
{
|
||||
if (mapping.Add(constant.Key))
|
||||
{
|
||||
builder.Append('\n');
|
||||
builder.Append("#define ");
|
||||
builder.Append(constant.Key);
|
||||
builder.Append(' ');
|
||||
builder.Append(constant.Value);
|
||||
builder.Append('\n');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Appends the discovered types for the current method.
|
||||
/// </summary>
|
||||
/// <param name="builder">The target <see cref="ArrayPoolStringBuilder"/> instance to write to.</param>
|
||||
/// <param name="mapping">The mapping of already discovered type names.</param>
|
||||
public void AppendTypes(ref ArrayPoolStringBuilder builder, HashSet<string> mapping)
|
||||
{
|
||||
foreach (KeyValuePair<string, string> type in this.types)
|
||||
{
|
||||
if (mapping.Add(type.Key))
|
||||
{
|
||||
builder.Append('\n');
|
||||
builder.Append(type.Value);
|
||||
builder.Append('\n');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Appends the discovered forward declarations for the current method.
|
||||
/// </summary>
|
||||
/// <param name="builder">The target <see cref="ArrayPoolStringBuilder"/> instance to write to.</param>
|
||||
/// <param name="mapping">The mapping of already discovered type names.</param>
|
||||
public void AppendForwardDeclarations(ref ArrayPoolStringBuilder builder, HashSet<string> mapping)
|
||||
{
|
||||
foreach (KeyValuePair<string, string> method in this.methods)
|
||||
{
|
||||
if (mapping.Add(method.Key))
|
||||
{
|
||||
builder.Append('\n');
|
||||
builder.Append(method.Key);
|
||||
builder.Append('\n');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Appends the discovered methods for the current method.
|
||||
/// </summary>
|
||||
/// <param name="builder">The target <see cref="ArrayPoolStringBuilder"/> instance to write to.</param>
|
||||
/// <param name="mapping">The mapping of already discovered type names.</param>
|
||||
public void AppendMethods(ref ArrayPoolStringBuilder builder, HashSet<string> mapping)
|
||||
{
|
||||
foreach (KeyValuePair<string, string> method in this.methods)
|
||||
{
|
||||
if (mapping.Remove(method.Key))
|
||||
{
|
||||
builder.Append('\n');
|
||||
builder.Append(method.Value);
|
||||
builder.Append('\n');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Appends the mapped source code for the current method.
|
||||
/// </summary>
|
||||
/// <param name="builder">The target <see cref="ArrayPoolStringBuilder"/> instance to write to.</param>
|
||||
/// <param name="name">The name to bind the method to.</param>
|
||||
public void AppendMappedInvokeMethod(ref ArrayPoolStringBuilder builder, string name)
|
||||
{
|
||||
builder.Append(this.invokeMethod.Replace(InvokeMethodIdentifier, name));
|
||||
}
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using ComputeSharp.Extensions;
|
||||
|
||||
#pragma warning disable IDE0052
|
||||
|
||||
namespace ComputeSharp.__Internals;
|
||||
|
||||
/// <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 not intended to be used directly by user code")]
|
||||
public sealed partial class ShaderMethodSourceAttribute : Attribute
|
||||
{
|
||||
/// <summary>
|
||||
/// The identifier for the invoke method, for late binding.
|
||||
/// </summary>
|
||||
internal const string InvokeMethodIdentifier = "__<NAME>__";
|
||||
|
||||
/// <summary>
|
||||
/// The fully qualified name of the current method.
|
||||
/// </summary>
|
||||
private readonly string methodName;
|
||||
|
||||
/// <summary>
|
||||
/// The source code for the target entry point method.
|
||||
/// </summary>
|
||||
private readonly string invokeMethod;
|
||||
|
||||
/// <summary>
|
||||
/// The collection of custom types.
|
||||
/// </summary>
|
||||
private readonly Dictionary<string, string> types;
|
||||
|
||||
/// <summary>
|
||||
/// The collection of processed methods.
|
||||
/// </summary>
|
||||
private readonly Dictionary<string, string> methods;
|
||||
|
||||
/// <summary>
|
||||
/// The collection of discovered constants.
|
||||
/// </summary>
|
||||
private readonly Dictionary<string, string> constants;
|
||||
|
||||
/// <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="invokeMethod">The source code for the target entry point method.</param>
|
||||
/// <param name="types">The collection of custom types.</param>
|
||||
/// <param name="methods">The collection of processed methods.</param>
|
||||
/// <param name="constants">The collection of discovered constants.</param>
|
||||
public ShaderMethodSourceAttribute(string methodName, string invokeMethod, object[] types, object[] methods, object[] constants)
|
||||
{
|
||||
this.methodName = methodName;
|
||||
this.invokeMethod = invokeMethod;
|
||||
this.types = types.Cast<string[]>().ToDictionary(static c => c[0], static c => c[1]);
|
||||
this.methods = methods.Cast<string[]>().ToDictionary(static c => c[0], static c => c[1]);
|
||||
this.constants = constants.Cast<string[]>().ToDictionary(static c => c[0], static c => c[1]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the associated <see cref="ShaderMethodSourceAttribute"/> instance for a specified delegate.
|
||||
/// </summary>
|
||||
/// <param name="function">The input <see cref="Delegate"/> instance to get info for.</param>
|
||||
/// <param name="name">The name of the shader field containing <paramref name="function"/>.</param>
|
||||
/// <returns>The associated <see cref="ShaderMethodSourceAttribute"/> instance for the given delegate.</returns>
|
||||
public static ShaderMethodSourceAttribute GetForDelegate(Delegate function, string name)
|
||||
{
|
||||
if (!function.Method.IsStatic)
|
||||
{
|
||||
return ThrowArgumentExceptionForNonStaticMethod(name);
|
||||
}
|
||||
|
||||
IEnumerable<ShaderMethodSourceAttribute> attributes = function.Method.DeclaringType!.Assembly.GetCustomAttributes<ShaderMethodSourceAttribute>();
|
||||
string methodName = function.Method.GetFullyQualifiedName();
|
||||
|
||||
foreach (ShaderMethodSourceAttribute attribute in attributes)
|
||||
{
|
||||
if (attribute.methodName.Equals(methodName))
|
||||
{
|
||||
return attribute;
|
||||
}
|
||||
}
|
||||
|
||||
return ThrowArgumentExceptionForMissingShaderMethodAttribute(name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Throws an <see cref="ArgumentException"/> when a given <see cref="Delegate"/> is not static.
|
||||
/// </summary>
|
||||
/// <param name="name">The name of the shader field containing the invalid method.</param>
|
||||
private static ShaderMethodSourceAttribute ThrowArgumentExceptionForNonStaticMethod(string name)
|
||||
{
|
||||
throw new ArgumentException($"The captured delegate \"{name}\" was wrapping a non static method (only static methods are supported for captured delegates).", name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Throws an <see cref="ArgumentException"/> when a given <see cref="Delegate"/> doesn't have <see cref="ShaderMethodAttribute"/> applied to it.
|
||||
/// </summary>
|
||||
/// <param name="name">The name of the shader field containing the invalid method.</param>
|
||||
private static ShaderMethodSourceAttribute ThrowArgumentExceptionForMissingShaderMethodAttribute(string name)
|
||||
{
|
||||
throw new ArgumentException($"The captured delegate \"{name}\" was wrapping a method without the [ShaderMethod] attribute applied to it.", name);
|
||||
}
|
||||
}
|
||||
@@ -57,9 +57,6 @@
|
||||
<!-- ComputeSharp APIs -->
|
||||
<Compile Include="..\ComputeSharp\Core\Attributes\EmbeddedBytecodeAttribute.cs" Link="ComputeSharp\Core\Attributes\EmbeddedBytecodeAttribute.cs" />
|
||||
<Compile Include="..\ComputeSharp\Core\Attributes\GroupSharedAttribute.cs" Link="ComputeSharp\Core\Attributes\GroupSharedAttribute.cs" />
|
||||
<Compile Include="..\ComputeSharp.Dynamic\Attributes\ShaderMethodAttribute.cs" Link="ComputeSharp\Core\Attributes\ShaderMethodAttribute.cs" />
|
||||
<Compile Include="..\ComputeSharp.Dynamic\Attributes\__Internals\ShaderMethodSourceAttribute.cs" Link="ComputeSharp\Core\Attributes\__Internals\ShaderMethodSourceAttribute.cs" />
|
||||
<Compile Include="..\ComputeSharp.Dynamic\Attributes\Extensions\MethodInfoExtensions.cs" Link="ComputeSharp\Extensions\MethodInfoExtensions.cs" />
|
||||
<Compile Include="..\ComputeSharp\Core\Dispatch\DispatchAxis.cs" Link="ComputeSharp\Core\Dispatch\DispatchAxis.cs" />
|
||||
<Compile Include="..\ComputeSharp\Core\Dispatch\DispatchSize.cs" Link="ComputeSharp\Core\Dispatch\DispatchSize.cs" />
|
||||
<Compile Include="..\ComputeSharp\Core\Dispatch\GridIds.cs" Link="ComputeSharp\Core\Dispatch\GridIds.cs" />
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
namespace ComputeSharp.SourceGenerators.Helpers;
|
||||
|
||||
/// <summary>
|
||||
/// A class containing additional factory methods for constructing syntax nodes, tokens and trivia.
|
||||
/// </summary>
|
||||
internal static class SyntaxFactoryHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates an <see cref="object"/>[] array expression with the nested groups in the input sequence.
|
||||
/// <para>
|
||||
/// That it, it applies the following transformation:
|
||||
/// <code>
|
||||
/// { ("K1", "V1"), ("K2", "V2") } => new object[] { new string[] { "K1", "V1" }, new string[] { "K2", "V2" } }
|
||||
/// </code>
|
||||
/// </para>
|
||||
/// </summary>
|
||||
/// <param name="groups">The input sequence of <see cref="string"/> groups.</param>
|
||||
/// <returns>An <see cref="ArrayCreationExpressionSyntax"/> instance with the described contents.</returns>
|
||||
public static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable<(string A, string B)> groups)
|
||||
{
|
||||
return
|
||||
ArrayCreationExpression(
|
||||
ArrayType(PredefinedType(Token(SyntaxKind.ObjectKeyword)))
|
||||
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
|
||||
.WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression)
|
||||
.AddExpressions(groups.Select(static group =>
|
||||
ArrayCreationExpression(
|
||||
ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword)))
|
||||
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
|
||||
.WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression)
|
||||
.AddExpressions(
|
||||
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(group.A)),
|
||||
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(group.B))))).ToArray()));
|
||||
}
|
||||
}
|
||||
@@ -421,7 +421,7 @@ partial class IShaderGenerator
|
||||
/// </summary>
|
||||
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
|
||||
/// <returns>A sequence of discovered constants to declare in the shader.</returns>
|
||||
internal static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary<IFieldSymbol, string> constantDefinitions)
|
||||
private static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary<IFieldSymbol, string> constantDefinitions)
|
||||
{
|
||||
using ImmutableArrayBuilder<(string, string)> builder = new();
|
||||
|
||||
@@ -444,7 +444,7 @@ partial class IShaderGenerator
|
||||
/// <param name="types">The sequence of discovered custom types.</param>
|
||||
/// <param name="instanceMethods">The collection of discovered instance methods for custom struct types.</param>
|
||||
/// <returns>A sequence of custom type definitions to add to the shader source.</returns>
|
||||
internal static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes(
|
||||
private static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes(
|
||||
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
|
||||
ISymbol sourceSymbol,
|
||||
IEnumerable<INamedTypeSymbol> types,
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
|
||||
namespace ComputeSharp.SourceGenerators.Models;
|
||||
|
||||
/// <summary>
|
||||
/// A model for extracted info on a processed HLSL method.
|
||||
/// </summary>
|
||||
/// <param name="MetadataName">The metadata name for the method.</param>
|
||||
/// <param name="EntryPoint">The meethod entry point.</param>
|
||||
/// <param name="DefinedTypes">The discovered declared types.</param>
|
||||
/// <param name="DefinedConstants">The discovered defined constants.</param>
|
||||
/// <param name="DependentMethods">The dependent captured methods.</param>
|
||||
internal sealed record HlslMethodSourceInfo(
|
||||
string MetadataName,
|
||||
string EntryPoint,
|
||||
EquatableArray<(string Name, string Definition)> DefinedTypes,
|
||||
EquatableArray<(string Name, string Value)> DefinedConstants,
|
||||
EquatableArray<(string Signature, string Definition)> DependentMethods);
|
||||
@@ -1,11 +0,0 @@
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Models;
|
||||
|
||||
namespace ComputeSharp.SourceGenerators.Models;
|
||||
|
||||
/// <summary>
|
||||
/// A model representing all necessary info for a full generation pass for a shader method.
|
||||
/// </summary>
|
||||
/// <param name="HlslMethodSource">The processed HLSL source for the shader method.</param>
|
||||
/// <param name="Diagnostcs">The discovered diagnostics, if any.</param>
|
||||
internal sealed record ShaderMethodInfo(HlslMethodSourceInfo HlslMethodSource, EquatableArray<DiagnosticInfo> Diagnostcs);
|
||||
@@ -1,190 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using ComputeSharp.__Internals;
|
||||
using ComputeSharp.SourceGeneration.Extensions;
|
||||
using ComputeSharp.SourceGeneration.Helpers;
|
||||
using ComputeSharp.SourceGeneration.Models;
|
||||
using ComputeSharp.SourceGeneration.SyntaxRewriters;
|
||||
using ComputeSharp.SourceGenerators.Models;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using static ComputeSharp.SourceGenerators.Helpers.SyntaxFactoryHelper;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
|
||||
namespace ComputeSharp.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A source generator for processing static methods referenced from compute shaders.
|
||||
/// </summary>
|
||||
[Generator(LanguageNames.CSharp)]
|
||||
public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public void Initialize(IncrementalGeneratorInitializationContext context)
|
||||
{
|
||||
// Get all declared methods (including global function declarations) with the [ShaderMethod] attribute, and their info
|
||||
IncrementalValuesProvider<ShaderMethodInfo> methodInfoWithErrors =
|
||||
context.SyntaxProvider
|
||||
.ForAttributeWithMetadataName(
|
||||
typeof(ShaderMethodAttribute).FullName,
|
||||
static (node, _) => node is MethodDeclarationSyntax { AttributeLists.Count: > 0 } or LocalFunctionStatementSyntax { Parent: GlobalStatementSyntax { Parent: CompilationUnitSyntax } },
|
||||
static (context, token) =>
|
||||
{
|
||||
HlslMethodSourceInfo hlslMethodSourceInfo = Execute.GetData(
|
||||
context.SemanticModel.Compilation,
|
||||
(CSharpSyntaxNode)context.TargetNode,
|
||||
(IMethodSymbol)context.TargetSymbol,
|
||||
out ImmutableArray<DiagnosticInfo> diagnostics);
|
||||
|
||||
return new ShaderMethodInfo(hlslMethodSourceInfo, diagnostics);
|
||||
});
|
||||
|
||||
// Output the diagnostics, if any
|
||||
context.ReportDiagnostics(
|
||||
methodInfoWithErrors
|
||||
.Select(static (item, _) => item.Diagnostcs));
|
||||
|
||||
// Generate the [ShaderMethodSource] attributes
|
||||
context.RegisterSourceOutput(methodInfoWithErrors, static (context, item) =>
|
||||
{
|
||||
CompilationUnitSyntax compilationUnit = Execute.GetSyntax(item.HlslMethodSource);
|
||||
string filename = item.HlslMethodSource.MetadataName.Replace('`', '-').Replace('+', '.');
|
||||
|
||||
context.AddSource($"{filename}.g.cs", compilationUnit.GetText(Encoding.UTF8));
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A helper with all logic to generate the attribute declarations.
|
||||
/// </summary>
|
||||
private static class Execute
|
||||
{
|
||||
/// <summary>
|
||||
/// Processes a given target method.
|
||||
/// </summary>
|
||||
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
|
||||
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> or <see cref="LocalFunctionStatementSyntax"/> node to process.</param>
|
||||
/// <param name="methodSymbol">The <see cref="IMethodSymbol"/> instance for the current method.</param>
|
||||
/// <param name="diagnostics">The resulting diagnostics from the processing operation.</param>
|
||||
public static HlslMethodSourceInfo GetData(
|
||||
Compilation compilation,
|
||||
CSharpSyntaxNode methodDeclaration,
|
||||
IMethodSymbol methodSymbol,
|
||||
out ImmutableArray<DiagnosticInfo> diagnostics)
|
||||
{
|
||||
using ImmutableArrayBuilder<DiagnosticInfo> builder = new();
|
||||
|
||||
// We need to sets to track all discovered custom types and static methods
|
||||
HashSet<INamedTypeSymbol> discoveredTypes = new(SymbolEqualityComparer.Default);
|
||||
Dictionary<IFieldSymbol, string> constantDefinitions = new(SymbolEqualityComparer.Default);
|
||||
Dictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods = new(SymbolEqualityComparer.Default); // Unused in this generator
|
||||
|
||||
// Explore the syntax tree and extract the processed info
|
||||
SemanticModelProvider semanticModel = new(compilation);
|
||||
(string entryPoint, ImmutableArray<(string Signature, string Definition)> dependentMethods) = GetProcessedMethods(builder, methodDeclaration, semanticModel, discoveredTypes, constantDefinitions);
|
||||
ImmutableArray<(string Name, string Definition)> definedTypes = IShaderGenerator.BuildHlslSource.GetDeclaredTypes(builder, methodSymbol, discoveredTypes, instanceMethods);
|
||||
ImmutableArray<(string Name, string Value)> definedConstants = IShaderGenerator.BuildHlslSource.GetDefinedConstants(constantDefinitions);
|
||||
|
||||
diagnostics = builder.ToImmutable();
|
||||
|
||||
return new(
|
||||
methodSymbol.GetFullyQualifiedMetadataName(includeParameters: true),
|
||||
entryPoint,
|
||||
definedTypes,
|
||||
definedConstants,
|
||||
dependentMethods);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a sequence of processed methods from a target method declaration.
|
||||
/// </summary>
|
||||
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
|
||||
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> or <see cref="LocalFunctionStatementSyntax"/> instance for the current method.</param>
|
||||
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the method to process.</param>
|
||||
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
|
||||
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
|
||||
/// <returns>A sequence of processed methods in <paramref name="methodDeclaration"/> (main method and all captured methods).</returns>
|
||||
private static (string TargetMethod, ImmutableArray<(string Signature, string Definition)> DependentMethods) GetProcessedMethods(
|
||||
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
|
||||
CSharpSyntaxNode methodDeclaration,
|
||||
SemanticModelProvider semanticModel,
|
||||
ICollection<INamedTypeSymbol> discoveredTypes,
|
||||
IDictionary<IFieldSymbol, string> constantDefinitions)
|
||||
{
|
||||
Dictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods = new(SymbolEqualityComparer.Default);
|
||||
Dictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods = new(SymbolEqualityComparer.Default);
|
||||
|
||||
ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, instanceMethods, constantDefinitions, diagnostics);
|
||||
|
||||
// Process the possible syntax nodes
|
||||
SyntaxNode visitedMethod = methodDeclaration switch
|
||||
{
|
||||
MethodDeclarationSyntax methodDeclarationSyntax => shaderSourceRewriter.Visit(methodDeclarationSyntax)!.WithIdentifier(Identifier(ShaderMethodSourceAttribute.InvokeMethodIdentifier)),
|
||||
LocalFunctionStatementSyntax functionStatementSyntax => shaderSourceRewriter.Visit(functionStatementSyntax)!.WithIdentifier(Identifier(ShaderMethodSourceAttribute.InvokeMethodIdentifier)),
|
||||
_ => throw new ArgumentException("Invalid method declaration syntax node type.")
|
||||
};
|
||||
|
||||
// Rewrite the method syntax tree
|
||||
string targetMethod = visitedMethod
|
||||
.WithoutTrivia()
|
||||
.NormalizeWhitespace(eol: "\n")
|
||||
.ToFullString();
|
||||
|
||||
using ImmutableArrayBuilder<(string, string)> methods = new();
|
||||
|
||||
// Emit the extracted local functions
|
||||
foreach (KeyValuePair<string, LocalFunctionStatementSyntax> localFunction in shaderSourceRewriter.LocalFunctions)
|
||||
{
|
||||
methods.Add((
|
||||
localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
|
||||
localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString()));
|
||||
}
|
||||
|
||||
// Emit the discovered static methods
|
||||
foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values)
|
||||
{
|
||||
methods.Add((
|
||||
staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
|
||||
staticMethod.NormalizeWhitespace(eol: "\n").ToFullString()));
|
||||
}
|
||||
|
||||
return (targetMethod, methods.ToImmutable());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="CompilationUnitSyntax"/> instance with the processed attribute.
|
||||
/// </summary>
|
||||
/// <param name="methodSourceInfo">The input <see cref="HlslMethodSourceInfo"/> instance to use.</param>
|
||||
public static CompilationUnitSyntax GetSyntax(HlslMethodSourceInfo methodSourceInfo)
|
||||
{
|
||||
// This produces an assembly attribute declaration as follows:
|
||||
//
|
||||
// // <auto-generated/>
|
||||
// #pragma warning disable
|
||||
// [assembly: global::ComputeSharp.ShaderMethodSourceAttribute(<ARGUMENTS>)]
|
||||
return
|
||||
CompilationUnit().AddAttributeLists(
|
||||
AttributeList(SingletonSeparatedList(
|
||||
Attribute(IdentifierName($"global::{typeof(ShaderMethodSourceAttribute).FullName}")).AddArgumentListArguments(
|
||||
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodSourceInfo.MetadataName))),
|
||||
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodSourceInfo.EntryPoint))),
|
||||
AttributeArgument(NestedArrayExpression(methodSourceInfo.DefinedTypes)),
|
||||
AttributeArgument(NestedArrayExpression(methodSourceInfo.DependentMethods)),
|
||||
AttributeArgument(NestedArrayExpression(methodSourceInfo.DefinedConstants)))))
|
||||
.WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList()))
|
||||
.WithOpenBracketToken(Token(TriviaList(
|
||||
Comment("// <auto-generated/>"),
|
||||
Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))),
|
||||
SyntaxKind.OpenBracketToken,
|
||||
TriviaList()))
|
||||
.WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword))))
|
||||
.NormalizeWhitespace(eol: "\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
新しいイシューから参照
ユーザーをブロックする