Merge pull request #703 from Sergio0694/dev/external-static-fields

Implement full support for static fields
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2023-12-06 21:58:02 +01:00
コミット f56458d4c9
11ファイル変更
+400 -171

検索条件に一致するファイルはありません

+27 -36
ファイルの表示
@@ -53,6 +53,7 @@ partial class D2DPixelShaderDescriptorGenerator
Dictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods = new(SymbolEqualityComparer.Default);
Dictionary<IMethodSymbol, (MethodDeclarationSyntax, MethodDeclarationSyntax)> constructors = new(SymbolEqualityComparer.Default);
Dictionary<IFieldSymbol, string> constantDefinitions = new(SymbolEqualityComparer.Default);
Dictionary<IFieldSymbol, (string, string, string?)> 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
/// <param name="structDeclarationSymbol">The type symbol for the shader type.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="staticFieldDefinitions">The collection of discovered static field definitions.</param>
/// <param name="token">The <see cref="CancellationToken"/> used to cancel the operation, if needed.</param>
/// <param name="needsD2D1RequiresScenePosition">Whether or not the shader needs the <c>[D2DRequiresScenePosition]</c> annotation.</param>
/// <returns>A sequence of static constant fields in <paramref name="structDeclarationSymbol"/>.</returns>
@@ -247,6 +251,7 @@ partial class D2DPixelShaderDescriptorGenerator
INamedTypeSymbol structDeclarationSymbol,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions,
IDictionary<IFieldSymbol, (string, string, string?)> 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
/// <param name="instanceMethods">The collection of discovered instance methods for custom struct types.</param>
/// <param name="constructors">The collection of discovered constructors for custom struct types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="staticFieldDefinitions">The collection of discovered static field definitions.</param>
/// <param name="needsD2D1RequiresScenePosition">Whether or not the shader needs the <c>[D2DRequiresScenePosition]</c> annotation.</param>
/// <param name="token">The <see cref="CancellationToken"/> used to cancel the operation, if needed.</param>
/// <returns>A sequence of processed methods in <paramref name="structDeclarationSymbol"/>, and the entry point.</returns>
@@ -330,6 +319,7 @@ partial class D2DPixelShaderDescriptorGenerator
IDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods,
IDictionary<IMethodSymbol, (MethodDeclarationSyntax, MethodDeclarationSyntax)> constructors,
IDictionary<IFieldSymbol, string> constantDefinitions,
IDictionary<IFieldSymbol, (string, string, string?)> staticFieldDefinitions,
CancellationToken token,
out bool needsD2D1RequiresScenePosition)
{
@@ -374,6 +364,7 @@ partial class D2DPixelShaderDescriptorGenerator
instanceMethods,
constructors,
constantDefinitions,
staticFieldDefinitions,
diagnostics,
token,
isShaderEntryPoint);
+5 -5
ファイルの表示
@@ -397,19 +397,19 @@ partial class DiagnosticDescriptors
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid shader static readonly field type.
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid static field type.
/// <para>
/// Format: <c>"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)"</c>.
/// Format: <c>"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)"</c>.
/// </para>
/// </summary>
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");
/// <summary>
+4 -8
ファイルの表示
@@ -29,18 +29,14 @@ partial class ShaderSourceRewriter
}
/// <inheritdoc/>
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);
}
/// <inheritdoc/>
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;
}
}
@@ -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();
}
/// <summary>
/// Tries to get and rewrite a given static field to be used in a shader.
/// </summary>
/// <param name="structDeclarationSymbol">The type symbol for the shader type.</param>
/// <param name="fieldSymbol">The symbol for the field to analyze.</param>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the type to process.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="staticFieldDefinitions">The collection of discovered static field definitions.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="token">The <see cref="CancellationToken"/> used to cancel the operation, if needed.</param>
/// <param name="name">The mapped name for the field.</param>
/// <param name="typeDeclaration">The type declaration for the field.</param>
/// <param name="assignmentExpression">The assignment expression for the field, if present.</param>
/// <param name="staticFieldRewriter">The <see cref="StaticFieldRewriter"/> instance used to rewrite the field expression.</param>
/// <returns>Whether the field was processed successfully and is valid.</returns>
public static bool TryGetStaticField(
INamedTypeSymbol structDeclarationSymbol,
IFieldSymbol fieldSymbol,
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions,
IDictionary<IFieldSymbol, (string, string, string?)> staticFieldDefinitions,
ImmutableArrayBuilder<DiagnosticInfo> 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;
}
/// <summary>
/// Gets the sequence of processed discovered custom types.
/// </summary>
+14 -2
ファイルの表示
@@ -33,18 +33,21 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
/// <param name="semanticModel">The <see cref="Microsoft.CodeAnalysis.SemanticModel"/> instance for the target syntax tree.</param>
/// <param name="discoveredTypes">The set of discovered custom types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="staticFieldDefinitions">The collection of discovered static field definitions.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="token">The <see cref="System.Threading.CancellationToken"/> value for the current operation.</param>
protected HlslSourceRewriter(
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions,
IDictionary<IFieldSymbol, (string, string, string?)> staticFieldDefinitions,
ImmutableArrayBuilder<DiagnosticInfo> 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
/// </summary>
protected IDictionary<IFieldSymbol, string> ConstantDefinitions { get; }
/// <summary>
/// Gets the collection of discovered static field definitions.
/// </summary>
protected IDictionary<IFieldSymbol, (string, string, string?)> StaticFieldDefinitions { get; }
/// <summary>
/// Gets the collection of produced <see cref="DiagnosticInfo"/> instances.
/// </summary>
@@ -382,11 +390,15 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
}
/// <inheritdoc/>
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)
{
+126 -74
ファイルの表示
@@ -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;
/// <summary>
/// A custom <see cref="CSharpSyntaxRewriter"/> type that processes C# methods to convert to HLSL compliant code.
/// </summary>
internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
/// <param name="shaderType">The type symbol for the shader type.</param>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the target syntax tree.</param>
/// <param name="discoveredTypes">The set of discovered custom types.</param>
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
/// <param name="instanceMethods">The collection of discovered instance methods for custom struct types.</param>
/// <param name="constructors">The collection of discovered constructors for custom struct types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="staticFieldDefinitions">The collection of discovered static field definitions.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="token">The <see cref="CancellationToken"/> value for the current operation.</param>
/// <param name="isEntryPoint">Whether or not the current instance is processing a shader entry point.</param>
internal sealed partial class ShaderSourceRewriter(
INamedTypeSymbol shaderType,
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods,
IDictionary<IMethodSymbol, (MethodDeclarationSyntax, MethodDeclarationSyntax)> constructors,
IDictionary<IFieldSymbol, string> constantDefinitions,
IDictionary<IFieldSymbol, (string, string, string?)> staticFieldDefinitions,
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
CancellationToken token,
bool isEntryPoint = false)
: HlslSourceRewriter(semanticModel, discoveredTypes, constantDefinitions, staticFieldDefinitions, diagnostics, token)
{
/// <summary>
/// The type symbol for the shader type.
/// </summary>
private readonly INamedTypeSymbol? shaderType;
private readonly INamedTypeSymbol shaderType = shaderType;
/// <summary>
/// The collection of discovered static methods.
/// </summary>
private readonly IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods;
private readonly IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods = staticMethods;
/// <summary>
/// The collection of discovered instance methods for custom struct types.
/// </summary>
private readonly IDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods;
private readonly IDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods = instanceMethods;
/// <summary>
/// The collection of discovered constructors for custom struct types.
/// </summary>
private readonly IDictionary<IMethodSymbol, (MethodDeclarationSyntax Stub, MethodDeclarationSyntax Ctor)> constructors;
private readonly IDictionary<IMethodSymbol, (MethodDeclarationSyntax Stub, MethodDeclarationSyntax Ctor)> constructors = constructors;
/// <summary>
/// The collection of processed local functions in the current tree.
/// </summary>
private readonly Dictionary<string, LocalFunctionStatementSyntax> localFunctions;
private readonly Dictionary<string, LocalFunctionStatementSyntax> localFunctions = [];
/// <summary>
/// The list of implicit variables to declare at the start of the body.
/// </summary>
private readonly List<VariableDeclarationSyntax> implicitVariables;
private readonly List<VariableDeclarationSyntax> implicitVariables = [];
/// <summary>
/// Whether or not the current instance is processing a shader entry point.
/// </summary>
private readonly bool isEntryPoint;
private readonly bool isEntryPoint = isEntryPoint;
/// <summary>
/// The identifier of the current <see cref="ConstructorDeclarationSyntax"/>, <see cref="MethodDeclarationSyntax"/>
@@ -67,70 +92,6 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
/// </summary>
private int localFunctionDepth;
/// <summary>
/// Creates a new <see cref="ShaderSourceRewriter"/> instance with the specified parameters.
/// </summary>
/// <param name="shaderType">The type symbol for the shader type.</param>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the target syntax tree.</param>
/// <param name="discoveredTypes">The set of discovered custom types.</param>
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
/// <param name="instanceMethods">The collection of discovered instance methods for custom struct types.</param>
/// <param name="constructors">The collection of discovered constructors for custom struct types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="token">The <see cref="CancellationToken"/> value for the current operation.</param>
/// <param name="isEntryPoint">Whether or not the current instance is processing a shader entry point.</param>
public ShaderSourceRewriter(
INamedTypeSymbol shaderType,
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods,
IDictionary<IMethodSymbol, (MethodDeclarationSyntax, MethodDeclarationSyntax)> constructors,
IDictionary<IFieldSymbol, string> constantDefinitions,
ImmutableArrayBuilder<DiagnosticInfo> 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;
}
/// <summary>
/// Creates a new <see cref="ShaderSourceRewriter"/> instance with the specified parameters.
/// </summary>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the target syntax tree.</param>
/// <param name="discoveredTypes">The set of discovered custom types.</param>
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
/// <param name="instanceMethods">The collection of discovered instance methods for custom struct types.</param>
/// <param name="constructors">The collection of discovered constructors for custom struct types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="token">The <see cref="CancellationToken"/> value for the current operation.</param>
private ShaderSourceRewriter(
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods,
IDictionary<IMethodSymbol, (MethodDeclarationSyntax, MethodDeclarationSyntax)> constructors,
IDictionary<IFieldSymbol, string> constantDefinitions,
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
CancellationToken token)
: base(semanticModel, discoveredTypes, constantDefinitions, diagnostics, token)
{
this.staticMethods = staticMethods;
this.instanceMethods = instanceMethods;
this.constructors = constructors;
this.implicitVariables = [];
this.localFunctions = [];
}
/// <summary>
/// Gets the collection of processed local functions in the current tree.
/// </summary>
@@ -373,6 +334,26 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
}
}
/// <inheritdoc/>
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);
}
/// <inheritdoc/>
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);
}
/// <summary>
/// Visits a static field access in an external type and rewrites it as needed.
/// </summary>
/// <param name="node">The current <see cref="SyntaxNode"/> instance for the static field.</param>
/// <param name="fieldSymbol">The <see cref="IFieldSymbol"/> instance for <paramref name="node"/>.</param>
/// <returns>The rewritten static field expression.</returns>
[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);
}
/// <summary>
/// Rewrites a sampled texture access.
/// </summary>
@@ -771,11 +817,17 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
/// <param name="operation">The <see cref="IMemberReferenceOperation"/> instance for the operation.</param>
/// <param name="node">The <see cref="MemberAccessExpressionSyntax"/> instance for the operation.</param>
/// <param name="mappedName">The mapped name for the property access.</param>
private partial void TrackKnownPropertyAccess(IMemberReferenceOperation operation, MemberAccessExpressionSyntax node, string mappedName);
partial void TrackKnownPropertyAccess(IMemberReferenceOperation operation, MemberAccessExpressionSyntax node, string mappedName);
/// <summary>
/// Tracks a method invocation for a known HLSL method.
/// </summary>
/// <param name="metadataName">The metadata name of the method being invoked.</param>
private partial void TrackKnownMethodInvocation(string metadataName);
partial void TrackKnownMethodInvocation(string metadataName);
/// <summary>
/// Tracks an access to an external static field.
/// </summary>
/// <param name="staticFieldRewriter">The <see cref="StaticFieldRewriter"/> instance used to rewrite the field expression.</param>
partial void TrackExternalStaticField(StaticFieldRewriter staticFieldRewriter);
}
+3 -1
ファイルの表示
@@ -23,15 +23,17 @@ namespace ComputeSharp.SourceGeneration.SyntaxRewriters;
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the target syntax tree.</param>
/// <param name="discoveredTypes">The set of discovered custom types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="staticFieldDefinitions">The collection of discovered static field definitions.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="token">The <see cref="CancellationToken"/> value for the current operation.</param>
internal sealed partial class StaticFieldRewriter(
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions,
IDictionary<IFieldSymbol, (string, string, string?)> staticFieldDefinitions,
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
CancellationToken token)
: HlslSourceRewriter(semanticModel, discoveredTypes, constantDefinitions, diagnostics, token)
: HlslSourceRewriter(semanticModel, discoveredTypes, constantDefinitions, staticFieldDefinitions, diagnostics, token)
{
/// <inheritdoc cref="CSharpSyntaxRewriter.Visit(SyntaxNode?)"/>
public ExpressionSyntax? Visit(VariableDeclaratorSyntax? node)
+27 -34
ファイルの表示
@@ -59,6 +59,7 @@ partial class ComputeShaderDescriptorGenerator
Dictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods = new(SymbolEqualityComparer.Default);
Dictionary<IMethodSymbol, (MethodDeclarationSyntax, MethodDeclarationSyntax)> constructors = new(SymbolEqualityComparer.Default);
Dictionary<IFieldSymbol, string> constantDefinitions = new(SymbolEqualityComparer.Default);
Dictionary<IFieldSymbol, (string, string, string?)> 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
/// <param name="structDeclarationSymbol">The type symbol for the shader type.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="staticFieldDefinitions">The collection of discovered static field definitions.</param>
/// <param name="token">The <see cref="CancellationToken"/> used to cancel the operation, if needed.</param>
/// <returns>A sequence of static constant fields in <paramref name="structDeclarationSymbol"/>.</returns>
private static ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields(
@@ -259,61 +263,47 @@ partial class ComputeShaderDescriptorGenerator
INamedTypeSymbol structDeclarationSymbol,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions,
IDictionary<IFieldSymbol, (string, string, string?)> 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
/// <param name="instanceMethods">The collection of discovered instance methods for custom struct types.</param>
/// <param name="constructors">The collection of discovered constructors for custom struct types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="staticFieldDefinitions">The collection of discovered static field definitions.</param>
/// <param name="isComputeShader">Indicates whether or not <paramref name="structDeclarationSymbol"/> represents a compute shader.</param>
/// <param name="token">The <see cref="CancellationToken"/> used to cancel the operation, if needed.</param>
/// <returns>A sequence of processed methods in <paramref name="structDeclarationSymbol"/>, and the entry point.</returns>
@@ -383,6 +374,7 @@ partial class ComputeShaderDescriptorGenerator
IDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods,
IDictionary<IMethodSymbol, (MethodDeclarationSyntax, MethodDeclarationSyntax)> constructors,
IDictionary<IFieldSymbol, string> constantDefinitions,
IDictionary<IFieldSymbol, (string, string, string?)> staticFieldDefinitions,
bool isComputeShader,
CancellationToken token)
{
@@ -433,6 +425,7 @@ partial class ComputeShaderDescriptorGenerator
instanceMethods,
constructors,
constantDefinitions,
staticFieldDefinitions,
diagnostics,
token,
isShaderEntryPoint);
+3 -3
ファイルの表示
@@ -515,17 +515,17 @@ partial class DiagnosticDescriptors
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid shader static field type.
/// <para>
/// Format: <c>"The compute shader of type {0} contains a static field "{1}" of an invalid type {2} (only primitive, vector and matrix types are supported)"</c>.
/// Format: <c>"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)"</c>.
/// </para>
/// </summary>
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");
/// <summary>
+1 -7
ファイルの表示
@@ -48,7 +48,7 @@ partial class ShaderSourceRewriter
}
/// <inheritdoc/>
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
}
}
}
/// <inheritdoc/>
private partial void TrackKnownMethodInvocation(string metadataName)
{
// No special tracking is needed for DX12 compute shaders
}
}
+93 -1
ファイルの表示
@@ -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<float> buffer = device.Get().AllocateReadWriteBuffer<float>(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<float> 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]