using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Globalization; using System.Linq; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; using ComputeSharp.SourceGeneration.Models; 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; /// /// A custom type that processes C# methods to convert to HLSL compliant code. /// internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter { /// /// The type symbol for the shader type. /// private readonly INamedTypeSymbol? shaderType; /// /// The collection of discovered static methods. /// private readonly IDictionary staticMethods; /// /// The collection of discovered instance methods for custom struct types. /// private readonly IDictionary instanceMethods; /// /// The collection of processed local functions in the current tree. /// private readonly Dictionary localFunctions; /// /// The list of implicit variables to declare at the start of the body. /// private readonly List implicitVariables; /// /// Whether or not the current instance is processing a shader entry point. /// private readonly bool isEntryPoint; /// /// The identifier of the current or tree being visited. /// private SyntaxToken currentMethodIdentifier; /// /// The current depth inside local declarations. /// private int localFunctionDepth; /// /// Creates a new instance with the specified parameters. /// /// The type symbol for the shader type. /// The instance for the target syntax tree. /// The set of discovered custom types. /// The set of discovered and processed static methods. /// The collection of discovered instance methods for custom struct types. /// The collection of discovered constant definitions. /// The collection of produced instances. /// Whether or not the current instance is processing a shader entry point. public ShaderSourceRewriter( INamedTypeSymbol shaderType, SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary staticMethods, IDictionary instanceMethods, IDictionary constantDefinitions, ImmutableArray.Builder diagnostics, bool isEntryPoint) : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) { this.shaderType = shaderType; this.staticMethods = staticMethods; this.instanceMethods = instanceMethods; this.localFunctions = new(); this.implicitVariables = new(); this.isEntryPoint = isEntryPoint; } /// /// Creates a new instance with the specified parameters. /// /// The instance for the target syntax tree. /// The set of discovered custom types. /// The set of discovered and processed static methods. /// The collection of discovered instance methods for custom struct types. /// The collection of discovered constant definitions. /// The collection of produced instances. public ShaderSourceRewriter( SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary staticMethods, IDictionary instanceMethods, IDictionary constantDefinitions, ImmutableArray.Builder diagnostics) : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) { this.staticMethods = staticMethods; this.instanceMethods = instanceMethods; this.implicitVariables = new(); this.localFunctions = new(); } /// /// Gets the collection of processed local functions in the current tree. /// public IReadOnlyDictionary LocalFunctions => this.localFunctions; /// public MethodDeclarationSyntax? Visit(MethodDeclarationSyntax? node) { if (node is null) { return null; } this.currentMethodIdentifier = node.Identifier; var updatedNode = (MethodDeclarationSyntax?)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()); // Add the tracked implicit declarations (at the start of the body) updatedNode = updatedNode.WithBody(implicitBlock).AddBodyStatements(updatedNode.Body!.Statements.ToArray()); } 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) { var updatedNode = (ParameterSyntax)base.VisitParameter(node)!; // Convert the C# parameter modifiers to the HLSL equivalent SyntaxToken modifier = node.Modifiers .Where(static m => m.Kind() is SyntaxKind.OutKeyword or SyntaxKind.RefKeyword or SyntaxKind.InKeyword) .Select(static m => m.Kind() switch { SyntaxKind.OutKeyword => m, SyntaxKind.InKeyword => m, SyntaxKind.RefKeyword => ParseToken("inout"), _ => Token(SyntaxKind.None) }).FirstOrDefault(); return updatedNode .WithAttributeLists(default) .ReplaceAndTrackType(updatedNode.Type!, node.Type!, SemanticModel.For(node), DiscoveredTypes) .WithModifiers(TokenList(modifier)); } /// public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node) { var updatedNode = ((LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node)!); if (SemanticModel.For(node).GetOperation(node) is IOperation { Kind: OperationKind.UsingDeclaration }) { Diagnostics.Add(UsingStatementOrDeclaration, node); } return updatedNode.ReplaceAndTrackType(updatedNode.Declaration.Type, node.Declaration.Type, SemanticModel.For(node), DiscoveredTypes); } /// public override SyntaxNode? VisitDeclarationExpression(DeclarationExpressionSyntax node) { var updatedNode = (DeclarationExpressionSyntax)base.VisitDeclarationExpression(node)!; updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); // Add the variable to the list of implicit declarations this.implicitVariables.Add(VariableDeclaration(updatedNode.Type).AddVariables(VariableDeclarator(updatedNode.Designation.ToString()))); return IdentifierName(updatedNode.Designation.ToString()); } /// public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node) { return ((MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!) .WithBlockBody() .WithoutAccessibilityModifiers() .WithAttributeLists(List()); } /// public override SyntaxNode? VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) { // 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) { var updatedNode = ((LocalFunctionStatementSyntax)base.VisitLocalFunctionStatement(node)!) .WithBlockBody() .WithAttributeLists(List()); 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 { 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; } } /// public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node) { var updatedNode = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node)!; if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) && SemanticModel.For(node).GetOperation(node) is IMemberReferenceOperation operation) { if (operation is IFieldReferenceOperation fieldOperation) { // If the member access is a constant, track it and replace the tree with the processed constant name if (fieldOperation.Field.IsConst && fieldOperation.Type!.TypeKind != TypeKind.Enum) { if (HlslKnownFields.TryGetMappedName(fieldOperation.Member.ToDisplayString(), out string? constantLiteral)) { return ParseExpression(constantLiteral!); } ConstantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture); var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); var constantName = $"__{ownerTypeName}__{fieldOperation.Field.Name}"; return IdentifierName(constantName); } // If the member access is a this. access, rewrite it to strip "this." if (node.Expression.IsKind(SyntaxKind.ThisExpression)) { return updatedNode.Name; } } // If the current member access is a field or property access, check the lookup table // to see if the member should be rewritten for HLSL compliance, and rewrite if needed. if (HlslKnownProperties.TryGetMappedName(operation.Member.ToDisplayString(), out string? mapping)) { // Allow specialized rewriters to track the property, if needed (eg. to emit diagnostics) TrackKnownPropertyAccess(operation, node, mapping!); // Static and instance members are handled differently, with static members being // converted into a literal expression, and instance getting an updated identifier. // For instance, consider these three cases: // - Vector3.One (static) => float3(1.0f, 1.0f, 1.0f) // - ThreadIds.X (custom) => ThreadIds.x // - uint3.X (instance) => [arg].x return operation.Member.IsStatic switch { true => ParseExpression(mapping!), 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; } /// public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node) { var updatedNode = (InvocationExpressionSyntax)base.VisitInvocationExpression(node)!; if (SemanticModel.For(node).GetOperation(node) is IInvocationOperation { TargetMethod: IMethodSymbol method } operation) { if (method.IsStatic) { 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, out bool requiresParametersMapping)) { if (requiresParametersMapping) { mapping = HlslKnownMethods.GetMappedNameWithParameters(method.Name, method.Parameters.Select(static p => p.Type.Name)); } // Allow specialized types to track the method invocation, if needed TrackKnownMethodInvocation(metadataName); return updatedNode.WithExpression(IdentifierName(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.currentMethodIdentifier.Text}__{method.Name}"; return updatedNode.WithExpression(IdentifierName(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, this.instanceMethods, ConstantDefinitions, Diagnostics); MethodDeclarationSyntax processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace(eol: "\n").WithoutTrivia(); this.staticMethods.Add(method, processedMethod.WithIdentifier(Identifier(methodIdentifier))); } return updatedNode.WithExpression(IdentifierName(methodIdentifier)); } } else { string metadataName = method.GetFullMetadataName(includeParameters: true); // Check whether this is a Sample(...) call on a normalized texture type if (HlslKnownMethods.TryGetMappedResourceSamplerAccessType(metadataName, out string? mapping)) { // Get the syntax for the argument syntax transformation (adding the vector type constructor if needed) ArgumentSyntax coordinateSyntax = mapping switch { not null => Argument(InvocationExpression(IdentifierName(mapping!), ArgumentList(updatedNode.ArgumentList.Arguments))), null => updatedNode.ArgumentList.Arguments[0] }; // Rewrite texture resource sampled accesses, if needed return RewriteSampledTextureAccess(operation, updatedNode.Expression, coordinateSyntax); } // If the instance is a struct type that is available in source, rewrite the instance method. // This path is only taken for instance methods for external struct types, not the shader itself. if (operation.TargetMethod.ContainingType is { TypeKind: TypeKind.Struct } structTypeSymbol && !SymbolEqualityComparer.Default.Equals(this.shaderType, structTypeSymbol)) { DiscoveredTypes.Add(structTypeSymbol); var methodIdentifier = method.GetFullMetadataName().ToHlslIdentifierName(); // Same as for static methods, ensure the method is available in source, and process it if so if (!this.instanceMethods.ContainsKey(method)) { if (method.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() is not MethodDeclarationSyntax methodNode) { Diagnostics.Add(InvalidMethodCall, node, method); return updatedNode; } ShaderSourceRewriter shaderSourceRewriter = new(SemanticModel, DiscoveredTypes, this.instanceMethods, this.instanceMethods, ConstantDefinitions, Diagnostics); MethodDeclarationSyntax processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace(eol: "\n").WithoutTrivia(); this.instanceMethods.Add(method, processedMethod.WithIdentifier(Identifier(methodIdentifier))); } // Rewrite the expression depending on its type: // - If it's a simple member expression, change the identifier name: eg. foo.Bar(...) => foo.NewName(...) // - If it's an identifier name, change it directly: eg. Bar(...) => NewName(...) return updatedNode.Expression switch { MemberAccessExpressionSyntax memberAccess => updatedNode.WithExpression(memberAccess.WithName(IdentifierName(methodIdentifier))), IdentifierNameSyntax identifierName => updatedNode.WithExpression(IdentifierName(methodIdentifier)), _ => throw new NotSupportedException($"Unsupported instance method expression type \"{updatedNode.Expression.GetType()}\".") }; } } } return updatedNode; } /// public override SyntaxNode? VisitArgument(ArgumentSyntax node) { var updatedNode = (ArgumentSyntax)base.VisitArgument(node)!; // Strip the ref keywords from arguments updatedNode = updatedNode.WithRefKindKeyword(Token(SyntaxKind.None)); // Track and rewrite the discarded declaration if (SemanticModel.For(node).GetOperation(node.Expression) is IDiscardOperation operation) { TypeSyntax typeSyntax = ParseTypeName(HlslKnownTypes.TrackType(operation.Type!, DiscoveredTypes)); string identifier = $"__implicit{this.implicitVariables.Count}"; // Add the variable to the list of implicit declarations this.implicitVariables.Add(VariableDeclaration(typeSyntax).AddVariables(VariableDeclarator(identifier))); return updatedNode.WithExpression(IdentifierName(identifier)); } return updatedNode; } /// /// Rewrites a sampled texture access. /// /// The instance for the sampled texture access. /// The input instance for the node to rewrite. /// The input with the updated arguments for the expression to rewrite. /// A representing the rewritten sampled texture access. private partial SyntaxNode RewriteSampledTextureAccess(IInvocationOperation operation, ExpressionSyntax expression, ArgumentSyntax arguments); /// /// Tracks a property access to a known HLSL property. /// /// The instance for the operation. /// The instance for the operation. /// The mapped name for the property access. private partial void TrackKnownPropertyAccess(IMemberReferenceOperation operation, MemberAccessExpressionSyntax node, string mappedName); /// /// Tracks a method invocation for a known HLSL method. /// /// The metadata name of the method being invoked. private partial void TrackKnownMethodInvocation(string metadataName); }