diff --git a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index b6e4504d..a45647db 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -264,6 +264,56 @@ internal sealed class ShaderSourceRewriter : HlslSourceRewriter false => updatedNode.WithName(IdentifierName(mapping!)) }; } + + // If the current member access is an access to any of the size properties in the available + // resource types (either buffer or texture types), then rewrite the subtree to transform the + // property access into an invocation of an autogenerated static helper method to get the target + // dimension for the buffer in use. The helper method is added to the list of static helpers. + if (operation is IPropertyReferenceOperation propertyOperation && + HlslKnownProperties.TryGetAccessorRankAndAxis(propertyOperation.Property.GetFullMetadataName(), out int rank, out int axis)) + { + IMethodSymbol key = propertyOperation.Property.GetMethod!; + + if (!this.staticMethods.TryGetValue(key, out MethodDeclarationSyntax? methodSyntax)) + { + INamedTypeSymbol resourceType = (INamedTypeSymbol)SemanticModel.For(node).GetTypeInfo(node.Expression).Type!; + string resourceName = HlslKnownTypes.GetMappedName(resourceType); + + // Create a static method to get a specified dimension for a target resource type. + // The method will automatically create the necessary number of temporary variables + // depending on the rank of the input resource (eg. 2 for Texture2D resources). + // For instance, this code will generate the following tree for Texture2D.Width: + // + // static int __get_Dimension0(Texture2D texture) + // { + // uint _0, _1; + // texture.GetDimensions(_0, _1); + // + // return _0; + // } + methodSyntax = + MethodDeclaration(PredefinedType(Token(SyntaxKind.IntKeyword)), $"__get_Dimension{axis}") + .AddModifiers(Token(SyntaxKind.StaticKeyword)) + .AddParameterListParameters( + Parameter(Identifier("resource")) + .WithType(IdentifierName(resourceName))) + .WithBody(Block( + LocalDeclarationStatement( + VariableDeclaration(PredefinedType(Token(SyntaxKind.UIntKeyword))) + .AddVariables(Enumerable.Range(0, rank).Select(static i => VariableDeclarator(Identifier("_" + i))).ToArray())), + ExpressionStatement( + InvocationExpression(MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("resource"), + IdentifierName("GetDimensions"))) + .AddArgumentListArguments(Enumerable.Range(0, rank).Select(static i => Argument(IdentifierName("_" + i))).ToArray())), + ReturnStatement(IdentifierName("_" + axis)))); + + this.staticMethods.Add(key, methodSyntax); + } + + return InvocationExpression(IdentifierName(methodSyntax.Identifier)).AddArgumentListArguments(Argument(updatedNode.Expression)); + } } return updatedNode;