From 10ba55d1561f2625f1542d91ed4b382bcc6314af Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 4 Sep 2022 15:21:00 +0200 Subject: [PATCH] Enable [ShaderMethod] support for global functions --- .../ShaderMethodSourceAttribute.cs | 4 +- .../SyntaxRewriters/ShaderSourceRewriter.cs | 124 ++++++++++++++---- .../ShaderMethodSourceGenerator.cs | 31 +++-- .../Core/Extensions/MethodInfoExtensions.cs | 14 +- 4 files changed, 128 insertions(+), 45 deletions(-) diff --git a/src/ComputeSharp.Dynamic/Attributes/__Internals/ShaderMethodSourceAttribute.cs b/src/ComputeSharp.Dynamic/Attributes/__Internals/ShaderMethodSourceAttribute.cs index d72109fe..b00de205 100644 --- a/src/ComputeSharp.Dynamic/Attributes/__Internals/ShaderMethodSourceAttribute.cs +++ b/src/ComputeSharp.Dynamic/Attributes/__Internals/ShaderMethodSourceAttribute.cs @@ -77,10 +77,10 @@ public sealed partial class ShaderMethodSourceAttribute : Attribute return ThrowArgumentExceptionForNonStaticMethod(name); } - var attributes = function.Method.DeclaringType!.Assembly.GetCustomAttributes(); + IEnumerable attributes = function.Method.DeclaringType!.Assembly.GetCustomAttributes(); string methodName = function.Method.GetFullyQualifiedName(); - foreach (var attribute in attributes) + foreach (ShaderMethodSourceAttribute attribute in attributes) { if (attribute.methodName.Equals(methodName)) { diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs index 8347860b..6a960102 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs @@ -46,9 +46,9 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter private readonly bool isEntryPoint; /// - /// The current tree being visited. + /// The identifier of the current or tree being visited. /// - private MethodDeclarationSyntax? currentMethod; + private SyntaxToken currentMethodIdentifier; /// /// The current depth inside local declarations. @@ -111,7 +111,12 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter /// 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; } + /// + 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; + } + /// public override SyntaxNode VisitParameter(ParameterSyntax node) { @@ -200,35 +239,62 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter /// public override SyntaxNode? VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) { - this.localFunctionDepth++; - - var updatedNode = - ((LocalFunctionStatementSyntax)base.VisitLocalFunctionStatement(node)!) - .WithBlockBody() - .WithAttributeLists(List()) - .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()); - 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()) + .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: "____". + 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: "____". - this.localFunctions.Add(updatedNode.Identifier.Text, updatedNode); - - return null; } /// @@ -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)); } diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index 52dde8f1..f293e6e4 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -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 /// 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. /// /// The input object currently in use. - /// The node to process. + /// The or node to process. /// The instance for the current method. /// The resulting diagnostics from the processing operation. public static HlslMethodSourceInfo GetData( Compilation compilation, - MethodDeclarationSyntax methodDeclaration, + CSharpSyntaxNode methodDeclaration, IMethodSymbol methodSymbol, out ImmutableArray diagnostics) { @@ -116,14 +117,14 @@ public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator /// Gets a sequence of processed methods from a target method declaration. /// /// The collection of produced instances. - /// The instance for the current method. + /// The or instance for the current method. /// The instance for the method to process. /// The collection of currently discovered types. /// The collection of discovered constant definitions. /// A sequence of processed methods in (main method and all captured methods). private static (string TargetMethod, ImmutableArray<(string Signature, string Definition)> DependentMethods) GetProcessedMethods( ImmutableArray.Builder diagnostics, - MethodDeclarationSyntax methodDeclaration, + CSharpSyntaxNode methodDeclaration, SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary 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(); diff --git a/src/ComputeSharp/Core/Extensions/MethodInfoExtensions.cs b/src/ComputeSharp/Core/Extensions/MethodInfoExtensions.cs index b2f1a9ac..81d7dfa7 100644 --- a/src/ComputeSharp/Core/Extensions/MethodInfoExtensions.cs +++ b/src/ComputeSharp/Core/Extensions/MethodInfoExtensions.cs @@ -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, @"<
\$>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})"; } }