From 3daafd3e16533f6ab9ca65d6802e4570b524a557 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 10 Jan 2021 18:37:13 +0100 Subject: [PATCH 1/5] Fixed handling of constants in source generators --- .../AutoConstructorGenerator.cs | 9 ++++----- .../IComputeShaderDataLoaderGenerator.cs | 2 ++ 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs b/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs index b82df4d0..40ebf95d 100644 --- a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs @@ -42,12 +42,11 @@ namespace ComputeSharp.SourceGenerators var structName = structDeclaration.Identifier.Text; var structModifiers = structDeclaration.Modifiers; var fields = ( - from fieldDeclaration in structDeclaration.Members.OfType() - let fieldType = fieldDeclaration.Declaration.Type - let typeName = semanticModel.GetTypeInfo(fieldType).Type!.ToDisplayString() + from fieldSymbol in structDeclarationSymbol.GetMembers().OfType() + where !fieldSymbol.IsConst + let typeName = fieldSymbol.Type!.ToDisplayString() let fieldFullType = ParseTypeName(typeName) - from fieldVariable in fieldDeclaration.Declaration.Variables - select (Type: fieldFullType, fieldVariable.Identifier)).ToImmutableArray(); + select (Type: fieldFullType, Identifier: Identifier(fieldSymbol.Name))).ToImmutableArray(); // Create the constructor declaration for the type. This will // produce a constructor with simple initialization of all variables: diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs index 1d1e59ec..2922aa8a 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs @@ -141,6 +141,8 @@ namespace ComputeSharp.SourceGenerators } else if (HlslKnownTypes.IsScalarOrVectorType(typeName)) { + if (fieldSymbol.IsConst) continue; + var (fieldSize, fieldPack) = HlslKnownSizes.GetTypeInfo(typeName); // Calculate the right offset with 16-bytes padding (HLSL constant buffer). From 27438f7a695ebb5357a05918fa3c4bbef2fbc43c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 10 Jan 2021 22:33:13 +0100 Subject: [PATCH 2/5] Implemented support for local shader constants --- .../IComputeShaderSourceAttribute.cs | 15 ++++++- .../Renderer/HlslShaderRenderer.cs | 16 ++++++-- .../Translation/IShaderLoader.cs | 5 +++ .../Translation/ShaderLoader{T}.cs | 39 +++++++++++++------ .../IComputeShaderSourceGenerator.cs | 38 ++++++++++++++++-- .../ShaderMethodSourceGenerator.cs | 2 +- .../SyntaxRewriters/ShaderSourceRewriter.cs | 32 +++++++++++++-- 7 files changed, 123 insertions(+), 24 deletions(-) diff --git a/src/ComputeSharp.Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs b/src/ComputeSharp.Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs index 163d3d5d..91c92c52 100644 --- a/src/ComputeSharp.Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs +++ b/src/ComputeSharp.Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs @@ -24,13 +24,21 @@ namespace ComputeSharp.__Internals /// The mapped collection of shader fields. /// The source code for the method. /// The collection of processed methods. - public IComputeShaderSourceAttribute(string shaderTypeName, string[] types, object[] args, string executeMethod, string[] methods) + /// The collection of discovered constants. + public IComputeShaderSourceAttribute( + string shaderTypeName, + string[] types, + object[] args, + string executeMethod, + string[] methods, + object[] constants) { ShaderTypeName = shaderTypeName; Types = types; Fields = args.Cast().ToDictionary(static arg => arg[0], static arg => (arg[1], arg[2])); ExecuteMethod = executeMethod; Methods = methods; + Constants = constants.Cast().ToDictionary(static c => c[0], static c => c[1]); } /// @@ -58,6 +66,11 @@ namespace ComputeSharp.__Internals /// internal IReadOnlyCollection Methods { get; } + /// + /// Gets the collection of discovered constants. + /// + internal IReadOnlyDictionary Constants { get; } + /// /// Gets the associated instance for a specified type. /// diff --git a/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs b/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs index a1a69c70..6ee1583f 100644 --- a/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs +++ b/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs @@ -31,17 +31,27 @@ namespace ComputeSharp.Shaders.Renderer builder.AppendLine("// AUTO GENERATED"); builder.AppendLine("// ================================================"); builder.AppendLine("// This shader was created by ComputeSharp."); - builder.AppendLine("// See: https://github.com/Sergio0694/ComputeSharp."); + builder.AppendLine("// See: https://github.com/Sergio0694/ComputeSharp."); + builder.AppendLine(); + + // Constants + foreach (var constant in info.ConstantsInfo) + { + builder.Append("#define "); + builder.Append(constant.Key); + builder.Append(' '); + builder.AppendLine(constant.Value); + builder.AppendLine(); + } // Declared types foreach (var type in info.DeclaredTypes) { - builder.AppendLine(); builder.AppendLine(type); + builder.AppendLine(); } // Captured variables - builder.AppendLine(); builder.AppendLine("cbuffer _ : register(b0)"); builder.AppendLine('{'); builder.AppendLine(" uint __x;"); diff --git a/src/ComputeSharp.Shaders/Translation/IShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/IShaderLoader.cs index 1a8b5be0..bf21f77e 100644 --- a/src/ComputeSharp.Shaders/Translation/IShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/IShaderLoader.cs @@ -28,6 +28,11 @@ namespace ComputeSharp.Shaders.Translation /// public IReadOnlyCollection MethodsInfo { get; } + /// + /// Gets the collection of constants to be declared in the shader. + /// + public IReadOnlyDictionary ConstantsInfo { get; } + /// /// Gets the collection of declared types for the shader. /// diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index 11ac00bd..6f3c62b0 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -61,6 +61,11 @@ namespace ComputeSharp.Shaders.Translation /// private readonly List methodsInfo = new(); + /// + /// The with the discovered constants for the shader. + /// + private readonly Dictionary constantsInfo = new(); + /// /// The with the collected declared types for the shader. /// @@ -93,6 +98,9 @@ namespace ComputeSharp.Shaders.Translation /// public IReadOnlyCollection MethodsInfo => this.methodsInfo; + /// + public IReadOnlyDictionary ConstantsInfo => this.constantsInfo; + /// public IReadOnlyCollection DeclaredTypes => this.declaredTypes; @@ -106,16 +114,34 @@ namespace ComputeSharp.Shaders.Translation { ShaderLoader @this = new(); + @this.LoadMethodMetadata(); + // Reading members through reflection requires an object parameter, so here we're just boxing // the input shader once to avoid allocating it multiple times while processing the shader. @this.d3D12DescriptorRanges1 = @this.LoadFieldsInfo(shader); - @this.LoadMethodMetadata(); @this.InitializeDispatchDataLoader(); return @this; } + /// + /// Loads the metadata info for the current shader. + /// + private void LoadMethodMetadata() + { + EntryPoint = Attribute.ExecuteMethod; + + this.methodsInfo.AddRange(Attribute.Methods); + + foreach (var pair in Attribute.Constants) + { + this.constantsInfo.Add(pair.Key, pair.Value); + } + + this.declaredTypes.AddRange(Attribute.Types); + } + /// /// Loads the fields info for the current shader being loaded. /// @@ -200,16 +226,5 @@ namespace ComputeSharp.Shaders.Translation } else ThrowHelper.ThrowArgumentException("Invalid captured variable"); } - - /// - /// Loads the metadata info for the current shader. - /// - private void LoadMethodMetadata() - { - EntryPoint = Attribute.ExecuteMethod; - - this.methodsInfo.AddRange(Attribute.Methods); - this.declaredTypes.AddRange(Attribute.Types); - } } } diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index 3aa284ea..fe67c4ef 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -45,6 +45,7 @@ namespace ComputeSharp.SourceGenerators // We need to sets to track all discovered custom types and static methods HashSet discoveredTypes = new(SymbolEqualityComparer.Default); Dictionary staticMethods = new(SymbolEqualityComparer.Default); + Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); // Helper that converts a sequence of string sequences into a nested array expression. // That is, this applies the following transformation: @@ -76,9 +77,10 @@ namespace ComputeSharp.SourceGenerators // Explore the syntax tree and extract the processed info var processedMembers = GetProcessedMembers(structDeclarationSymbol, discoveredTypes).ToArray(); - var (entryPoint, localFunctions) = GetProcessedMethods(structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods); + var (entryPoint, localFunctions) = GetProcessedMethods(structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions); var processedTypes = GetProcessedTypes(discoveredTypes).ToArray(); var processedMethods = localFunctions.Concat(staticMethods.Values).Select(static method => method.NormalizeWhitespace().ToFullString()).ToArray(); + var processedConstants = GetProcessedConstants(structDeclarationSymbol, constantDefinitions); // Create the compilation unit with the source attribute var source = @@ -90,7 +92,8 @@ namespace ComputeSharp.SourceGenerators AttributeArgument(ArrayExpression(processedTypes)), AttributeArgument(NestedArrayExpression(processedMembers)), AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(entryPoint))), - AttributeArgument(ArrayExpression(processedMethods))))) + AttributeArgument(ArrayExpression(processedMethods)), + AttributeArgument(NestedArrayExpression(processedConstants))))) .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) .NormalizeWhitespace() @@ -138,6 +141,7 @@ namespace ComputeSharp.SourceGenerators /// The instance for the type to process. /// The collection of currently discovered types. /// The set of discovered and processed static methods. + /// The collection of discovered constant definitions. /// A sequence of processed methods in , and the entry point. [Pure] private static (string EntryPoint, IEnumerable Methods) GetProcessedMethods( @@ -145,7 +149,8 @@ namespace ComputeSharp.SourceGenerators INamedTypeSymbol structDeclarationSymbol, SemanticModel semanticModel, ICollection discoveredTypes, - IDictionary staticMethods) + IDictionary staticMethods, + IDictionary constantDefinitions) { // Find all declared methods in the type ImmutableArray methodDeclarations = ( @@ -159,7 +164,7 @@ namespace ComputeSharp.SourceGenerators foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) { IMethodSymbol methodDeclarationSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration)!; - ShaderSourceRewriter shaderSourceRewriter = new(structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods); + ShaderSourceRewriter shaderSourceRewriter = new(structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions); // Rewrite the method syntax tree var processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia(); @@ -189,6 +194,31 @@ namespace ComputeSharp.SourceGenerators return (entryPoint!, methods); } + /// + /// Gets a sequence of discovered constants. + /// + /// The type symbol for the shader type. + /// The collection of discovered constant definitions. + /// A sequence of discovered constants to declare in the shader. + [Pure] + private static IEnumerable> GetProcessedConstants(INamedTypeSymbol structDeclarationSymbol, IReadOnlyDictionary constantDefinitions) + { + foreach (var constant in constantDefinitions) + { + if (SymbolEqualityComparer.Default.Equals(structDeclarationSymbol, constant.Key.ContainingSymbol)) + { + yield return new string[] { constant.Key.Name, constant.Value }; + } + else + { + var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).GetFullMetadataName().Replace(".", "__"); + var constantName = $"{ownerTypeName}__{constant.Key.Name}"; + + yield return new string[] { constantName, constant.Value }; + } + } + } + /// /// Gets the sequence of processed discovered custom types. /// diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index 7ce2bf63..3d39992e 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -96,7 +96,7 @@ namespace ComputeSharp.SourceGenerators ICollection discoveredTypes, IDictionary staticMethods) { - ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods); + ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, null); // TODO: implement constant support // Rewrite the method syntax tree var processedMethod = shaderSourceRewriter diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index d110eb45..fc4022a9 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -37,6 +37,11 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// private readonly IDictionary staticMethods; + /// + /// The collection of discovered constant definitions. + /// + private readonly IDictionary constantDefinitions; + /// /// The collection of processed local functions in the current tree. /// @@ -59,16 +64,19 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// 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 constant definitions. public ShaderSourceRewriter( INamedTypeSymbol shaderType, SemanticModel semanticModel, ICollection discoveredTypes, - IDictionary staticMethods) + IDictionary staticMethods, + IDictionary constantDefinitions) { this.shaderType = shaderType; this.semanticModel = semanticModel; this.discoveredTypes = discoveredTypes; this.staticMethods = staticMethods; + this.constantDefinitions = constantDefinitions; this.localFunctions = new(); this.implicitVariables = new(); } @@ -79,14 +87,17 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// 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 constant definitions. public ShaderSourceRewriter( SemanticModel semanticModel, ICollection discoveredTypes, - IDictionary staticMethods) + IDictionary staticMethods, + IDictionary constantDefinitions) { this.semanticModel = semanticModel; this.discoveredTypes = discoveredTypes; this.staticMethods = staticMethods; + this.constantDefinitions = constantDefinitions; this.implicitVariables = new(); this.localFunctions = new(); } @@ -398,7 +409,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters if (!this.staticMethods.ContainsKey(method)) { - ShaderSourceRewriter shaderSourceRewriter = new(this.semanticModel, this.discoveredTypes, this.staticMethods); + ShaderSourceRewriter shaderSourceRewriter = new(this.semanticModel, this.discoveredTypes, this.staticMethods, this.constantDefinitions); MethodDeclarationSyntax methodNode = (MethodDeclarationSyntax)method.DeclaringSyntaxReferences[0].GetSyntax(), processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace().WithoutTrivia(); @@ -452,6 +463,21 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters return updatedNode; } + /// + public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node) + { + var updatedNode = (IdentifierNameSyntax)base.VisitIdentifierName(node)!; + + if (this.semanticModel.GetOperation(node) is IFieldReferenceOperation operation && + operation.Field.IsConst && + !this.constantDefinitions.ContainsKey(operation.Field)) + { + this.constantDefinitions.Add(operation.Field, operation.Field.ConstantValue!.ToString()); + } + + return updatedNode; + } + /// public override SyntaxToken VisitToken(SyntaxToken token) { From ad58397e1d12958f4c62d1469abdbb2d04ae8d7c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 10 Jan 2021 22:49:36 +0100 Subject: [PATCH 3/5] Fixed handling of constants in parent type hierarchy --- .../Renderer/HlslShaderRenderer.cs | 18 +++++++++++------- .../IComputeShaderSourceGenerator.cs | 18 +++++------------- .../SyntaxRewriters/ShaderSourceRewriter.cs | 5 +++++ 3 files changed, 21 insertions(+), 20 deletions(-) diff --git a/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs b/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs index 6ee1583f..b3066e31 100644 --- a/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs +++ b/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs @@ -32,26 +32,30 @@ namespace ComputeSharp.Shaders.Renderer builder.AppendLine("// ================================================"); builder.AppendLine("// This shader was created by ComputeSharp."); builder.AppendLine("// See: https://github.com/Sergio0694/ComputeSharp."); - builder.AppendLine(); // Constants - foreach (var constant in info.ConstantsInfo) + if (info.ConstantsInfo.Count > 0) { - builder.Append("#define "); - builder.Append(constant.Key); - builder.Append(' '); - builder.AppendLine(constant.Value); builder.AppendLine(); + + foreach (var constant in info.ConstantsInfo) + { + builder.Append("#define "); + builder.Append(constant.Key); + builder.Append(' '); + builder.AppendLine(constant.Value); + } } // Declared types foreach (var type in info.DeclaredTypes) { - builder.AppendLine(type); builder.AppendLine(); + builder.AppendLine(type); } // Captured variables + builder.AppendLine(); builder.AppendLine("cbuffer _ : register(b0)"); builder.AppendLine('{'); builder.AppendLine(" uint __x;"); diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index fe67c4ef..5e96e74c 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -80,7 +80,7 @@ namespace ComputeSharp.SourceGenerators var (entryPoint, localFunctions) = GetProcessedMethods(structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions); var processedTypes = GetProcessedTypes(discoveredTypes).ToArray(); var processedMethods = localFunctions.Concat(staticMethods.Values).Select(static method => method.NormalizeWhitespace().ToFullString()).ToArray(); - var processedConstants = GetProcessedConstants(structDeclarationSymbol, constantDefinitions); + var processedConstants = GetProcessedConstants(constantDefinitions); // Create the compilation unit with the source attribute var source = @@ -197,25 +197,17 @@ namespace ComputeSharp.SourceGenerators /// /// Gets a sequence of discovered constants. /// - /// The type symbol for the shader type. /// The collection of discovered constant definitions. /// A sequence of discovered constants to declare in the shader. [Pure] - private static IEnumerable> GetProcessedConstants(INamedTypeSymbol structDeclarationSymbol, IReadOnlyDictionary constantDefinitions) + private static IEnumerable> GetProcessedConstants(IReadOnlyDictionary constantDefinitions) { foreach (var constant in constantDefinitions) { - if (SymbolEqualityComparer.Default.Equals(structDeclarationSymbol, constant.Key.ContainingSymbol)) - { - yield return new string[] { constant.Key.Name, constant.Value }; - } - else - { - var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).GetFullMetadataName().Replace(".", "__"); - var constantName = $"{ownerTypeName}__{constant.Key.Name}"; + var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().Replace(".", "__"); + var constantName = $"__{ownerTypeName}__{constant.Key.Name}"; - yield return new string[] { constantName, constant.Value }; - } + yield return new string[] { constantName, constant.Value }; } } diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index fc4022a9..6580be03 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -473,6 +473,11 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters !this.constantDefinitions.ContainsKey(operation.Field)) { this.constantDefinitions.Add(operation.Field, operation.Field.ConstantValue!.ToString()); + + var ownerTypeName = ((INamedTypeSymbol)operation.Field.ContainingSymbol).ToDisplayString().Replace(".", "__"); + var constantName = $"__{ownerTypeName}__{operation.Field.Name}"; + + return IdentifierName(constantName); } return updatedNode; From 4b5c422bc3c05332104e727ba91958a41b6cd69a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 11 Jan 2021 13:38:03 +0100 Subject: [PATCH 4/5] Implemented constant support for member accesses --- .../SyntaxRewriters/ShaderSourceRewriter.cs | 21 +++++++++---------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 6580be03..80112469 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -293,14 +293,15 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) && this.semanticModel.GetOperation(node) is IMemberReferenceOperation operation) { - // If the current member access is to a constant, hardcode the value in HLSL - if (operation.ConstantValue is { HasValue: true } and { Value: object value }) + // If the member access is a constant, track it and replace the tree with the processed constant name + if (operation is IFieldReferenceOperation fieldOperation && fieldOperation.Field.IsConst) { - return ParseExpression(value switch - { - IFormattable f => f.ToString(null, CultureInfo.InvariantCulture), - _ => value.ToString() - }); + this.constantDefinitions[fieldOperation.Field] = fieldOperation.Field.ConstantValue!.ToString(); + + var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().Replace(".", "__"); + var constantName = $"__{ownerTypeName}__{fieldOperation.Field.Name}"; + + return IdentifierName(constantName); } // If the current member access is a field or property access, check the lookup table @@ -468,11 +469,9 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters { var updatedNode = (IdentifierNameSyntax)base.VisitIdentifierName(node)!; - if (this.semanticModel.GetOperation(node) is IFieldReferenceOperation operation && - operation.Field.IsConst && - !this.constantDefinitions.ContainsKey(operation.Field)) + if (this.semanticModel.GetOperation(node) is IFieldReferenceOperation operation && operation.Field.IsConst) { - this.constantDefinitions.Add(operation.Field, operation.Field.ConstantValue!.ToString()); + this.constantDefinitions[operation.Field] = operation.Field.ConstantValue!.ToString(); var ownerTypeName = ((INamedTypeSymbol)operation.Field.ContainingSymbol).ToDisplayString().Replace(".", "__"); var constantName = $"__{ownerTypeName}__{operation.Field.Name}"; From 075c7cdf9a75584b67c9ef7667f443561c1f2506 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 11 Jan 2021 14:01:33 +0100 Subject: [PATCH 5/5] Implemented constant support for methods, code refactoring --- .../ShaderMethodSourceAttribute.cs | 10 ++- .../Translation/ShaderLoader{T}.cs | 8 ++- .../Helpers/SyntaxFactoryHelper.cs | 61 +++++++++++++++++++ .../IComputeShaderSourceGenerator.cs | 31 +--------- .../ShaderMethodSourceGenerator.cs | 27 +++----- 5 files changed, 88 insertions(+), 49 deletions(-) create mode 100644 src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs diff --git a/src/ComputeSharp.Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs b/src/ComputeSharp.Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs index 195ea4d2..97104dfd 100644 --- a/src/ComputeSharp.Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs +++ b/src/ComputeSharp.Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.Contracts; +using System.Linq; using System.Reflection; using ComputeSharp.Core.Extensions; using ComputeSharp.Exceptions; @@ -35,13 +36,15 @@ namespace ComputeSharp.__Internals /// The collection of custom types. /// The source code for the target entry point method. /// The collection of processed methods. - public ShaderMethodSourceAttribute(string methodName, string[] types, string invokeMethod, string[] methods) + /// The collection of discovered constants. + public ShaderMethodSourceAttribute(string methodName, string[] types, string invokeMethod, string[] methods, object[] constants) { this.invokeMethod = invokeMethod; MethodName = methodName; Types = types; Methods = methods; + Constants = constants.Cast().ToDictionary(static c => c[0], static c => c[1]); } /// @@ -59,6 +62,11 @@ namespace ComputeSharp.__Internals /// internal IReadOnlyCollection Methods { get; } + /// + /// Gets the collection of discovered constants. + /// + internal IReadOnlyDictionary Constants { get; } + /// /// Gets the mapped source code for the current method. /// diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index 6f3c62b0..12606154 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -132,14 +132,13 @@ namespace ComputeSharp.Shaders.Translation { EntryPoint = Attribute.ExecuteMethod; + this.declaredTypes.AddRange(Attribute.Types); this.methodsInfo.AddRange(Attribute.Methods); foreach (var pair in Attribute.Constants) { this.constantsInfo.Add(pair.Key, pair.Value); } - - this.declaredTypes.AddRange(Attribute.Types); } /// @@ -223,6 +222,11 @@ namespace ComputeSharp.Shaders.Translation this.declaredTypes.AddRange(methodSource.Types); this.methodsInfo.Add(methodSource.GetMappedInvokeMethod(hlslName)); this.methodsInfo.AddRange(methodSource.Methods); + + foreach (var pair in methodSource.Constants) + { + this.constantsInfo[pair.Key] = pair.Value; + } } else ThrowHelper.ThrowArgumentException("Invalid captured variable"); } diff --git a/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs b/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs new file mode 100644 index 00000000..5fb2c00a --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs @@ -0,0 +1,61 @@ +using System.Collections.Generic; +using System.Diagnostics.Contracts; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.SourceGenerators.Helpers +{ + /// + /// A class containing additional factory methods for constructing syntax nodes, tokens and trivia. + /// + internal static class SyntaxFactoryHelper + { + /// + /// Creates a [] array expression from the given sequence of instances. + /// + /// That it, it applies the following transformation: + /// + /// { "S1", "S2" } => new string[] { "S1", "S2" } + /// + /// + /// + /// The input sequence of instances. + /// An instance with the described contents. + [Pure] + public static ArrayCreationExpressionSyntax ArrayExpression(IEnumerable values) + { + return + ArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword))) + .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) + .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) + .AddExpressions(values.Select(static value => LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(value))).ToArray())); + } + + /// + /// Creates an [] array expression with the nested groups in the input sequence. + /// + /// That it, it applies the following transformation: + /// + /// { ("K1", "V1"), ("K2", "V2") } => new object[] { new[] { "K1", "V1" }, new[] { "K2", "V2" } } + /// + /// + /// + /// The input sequence of groups. + /// An instance with the described contents. + [Pure] + public static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable> groups) + { + return + ArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ObjectKeyword))) + .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) + .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) + .AddExpressions(groups.Select(static group => + ImplicitArrayCreationExpression(InitializerExpression(SyntaxKind.ArrayInitializerExpression).AddExpressions( + group.Select(static item => LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item))).ToArray()))).ToArray())); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index 5e96e74c..c1b061a3 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -12,6 +12,7 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; +using static ComputeSharp.SourceGenerators.Helpers.SyntaxFactoryHelper; #pragma warning disable CS0618 @@ -47,34 +48,6 @@ namespace ComputeSharp.SourceGenerators Dictionary staticMethods = new(SymbolEqualityComparer.Default); Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); - // Helper that converts a sequence of string sequences 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 NestedArrayExpression(IEnumerable> groups) - { - return - ArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ObjectKeyword))) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) - .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) - .AddExpressions(groups.Select(static group => - ImplicitArrayCreationExpression(InitializerExpression(SyntaxKind.ArrayInitializerExpression).AddExpressions( - group.Select(static item => LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item))).ToArray()))).ToArray())); - } - - // Helper that converts a sequence of strings into an array expression. - // That is, this applies the following transformation: - // - { "S1", "S2" } => new string[] { "S1", "S2" } - static ArrayCreationExpressionSyntax ArrayExpression(IEnumerable values) - { - return - ArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword))) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) - .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) - .AddExpressions(values.Select(static value => LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(value))).ToArray())); - } - // Explore the syntax tree and extract the processed info var processedMembers = GetProcessedMembers(structDeclarationSymbol, discoveredTypes).ToArray(); var (entryPoint, localFunctions) = GetProcessedMethods(structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions); @@ -200,7 +173,7 @@ namespace ComputeSharp.SourceGenerators /// The collection of discovered constant definitions. /// A sequence of discovered constants to declare in the shader. [Pure] - private static IEnumerable> GetProcessedConstants(IReadOnlyDictionary constantDefinitions) + internal static IEnumerable> GetProcessedConstants(IReadOnlyDictionary constantDefinitions) { foreach (var constant in constantDefinitions) { diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index 3d39992e..6d817f4b 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -11,6 +11,7 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; +using static ComputeSharp.SourceGenerators.Helpers.SyntaxFactoryHelper; #pragma warning disable CS0618 @@ -44,23 +45,12 @@ namespace ComputeSharp.SourceGenerators // We need to sets to track all discovered custom types and static methods HashSet discoveredTypes = new(SymbolEqualityComparer.Default); Dictionary staticMethods = new(SymbolEqualityComparer.Default); + Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); // Explore the syntax tree and extract the processed info - var (invokeMethod, processedMethods) = GetProcessedMethods(methodDeclaration, semanticModel, discoveredTypes, staticMethods); + var (invokeMethod, processedMethods) = GetProcessedMethods(methodDeclaration, semanticModel, discoveredTypes, staticMethods, constantDefinitions); var processedTypes = IComputeShaderSourceGenerator.GetProcessedTypes(discoveredTypes).ToArray(); - - // Helper that converts a sequence of strings into an array expression. - // That is, this applies the following transformation: - // - { "S1", "S2" } => new string[] { "S1", "S2" } - static ArrayCreationExpressionSyntax ArrayExpression(IEnumerable values) - { - return - ArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword))) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) - .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) - .AddExpressions(values.Select(static value => LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(value))).ToArray())); - } + var processedConstants = IComputeShaderSourceGenerator.GetProcessedConstants(constantDefinitions); // Create the compilation unit with the source attribute var source = @@ -70,7 +60,8 @@ namespace ComputeSharp.SourceGenerators AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodDeclarationSymbol.GetFullMetadataName(true)))), AttributeArgument(ArrayExpression(processedTypes)), AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(invokeMethod))), - AttributeArgument(ArrayExpression(processedMethods))))) + AttributeArgument(ArrayExpression(processedMethods)), + AttributeArgument(NestedArrayExpression(processedConstants))))) .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) .NormalizeWhitespace() @@ -88,15 +79,17 @@ namespace ComputeSharp.SourceGenerators /// The instance for the method to process. /// The collection of currently discovered types. /// The set of discovered and processed static methods. + /// The collection of discovered constant definitions. /// A sequence of processed methods in . [Pure] private static (string InvokeMethod, IEnumerable Methods) GetProcessedMethods( MethodDeclarationSyntax methodDeclaration, SemanticModel semanticModel, ICollection discoveredTypes, - IDictionary staticMethods) + IDictionary staticMethods, + IDictionary constantDefinitions) { - ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, null); // TODO: implement constant support + ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, constantDefinitions); // Rewrite the method syntax tree var processedMethod = shaderSourceRewriter