From 83d64d4db8b307fba02ab9894b7b807f7e09ed76 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 27 Nov 2020 19:52:59 +0100 Subject: [PATCH] Added discovery of types in a shader --- .../Extensions/SyntaxNodeExtensions.cs | 10 +++--- .../IComputeShaderSourceAttributeGenerator.cs | 34 ++++++++++++------- .../Mappings/HlslKnownTypes.cs | 17 +++++++--- .../SyntaxRewriters/ShaderSourceRewriter.cs | 19 ++++++++++- 4 files changed, 58 insertions(+), 22 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs index caaccb89..529fbaaf 100644 --- a/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs +++ b/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs @@ -48,15 +48,17 @@ namespace ComputeSharp.SourceGenerators.Extensions public static TRoot ReplaceType(this TRoot node, TypeSyntax targetType, SyntaxNode sourceType, SemanticModel semanticModel) where TRoot : SyntaxNode { - if (semanticModel.GetTypeInfo(sourceType).Type is ITypeSymbol typeSymbol && - HlslKnownTypes.TryGetMappedName(typeSymbol.ToDisplayString(FullyQualifiedWithoutGlobalFormat), out string? mappedName)) + ITypeSymbol typeSymbol = semanticModel.GetTypeInfo(sourceType).Type!; + string typeName = typeSymbol.ToDisplayString(FullyQualifiedWithoutGlobalFormat); + + if (HlslKnownTypes.TryGetMappedName(typeName, out string? mappedName)) { TypeSyntax newType = ParseTypeName(mappedName!); return node.ReplaceNode(targetType, newType); } - return node; + return node.ReplaceNode(targetType, ParseTypeName(typeName.Replace(".", "::"))); } /// @@ -77,7 +79,7 @@ namespace ComputeSharp.SourceGenerators.Extensions return ParseTypeName(mappedName!); } - return ParseTypeName(typeName); + return ParseTypeName(typeName.Replace(".", "::")); } /// diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceAttributeGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceAttributeGenerator.cs index eb68b9c5..5299a039 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceAttributeGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceAttributeGenerator.cs @@ -39,7 +39,10 @@ namespace ComputeSharp.SourceGenerators INamedTypeSymbol structDeclarationSymbol = semanticModel.GetDeclaredSymbol(structDeclaration)!; // Only process compute shader types - if (!structDeclarationSymbol.Interfaces.Any(interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader))) continue; + if (!structDeclarationSymbol.Interfaces.Any(interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader))) continue; + + // The list to use to track all discovered custom types + HashSet discoveredTypes = new(SymbolEqualityComparer.Default); // Helper that converts a sequence of string pairs into a nested array expression. // That is, this applies the following transformation: @@ -63,8 +66,8 @@ namespace ComputeSharp.SourceGenerators AttributeList(SingletonSeparatedList( Attribute(IdentifierName(typeof(IComputeShaderSourceAttribute).FullName)).AddArgumentListArguments( AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(structDeclarationSymbol.GetFullMetadataName()))), - AttributeArgument(NestedPairsArrayExpression(GetProcessedMembers(structDeclarationSymbol))), - AttributeArgument(NestedPairsArrayExpression(GetProcessedMethods(structDeclaration, semanticModel)))))) + AttributeArgument(NestedPairsArrayExpression(GetProcessedMembers(structDeclarationSymbol, discoveredTypes))), + AttributeArgument(NestedPairsArrayExpression(GetProcessedMethods(structDeclaration, semanticModel, discoveredTypes)))))) .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) .NormalizeWhitespace() @@ -81,17 +84,21 @@ namespace ComputeSharp.SourceGenerators /// The input instance to process. /// A sequence of captured members in . [Pure] - private static IEnumerable<(string Key, string Value)> GetProcessedMembers(INamedTypeSymbol structDeclarationSymbol) + private static IEnumerable<(string Key, string Value)> GetProcessedMembers(INamedTypeSymbol structDeclarationSymbol, HashSet types) { - foreach (string memberName in ( - from member in structDeclarationSymbol.GetMembers() - where member.Kind == SymbolKind.Field || - member.Kind == SymbolKind.Property - select member.Name).Distinct()) + foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { - _ = HlslKnownKeywords.TryGetMappedName(memberName, out string? mapping); + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); - yield return (memberName, mapping ?? memberName); + // Yield back the current mapping for the name (if the name used a reserved keyword) + yield return (fieldSymbol.Name, mapping ?? fieldSymbol.Name); + + // Track the type of items in the current buffer + if (fieldSymbol.Type is INamedTypeSymbol fieldType && + HlslKnownTypes.IsStructuredBufferType(fieldType.GetFullMetadataName())) + { + _ = types.Add((INamedTypeSymbol)fieldType.TypeArguments[0]); + } } } @@ -104,7 +111,8 @@ namespace ComputeSharp.SourceGenerators [Pure] private static IEnumerable<(string Key, string Value)> GetProcessedMethods( StructDeclarationSyntax structDeclaration, - SemanticModel semanticModel) + SemanticModel semanticModel, + HashSet types) { // Find all declared methods in the type ImmutableArray methodDeclarations = ( @@ -115,7 +123,7 @@ namespace ComputeSharp.SourceGenerators foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) { IMethodSymbol methodDeclarationSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration)!; - ShaderSourceRewriter shaderSourceRewriter = new(semanticModel); + ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, types); // Rewrite the method syntax tree var processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia(); diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs index fd21f6f6..7ed2ebd5 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -37,10 +37,7 @@ namespace ComputeSharp.SourceGenerators.Mappings [typeof(double).FullName] = "double", [typeof(Double2).FullName] = "double2", [typeof(Double3).FullName] = "double3", - [typeof(Double4).FullName] = "double4", - [typeof(ThreadIds).FullName] = "uint3", - ["ComputeSharp.ReadOnlyBuffer"] = "StructuredBuffer", - ["ComputeSharp.ReadWriteBuffer"] = "RWStructuredBuffer" + [typeof(Double4).FullName] = "double4" }; /// @@ -55,6 +52,18 @@ namespace ComputeSharp.SourceGenerators.Mappings typeof(Double2), typeof(Double3), typeof(Double4) }); + /// + /// Checks whether or not a given type name matches a structured buffer type. + /// + /// The input type name to check. + /// Whether or not represents a structured buffer type. + public static bool IsStructuredBufferType(string typeName) + { + return + typeName == "ComputeSharp.ReadOnlyBuffer`1" || + typeName == "ComputeSharp.ReadWriteBuffer`1"; + } + /// /// Gets the mapped HLSL-compatible type name for the input type name. /// diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 9edc55c7..b5634739 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -21,6 +21,11 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// private readonly SemanticModel semanticModel; + /// + /// The set of discovered custom types. + /// + private readonly HashSet discoveredTypes; + /// /// The collection of processed local functions in the current tree. /// @@ -35,9 +40,11 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// Creates a new instance with the specified parameters. /// /// The instance for the target syntax tree. - public ShaderSourceRewriter(SemanticModel semanticModel) + /// The set of discovered custom types. + public ShaderSourceRewriter(SemanticModel semanticModel, HashSet discoveredTypes) { this.semanticModel = semanticModel; + this.discoveredTypes = discoveredTypes; this.localFunctions = new(); } @@ -69,6 +76,8 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters { var updatedNode = (CastExpressionSyntax)base.VisitCastExpression(node)!; + _ = this.discoveredTypes.Add((INamedTypeSymbol)this.semanticModel.GetTypeInfo(node.Type).Type!); + return updatedNode.ReplaceType(updatedNode.Type, node.Type, this.semanticModel); } @@ -77,6 +86,8 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters { var updatedNode = ((LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node)!); + _ = this.discoveredTypes.Add((INamedTypeSymbol)this.semanticModel.GetTypeInfo(node.Declaration.Type).Type!); + return updatedNode.ReplaceType(updatedNode.Declaration.Type, node.Declaration.Type, this.semanticModel); } @@ -85,6 +96,8 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters { var updatedNode = (ObjectCreationExpressionSyntax)base.VisitObjectCreationExpression(node)!; + _ = this.discoveredTypes.Add((INamedTypeSymbol)this.semanticModel.GetTypeInfo(node.Type).Type!); + updatedNode = updatedNode.ReplaceType(updatedNode.Type, node.Type, this.semanticModel); // New objects use the default HLSL cast syntax, eg. (float4)0 @@ -101,6 +114,8 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters { var updatedNode = (ImplicitObjectCreationExpressionSyntax)base.VisitImplicitObjectCreationExpression(node)!; + _ = this.discoveredTypes.Add((INamedTypeSymbol)this.semanticModel.GetTypeInfo(node).Type!); + TypeSyntax explicitType = IdentifierName("").ReplaceType(node, this.semanticModel); // Mutate the syntax like with explicit object creation expressions @@ -117,6 +132,8 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters { var updatedNode = (DefaultExpressionSyntax)base.VisitDefaultExpression(node)!; + _ = this.discoveredTypes.Add((INamedTypeSymbol)this.semanticModel.GetTypeInfo(node.Type).Type!); + updatedNode = updatedNode.ReplaceType(updatedNode.Type, node.Type, this.semanticModel); // A default expression becomes (T)0 in HLSL