From 3d7c4c7cb6f37121e02cf7d5cf9e5525d9c8c12a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 25 Nov 2020 18:40:50 +0100 Subject: [PATCH] Implemented SG-powered mapping of captured fields --- .../Attributes/IComputeShaderSource.cs | 34 +++- .../Translation/ShaderLoader{T}.cs | 21 ++- .../IComputeShaderSourceAttributeGenerator.cs | 147 ++++++++++++------ 3 files changed, 135 insertions(+), 67 deletions(-) diff --git a/src/ComputeSharp.Core/Attributes/IComputeShaderSource.cs b/src/ComputeSharp.Core/Attributes/IComputeShaderSource.cs index 3978ffee..e0c62ded 100644 --- a/src/ComputeSharp.Core/Attributes/IComputeShaderSource.cs +++ b/src/ComputeSharp.Core/Attributes/IComputeShaderSource.cs @@ -1,5 +1,9 @@ using System; +using System.Collections.Generic; using System.ComponentModel; +using System.Diagnostics.Contracts; +using System.Linq; +using System.Reflection; namespace ComputeSharp { @@ -18,26 +22,40 @@ namespace ComputeSharp /// The fully qualified name of the shader type. /// The name of the current method. /// The source code of the target method. - public IComputeShaderSourceAttribute(string shaderTypeName, string methodName, string source) + public IComputeShaderSourceAttribute(string shaderTypeName, object[] args, object[] methods) { ShaderTypeName = shaderTypeName; - MethodName = methodName; - Source = source; + Fields = args.Cast().ToDictionary(static arg => arg[0], static arg => arg[1]); + Methods = methods.Cast().ToDictionary(static method => method[0], static method => method[1]); } /// /// Gets the fully qualified name of the shader type. /// - public string ShaderTypeName { get; } + internal string ShaderTypeName { get; } /// - /// Gets the name of the current method. + /// Gets the mapping of field names. /// - public string MethodName { get; } + internal IReadOnlyDictionary Fields { get; } /// - /// Gets the source code of the target method. + /// Gets the mapping of methods and their source code. /// - public string Source { get; } + internal IReadOnlyDictionary Methods { get; } + + /// + /// Gets the associated instance for a specified type. + /// + /// The shader type to get the attribute for. + /// The associated instance for type . + [Pure] + internal static IComputeShaderSourceAttribute GetForType() + { + return ( + from attribute in typeof(T).Assembly.GetCustomAttributes() + where attribute.ShaderTypeName == typeof(T).FullName + select attribute).Single(); + } } } \ No newline at end of file diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index 39560f40..a65f7e77 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -25,6 +25,11 @@ namespace ComputeSharp.Shaders.Translation internal sealed partial class ShaderLoader where T : struct, IComputeShader { + /// + /// The associated instance for the current shader type. + /// + private static IComputeShaderSourceAttribute Attribute = IComputeShaderSourceAttribute.GetForType(); + /// /// The number of constant buffers to define in the shader. /// @@ -126,7 +131,7 @@ namespace ComputeSharp.Shaders.Translation object box = shader; @this.LoadFieldsInfo(box); - @this.LoadMethodSource(box); + @this.LoadMethodSource(); @this.BuildDispatchDataLoader(); return @this; @@ -166,11 +171,10 @@ namespace ComputeSharp.Shaders.Translation /// /// The boxed instance to use to build the shader /// The target to load - /// The optional explicit name to use for the field - private void LoadFieldInfo(object shader, ReadableMember memberInfo, string? name = null) + private void LoadFieldInfo(object shader, ReadableMember memberInfo) { Type fieldType = memberInfo.MemberType; - string fieldName = name; // TODO: implement this for SG + string fieldName = Attribute.Fields[memberInfo.Name]; // Constant buffer if (HlslKnownTypes.IsConstantBufferType(fieldType)) @@ -235,14 +239,9 @@ namespace ComputeSharp.Shaders.Translation /// /// Loads the entry method for the current shader being loaded /// - /// The boxed instance to use to build the shader - private void LoadMethodSource(object shader) + private void LoadMethodSource() { - EntryPoint = ( - from attribute in typeof(T).Assembly.GetCustomAttributes() - where attribute.ShaderTypeName == typeof(T).FullName && - attribute.MethodName == nameof(IComputeShader.Execute) - select attribute.Source).First(); + EntryPoint = Attribute.Methods[nameof(IComputeShader.Execute)]; } } } diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceAttributeGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceAttributeGenerator.cs index b6c14153..1847e4fd 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceAttributeGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceAttributeGenerator.cs @@ -1,6 +1,9 @@ -using System.Collections.Immutable; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.Contracts; using System.Linq; using System.Text; +using ComputeSharp.Shaders.Mappings; using ComputeSharp.SourceGenerators.Extensions; using ComputeSharp.SourceGenerators.SyntaxRewriters; using Microsoft.CodeAnalysis; @@ -36,56 +39,104 @@ 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; - var structFullName = structDeclarationSymbol.GetFullMetadataName(); - - // Find all declared methods in the type - ImmutableArray methodDeclarations = ( - from syntaxNode in structDeclaration.DescendantNodes() - where syntaxNode.IsKind(SyntaxKind.MethodDeclaration) - select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray(); - - foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) + // Helper that converts a sequence of string pairs into a nested array expression. + // That is, this applies the following transformation: + // - { ("K1", "V1"), ("K2", "V2") } => new object[] { new[] { "K1", "V1" }, new[] { "K2", "V2" } } + static ArrayCreationExpressionSyntax NestedPairsArrayExpression(IEnumerable<(string Key, string Value)> pairs) { - IMethodSymbol methodDeclarationSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration)!; - - // Rewrite the method syntax tree - var processedMethod = new ShaderSourceRewriter(semanticModel).Visit(methodDeclaration)!.WithoutTrivia(); - - // If the method is the shader entry point, do additional processing - if (methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) && - methodDeclarationSymbol.ReturnsVoid && - methodDeclarationSymbol.TypeParameters.Length == 0 && - methodDeclarationSymbol.Parameters.Length == 1 && - methodDeclarationSymbol.Parameters[0].Type.ToDisplayString() == typeof(ThreadIds).FullName) - { - var parameterName = methodDeclarationSymbol.Parameters[0].Name; - - processedMethod = new ExecuteMethodRewriter(parameterName).Visit(processedMethod)!; - } - - // Produce the final method source - var processedMethodSource = processedMethod.NormalizeWhitespace().ToFullString(); - - // Create the compilation unit with the source attribute - var source = - CompilationUnit().AddAttributeLists( - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName(typeof(IComputeShaderSourceAttribute).FullName)).AddArgumentListArguments( - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(structFullName))), - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodDeclarationSymbol.Name))), - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(processedMethodSource)))))) - .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) - .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) - .NormalizeWhitespace() - .ToFullString(); - - var generatedFileName = $"__ComputeSharp_{nameof(IComputeShaderSourceAttribute)}_{structDeclarationSymbol.Name}_{methodDeclarationSymbol.Name}"; - - // Add the method source attribute - context.AddSource(generatedFileName, SourceText.From(source, Encoding.UTF8)); + return + ArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ObjectKeyword))) + .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) + .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) + .AddExpressions(pairs.Select(pair => + ImplicitArrayCreationExpression(InitializerExpression(SyntaxKind.ArrayInitializerExpression).AddExpressions( + LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(pair.Key)), + LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(pair.Value))))).ToArray())); } + + // Create the compilation unit with the source attribute + var source = + CompilationUnit().AddAttributeLists( + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName(typeof(IComputeShaderSourceAttribute).FullName)).AddArgumentListArguments( + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(structDeclarationSymbol.GetFullMetadataName()))), + AttributeArgument(NestedPairsArrayExpression(GetProcessedMembers(structDeclarationSymbol))), + AttributeArgument(NestedPairsArrayExpression(GetProcessedMethods(structDeclaration, semanticModel)))))) + .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) + .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) + .NormalizeWhitespace() + .ToFullString(); + + var generatedFileName = $"__ComputeSharp_{nameof(IComputeShaderSourceAttribute)}_{structDeclarationSymbol.Name}"; + + // Add the method source attribute + context.AddSource(generatedFileName, SourceText.From(source, Encoding.UTF8)); + } + } + + /// + /// Gets a sequence of captured members and their mapped names. + /// + /// The input instance to process. + /// A sequence of captured members in . + [Pure] + private static IEnumerable<(string Key, string Value)> GetProcessedMembers(INamedTypeSymbol structDeclarationSymbol) + { + foreach (string memberName in ( + from member in structDeclarationSymbol.GetMembers() + where member.Kind == SymbolKind.Field || + member.Kind == SymbolKind.Property + select member.Name).Distinct()) + { + _ = HlslKnownKeywords.TryGetMappedName(memberName, out string? mapping); + + yield return (memberName, mapping ?? memberName); + } + } + + /// + /// Gets a sequence of processed methods declared within a given type. + /// + /// The instance for the current type. + /// The instance for the type to process. + /// A sequence of processed methods in . + [Pure] + private static IEnumerable<(string Key, string Value)> GetProcessedMethods( + StructDeclarationSyntax structDeclaration, + SemanticModel semanticModel) + { + // Find all declared methods in the type + ImmutableArray methodDeclarations = ( + from syntaxNode in structDeclaration.DescendantNodes() + where syntaxNode.IsKind(SyntaxKind.MethodDeclaration) + select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray(); + + foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) + { + IMethodSymbol methodDeclarationSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration)!; + + // Rewrite the method syntax tree + var processedMethod = new ShaderSourceRewriter(semanticModel).Visit(methodDeclaration)!.WithoutTrivia(); + + // If the method is the shader entry point, do additional processing + if (methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) && + methodDeclarationSymbol.ReturnsVoid && + methodDeclarationSymbol.TypeParameters.Length == 0 && + methodDeclarationSymbol.Parameters.Length == 1 && + methodDeclarationSymbol.Parameters[0].Type.ToDisplayString() == typeof(ThreadIds).FullName) + { + var parameterName = methodDeclarationSymbol.Parameters[0].Name; + + processedMethod = new ExecuteMethodRewriter(parameterName).Visit(processedMethod)!; + } + + // Produce the final method source + var processedMethodSource = processedMethod.NormalizeWhitespace().ToFullString(); + + yield return (methodDeclarationSymbol.Name, processedMethodSource); } } }