diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs index d070d38e..150cc289 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs @@ -53,6 +53,7 @@ partial class D2DPixelShaderDescriptorGenerator Dictionary instanceMethods = new(SymbolEqualityComparer.Default); Dictionary constructors = new(SymbolEqualityComparer.Default); Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); + Dictionary staticFieldDefinitions = new(SymbolEqualityComparer.Default); token.ThrowIfCancellationRequested(); @@ -78,6 +79,7 @@ partial class D2DPixelShaderDescriptorGenerator instanceMethods, constructors, constantDefinitions, + staticFieldDefinitions, token, out bool methodsNeedD2D1RequiresScenePosition); @@ -89,6 +91,7 @@ partial class D2DPixelShaderDescriptorGenerator structDeclarationSymbol, discoveredTypes, constantDefinitions, + staticFieldDefinitions, token, out bool fieldsNeedD2D1RequiresScenePosition); @@ -238,6 +241,7 @@ partial class D2DPixelShaderDescriptorGenerator /// The type symbol for the shader type. /// The collection of currently discovered types. /// The collection of discovered constant definitions. + /// The collection of discovered static field definitions. /// The used to cancel the operation, if needed. /// Whether or not the shader needs the [D2DRequiresScenePosition] annotation. /// A sequence of static constant fields in . @@ -247,6 +251,7 @@ partial class D2DPixelShaderDescriptorGenerator INamedTypeSymbol structDeclarationSymbol, ICollection discoveredTypes, IDictionary constantDefinitions, + IDictionary staticFieldDefinitions, CancellationToken token, out bool needsD2D1RequiresScenePosition) { @@ -256,52 +261,35 @@ partial class D2DPixelShaderDescriptorGenerator foreach (ISymbol memberSymbol in structDeclarationSymbol.GetMembers()) { - // Find all declared static fields in the type - if (memberSymbol is not IFieldSymbol { IsImplicitlyDeclared: false, IsStatic: true, IsConst: false, } fieldSymbol) + if (memberSymbol is not IFieldSymbol fieldSymbol) { continue; } - if (!fieldSymbol.TryGetSyntaxNode(token, out VariableDeclaratorSyntax? variableDeclarator)) - { - continue; - } - - // Constant properties must be of a primitive, vector or matrix type - if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol || - !HlslKnownTypes.IsKnownHlslType(typeSymbol.GetFullyQualifiedMetadataName())) - { - diagnostics.Add(InvalidShaderStaticFieldType, variableDeclarator, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); - - continue; - } - - _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); - - string typeDeclaration = fieldSymbol.IsReadOnly switch - { - true => $"static const {HlslKnownTypes.GetMappedName(typeSymbol)}", - false => $"static {HlslKnownTypes.GetMappedName(typeSymbol)}" - }; - - token.ThrowIfCancellationRequested(); - - StaticFieldRewriter staticFieldRewriter = new( + if (HlslDefinitionsSyntaxProcessor.TryGetStaticField( + structDeclarationSymbol, + fieldSymbol, semanticModel, discoveredTypes, constantDefinitions, + staticFieldDefinitions, diagnostics, - token); + token, + out string? name, + out string? typeDeclaration, + out string? assignmentExpression, + out StaticFieldRewriter? staticFieldRewriter)) + { + needsD2D1RequiresScenePosition |= staticFieldRewriter.NeedsD2DRequiresScenePositionAttribute; - ExpressionSyntax? processedDeclaration = staticFieldRewriter.Visit(variableDeclarator); + builder.Add((name, typeDeclaration, assignmentExpression)); + } + } - token.ThrowIfCancellationRequested(); - - string? assignment = processedDeclaration?.NormalizeWhitespace(eol: "\n").ToFullString(); - - needsD2D1RequiresScenePosition |= staticFieldRewriter.NeedsD2DRequiresScenePositionAttribute; - - builder.Add((mapping ?? fieldSymbol.Name, typeDeclaration, assignment)); + // Also gather the external static fields (same as in the DX12 generator) + foreach ((string, string, string?) externalField in staticFieldDefinitions.Values) + { + builder.Add(externalField); } return builder.ToImmutable(); @@ -318,6 +306,7 @@ partial class D2DPixelShaderDescriptorGenerator /// The collection of discovered instance methods for custom struct types. /// The collection of discovered constructors for custom struct types. /// The collection of discovered constant definitions. + /// The collection of discovered static field definitions. /// Whether or not the shader needs the [D2DRequiresScenePosition] annotation. /// The used to cancel the operation, if needed. /// A sequence of processed methods in , and the entry point. @@ -330,6 +319,7 @@ partial class D2DPixelShaderDescriptorGenerator IDictionary instanceMethods, IDictionary constructors, IDictionary constantDefinitions, + IDictionary staticFieldDefinitions, CancellationToken token, out bool needsD2D1RequiresScenePosition) { @@ -374,6 +364,7 @@ partial class D2DPixelShaderDescriptorGenerator instanceMethods, constructors, constantDefinitions, + staticFieldDefinitions, diagnostics, token, isShaderEntryPoint); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index b2d42ef9..c54cbe30 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -397,19 +397,19 @@ partial class DiagnosticDescriptors helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); /// - /// Gets a for an invalid shader static readonly field type. + /// Gets a for an invalid static field type. /// - /// Format: "The pixel shader of type {0} contains a static readonly field "{1}" of an invalid type {2} (only primitive, vector and matrix types are supported)". + /// Format: "The pixel shader of type {0} contains or references a static field "{1}" of an invalid type {2} (only primitive, vector and matrix types are supported)". /// /// public static readonly DiagnosticDescriptor InvalidShaderStaticFieldType = new( id: "CMPSD2D0030", - title: "Invalid shader static readonly field type", - messageFormat: """The pixel shader of type {0} contains a static readonly field "{1}" of an invalid type {2} (only primitive, vector and matrix types are supported)""", + title: "Invalid shader static field type", + messageFormat: """The pixel shader of type {0} contains or references a static field "{1}" of an invalid type {2} (only primitive, vector and matrix types are supported)""", category: "ComputeSharp.D2D1.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, - description: "A type representing a pixel shader contains a static readonly field of a type that is not supported.", + description: "A type representing a pixel shader contains or references a static field of a type that is not supported.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); /// diff --git a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 4ddd4301..9b505839 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -29,18 +29,14 @@ partial class ShaderSourceRewriter } /// - private partial void TrackKnownPropertyAccess(IMemberReferenceOperation operation, MemberAccessExpressionSyntax node, string mappedName) + partial void TrackKnownMethodInvocation(string metadataName) { - // No special tracking is needed for D2D1 shaders + NeedsD2DRequiresScenePositionAttribute |= HlslKnownMethods.NeedsD2DRequiresScenePositionAttribute(metadataName); } /// - private partial void TrackKnownMethodInvocation(string metadataName) + partial void TrackExternalStaticField(StaticFieldRewriter staticFieldRewriter) { - // Track whether the method needs [D2DRequiresScenePosition] - if (HlslKnownMethods.NeedsD2DRequiresScenePositionAttribute(metadataName)) - { - NeedsD2DRequiresScenePositionAttribute = true; - } + NeedsD2DRequiresScenePositionAttribute |= staticFieldRewriter.NeedsD2DRequiresScenePositionAttribute; } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs index 22919a98..cbff40dd 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs @@ -1,10 +1,13 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Threading; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; using ComputeSharp.SourceGeneration.Models; +using ComputeSharp.SourceGeneration.SyntaxRewriters; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -38,6 +41,100 @@ internal static class HlslDefinitionsSyntaxProcessor return builder.ToImmutable(); } + /// + /// Tries to get and rewrite a given static field to be used in a shader. + /// + /// The type symbol for the shader type. + /// The symbol for the field to analyze. + /// The instance for the type to process. + /// The collection of currently discovered types. + /// The collection of discovered constant definitions. + /// The collection of discovered static field definitions. + /// The collection of produced instances. + /// The used to cancel the operation, if needed. + /// The mapped name for the field. + /// The type declaration for the field. + /// The assignment expression for the field, if present. + /// The instance used to rewrite the field expression. + /// Whether the field was processed successfully and is valid. + public static bool TryGetStaticField( + INamedTypeSymbol structDeclarationSymbol, + IFieldSymbol fieldSymbol, + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary constantDefinitions, + IDictionary staticFieldDefinitions, + ImmutableArrayBuilder diagnostics, + CancellationToken token, + [NotNullWhen(true)] out string? name, + [NotNullWhen(true)] out string? typeDeclaration, + out string? assignmentExpression, + [NotNullWhen(true)] out StaticFieldRewriter? staticFieldRewriter) + { + if (fieldSymbol.IsImplicitlyDeclared || !fieldSymbol.IsStatic || fieldSymbol.IsConst) + { + goto Failure; + } + + if (!fieldSymbol.TryGetSyntaxNode(token, out VariableDeclaratorSyntax? variableDeclarator)) + { + goto Failure; + } + + // Static fields must be of a primitive, vector or matrix type + if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol || + !HlslKnownTypes.IsKnownHlslType(typeSymbol.GetFullyQualifiedMetadataName())) + { + diagnostics.Add(InvalidShaderStaticFieldType, variableDeclarator, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + + goto Failure; + } + + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); + + // The field name is either the mapped name (if a reserved name) or just the field name. + // This method is shared across external fields too, and callers can just override this. + name = mapping ?? fieldSymbol.Name; + + // Readonly fields are rewritten to static const fields, and mutable fields are just static. + // Note that there's no protection for mutable static fields that may have been written to + // in C# elsewhere. Shader authors should be aware that those writes would not appear in HLSL, + // as each shader invocation would only see the initial assignment value (or the default value). + typeDeclaration = fieldSymbol.IsReadOnly switch + { + true => $"static const {HlslKnownTypes.GetMappedName(typeSymbol)}", + false => $"static {HlslKnownTypes.GetMappedName(typeSymbol)}" + }; + + token.ThrowIfCancellationRequested(); + + // Create the rewriter to use, which is also returned to callers so they can extract any additional + // info if needed. For instance, the D2D generator will check if the dispatch position is required. + staticFieldRewriter = new StaticFieldRewriter( + semanticModel, + discoveredTypes, + constantDefinitions, + staticFieldDefinitions, + diagnostics, + token); + + ExpressionSyntax? processedDeclaration = staticFieldRewriter.Visit(variableDeclarator); + + token.ThrowIfCancellationRequested(); + + assignmentExpression = processedDeclaration?.NormalizeWhitespace(eol: "\n").ToFullString(); + + return true; + + Failure: + name = null; + typeDeclaration = null; + assignmentExpression = null; + staticFieldRewriter = null; + + return false; + } + /// /// Gets the sequence of processed discovered custom types. /// diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs index 320805ef..e035e44a 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs @@ -33,18 +33,21 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// The instance for the target syntax tree. /// The set of discovered custom types. /// The collection of discovered constant definitions. + /// The collection of discovered static field definitions. /// The collection of produced instances. /// The value for the current operation. protected HlslSourceRewriter( SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary constantDefinitions, + IDictionary staticFieldDefinitions, ImmutableArrayBuilder diagnostics, CancellationToken token) { SemanticModel = semanticModel; DiscoveredTypes = discoveredTypes; ConstantDefinitions = constantDefinitions; + StaticFieldDefinitions = staticFieldDefinitions; Diagnostics = diagnostics; CancellationToken = token; } @@ -64,6 +67,11 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// protected IDictionary ConstantDefinitions { get; } + /// + /// Gets the collection of discovered static field definitions. + /// + protected IDictionary StaticFieldDefinitions { get; } + /// /// Gets the collection of produced instances. /// @@ -382,11 +390,15 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter } /// - public sealed override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node) + public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node) { IdentifierNameSyntax updatedNode = (IdentifierNameSyntax)base.VisitIdentifierName(node)!; - if (SemanticModel.For(node).GetOperation(node) is IFieldReferenceOperation operation && + // Only gather constants directly accessed by name. We can also pre-filter to exclude invocations + // and member access expressions, as those will be handled separately. Doing so avoids unnecessarily + // retrieving semantic information for every identifier, which would otherwise be fairly expensive. + if (node.Parent is not (InvocationExpressionSyntax or MemberAccessExpressionSyntax) && + SemanticModel.For(node).GetOperation(node) is IFieldReferenceOperation operation && operation.Field.IsConst && operation.Type!.TypeKind != TypeKind.Enum) { diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs index 26e677a6..30ccf728 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading; @@ -7,6 +8,7 @@ using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; using ComputeSharp.SourceGeneration.Models; +using ComputeSharp.SourceGeneration.SyntaxProcessors; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -19,42 +21,65 @@ 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. +/// 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 constructors for custom struct types. +/// The collection of discovered constant definitions. +/// The collection of discovered static field definitions. +/// The collection of produced instances. +/// The value for the current operation. +/// Whether or not the current instance is processing a shader entry point. +internal sealed partial class ShaderSourceRewriter( + INamedTypeSymbol shaderType, + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary staticMethods, + IDictionary instanceMethods, + IDictionary constructors, + IDictionary constantDefinitions, + IDictionary staticFieldDefinitions, + ImmutableArrayBuilder diagnostics, + CancellationToken token, + bool isEntryPoint = false) + : HlslSourceRewriter(semanticModel, discoveredTypes, constantDefinitions, staticFieldDefinitions, diagnostics, token) { /// /// The type symbol for the shader type. /// - private readonly INamedTypeSymbol? shaderType; + private readonly INamedTypeSymbol shaderType = shaderType; /// /// The collection of discovered static methods. /// - private readonly IDictionary staticMethods; + private readonly IDictionary staticMethods = staticMethods; /// /// The collection of discovered instance methods for custom struct types. /// - private readonly IDictionary instanceMethods; + private readonly IDictionary instanceMethods = instanceMethods; /// /// The collection of discovered constructors for custom struct types. /// - private readonly IDictionary constructors; + private readonly IDictionary constructors = constructors; /// /// The collection of processed local functions in the current tree. /// - private readonly Dictionary localFunctions; + private readonly Dictionary localFunctions = []; /// /// The list of implicit variables to declare at the start of the body. /// - private readonly List implicitVariables; + private readonly List implicitVariables = []; /// /// Whether or not the current instance is processing a shader entry point. /// - private readonly bool isEntryPoint; + private readonly bool isEntryPoint = isEntryPoint; /// /// The identifier of the current , @@ -67,70 +92,6 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter /// 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 constructors for custom struct types. - /// The collection of discovered constant definitions. - /// The collection of produced instances. - /// The value for the current operation. - /// 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 constructors, - IDictionary constantDefinitions, - ImmutableArrayBuilder diagnostics, - CancellationToken token, - bool isEntryPoint) - : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics, token) - { - this.shaderType = shaderType; - this.staticMethods = staticMethods; - this.instanceMethods = instanceMethods; - this.constructors = constructors; - this.localFunctions = []; - this.implicitVariables = []; - 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 constructors for custom struct types. - /// The collection of discovered constant definitions. - /// The collection of produced instances. - /// The value for the current operation. - private ShaderSourceRewriter( - SemanticModelProvider semanticModel, - ICollection discoveredTypes, - IDictionary staticMethods, - IDictionary instanceMethods, - IDictionary constructors, - IDictionary constantDefinitions, - ImmutableArrayBuilder diagnostics, - CancellationToken token) - : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics, token) - { - this.staticMethods = staticMethods; - this.instanceMethods = instanceMethods; - this.constructors = constructors; - this.implicitVariables = []; - this.localFunctions = []; - } - /// /// Gets the collection of processed local functions in the current tree. /// @@ -373,6 +334,26 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter } } + /// + public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node) + { + // Intercept identifier names to catch whether we are accessing a static field from its containing type. + // This needs special handling, as it would not go through the usual member access path. If we are doing + // this, then we rewrite it with the shared logic for all static fields, otherwise we return the normal + // visit. Before getting semantic information, we can pre-filter to exclude invocation expressions and + // member access expressions. This is safe, because those two parent nodes would already be handled. + // We also only process fields from external types, as those in shader types don't need handling here. + // This is because they're lowered to the same identifier name, without fully qualified names to rewrite. + if (node.Parent is not (InvocationExpressionSyntax or MemberAccessExpressionSyntax) && + SemanticModel.For(node).GetOperation(node) is IFieldReferenceOperation { Field.IsStatic: true } operation && + !SymbolEqualityComparer.Default.Equals(operation.Field.ContainingType, this.shaderType)) + { + return VisitExternalStaticFieldAccess(null, operation.Field) ?? base.VisitIdentifierName(node); + } + + return base.VisitIdentifierName(node); + } + /// public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node) { @@ -407,6 +388,23 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter { return updatedNode.Name; } + + // Handle static fields, which can be either in the shader type itself, or in external types + if (fieldOperation.Field.IsStatic) + { + // Special case static fields in the shader type itself. Those are already discovered separately, when crawling + // all members of the shader type. But, if this path was hit, it means that they are accessed via a member access + // expression, which means they need to be rewritten to match the simple name they will have in the shader. This + // is often the case if they're accessed from external types. So we just map the name and use that expression. + if (SymbolEqualityComparer.Default.Equals(fieldOperation.Field.ContainingType, this.shaderType)) + { + _ = HlslKnownKeywords.TryGetMappedName(fieldOperation.Field.Name, out string? mappedFieldName); + + return IdentifierName(mappedFieldName ?? fieldOperation.Field.Name); + } + + return VisitExternalStaticFieldAccess(updatedNode, fieldOperation.Field); + } } // If the current member access is a field or property access, check the lookup table @@ -539,12 +537,14 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter } ShaderSourceRewriter shaderSourceRewriter = new( + this.shaderType, SemanticModel, DiscoveredTypes, this.staticMethods, this.instanceMethods, this.constructors, ConstantDefinitions, + StaticFieldDefinitions, Diagnostics, CancellationToken); @@ -592,12 +592,14 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter } ShaderSourceRewriter shaderSourceRewriter = new( + this.shaderType, SemanticModel, DiscoveredTypes, this.instanceMethods, this.instanceMethods, this.constructors, ConstantDefinitions, + StaticFieldDefinitions, Diagnostics, CancellationToken); @@ -679,12 +681,14 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter } ShaderSourceRewriter shaderSourceRewriter = new( + this.shaderType, SemanticModel, DiscoveredTypes, this.instanceMethods, this.instanceMethods, this.constructors, ConstantDefinitions, + StaticFieldDefinitions, Diagnostics, CancellationToken); @@ -756,6 +760,48 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter return base.VisitUserDefinedObjectCreationExpression(node, updatedNode, targetType); } + /// + /// Visits a static field access in an external type and rewrites it as needed. + /// + /// The current instance for the static field. + /// The instance for . + /// The rewritten static field expression. + [return: NotNullIfNotNull(nameof(node))] + private SyntaxNode? VisitExternalStaticFieldAccess(SyntaxNode? node, IFieldSymbol fieldSymbol) + { + if (!StaticFieldDefinitions.TryGetValue(fieldSymbol, out (string Name, string, string?) fieldInfo)) + { + // Execute the same logic as for shader static fields, to process them and extract the relevant info. + // In this case, we use the fully qualified name of the field as identifier, not just the field name. + if (HlslDefinitionsSyntaxProcessor.TryGetStaticField( + this.shaderType, + fieldSymbol, + SemanticModel, + DiscoveredTypes, + ConstantDefinitions, + StaticFieldDefinitions, + Diagnostics, + CancellationToken, + out _, + out string? typeDeclaration, + out string? assignmentExpression, + out _)) + { + fieldInfo.Name = fieldSymbol.GetFullyQualifiedMetadataName().ToHlslIdentifierName(); + + StaticFieldDefinitions.Add(fieldSymbol, (fieldInfo.Name, typeDeclaration, assignmentExpression)); + } + else + { + // We failed to process the field for whatever reason. Just stop rewriting it and return + // the current updated node. We'll have some diagnostic for this case emitted previously. + return node; + } + } + + return IdentifierName(fieldInfo.Name); + } + /// /// Rewrites a sampled texture access. /// @@ -771,11 +817,17 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter /// 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); + 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); + partial void TrackKnownMethodInvocation(string metadataName); + + /// + /// Tracks an access to an external static field. + /// + /// The instance used to rewrite the field expression. + partial void TrackExternalStaticField(StaticFieldRewriter staticFieldRewriter); } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/StaticFieldRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/StaticFieldRewriter.cs index 2d8fddcf..11b3cc55 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/StaticFieldRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/StaticFieldRewriter.cs @@ -23,15 +23,17 @@ namespace ComputeSharp.SourceGeneration.SyntaxRewriters; /// The instance for the target syntax tree. /// The set of discovered custom types. /// The collection of discovered constant definitions. +/// The collection of discovered static field definitions. /// The collection of produced instances. /// The value for the current operation. internal sealed partial class StaticFieldRewriter( SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary constantDefinitions, + IDictionary staticFieldDefinitions, ImmutableArrayBuilder diagnostics, CancellationToken token) - : HlslSourceRewriter(semanticModel, discoveredTypes, constantDefinitions, diagnostics, token) + : HlslSourceRewriter(semanticModel, discoveredTypes, constantDefinitions, staticFieldDefinitions, diagnostics, token) { /// public ExpressionSyntax? Visit(VariableDeclaratorSyntax? node) diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs index c2e3c8d9..6c60560f 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs @@ -59,6 +59,7 @@ partial class ComputeShaderDescriptorGenerator Dictionary instanceMethods = new(SymbolEqualityComparer.Default); Dictionary constructors = new(SymbolEqualityComparer.Default); Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); + Dictionary staticFieldDefinitions = new(SymbolEqualityComparer.Default); // Setup the semantic model and basic properties INamedTypeSymbol? pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: "IComputeShader" }); @@ -93,6 +94,7 @@ partial class ComputeShaderDescriptorGenerator instanceMethods, constructors, constantDefinitions, + staticFieldDefinitions, isComputeShader, token); @@ -105,6 +107,7 @@ partial class ComputeShaderDescriptorGenerator structDeclarationSymbol, discoveredTypes, constantDefinitions, + staticFieldDefinitions, token); token.ThrowIfCancellationRequested(); @@ -251,6 +254,7 @@ partial class ComputeShaderDescriptorGenerator /// The type symbol for the shader type. /// The collection of currently discovered types. /// The collection of discovered constant definitions. + /// The collection of discovered static field definitions. /// The used to cancel the operation, if needed. /// A sequence of static constant fields in . private static ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields( @@ -259,61 +263,47 @@ partial class ComputeShaderDescriptorGenerator INamedTypeSymbol structDeclarationSymbol, ICollection discoveredTypes, IDictionary constantDefinitions, + IDictionary staticFieldDefinitions, CancellationToken token) { using ImmutableArrayBuilder<(string, string, string?)> builder = new(); foreach (ISymbol memberSymbol in structDeclarationSymbol.GetMembers()) { - // Find all declared static fields in the type + // Pre-filter fields that cannot be valid, to reduce the calls to check the [GroupShared] attribute if (memberSymbol is not IFieldSymbol { IsImplicitlyDeclared: false, IsStatic: true, IsConst: false, } fieldSymbol) { continue; } - if (!fieldSymbol.TryGetSyntaxNode(token, out VariableDeclaratorSyntax? variableDeclarator)) - { - continue; - } - + // Ignore [GroupShared] fields, they'll be gathered in a separate rewriting step if (fieldSymbol.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.GroupSharedAttribute", out _)) { continue; } - // Constant properties must be of a primitive, vector or matrix type - if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol || - !HlslKnownTypes.IsKnownHlslType(typeSymbol.GetFullyQualifiedMetadataName())) - { - diagnostics.Add(InvalidShaderStaticFieldType, variableDeclarator, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); - - continue; - } - - _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); - - string typeDeclaration = fieldSymbol.IsReadOnly switch - { - true => $"static const {HlslKnownTypes.GetMappedName(typeSymbol)}", - false => $"static {HlslKnownTypes.GetMappedName(typeSymbol)}" - }; - - token.ThrowIfCancellationRequested(); - - StaticFieldRewriter staticFieldRewriter = new( + if (HlslDefinitionsSyntaxProcessor.TryGetStaticField( + structDeclarationSymbol, + fieldSymbol, semanticModel, discoveredTypes, constantDefinitions, + staticFieldDefinitions, diagnostics, - token); + token, + out string? name, + out string? typeDeclaration, + out string? assignmentExpression, + out _)) + { + builder.Add((name, typeDeclaration, assignmentExpression)); + } + } - ExpressionSyntax? processedDeclaration = staticFieldRewriter.Visit(variableDeclarator); - - token.ThrowIfCancellationRequested(); - - string? assignment = processedDeclaration?.NormalizeWhitespace(eol: "\n").ToFullString(); - - builder.Add((mapping ?? fieldSymbol.Name, typeDeclaration, assignment)); + // Also gather the external static fields + foreach ((string, string, string?) externalField in staticFieldDefinitions.Values) + { + builder.Add(externalField); } return builder.ToImmutable(); @@ -371,6 +361,7 @@ partial class ComputeShaderDescriptorGenerator /// The collection of discovered instance methods for custom struct types. /// The collection of discovered constructors for custom struct types. /// The collection of discovered constant definitions. + /// The collection of discovered static field definitions. /// Indicates whether or not represents a compute shader. /// The used to cancel the operation, if needed. /// A sequence of processed methods in , and the entry point. @@ -383,6 +374,7 @@ partial class ComputeShaderDescriptorGenerator IDictionary instanceMethods, IDictionary constructors, IDictionary constantDefinitions, + IDictionary staticFieldDefinitions, bool isComputeShader, CancellationToken token) { @@ -433,6 +425,7 @@ partial class ComputeShaderDescriptorGenerator instanceMethods, constructors, constantDefinitions, + staticFieldDefinitions, diagnostics, token, isShaderEntryPoint); diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index c2f305f8..85078b3a 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -515,17 +515,17 @@ partial class DiagnosticDescriptors /// /// Gets a for an invalid shader static field type. /// - /// Format: "The compute shader of type {0} contains a static field "{1}" of an invalid type {2} (only primitive, vector and matrix types are supported)". + /// Format: "The compute shader of type {0} contains or references a static field "{1}" of an invalid type {2} (only primitive, vector and matrix types are supported)". /// /// public static readonly DiagnosticDescriptor InvalidShaderStaticFieldType = new( id: "CMPS0038", title: "Invalid shader static field type", - messageFormat: """The compute shader of type {0} contains a static field "{1}" of an invalid type {2} (only primitive, vector and matrix types are supported)""", + messageFormat: """The compute shader of type {0} contains or references a static field "{1}" of an invalid type {2} (only primitive, vector and matrix types are supported)""", category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, - description: "A type representing a compute shader contains a static field of a type that is not supported.", + description: "A type representing a compute shader contains or references a static field of a type that is not supported.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); /// diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 4d684730..9a7b0748 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -48,7 +48,7 @@ partial class ShaderSourceRewriter } /// - private partial void TrackKnownPropertyAccess(IMemberReferenceOperation operation, MemberAccessExpressionSyntax node, string mappedName) + partial void TrackKnownPropertyAccess(IMemberReferenceOperation operation, MemberAccessExpressionSyntax node, string mappedName) { // Mark which dispatch properties have been used, to optimize the declaration afterwards if (operation.Member.IsStatic) @@ -88,10 +88,4 @@ partial class ShaderSourceRewriter } } } - - /// - private partial void TrackKnownMethodInvocation(string metadataName) - { - // No special tracking is needed for DX12 compute shaders - } } \ No newline at end of file diff --git a/tests/ComputeSharp.Tests/ShaderRewriterTests.cs b/tests/ComputeSharp.Tests/ShaderRewriterTests.cs index c0c30d32..1a36df60 100644 --- a/tests/ComputeSharp.Tests/ShaderRewriterTests.cs +++ b/tests/ComputeSharp.Tests/ShaderRewriterTests.cs @@ -5,7 +5,7 @@ using ComputeSharp.Tests.Attributes; using ComputeSharp.Tests.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; -#pragma warning disable IDE0007, IDE0008, IDE0009 +#pragma warning disable IDE0002, IDE0007, IDE0008, IDE0009 namespace ComputeSharp.Tests; @@ -485,6 +485,98 @@ public partial class ShaderRewriterTests } } + [CombinatorialTestMethod] + [AllDevices] + public void ShaderWithMixedStaticFieldsInExternalTypes(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(16); + + device.Get().For(1, new MixedStaticFieldsInExternalTypesShader(buffer)); + + float[] results = buffer.ToArray(); + + Assert.AreEqual(3.14f, results[0]); + Assert.AreEqual(111, results[1]); + Assert.AreEqual(0, results[2]); + Assert.AreEqual(222, results[3]); + Assert.AreEqual(6.28f, results[4]); + Assert.AreEqual(42, results[5]); + Assert.AreEqual(0, results[6]); + Assert.AreEqual(333, results[7]); + Assert.AreEqual(2, results[8]); + Assert.AreEqual(444, results[9]); + Assert.AreEqual(123, results[10]); + Assert.AreEqual(666, results[11]); + Assert.AreEqual(3.14f, results[12]); + Assert.AreEqual(3.14f, results[13]); + Assert.AreEqual(6.28f, results[14]); + } + + [AutoConstructor] + [ThreadGroupSize(DefaultThreadGroupSizes.X)] + [GeneratedComputeShaderDescriptor] + internal readonly partial struct MixedStaticFieldsInExternalTypesShader : IComputeShader + { + public static readonly float PI = 3.14f; + public static readonly int A = 111; + public static int B; + public static int C = 222; + + private readonly ReadWriteBuffer buffer; + + public void Execute() + { + // Read static fields from this shader + buffer[0] = PI; + buffer[1] = A; + buffer[2] = B; + buffer[3] = C; + + // Read static fields from an external type + buffer[4] = ExternalType.PI2; + buffer[5] = ExternalType.A; + buffer[6] = ExternalType.B; + buffer[7] = ExternalType.C; + + // Mutate the fields and check again + B += 2; + C *= 2; + ExternalType.B = 123; + ExternalType.C *= 2; + + buffer[8] = B; + buffer[9] = C; + buffer[10] = ExternalType.B; + buffer[11] = ExternalType.C; + + // Access shader fields via a member access + buffer[12] = MixedStaticFieldsInExternalTypesShader.PI; + buffer[13] = ExternalType.ReadPI(); + + // Access an external field as an identifier name + buffer[14] = ExternalType.ReadPI2(); + } + } + + internal static class ExternalType + { + public static readonly float PI2 = 6.28f; + public static readonly int A = 42; + public static int B; + public static int C = 333; + + public static float ReadPI() + { + return MixedStaticFieldsInExternalTypesShader.PI; + } + + // See https://github.com/Sergio0694/ComputeSharp/issues/298 + public static float ReadPI2() + { + return PI2; + } + } + // See https://github.com/Sergio0694/ComputeSharp/issues/278 [CombinatorialTestMethod] [AllDevices]