Enable [ShaderMethod] support for global functions
このコミットが含まれているのは:
1 親
1d0856ff12
コミット
10ba55d156
4ファイル変更
+128
-45
検索条件に一致するファイルはありません
@@ -77,10 +77,10 @@ public sealed partial class ShaderMethodSourceAttribute : Attribute
|
||||
return ThrowArgumentExceptionForNonStaticMethod(name);
|
||||
}
|
||||
|
||||
var attributes = function.Method.DeclaringType!.Assembly.GetCustomAttributes<ShaderMethodSourceAttribute>();
|
||||
IEnumerable<ShaderMethodSourceAttribute> attributes = function.Method.DeclaringType!.Assembly.GetCustomAttributes<ShaderMethodSourceAttribute>();
|
||||
string methodName = function.Method.GetFullyQualifiedName();
|
||||
|
||||
foreach (var attribute in attributes)
|
||||
foreach (ShaderMethodSourceAttribute attribute in attributes)
|
||||
{
|
||||
if (attribute.methodName.Equals(methodName))
|
||||
{
|
||||
|
||||
@@ -46,9 +46,9 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
|
||||
private readonly bool isEntryPoint;
|
||||
|
||||
/// <summary>
|
||||
/// The current <see cref="MethodDeclarationSyntax"/> tree being visited.
|
||||
/// The identifier of the current <see cref="MethodDeclarationSyntax"/> or <see cref="LocalFunctionStatementSyntax"/> tree being visited.
|
||||
/// </summary>
|
||||
private MethodDeclarationSyntax? currentMethod;
|
||||
private SyntaxToken currentMethodIdentifier;
|
||||
|
||||
/// <summary>
|
||||
/// The current depth inside local declarations.
|
||||
@@ -111,7 +111,12 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
|
||||
/// <inheritdoc cref="CSharpSyntaxRewriter.Visit(SyntaxNode?)"/>
|
||||
public MethodDeclarationSyntax? Visit(MethodDeclarationSyntax? node)
|
||||
{
|
||||
this.currentMethod = node;
|
||||
if (node is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
this.currentMethodIdentifier = node.Identifier;
|
||||
|
||||
var updatedNode = (MethodDeclarationSyntax?)base.Visit(node)!;
|
||||
|
||||
@@ -138,6 +143,40 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
|
||||
return updatedNode;
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="CSharpSyntaxRewriter.Visit(SyntaxNode?)"/>
|
||||
public LocalFunctionStatementSyntax? Visit(LocalFunctionStatementSyntax? node)
|
||||
{
|
||||
if (node is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
this.currentMethodIdentifier = node.Identifier;
|
||||
|
||||
var updatedNode = (LocalFunctionStatementSyntax?)base.Visit(node)!;
|
||||
|
||||
updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel.For(node), DiscoveredTypes);
|
||||
|
||||
if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword)))
|
||||
{
|
||||
Diagnostics.Add(AsyncModifierOnMethodOrFunction, node);
|
||||
}
|
||||
|
||||
if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword)))
|
||||
{
|
||||
Diagnostics.Add(UnsafeModifierOnMethodOrFunction, node);
|
||||
}
|
||||
|
||||
if (updatedNode is not null)
|
||||
{
|
||||
var implicitBlock = Block(this.implicitVariables.Select(static v => LocalDeclarationStatement(v)).ToArray());
|
||||
|
||||
updatedNode = updatedNode.WithBody(implicitBlock).AddBodyStatements(updatedNode.Body!.Statements.ToArray());
|
||||
}
|
||||
|
||||
return updatedNode;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode VisitParameter(ParameterSyntax node)
|
||||
{
|
||||
@@ -200,35 +239,62 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitLocalFunctionStatement(LocalFunctionStatementSyntax node)
|
||||
{
|
||||
this.localFunctionDepth++;
|
||||
|
||||
var updatedNode =
|
||||
((LocalFunctionStatementSyntax)base.VisitLocalFunctionStatement(node)!)
|
||||
.WithBlockBody()
|
||||
.WithAttributeLists(List<AttributeListSyntax>())
|
||||
.WithIdentifier(Identifier($"__{this.currentMethod!.Identifier.Text}__{node.Identifier.Text}"));
|
||||
|
||||
updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel.For(node), DiscoveredTypes);
|
||||
|
||||
if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword)))
|
||||
// If the current identifier matches the one for the current method, it means the local function
|
||||
// statement is the one being inspected, and it's nto coming from a local function in a method
|
||||
// being parsed. That is, this was a blobal method that was annotated in source.
|
||||
if (node.Identifier == this.currentMethodIdentifier)
|
||||
{
|
||||
Diagnostics.Add(AsyncModifierOnMethodOrFunction, node);
|
||||
}
|
||||
var updatedNode =
|
||||
((LocalFunctionStatementSyntax)base.VisitLocalFunctionStatement(node)!)
|
||||
.WithBlockBody()
|
||||
.WithAttributeLists(List<AttributeListSyntax>());
|
||||
|
||||
if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword)))
|
||||
updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel.For(node), DiscoveredTypes);
|
||||
|
||||
if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword)))
|
||||
{
|
||||
Diagnostics.Add(AsyncModifierOnMethodOrFunction, node);
|
||||
}
|
||||
|
||||
if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword)))
|
||||
{
|
||||
Diagnostics.Add(UnsafeModifierOnMethodOrFunction, node);
|
||||
}
|
||||
|
||||
return updatedNode;
|
||||
}
|
||||
else
|
||||
{
|
||||
Diagnostics.Add(UnsafeModifierOnMethodOrFunction, node);
|
||||
this.localFunctionDepth++;
|
||||
|
||||
var updatedNode =
|
||||
((LocalFunctionStatementSyntax)base.VisitLocalFunctionStatement(node)!)
|
||||
.WithBlockBody()
|
||||
.WithAttributeLists(List<AttributeListSyntax>())
|
||||
.WithIdentifier(Identifier($"__{this.currentMethodIdentifier.Text}__{node.Identifier.Text}"));
|
||||
|
||||
updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel.For(node), DiscoveredTypes);
|
||||
|
||||
if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword)))
|
||||
{
|
||||
Diagnostics.Add(AsyncModifierOnMethodOrFunction, node);
|
||||
}
|
||||
|
||||
if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword)))
|
||||
{
|
||||
Diagnostics.Add(UnsafeModifierOnMethodOrFunction, node);
|
||||
}
|
||||
|
||||
this.localFunctionDepth--;
|
||||
|
||||
// HLSL doesn't support local functions, so we first process them as usual and then remove
|
||||
// them from the current syntax tree completely. These will be added to the shader source
|
||||
// as external static method with a special name to avoid conflicts with other methods.
|
||||
// The name will simply be in the format: "__<MethodName>__<FunctionName>".
|
||||
this.localFunctions.Add(updatedNode.Identifier.Text, updatedNode);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
this.localFunctionDepth--;
|
||||
|
||||
// HLSL doesn't support local functions, so we first process them as usual and then remove
|
||||
// them from the current syntax tree completely. These will be added to the shader source
|
||||
// as external static method with a special name to avoid conflicts with other methods.
|
||||
// The name will simply be in the format: "__<MethodName>__<FunctionName>".
|
||||
this.localFunctions.Add(updatedNode.Identifier.Text, updatedNode);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
@@ -370,7 +436,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
|
||||
// updated name is detailed in the override handling the local function statement.
|
||||
if (method.MethodKind == MethodKind.LocalFunction)
|
||||
{
|
||||
var functionIdentifier = $"__{this.currentMethod!.Identifier.Text}__{method.Name}";
|
||||
var functionIdentifier = $"__{this.currentMethodIdentifier.Text}__{method.Name}";
|
||||
|
||||
return updatedNode.WithExpression(IdentifierName(functionIdentifier));
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Collections.Generic;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@@ -27,13 +28,13 @@ public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator
|
||||
/// <inheritdoc/>
|
||||
public void Initialize(IncrementalGeneratorInitializationContext context)
|
||||
{
|
||||
// Get all declared methods with the [ShaderMethod] attribute
|
||||
IncrementalValuesProvider<(MethodDeclarationSyntax Syntax, IMethodSymbol Symbol)> structDeclarations =
|
||||
// Get all declared methods (including global function declarations) with the [ShaderMethod] attribute
|
||||
IncrementalValuesProvider<(CSharpSyntaxNode Syntax, IMethodSymbol Symbol)> structDeclarations =
|
||||
context.SyntaxProvider
|
||||
.CreateSyntaxProvider(
|
||||
static (node, token) => node is MethodDeclarationSyntax { AttributeLists.Count: > 0 } methodDeclaration,
|
||||
static (node, token) => node is MethodDeclarationSyntax { AttributeLists.Count: > 0 } or LocalFunctionStatementSyntax { Parent: GlobalStatementSyntax { Parent: CompilationUnitSyntax }, AttributeLists.Count: > 0 },
|
||||
static (context, token) => (
|
||||
Syntax: (MethodDeclarationSyntax)context.Node,
|
||||
Syntax: (CSharpSyntaxNode)context.Node,
|
||||
Symbol: (IMethodSymbol?)context.SemanticModel.GetDeclaredSymbol(context.Node, token)))
|
||||
.Where(static item => item.Symbol is not null &&
|
||||
item.Symbol.GetAttributes().Any(static a => a.AttributeClass?.ToDisplayString() == typeof(ShaderMethodAttribute).FullName))!;
|
||||
@@ -81,12 +82,12 @@ public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator
|
||||
/// 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"/> node to process.</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,
|
||||
MethodDeclarationSyntax methodDeclaration,
|
||||
CSharpSyntaxNode methodDeclaration,
|
||||
IMethodSymbol methodSymbol,
|
||||
out ImmutableArray<Diagnostic> diagnostics)
|
||||
{
|
||||
@@ -116,14 +117,14 @@ public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator
|
||||
/// Gets a sequence of processed methods from a target method declaration.
|
||||
/// </summary>
|
||||
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
|
||||
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> instance for the current method.</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(
|
||||
ImmutableArray<Diagnostic>.Builder diagnostics,
|
||||
MethodDeclarationSyntax methodDeclaration,
|
||||
CSharpSyntaxNode methodDeclaration,
|
||||
SemanticModelProvider semanticModel,
|
||||
ICollection<INamedTypeSymbol> discoveredTypes,
|
||||
IDictionary<IFieldSymbol, string> constantDefinitions)
|
||||
@@ -132,10 +133,16 @@ public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator
|
||||
|
||||
ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, 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
|
||||
var targetMethod = shaderSourceRewriter
|
||||
.Visit(methodDeclaration)!
|
||||
.WithIdentifier(Identifier(ShaderMethodSourceAttribute.InvokeMethodIdentifier))
|
||||
string targetMethod = visitedMethod
|
||||
.WithoutTrivia()
|
||||
.NormalizeWhitespace(eol: "\n")
|
||||
.ToFullString();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace ComputeSharp.Core.Extensions;
|
||||
|
||||
@@ -17,13 +18,22 @@ internal static class MethodInfoExtensions
|
||||
{
|
||||
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 $"{method.DeclaringType!.FullName!}.{method.Name}<{arguments}>({parameters})";
|
||||
return $"{declaringType}.{methodName}<{arguments}>({parameters})";
|
||||
}
|
||||
|
||||
return $"{method.DeclaringType!.FullName!}.{method.Name}({parameters})";
|
||||
return $"{declaringType}.{methodName}({parameters})";
|
||||
}
|
||||
}
|
||||
新しいイシューから参照
ユーザーをブロックする