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.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs index 22919a98..97f6d3d6 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,97 @@ 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 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, + 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, + 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.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"); ///