diff --git a/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs index 529fbaaf..9dee6682 100644 --- a/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs +++ b/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs @@ -1,4 +1,5 @@ -using System.Diagnostics.Contracts; +using System.Collections.Generic; +using System.Diagnostics.Contracts; using ComputeSharp.SourceGenerators.Mappings; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -27,12 +28,13 @@ namespace ComputeSharp.SourceGenerators.Extensions /// The input to check and modify if needed. /// The source to use to get type into from . /// The instance with info on the input tree. + /// The collection of currently discovered types. /// A instance that represents a type compatible with HLSL. [Pure] - public static TRoot ReplaceType(this TRoot node, SyntaxNode sourceType, SemanticModel semanticModel) + public static TRoot ReplaceAndTrackType(this TRoot node, SyntaxNode sourceType, SemanticModel semanticModel, ICollection discoveredTypes) where TRoot : TypeSyntax { - return node.ReplaceType(node, sourceType, semanticModel); + return node.ReplaceAndTrackType(node, sourceType, semanticModel, discoveredTypes); } /// @@ -43,14 +45,17 @@ namespace ComputeSharp.SourceGenerators.Extensions /// The target node to replace. /// The source to use to get type into from . /// The instance with info on the input tree. + /// The collection of currently discovered types. /// A instance that represents a type compatible with HLSL. [Pure] - public static TRoot ReplaceType(this TRoot node, TypeSyntax targetType, SyntaxNode sourceType, SemanticModel semanticModel) + public static TRoot ReplaceAndTrackType(this TRoot node, TypeSyntax targetType, SyntaxNode sourceType, SemanticModel semanticModel, ICollection discoveredTypes) where TRoot : SyntaxNode { ITypeSymbol typeSymbol = semanticModel.GetTypeInfo(sourceType).Type!; string typeName = typeSymbol.ToDisplayString(FullyQualifiedWithoutGlobalFormat); + discoveredTypes.Add((INamedTypeSymbol)typeSymbol); + if (HlslKnownTypes.TryGetMappedName(typeName, out string? mappedName)) { TypeSyntax newType = ParseTypeName(mappedName!); @@ -66,14 +71,17 @@ namespace ComputeSharp.SourceGenerators.Extensions /// /// The type of the input instance. /// The input to check and modify if needed. - /// The to use for the input node. + /// The instance with info on the input tree. + /// The collection of currently discovered types. /// A instance that represents a type compatible with HLSL. [Pure] - public static TypeSyntax ReplaceType(this LiteralExpressionSyntax node, SemanticModel semanticModel) + public static TypeSyntax ReplaceAndTrackType(this LiteralExpressionSyntax node, SemanticModel semanticModel, ICollection discoveredTypes) { ITypeSymbol typeSymbol = semanticModel.GetTypeInfo(node).Type!; string typeName = typeSymbol.ToDisplayString(FullyQualifiedWithoutGlobalFormat); + discoveredTypes.Add((INamedTypeSymbol)typeSymbol); + if (HlslKnownTypes.TryGetMappedName(typeName, out string? mappedName)) { return ParseTypeName(mappedName!); diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceAttributeGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceAttributeGenerator.cs index 5299a039..1446f39c 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceAttributeGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceAttributeGenerator.cs @@ -66,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, discoveredTypes))), - AttributeArgument(NestedPairsArrayExpression(GetProcessedMethods(structDeclaration, semanticModel, discoveredTypes)))))) + AttributeArgument(NestedPairsArrayExpression(GetProcessedMembers(structDeclarationSymbol, discoveredTypes).ToArray())), + AttributeArgument(NestedPairsArrayExpression(GetProcessedMethods(structDeclaration, semanticModel, discoveredTypes).ToArray()))))) .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) .NormalizeWhitespace() @@ -82,9 +82,10 @@ namespace ComputeSharp.SourceGenerators /// Gets a sequence of captured members and their mapped names. /// /// The input instance to process. + /// The collection of currently discovered types. /// A sequence of captured members in . [Pure] - private static IEnumerable<(string Key, string Value)> GetProcessedMembers(INamedTypeSymbol structDeclarationSymbol, HashSet types) + private static IEnumerable<(string Key, string Value)> GetProcessedMembers(INamedTypeSymbol structDeclarationSymbol, ICollection types) { foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { @@ -97,7 +98,7 @@ namespace ComputeSharp.SourceGenerators if (fieldSymbol.Type is INamedTypeSymbol fieldType && HlslKnownTypes.IsStructuredBufferType(fieldType.GetFullMetadataName())) { - _ = types.Add((INamedTypeSymbol)fieldType.TypeArguments[0]); + types.Add((INamedTypeSymbol)fieldType.TypeArguments[0]); } } } @@ -107,12 +108,13 @@ namespace ComputeSharp.SourceGenerators /// /// The instance for the current type. /// The instance for the type to process. + /// The collection of currently discovered types. /// A sequence of processed methods in . [Pure] private static IEnumerable<(string Key, string Value)> GetProcessedMethods( StructDeclarationSyntax structDeclaration, SemanticModel semanticModel, - HashSet types) + ICollection types) { // Find all declared methods in the type ImmutableArray methodDeclarations = ( @@ -152,6 +154,42 @@ namespace ComputeSharp.SourceGenerators } } } + + /// + /// Gets the sequence of processed discovered custom types. + /// + /// The sequence of discovered custom types. + /// A sequence of custom type definitions to add to the shader source. + public static IEnumerable GetProcessedTypes(IEnumerable types) + { + foreach (var type in HlslKnownTypes.GetCustomTypes(types)) + { + var structDeclaration = StructDeclaration(type.Name).WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + + // Declare the fields of the current type + foreach (var field in type.GetMembers().OfType()) + { + INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type; + + structDeclaration = structDeclaration.AddMembers( + FieldDeclaration(VariableDeclaration(IdentifierName( + fieldType.GetFullMetadataName())).AddVariables( + VariableDeclarator(Identifier(field.Name))))); + } + + MemberDeclarationSyntax memberDeclaration = structDeclaration; + INamespaceSymbol? currentNamespace = type.ContainingNamespace; + + // Recursively declare the containing namespaces + while (currentNamespace is { IsGlobalNamespace: false }) + { + memberDeclaration = NamespaceDeclaration(IdentifierName(currentNamespace.Name)).AddMembers(memberDeclaration); + currentNamespace = currentNamespace.ContainingNamespace; + } + + yield return memberDeclaration; + } + } } } diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs index 7ed2ebd5..9e5eca2a 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -1,6 +1,8 @@ using System; using System.Collections.Generic; using System.Numerics; +using ComputeSharp.SourceGenerators.Extensions; +using Microsoft.CodeAnalysis; namespace ComputeSharp.SourceGenerators.Mappings { @@ -37,7 +39,8 @@ namespace ComputeSharp.SourceGenerators.Mappings [typeof(double).FullName] = "double", [typeof(Double2).FullName] = "double2", [typeof(Double3).FullName] = "double3", - [typeof(Double4).FullName] = "double4" + [typeof(Double4).FullName] = "double4", + [typeof(ThreadIds).FullName] = "uint3", }; /// @@ -73,5 +76,36 @@ namespace ComputeSharp.SourceGenerators.Mappings { return KnownTypes.TryGetValue(originalName, out mappedName); } + + /// + /// Gets the sequence of unique custom types from a collection of discovered types. + /// + /// The input collection of discovered types. + /// The list of unique custom types. + public static IEnumerable GetCustomTypes(IEnumerable discoveredTypes) + { + // Local function to recursively gather nested types + static void ExploreTypes(INamedTypeSymbol type, HashSet customTypes) + { + if (KnownTypes.ContainsKey(type.GetFullMetadataName())) return; + + customTypes.Add(type); + + foreach (var field in type.GetMembers().OfType()) + { + ExploreTypes((INamedTypeSymbol)field.Type, customTypes); + } + } + + HashSet customTypes = new(SymbolEqualityComparer.Default); + + // Explore all input types and their nested types + foreach (INamedTypeSymbol type in discoveredTypes) + { + ExploreTypes(type, customTypes); + } + + return customTypes; + } } } diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index b5634739..dcc5cd45 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -22,9 +22,9 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters private readonly SemanticModel semanticModel; /// - /// The set of discovered custom types. + /// The collection of discovered custom types. /// - private readonly HashSet discoveredTypes; + private readonly ICollection discoveredTypes; /// /// The collection of processed local functions in the current tree. @@ -41,7 +41,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// /// The instance for the target syntax tree. /// The set of discovered custom types. - public ShaderSourceRewriter(SemanticModel semanticModel, HashSet discoveredTypes) + public ShaderSourceRewriter(SemanticModel semanticModel, ICollection discoveredTypes) { this.semanticModel = semanticModel; this.discoveredTypes = discoveredTypes; @@ -68,7 +68,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters return updatedNode .WithAttributeLists(default) - .ReplaceType(updatedNode.Type!, node.Type!, this.semanticModel); + .ReplaceAndTrackType(updatedNode.Type!, node.Type!, this.semanticModel, this.discoveredTypes); } /// @@ -76,9 +76,7 @@ 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); + return updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, this.semanticModel, this.discoveredTypes); } /// @@ -86,9 +84,7 @@ 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); + return updatedNode.ReplaceAndTrackType(updatedNode.Declaration.Type, node.Declaration.Type, this.semanticModel, this.discoveredTypes); } /// @@ -96,9 +92,7 @@ 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); + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, this.semanticModel, this.discoveredTypes); // New objects use the default HLSL cast syntax, eg. (float4)0 if (updatedNode.ArgumentList!.Arguments.Count == 0) @@ -114,9 +108,7 @@ 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); + TypeSyntax explicitType = IdentifierName("").ReplaceAndTrackType(node, this.semanticModel, this.discoveredTypes); // Mutate the syntax like with explicit object creation expressions if (updatedNode.ArgumentList!.Arguments.Count == 0) @@ -132,9 +124,7 @@ 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); + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, this.semanticModel, this.discoveredTypes); // A default expression becomes (T)0 in HLSL return CastExpression(updatedNode.Type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); @@ -147,8 +137,10 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters if (node.IsKind(SyntaxKind.DefaultLiteralExpression)) { + TypeSyntax type = node.ReplaceAndTrackType(this.semanticModel, this.discoveredTypes); + // Same HLSL-style expression in the form (T)0 - return CastExpression(node.ReplaceType(this.semanticModel), LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); + return CastExpression(type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); } return node;