diff --git a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs deleted file mode 100644 index d33cd576..00000000 --- a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs +++ /dev/null @@ -1,37 +0,0 @@ -using ComputeSharp.SourceGeneration.Mappings; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Operations; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -namespace ComputeSharp.SourceGeneration.SyntaxRewriters; - -/// -partial class HlslSourceRewriter -{ - /// - private partial SyntaxNode RewriteSampledTextureAccess(IPropertyReferenceOperation operation, ElementAccessExpressionSyntax node, string? mappedType) - { - // Get the syntax for the argument syntax transformation as described above - ArgumentSyntax coordinateSyntax = mappedType switch - { - not null => Argument(InvocationExpression(IdentifierName(mappedType!), ArgumentList(node.ArgumentList.Arguments))), - null => node.ArgumentList.Arguments[0] - }; - - string fieldName = (operation.Instance as IFieldReferenceOperation)?.Member.Name ?? ""; - - _ = HlslKnownKeywords.TryGetMappedName(fieldName, out string? mapped); - - // Transform an indexer syntax into a sampling call with the implicit static linear sampler. - // For instance: texture[uv] will be rewritten as texture.Sample(__sampler__texture, uv). - return - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - node.Expression, - IdentifierName("Sample"))) - .AddArgumentListArguments(Argument(IdentifierName($"__sampler__{mapped ?? fieldName}")), coordinateSyntax); - } -} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 98ff4360..567c7489 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -1,6 +1,8 @@ using ComputeSharp.SourceGeneration.Mappings; +using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Operations; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.SourceGeneration.SyntaxRewriters; @@ -12,6 +14,27 @@ partial class ShaderSourceRewriter /// public bool NeedsD2DRequiresScenePositionAttribute { get; private set; } + /// + private partial SyntaxNode RewriteSampledTextureAccess(IInvocationOperation operation, InvocationExpressionSyntax node, string? mappedType) + { + // Get the syntax for the argument syntax transformation (to pack arguments if needed, just like in the DX12 rewriter) + ArgumentSyntax coordinateSyntax = mappedType switch + { + not null => Argument(InvocationExpression(IdentifierName(mappedType!), ArgumentList(node.ArgumentList.Arguments))), + null => node.ArgumentList.Arguments[0] + }; + + string fieldName = (operation.Instance as IFieldReferenceOperation)?.Member.Name ?? ""; + + _ = HlslKnownKeywords.TryGetMappedName(fieldName, out string? mapped); + + // Transform an indexer syntax into a sampling call with the implicit static linear sampler. + // For instance: texture.Sample(uv) will be rewritten as texture.Sample(__sampler__texture, uv). + return + InvocationExpression(node.Expression) + .AddArgumentListArguments(Argument(IdentifierName($"__sampler__{mapped ?? fieldName}")), coordinateSyntax); + } + /// private partial void TrackKnownPropertyAccess(IMemberReferenceOperation operation, MemberAccessExpressionSyntax node, string mappedName) { diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs index abd9e52f..e487032c 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs @@ -251,12 +251,6 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter return updatedNode.WithArgumentList(BracketedArgumentList(SingletonSeparatedList(Argument(index)))); } - // Rewrite texture resource sampled accesses, if needed - if (HlslKnownProperties.TryGetMappedResourceSamplerAccessType(propertyName, out mapping)) - { - return RewriteSampledTextureAccess(operation, updatedNode, mapping); - } - // If the current property is a swizzled matrix indexer, ensure all the arguments are constants, and rewrite // the property access to the corresponding HLSL syntax. For instance, m[M11, M12] will become m._m00_m01. if (HlslKnownProperties.IsKnownMatrixIndexer(propertyName)) @@ -331,13 +325,4 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter return updatedToken.WithoutTrivia(); } - - /// - /// Rewrites a sampled texture access. - /// - /// The instance for the sampled texture access. - /// The input instance for the node to rewrite. - /// The mapped type name to use for the sampled access, if any. - /// A representing the rewritten sampled texture access. - private partial SyntaxNode RewriteSampledTextureAccess(IPropertyReferenceOperation operation, ElementAccessExpressionSyntax node, string? mappedType); } diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs index afc989db..d4bfbc6d 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs @@ -344,56 +344,62 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter { var updatedNode = (InvocationExpressionSyntax)base.VisitInvocationExpression(node)!; - if (SemanticModel.For(node).GetOperation(node) is IInvocationOperation operation && - operation.TargetMethod is IMethodSymbol method && - method.IsStatic) + if (SemanticModel.For(node).GetOperation(node) is IInvocationOperation { TargetMethod: IMethodSymbol method } operation) { string metadataName = method.GetFullMetadataName(); - // If the invocation consists of invoking a static method that has a direct - // mapping to HLSL, rewrite the expression in the current invocation node. - // For instance: Math.Abs(expr) => abs(expr). - if (HlslKnownMethods.TryGetMappedName(metadataName, out string? mapping)) + if (method.IsStatic) { - // Allow specialized types to track the method invocation, if needed - TrackKnownMethodInvocation(metadataName); - - return updatedNode.WithExpression(ParseExpression(mapping!)); - } - - // Update the name if the target is a local function. The exact schema for the - // 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}"; - - return updatedNode.WithExpression(ParseExpression(functionIdentifier)); - } - - // If the method is an external static method, import and rewrite it as well. - // This assumes that the target method is actually part of the same compilation. - // We need to check the declaring type to avoid rewriting static methods in the shader - // type as well, as they will be processed by the generator in a different path. - if (!SymbolEqualityComparer.Default.Equals(this.shaderType, method.ContainingType)) - { - var methodIdentifier = method.GetFullMetadataName().ToHlslIdentifierName(); - - if (!this.staticMethods.ContainsKey(method)) + // If the invocation consists of invoking a static method that has a direct + // mapping to HLSL, rewrite the expression in the current invocation node. + // For instance: Math.Abs(expr) => abs(expr). + if (HlslKnownMethods.TryGetMappedName(metadataName, out string? mapping)) { - if (method.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() is not MethodDeclarationSyntax methodNode) - { - Diagnostics.Add(InvalidMethodCall, node, method); + // Allow specialized types to track the method invocation, if needed + TrackKnownMethodInvocation(metadataName); - return updatedNode; - } - - ShaderSourceRewriter shaderSourceRewriter = new(SemanticModel, DiscoveredTypes, this.staticMethods, ConstantDefinitions, Diagnostics); - MethodDeclarationSyntax processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace(eol: "\n").WithoutTrivia(); - - this.staticMethods.Add(method, processedMethod.WithIdentifier(Identifier(methodIdentifier))); + return updatedNode.WithExpression(ParseExpression(mapping!)); } - return updatedNode.WithExpression(ParseExpression(methodIdentifier)); + // Update the name if the target is a local function. The exact schema for the + // 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}"; + + return updatedNode.WithExpression(ParseExpression(functionIdentifier)); + } + + // If the method is an external static method, import and rewrite it as well. + // This assumes that the target method is actually part of the same compilation. + // We need to check the declaring type to avoid rewriting static methods in the shader + // type as well, as they will be processed by the generator in a different path. + if (!SymbolEqualityComparer.Default.Equals(this.shaderType, method.ContainingType)) + { + var methodIdentifier = method.GetFullMetadataName().ToHlslIdentifierName(); + + if (!this.staticMethods.ContainsKey(method)) + { + if (method.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() is not MethodDeclarationSyntax methodNode) + { + Diagnostics.Add(InvalidMethodCall, node, method); + + return updatedNode; + } + + ShaderSourceRewriter shaderSourceRewriter = new(SemanticModel, DiscoveredTypes, this.staticMethods, ConstantDefinitions, Diagnostics); + MethodDeclarationSyntax processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace(eol: "\n").WithoutTrivia(); + + this.staticMethods.Add(method, processedMethod.WithIdentifier(Identifier(methodIdentifier))); + } + + return updatedNode.WithExpression(ParseExpression(methodIdentifier)); + } + } + else if (HlslKnownMethods.TryGetMappedResourceSamplerAccessType(metadataName, out string? mapping)) + { + // Rewrite texture resource sampled accesses, if needed + return RewriteSampledTextureAccess(operation, updatedNode, mapping); } } @@ -423,6 +429,17 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter return updatedNode; } + + + /// + /// Rewrites a sampled texture access. + /// + /// The instance for the sampled texture access. + /// The input instance for the node to rewrite. + /// The mapped type name to use for the sampled access, if any. + /// A representing the rewritten sampled texture access. + private partial SyntaxNode RewriteSampledTextureAccess(IInvocationOperation operation, InvocationExpressionSyntax node, string? mappedType); + /// /// Tracks a property access to a known HLSL property. /// diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs deleted file mode 100644 index d0d8f78c..00000000 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs +++ /dev/null @@ -1,42 +0,0 @@ -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Operations; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -namespace ComputeSharp.SourceGeneration.SyntaxRewriters; - -/// -partial class HlslSourceRewriter -{ - /// - /// Gets whether or not the shader uses a texture sampler at least once. - /// - public bool IsSamplerUsed { get; private set; } - - /// - private partial SyntaxNode RewriteSampledTextureAccess(IPropertyReferenceOperation operation, ElementAccessExpressionSyntax node, string? mappedType) - { - IsSamplerUsed = true; - - // Get the syntax for the argument syntax transformation as described above - ArgumentSyntax coordinateSyntax = mappedType switch - { - not null => Argument(InvocationExpression(IdentifierName(mappedType!), ArgumentList(node.ArgumentList.Arguments))), - null => node.ArgumentList.Arguments[0] - }; - - // Transform an indexer syntax into a sampling call with the implicit static linear sampler. - // For instance: texture[uv] will be rewritten as texture.SampleLevel(__sampler, uv, 0). - return - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - node.Expression, - IdentifierName("SampleLevel"))) - .AddArgumentListArguments( - Argument(IdentifierName("__sampler")), - coordinateSyntax, - Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))); - } -} diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 9ce11b03..9f48c11b 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -1,9 +1,11 @@ using System; using ComputeSharp.SourceGeneration.Extensions; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Operations; using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.SourceGeneration.SyntaxRewriters; @@ -25,6 +27,33 @@ partial class ShaderSourceRewriter /// public bool IsGridIdsUsed { get; set; } + /// + /// Gets whether or not the shader uses a texture sampler at least once. + /// + public bool IsSamplerUsed { get; private set; } + + /// + private partial SyntaxNode RewriteSampledTextureAccess(IInvocationOperation operation, InvocationExpressionSyntax node, string? mappedType) + { + IsSamplerUsed = true; + + // Get the syntax for the argument syntax transformation (adding the vector type constructor if needed) + ArgumentSyntax coordinateSyntax = mappedType switch + { + not null => Argument(InvocationExpression(IdentifierName(mappedType!), ArgumentList(node.ArgumentList.Arguments))), + null => node.ArgumentList.Arguments[0] + }; + + // Transform a method invocation syntax into a sampling call with the implicit static linear sampler. + // For instance: texture.Sample(uv) will be rewritten as texture.SampleLevel(__sampler, uv, 0). + return + InvocationExpression(((MemberAccessExpressionSyntax)node.Expression).WithName(IdentifierName("SampleLevel"))) + .AddArgumentListArguments( + Argument(IdentifierName("__sampler")), + coordinateSyntax, + Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))); + } + /// private partial void TrackKnownPropertyAccess(IMemberReferenceOperation operation, MemberAccessExpressionSyntax node, string mappedName) {