Merge pull request #103 from Sergio0694/feature/constant-properties

Added shader constants support
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2021-03-07 22:52:55 +01:00
コミット c7ace92509
16ファイル変更
+1106 -527

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

+24 -1
ファイルの表示
@@ -13,6 +13,7 @@
- [GPU resource types](#gpu-resource-types)
- [HLSL vector and matrix types](#hlsl-vector-and-matrix-types)
- [HLSL intrinsics](#hlsl-intrinsics)
- [Shader constants](#shader-constants)
- [Working with images](#working-with-images)
- [Shader metaprogramming](#shader-metaprogramming)
- [Requirements](#requirements)
@@ -139,7 +140,7 @@ public readonly struct SoftmaxActivation : IComputeShader
public readonly ReadWriteBuffer<float> buffer;
public readonly float k;
public void Execute(ThreadIds ids)
public void Execute()
{
float exp = Hlsl.Exp(k * buffer[ThreadIds.X]);
float log = Hlsl.Log(1 + exp);
@@ -149,6 +150,28 @@ public readonly struct SoftmaxActivation : IComputeShader
}
```
## Shader constants
One common approach to make shaders easier to modify and experiment with is to separate the parameters being used from the code using them, by defining them as constants. **ComputeSharp** has special handling for this, and will rewrite static readonly properties as static constants in the generated shaders, which are optimized by the compiler for frequent access during execution. The advantage of using constants is that they're directly embedded into a compiled shader, so they don't need to be loaded in memory whenever a shader is dispatched. Constant properties can be of any of the supported HLSL primitive types, including vector and matrix types. Furthermore, the initialization of these constants can also use any of the available HLSL intrinsics. If the same result is being used multiple times while a shader is executed, moving values to a shader constant is a good way to avoid repeatedly computing the same value over and over for each invocation.
Here is an example of how shader constants can be declared and used:
```csharp
[AutoConstructor]
public readonly struct SampleShaderWithConstants : IComputeShader
{
public readonly ReadWriteBuffer<float> buffer;
private static float Pi => 3.14f;
private static Float2 SinCosPi => new(Hlsl.Sin(Pi), Hlsl.Cos(Pi));
public void Execute()
{
buffer[ThreadIds.X] = Pi + SinCosPi.X * SinCosPi.Y;
}
}
```
## Working with images
As mentioned in the [GPU resource types](#gpu-resource-types) paragraph, there are several texture types that are specialized to work on image pixels, such as `ReadWriteTexture2D<T, TPixel>`. Let's imagine we want to write a compute shader that applies some image processing filter: we will need to load an image (eg. using [ImageSharp](https://github.com/SixLabors/ImageSharp), or just the `System.Drawing` APIs) and then process it on the GPU, but without spending time on the CPU to convert pixels from a format such as RGBA32 to the normalized `float` values we want our shader to work on. We can do this by utilizing the `ReadWriteTexture2D<T, TPixel>` type as follows:
+10 -5
ファイルの表示
@@ -30,6 +30,12 @@
private const float Ambient = 0.32184f;
private const float Diffuse = 0.5f;
private static Float3 LightDir => 1.0f;
private static Float3 LightColor => new(1.0f, 1.0f, 0.858824f);
private static Float3 LightDir2 => new(1.0f, -1.0f, 1.0f);
private static Float3 LightColor2 => new(0, 0.333333f, 1.0f);
private static Float3 Offset => new(0.92858f, 0.92858f, 0.32858f);
/// <summary>
/// Rotates a given <see cref="Float2"/> value by a specified amount.
/// </summary>
@@ -44,15 +50,15 @@
/// </summary>
private static Float3 GetLight(in Float3 color, in Float3 normal)
{
Float3 lightDir = Hlsl.Normalize((Float3)1);
Float3 lightDir = Hlsl.Normalize(LightDir);
float diffuse = Hlsl.Max(0.0f, Hlsl.Dot(-normal, lightDir));
Float3 lightDir2 = Hlsl.Normalize(new Float3(1.0f, -1.0f, 1.0f));
Float3 lightDir2 = Hlsl.Normalize(LightDir2);
float diffuse2 = Hlsl.Max(0.0f, Hlsl.Dot(-normal, lightDir2));
return
(diffuse * Diffuse) * (new Float3(1.0f, 1.0f, 0.858824f) * color) +
(diffuse2 * Diffuse) * (new Float3(0.0f, 0.333333f, 1.0f) * color);
(diffuse * Diffuse) * (LightColor * color) +
(diffuse2 * Diffuse) * (LightColor2 * color);
}
/// <summary>
@@ -70,7 +76,6 @@
z = Hlsl.Abs(1.0f - Mod(z, 2.0f));
float d = 1000.0f;
Float3 Offset = new(0.92858f, 0.92858f, 0.32858f);
for (int n = 0; n < Iterations; n++)
{
+2 -2
ファイルの表示
@@ -19,6 +19,8 @@
/// </summary>
public readonly float time;
private static Float3x3 m3 => new Float3x3(0.33338f, 0.56034f, -0.71817f, -0.87887f, 0.32651f, -0.15323f, 0.15162f, 0.69596f, 0.61339f) * 1.93f;
private static Float2x2 Rotate(in float a)
{
float c = Hlsl.Cos(a), s = Hlsl.Sin(a);
@@ -59,8 +61,6 @@
z *= 0.57f;
trk *= 1.4f;
Float3x3 m3 = new Float3x3(0.33338f, 0.56034f, -0.71817f, -0.87887f, 0.32651f, -0.15323f, 0.15162f, 0.69596f, 0.61339f) * 1.93f;
p = Hlsl.Mul(p, m3);
}
+5 -1
ファイルの表示
@@ -46,4 +46,8 @@ CMPS0038 | ComputeSharp.SourceGenerators.IComputeShaderDataLoaderGenerator | War
CMPS0039 | ComputeSharp.SourceGenerators.IComputeShaderHashCodeGenerator | Warning | IComputeShaderHashCodeGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0040 | ComputeSharp.SourceGenerators.IComputeShaderSourceGenerator | Warning | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0041 | ComputeSharp.SourceGenerators.ShaderMethodSourceGenerator | Warning | ShaderMethodSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0042 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0042 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0043 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0044 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0045 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0046 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+64 -12
ファイルの表示
@@ -89,9 +89,6 @@ namespace ComputeSharp.SourceGenerators.Diagnostics
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid <see cref="ThreadIds"/> usage.
/// <para>
/// Format: <c>"The ThreadIds type is used in method {0} of type {1}"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor InvalidThreadIdsUsage = new(
id: "CMPS0006",
@@ -105,9 +102,6 @@ namespace ComputeSharp.SourceGenerators.Diagnostics
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid <see cref="GroupIds"/> usage.
/// <para>
/// Format: <c>"The GroupIds type is used in method {0} of type {1}"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor InvalidGroupIdsUsage = new(
id: "CMPS0007",
@@ -121,9 +115,6 @@ namespace ComputeSharp.SourceGenerators.Diagnostics
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid <see cref="GroupSize"/> usage.
/// <para>
/// Format: <c>"The GroupSize type is used in method {0} of type {1}"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor InvalidGroupSizeUsage = new(
id: "CMPS0008",
@@ -137,9 +128,6 @@ namespace ComputeSharp.SourceGenerators.Diagnostics
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid <see cref="WarpIds"/> usage.
/// <para>
/// Format: <c>"The WarpIds type is used in method {0} of type {1}"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor InvalidWarpIdsUsage = new(
id: "CMPS0009",
@@ -600,5 +588,69 @@ namespace ComputeSharp.SourceGenerators.Diagnostics
isEnabledByDefault: true,
description: "The arguments in a swizzled indexer for a matrix type must be compile-time constants.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid shader constant property type.
/// <para>
/// Format: <c>"The compute shader of type {0} contains a constant property \"{1}\" of an invalid type {2} (only primitive, vector and matrix types are supported)"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor InvalidShaderConstantPropertyType = new(
id: "CMPS0043",
title: "Invalid shader constant property type",
messageFormat: "The compute shader of type {0} contains a constant property \"{1}\" of an invalid type {2} (only primitive, vector and matrix types are supported)",
category: typeof(IComputeShader).FullName,
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A type representing a compute shader contains a constant property of a type that is not supported.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid shader constant property declaration.
/// <para>
/// Format: <c>"The compute shader of type {0} contains a constant property \"{1}\" with an invalid declaration (must use a lambda expression)"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor InvalidShaderConstantPropertyDeclaration = new(
id: "CMPS0044",
title: "Invalid shader constant property",
messageFormat: "The compute shader of type {0} contains a constant property \"{1}\" with an invalid declaration (must use a lambda expression)",
category: typeof(IComputeShader).FullName,
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A type representing a compute shader contains a constant property with an invalid declaration.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid shader constant property declaration.
/// <para>
/// Format: <c>"The compute shader of type {0} contains a mutable property \"{1}\" (only readonly properties are supported)"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor NonReadonlyShaderPropertyDeclaration = new(
id: "CMPS0045",
title: "Invalid shader constant property",
messageFormat: "The compute shader of type {0} contains a mutable property \"{1}\" (only readonly properties are supported)",
category: typeof(IComputeShader).FullName,
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A type representing a compute shader contains a non readonly property declaration.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid shader constant property declaration.
/// <para>
/// Format: <c>"The compute shader of type {0} contains an instance property \"{1}\" (only static properties are supported)"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor InstanceShaderPropertyDeclaration = new(
id: "CMPS0046",
title: "Invalid shader constant property",
messageFormat: "The compute shader of type {0} contains an instance property \"{1}\" (only static properties are supported)",
category: typeof(IComputeShader).FullName,
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A type representing a compute shader contains an instance property declaration.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
}
}
+78 -4
ファイルの表示
@@ -71,12 +71,13 @@ namespace ComputeSharp.SourceGenerators
Dictionary<IFieldSymbol, string> constantDefinitions = new(SymbolEqualityComparer.Default);
// Explore the syntax tree and extract the processed info
var processedMembers = GetProcessedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray();
var processedMembers = GetProcessedFields(context, structDeclarationSymbol, discoveredTypes).ToArray();
var sharedBuffers = GetGroupSharedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray();
var (entryPoint, localFunctions) = GetProcessedMethods(context, 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(constantDefinitions);
var staticConstants = GetConstantProperties(context, semanticModel, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions);
// Create the compilation unit with the source attribute
var source =
@@ -90,6 +91,7 @@ namespace ComputeSharp.SourceGenerators
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(entryPoint))),
AttributeArgument(ArrayExpression(processedMethods)),
AttributeArgument(NestedArrayExpression(processedConstants)),
AttributeArgument(NestedArrayExpression(staticConstants)),
AttributeArgument(NestedArrayExpression(sharedBuffers)))))
.WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList()))
.WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword))))
@@ -101,14 +103,14 @@ namespace ComputeSharp.SourceGenerators
}
/// <summary>
/// Gets a sequence of captured members and their mapped names.
/// Gets a sequence of captured fields and their mapped names.
/// </summary>
/// <param name="context">The current generator context in use.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="types">The collection of currently discovered types.</param>
/// <returns>A sequence of captured members in <paramref name="structDeclarationSymbol"/>.</returns>
/// <returns>A sequence of captured fields in <paramref name="structDeclarationSymbol"/>.</returns>
[Pure]
private static IEnumerable<IEnumerable<string>> GetProcessedMembers(
private static IEnumerable<IEnumerable<string>> GetProcessedFields(
GeneratorExecutionContext context,
INamedTypeSymbol structDeclarationSymbol,
ICollection<INamedTypeSymbol> types)
@@ -171,6 +173,78 @@ namespace ComputeSharp.SourceGenerators
}
}
/// <summary>
/// Gets a sequence of shader static constant properties and their mapped names.
/// </summary>
/// <param name="context">The current generator context in use.</param>
/// <param name="semanticModel">The <see cref="SemanticModel"/> instance for the type to process.</param>
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> instance for the current type.</param>
/// <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>
/// <returns>A sequence of static constant properties in <paramref name="structDeclarationSymbol"/>.</returns>
[Pure]
private static IEnumerable<IEnumerable<string>> GetConstantProperties(
GeneratorExecutionContext context,
SemanticModel semanticModel,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions)
{
foreach (var propertyDeclaration in structDeclaration.Members.OfType<PropertyDeclarationSyntax>())
{
IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(propertyDeclaration)!;
if (!propertySymbol.IsStatic)
{
context.ReportDiagnostic(InstanceShaderPropertyDeclaration, propertyDeclaration, structDeclarationSymbol, propertySymbol.Name);
continue;
}
if (!propertySymbol.IsReadOnly)
{
context.ReportDiagnostic(NonReadonlyShaderPropertyDeclaration, propertyDeclaration, structDeclarationSymbol, propertySymbol.Name);
continue;
}
// Constant properties must be named type symbols
if (propertySymbol.Type is not INamedTypeSymbol typeSymbol)
{
context.ReportDiagnostic(InvalidShaderConstantPropertyType, propertyDeclaration, structDeclarationSymbol, propertySymbol.Name, propertySymbol.Type);
continue;
}
string metadataName = typeSymbol.GetFullMetadataName();
// Constant properties must be of a primitive, vector or matrix type
if (!HlslKnownTypes.IsKnownHlslType(metadataName))
{
context.ReportDiagnostic(InvalidShaderConstantPropertyType, propertyDeclaration, structDeclarationSymbol, propertySymbol.Name, propertySymbol.Type);
continue;
}
ConstantPropertyRewriter constantPropertyRewriter = new(
semanticModel,
discoveredTypes,
constantDefinitions,
context);
if (constantPropertyRewriter.Visit(propertyDeclaration) is ExpressionSyntax expression)
{
string typeName = HlslKnownTypes.GetMappedName(typeSymbol);
_ = HlslKnownKeywords.TryGetMappedName(propertySymbol.Name, out string? mapping);
yield return new[] { mapping ?? propertySymbol.Name, typeName, expression.NormalizeWhitespace().ToFullString() };
}
}
}
/// <summary>
/// Gets a sequence of captured members and their mapped names.
/// </summary>
+140
ファイルの表示
@@ -0,0 +1,140 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using ComputeSharp.SourceGenerators.Diagnostics;
using ComputeSharp.SourceGenerators.Extensions;
using ComputeSharp.SourceGenerators.Mappings;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Operations;
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.SourceGenerators.SyntaxRewriters
{
/// <summary>
/// A custom <see cref="CSharpSyntaxRewriter"/> type that processes C# static properties to convert to HLSL static constants.
/// </summary>
internal sealed class ConstantPropertyRewriter : HlslSourceRewriter
{
/// <summary>
/// Creates a new <see cref="ConstantPropertyRewriter"/> instance with the specified parameters.
/// </summary>
/// <param name="semanticModel">The <see cref="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="context">The current generator context in use.</param>
public ConstantPropertyRewriter(
SemanticModel semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions,
GeneratorExecutionContext context)
: base(semanticModel, discoveredTypes, constantDefinitions, context)
{
}
/// <inheritdoc cref="CSharpSyntaxRewriter.Visit(SyntaxNode?)"/>
public ExpressionSyntax? Visit(PropertyDeclarationSyntax? node)
{
if (node!.ExpressionBody is null)
{
Context.ReportDiagnostic(
InvalidShaderConstantPropertyDeclaration,
node,
SemanticModel.GetDeclaredSymbol(node.FirstAncestorOrSelf<StructDeclarationSyntax>()!)!,
SemanticModel.GetDeclaredSymbol(node)!.Name);
return null;
}
ArrowExpressionClauseSyntax? updatedNode = (ArrowExpressionClauseSyntax?)Visit(node.ExpressionBody)!;
return updatedNode.Expression;
}
/// <inheritdoc/>
public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node)
{
var updatedNode = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node)!;
if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) &&
SemanticModel.GetOperation(node) is IMemberReferenceOperation operation)
{
// Track and replace constants
if (operation is IFieldReferenceOperation fieldOperation &&
fieldOperation.Field.IsConst &&
fieldOperation.Type.TypeKind != TypeKind.Enum)
{
ConstantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture);
var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().Replace(".", "__");
var constantName = $"__{ownerTypeName}__{fieldOperation.Field.Name}";
return IdentifierName(constantName);
}
if (HlslKnownMembers.TryGetMappedName(operation.Member.ToDisplayString(), out string? mapping))
{
if (operation.Member.IsStatic)
{
string typeName = operation.Member.ContainingType.GetFullMetadataName();
// Special dispatch types are not supported from static constants
DiagnosticDescriptor? descriptor = typeName switch
{
_ when typeName == typeof(ThreadIds).FullName => InvalidThreadIdsUsage,
_ when typeName == typeof(GroupIds).FullName => InvalidGroupIdsUsage,
_ when typeName == typeof(GroupSize).FullName => InvalidGroupSizeUsage,
_ when typeName == typeof(WarpIds).FullName => InvalidWarpIdsUsage,
_ => null
};
if (descriptor is not null)
{
Context.ReportDiagnostic(descriptor, node);
}
}
// Rewrite static and instance mapped members
return operation.Member.IsStatic switch
{
true => ParseExpression(mapping!),
false => updatedNode.WithName(IdentifierName(mapping!))
};
}
}
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node)
{
var updatedNode = (InvocationExpressionSyntax)base.VisitInvocationExpression(node)!;
if (SemanticModel.GetOperation(node) is IInvocationOperation operation &&
operation.TargetMethod is IMethodSymbol method &&
method.IsStatic)
{
// Rewrite HLSL intrinsic methods
if (HlslKnownMethods.TryGetMappedName(method.GetFullMetadataName(), out string? mapping))
{
return updatedNode.WithExpression(ParseExpression(mapping!));
}
}
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxNode? VisitArgument(ArgumentSyntax node)
{
var updatedNode = (ArgumentSyntax)base.VisitArgument(node)!;
updatedNode = updatedNode.WithRefKindKeyword(Token(SyntaxKind.None));
return updatedNode;
}
}
}
+221
ファイルの表示
@@ -0,0 +1,221 @@
using ComputeSharp.SourceGenerators.Diagnostics;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
namespace ComputeSharp.SourceGenerators.SyntaxRewriters
{
/// <inheritdoc cref="HlslSourceRewriter"/>
internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
{
/// <inheritdoc/>
public override SyntaxNode? VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
{
var updatedNode = (AnonymousObjectCreationExpressionSyntax)base.VisitAnonymousObjectCreationExpression(node)!;
Context.ReportDiagnostic(AnonymousObjectCreationExpression, node);
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxNode? VisitAwaitExpression(AwaitExpressionSyntax node)
{
Context.ReportDiagnostic(AwaitExpression, node);
return base.VisitAwaitExpression(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitCheckedExpression(CheckedExpressionSyntax node)
{
Context.ReportDiagnostic(CheckedExpression, node);
return base.VisitCheckedExpression(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitCheckedStatement(CheckedStatementSyntax node)
{
Context.ReportDiagnostic(CheckedStatement, node);
return base.VisitCheckedStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitFixedStatement(FixedStatementSyntax node)
{
Context.ReportDiagnostic(FixedStatement, node);
return base.VisitFixedStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitForEachStatement(ForEachStatementSyntax node)
{
Context.ReportDiagnostic(ForEachStatement, node);
return base.VisitForEachStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitForEachVariableStatement(ForEachVariableStatementSyntax node)
{
Context.ReportDiagnostic(ForEachStatement, node);
return base.VisitForEachVariableStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitLockStatement(LockStatementSyntax node)
{
Context.ReportDiagnostic(LockStatement, node);
return base.VisitLockStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitQueryExpression(QueryExpressionSyntax node)
{
Context.ReportDiagnostic(QueryExpression, node);
return base.VisitQueryExpression(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitRangeExpression(RangeExpressionSyntax node)
{
Context.ReportDiagnostic(RangeExpression, node);
return base.VisitRangeExpression(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitRecursivePattern(RecursivePatternSyntax node)
{
Context.ReportDiagnostic(RecursivePattern, node);
return base.VisitRecursivePattern(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitRefType(RefTypeSyntax node)
{
Context.ReportDiagnostic(RefType, node);
return base.VisitRefType(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitRelationalPattern(RelationalPatternSyntax node)
{
Context.ReportDiagnostic(RelationalPattern, node);
return base.VisitRelationalPattern(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitSizeOfExpression(SizeOfExpressionSyntax node)
{
Context.ReportDiagnostic(SizeOfExpression, node);
return base.VisitSizeOfExpression(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node)
{
Context.ReportDiagnostic(StackAllocArrayCreationExpression, node);
return base.VisitStackAllocArrayCreationExpression(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitThrowExpression(ThrowExpressionSyntax node)
{
Context.ReportDiagnostic(ThrowExpressionOrStatement, node);
return base.VisitThrowExpression(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitThrowStatement(ThrowStatementSyntax node)
{
Context.ReportDiagnostic(ThrowExpressionOrStatement, node);
return base.VisitThrowStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitTryStatement(TryStatementSyntax node)
{
Context.ReportDiagnostic(TryStatement, node);
return base.VisitTryStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitTupleType(TupleTypeSyntax node)
{
Context.ReportDiagnostic(TupleType, node);
return base.VisitTupleType(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitUsingStatement(UsingStatementSyntax node)
{
Context.ReportDiagnostic(UsingStatementOrDeclaration, node);
return base.VisitUsingStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitVariableDeclarator(VariableDeclaratorSyntax node)
{
var updatedNode = (VariableDeclaratorSyntax)base.VisitVariableDeclarator(node)!;
if (node.Initializer is null &&
node.Parent is VariableDeclarationSyntax declaration &&
SemanticModel.GetTypeInfo(declaration.Type).Type is ITypeSymbol { IsUnmanagedType: false } type)
{
Context.ReportDiagnostic(InvalidObjectDeclaration, node, type);
}
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxNode? VisitYieldStatement(YieldStatementSyntax node)
{
Context.ReportDiagnostic(YieldStatement, node);
return base.VisitYieldStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitFunctionPointerType(FunctionPointerTypeSyntax node)
{
Context.ReportDiagnostic(FunctionPointer, node);
return base.VisitFunctionPointerType(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitPointerType(PointerTypeSyntax node)
{
Context.ReportDiagnostic(PointerType, node);
return base.VisitPointerType(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitUnsafeStatement(UnsafeStatementSyntax node)
{
Context.ReportDiagnostic(UnsafeStatement, node);
return base.VisitUnsafeStatement(node);
}
}
}
+287
ファイルの表示
@@ -0,0 +1,287 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using ComputeSharp.SourceGenerators.Diagnostics;
using ComputeSharp.SourceGenerators.Extensions;
using ComputeSharp.SourceGenerators.Mappings;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Operations;
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.SourceGenerators.SyntaxRewriters
{
/// <summary>
/// A base <see cref="CSharpSyntaxRewriter"/> type that processes C# source to convert to HLSL compliant code.
/// This class contains only the shared logic for all derived HLSL source rewriters.
/// </summary>
internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
{
/// <summary>
/// Creates a new <see cref="HlslSourceRewriter"/> instance with the specified parameters.
/// </summary>
/// <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="context">The current generator context in use.</param>
protected HlslSourceRewriter(
SemanticModel semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions,
GeneratorExecutionContext context)
{
SemanticModel = semanticModel;
DiscoveredTypes = discoveredTypes;
ConstantDefinitions = constantDefinitions;
Context = context;
}
/// <summary>
/// The <see cref="Microsoft.CodeAnalysis.SemanticModel"/> instance with semantic info on the target syntax tree.
/// </summary>
protected readonly SemanticModel SemanticModel;
/// <summary>
/// The collection of discovered custom types.
/// </summary>
protected readonly ICollection<INamedTypeSymbol> DiscoveredTypes;
/// <summary>
/// The collection of discovered constant definitions.
/// </summary>
protected readonly IDictionary<IFieldSymbol, string> ConstantDefinitions;
/// <summary>
/// The current generator context in use.
/// </summary>
protected readonly GeneratorExecutionContext Context;
/// <inheritdoc/>
public override SyntaxNode VisitCastExpression(CastExpressionSyntax node)
{
var updatedNode = (CastExpressionSyntax)base.VisitCastExpression(node)!;
return updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel, DiscoveredTypes);
}
/// <inheritdoc/>
public override SyntaxNode VisitObjectCreationExpression(ObjectCreationExpressionSyntax node)
{
var updatedNode = (ObjectCreationExpressionSyntax)base.VisitObjectCreationExpression(node)!;
if (SemanticModel.GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type)
{
Context.ReportDiagnostic(InvalidObjectCreationExpression, node, type);
}
updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node, SemanticModel, DiscoveredTypes);
// New objects use the default HLSL cast syntax, eg. (float4)0
if (updatedNode.ArgumentList!.Arguments.Count == 0)
{
return CastExpression(updatedNode.Type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)));
}
// Add explicit casts for matrix constructors to help the overload resolution
if (SemanticModel.GetTypeInfo(node).Type is ITypeSymbol matrixType &&
HlslKnownTypes.IsMatrixType(matrixType.GetFullMetadataName()))
{
for (int i = 0; i < node.ArgumentList!.Arguments.Count; i++)
{
IArgumentOperation argumentOperation = (IArgumentOperation)SemanticModel.GetOperation(node.ArgumentList.Arguments[i])!;
INamedTypeSymbol elementType = (INamedTypeSymbol)argumentOperation.Parameter.Type;
updatedNode = updatedNode.ReplaceNode(
updatedNode.ArgumentList!.Arguments[i].Expression,
CastExpression(IdentifierName(HlslKnownTypes.GetMappedName(elementType)), updatedNode.ArgumentList.Arguments[i].Expression));
}
}
return InvocationExpression(updatedNode.Type, updatedNode.ArgumentList!);
}
/// <inheritdoc/>
public override SyntaxNode VisitImplicitObjectCreationExpression(ImplicitObjectCreationExpressionSyntax node)
{
var updatedNode = (ImplicitObjectCreationExpressionSyntax)base.VisitImplicitObjectCreationExpression(node)!;
if (SemanticModel.GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type)
{
Context.ReportDiagnostic(InvalidObjectCreationExpression, node, type);
}
TypeSyntax explicitType = IdentifierName("").ReplaceAndTrackType(node, SemanticModel, DiscoveredTypes);
// Mutate the syntax like with explicit object creation expressions
if (updatedNode.ArgumentList!.Arguments.Count == 0)
{
return CastExpression(explicitType, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)));
}
// Add explicit casts like with the explicit object creation expressions above
if (SemanticModel.GetTypeInfo(node).Type is ITypeSymbol matrixType &&
HlslKnownTypes.IsMatrixType(matrixType.GetFullMetadataName()))
{
for (int i = 0; i < node.ArgumentList.Arguments.Count; i++)
{
IArgumentOperation argumentOperation = (IArgumentOperation)SemanticModel.GetOperation(node.ArgumentList.Arguments[i])!;
INamedTypeSymbol elementType = (INamedTypeSymbol)argumentOperation.Parameter.Type;
updatedNode = updatedNode.ReplaceNode(
updatedNode.ArgumentList.Arguments[i].Expression,
CastExpression(IdentifierName(HlslKnownTypes.GetMappedName(elementType)), updatedNode.ArgumentList.Arguments[i].Expression));
}
}
return InvocationExpression(explicitType, updatedNode.ArgumentList);
}
/// <inheritdoc/>
public override SyntaxNode VisitDefaultExpression(DefaultExpressionSyntax node)
{
var updatedNode = (DefaultExpressionSyntax)base.VisitDefaultExpression(node)!;
updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel, DiscoveredTypes);
// A default expression becomes (T)0 in HLSL
return CastExpression(updatedNode.Type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)));
}
/// <inheritdoc/>
public override SyntaxNode? VisitLiteralExpression(LiteralExpressionSyntax node)
{
var updatedNode = (LiteralExpressionSyntax)base.VisitLiteralExpression(node)!;
if (updatedNode.IsKind(SyntaxKind.DefaultLiteralExpression))
{
TypeSyntax type = node.TrackType(SemanticModel, DiscoveredTypes);
// Same HLSL-style expression in the form (T)0
return CastExpression(type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)));
}
else if (updatedNode.IsKind(SyntaxKind.NumericLiteralExpression) &&
SemanticModel.GetOperation(node) is ILiteralOperation operation &&
operation.Type is INamedTypeSymbol type)
{
// If the expression is a literal floating point value, we need to ensure the proper suffixes are
// used in the HLSL representation. Floating point values accept either f or F, but they don't work
// when the literal doesn't contain a decimal point. Since 32 bit floating point values are the default
// in HLSL, we can remove the suffix entirely. As for 64 bit values, we simply use the 'L' suffix.
if (type.GetFullMetadataName().Equals(typeof(float).FullName))
{
string literal = updatedNode.Token.ValueText;
if (!literal.Contains('.')) literal += ".0";
return updatedNode.WithToken(Literal(literal, 0f));
}
else if (type.GetFullMetadataName().Equals(typeof(double).FullName))
{
return updatedNode.WithToken(Literal(updatedNode.Token.ValueText + "L", 0d));
}
}
else if (updatedNode.IsKind(SyntaxKind.StringLiteralExpression))
{
Context.ReportDiagnostic(StringLiteralExpression, node);
}
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxNode? VisitElementAccessExpression(ElementAccessExpressionSyntax node)
{
var updatedNode = (ElementAccessExpressionSyntax)base.VisitElementAccessExpression(node)!;
if (SemanticModel.GetOperation(node) is IPropertyReferenceOperation operation)
{
string propertyName = operation.Property.GetFullMetadataName();
// Rewrite texture resource indices taking vectors into individual indices as per HLSL spec.
// For instance: texture[ThreadIds.XY] will be rewritten as texture[ThreadIds.X, ThreadIds.Y].
if (HlslKnownMembers.TryGetMappedResourceIndexerTypeName(propertyName, out string? mapping))
{
var index = InvocationExpression(IdentifierName(mapping!), ArgumentList(updatedNode.ArgumentList.Arguments));
return updatedNode.WithArgumentList(BracketedArgumentList(SingletonSeparatedList(Argument(index))));
}
// If the current property is a swizzled matrix indexer, ensure all the arguments are constants, and rewrite
// the property access to the corresponding HLSL syntax. For instance, m[M11, M12] will become m._m00_m01.
if (HlslKnownMembers.IsKnownMatrixIndexer(propertyName))
{
bool isValid = true;
// Validate the arguments
foreach (ArgumentSyntax argument in node.ArgumentList.Arguments)
{
if (SemanticModel.GetOperation(argument.Expression) is not IFieldReferenceOperation fieldReference ||
!HlslKnownMembers.IsKnownMatrixIndex(fieldReference.Field.GetFullMetadataName()))
{
Context.ReportDiagnostic(NonConstantMatrixSwizzledIndex, argument);
isValid = false;
}
}
if (isValid)
{
// Rewrite the indexer as a property access
string hlslPropertyName = string.Join("",
from argument in node.ArgumentList.Arguments
let fieldReference = (IFieldReferenceOperation)SemanticModel.GetOperation(argument.Expression)!
let fieldName = fieldReference.Field.Name
let row = (char)(fieldName[1] - 1)
let column = (char)(fieldName[2] - 1)
select $"_m{row}{column}");
return MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
updatedNode.Expression,
IdentifierName(hlslPropertyName));
}
}
}
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node)
{
var updatedNode = (IdentifierNameSyntax)base.VisitIdentifierName(node)!;
if (SemanticModel.GetOperation(node) is IFieldReferenceOperation operation &&
operation.Field.IsConst &&
operation.Type.TypeKind != TypeKind.Enum)
{
ConstantDefinitions[operation.Field] = ((IFormattable)operation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture);
var ownerTypeName = ((INamedTypeSymbol)operation.Field.ContainingSymbol).ToDisplayString().Replace(".", "__");
var constantName = $"__{ownerTypeName}__{operation.Field.Name}";
return IdentifierName(constantName);
}
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxToken VisitToken(SyntaxToken token)
{
SyntaxToken updatedToken = base.VisitToken(token);
// Replace all identifier tokens when needed, to avoid colliding with HLSL keywords
if (updatedToken.IsKind(SyntaxKind.IdentifierToken) &&
HlslKnownKeywords.TryGetMappedName(updatedToken.Text, out string? mapped))
{
return ParseToken(mapped!);
}
return updatedToken.WithoutTrivia();
}
}
}
+26 -486
ファイルの表示
@@ -17,33 +17,18 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
/// <summary>
/// A custom <see cref="CSharpSyntaxRewriter"/> type that processes C# methods to convert to HLSL compliant code.
/// </summary>
internal sealed class ShaderSourceRewriter : CSharpSyntaxRewriter
internal sealed class ShaderSourceRewriter : HlslSourceRewriter
{
/// <summary>
/// The type symbol for the shader type.
/// </summary>
private readonly INamedTypeSymbol? shaderType;
/// <summary>
/// The <see cref="SemanticModel"/> instance with semantic info on the target syntax tree.
/// </summary>
private readonly SemanticModel semanticModel;
/// <summary>
/// The collection of discovered custom types.
/// </summary>
private readonly ICollection<INamedTypeSymbol> discoveredTypes;
/// <summary>
/// The collection of discovered static methods.
/// </summary>
private readonly IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods;
/// <summary>
/// The collection of discovered constant definitions.
/// </summary>
private readonly IDictionary<IFieldSymbol, string> constantDefinitions;
/// <summary>
/// The collection of processed local functions in the current tree.
/// </summary>
@@ -54,11 +39,6 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
/// </summary>
private readonly List<VariableDeclarationSyntax> implicitVariables;
/// <summary>
/// The current generator context in use.
/// </summary>
private readonly GeneratorExecutionContext context;
/// <summary>
/// Whether or not the current instance is processing a shader entry point.
/// </summary>
@@ -92,15 +72,12 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
IDictionary<IFieldSymbol, string> constantDefinitions,
GeneratorExecutionContext context,
bool isEntryPoint)
: base(semanticModel, discoveredTypes, constantDefinitions, context)
{
this.shaderType = shaderType;
this.semanticModel = semanticModel;
this.discoveredTypes = discoveredTypes;
this.staticMethods = staticMethods;
this.constantDefinitions = constantDefinitions;
this.localFunctions = new();
this.implicitVariables = new();
this.context = context;
this.isEntryPoint = isEntryPoint;
}
@@ -118,14 +95,11 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IFieldSymbol, string> constantDefinitions,
GeneratorExecutionContext context)
: base(semanticModel, discoveredTypes, constantDefinitions, context)
{
this.semanticModel = semanticModel;
this.discoveredTypes = discoveredTypes;
this.staticMethods = staticMethods;
this.constantDefinitions = constantDefinitions;
this.implicitVariables = new();
this.localFunctions = new();
this.context = context;
}
/// <summary>
@@ -155,16 +129,16 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
var updatedNode = (MethodDeclarationSyntax?)base.Visit(node)!;
updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, this.semanticModel, this.discoveredTypes);
updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel, DiscoveredTypes);
if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword)))
{
this.context.ReportDiagnostic(AsyncModifierOnMethodOrFunction, node);
Context.ReportDiagnostic(AsyncModifierOnMethodOrFunction, node);
}
if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword)))
{
this.context.ReportDiagnostic(UnsafeModifierOnMethodOrFunction, node);
Context.ReportDiagnostic(UnsafeModifierOnMethodOrFunction, node);
}
if (updatedNode is not null)
@@ -197,163 +171,21 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
return updatedNode
.WithAttributeLists(default)
.ReplaceAndTrackType(updatedNode.Type!, node.Type!, this.semanticModel, this.discoveredTypes)
.ReplaceAndTrackType(updatedNode.Type!, node.Type!, SemanticModel, DiscoveredTypes)
.WithModifiers(TokenList(modifier));
}
/// <inheritdoc/>
public override SyntaxNode VisitCastExpression(CastExpressionSyntax node)
{
var updatedNode = (CastExpressionSyntax)base.VisitCastExpression(node)!;
return updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, this.semanticModel, this.discoveredTypes);
}
/// <inheritdoc/>
public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node)
{
var updatedNode = ((LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node)!);
if (this.semanticModel.GetOperation(node) is IOperation { Kind: OperationKind.UsingDeclaration })
if (SemanticModel.GetOperation(node) is IOperation { Kind: OperationKind.UsingDeclaration })
{
this.context.ReportDiagnostic(UsingStatementOrDeclaration, node);
Context.ReportDiagnostic(UsingStatementOrDeclaration, node);
}
return updatedNode.ReplaceAndTrackType(updatedNode.Declaration.Type, node.Declaration.Type, this.semanticModel, this.discoveredTypes);
}
/// <inheritdoc/>
public override SyntaxNode VisitObjectCreationExpression(ObjectCreationExpressionSyntax node)
{
var updatedNode = (ObjectCreationExpressionSyntax)base.VisitObjectCreationExpression(node)!;
if (this.semanticModel.GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type)
{
this.context.ReportDiagnostic(InvalidObjectCreationExpression, node, type);
}
updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node, this.semanticModel, this.discoveredTypes);
// New objects use the default HLSL cast syntax, eg. (float4)0
if (updatedNode.ArgumentList!.Arguments.Count == 0)
{
return CastExpression(updatedNode.Type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)));
}
// Add explicit casts for matrix constructors to help the overload resolution
if (this.semanticModel.GetTypeInfo(node).Type is ITypeSymbol matrixType &&
HlslKnownTypes.IsMatrixType(matrixType.GetFullMetadataName()))
{
for (int i = 0; i < node.ArgumentList!.Arguments.Count; i++)
{
IArgumentOperation argumentOperation = (IArgumentOperation)this.semanticModel.GetOperation(node.ArgumentList.Arguments[i])!;
INamedTypeSymbol elementType = (INamedTypeSymbol)argumentOperation.Parameter.Type;
updatedNode = updatedNode.ReplaceNode(
updatedNode.ArgumentList!.Arguments[i].Expression,
CastExpression(IdentifierName(HlslKnownTypes.GetMappedName(elementType)), updatedNode.ArgumentList.Arguments[i].Expression));
}
}
return InvocationExpression(updatedNode.Type, updatedNode.ArgumentList!);
}
/// <inheritdoc/>
public override SyntaxNode? VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
{
var updatedNode = (AnonymousObjectCreationExpressionSyntax)base.VisitAnonymousObjectCreationExpression(node)!;
this.context.ReportDiagnostic(DiagnosticDescriptors.AnonymousObjectCreationExpression, node);
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxNode VisitImplicitObjectCreationExpression(ImplicitObjectCreationExpressionSyntax node)
{
var updatedNode = (ImplicitObjectCreationExpressionSyntax)base.VisitImplicitObjectCreationExpression(node)!;
if (this.semanticModel.GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type)
{
this.context.ReportDiagnostic(InvalidObjectCreationExpression, node, type);
}
TypeSyntax explicitType = IdentifierName("").ReplaceAndTrackType(node, this.semanticModel, this.discoveredTypes);
// Mutate the syntax like with explicit object creation expressions
if (updatedNode.ArgumentList!.Arguments.Count == 0)
{
return CastExpression(explicitType, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)));
}
// Add explicit casts like with the explicit object creation expressions above
if (this.semanticModel.GetTypeInfo(node).Type is ITypeSymbol matrixType &&
HlslKnownTypes.IsMatrixType(matrixType.GetFullMetadataName()))
{
for (int i = 0; i < node.ArgumentList.Arguments.Count; i++)
{
IArgumentOperation argumentOperation = (IArgumentOperation)this.semanticModel.GetOperation(node.ArgumentList.Arguments[i])!;
INamedTypeSymbol elementType = (INamedTypeSymbol)argumentOperation.Parameter.Type;
updatedNode = updatedNode.ReplaceNode(
updatedNode.ArgumentList.Arguments[i].Expression,
CastExpression(IdentifierName(HlslKnownTypes.GetMappedName(elementType)), updatedNode.ArgumentList.Arguments[i].Expression));
}
}
return InvocationExpression(explicitType, updatedNode.ArgumentList);
}
/// <inheritdoc/>
public override SyntaxNode VisitDefaultExpression(DefaultExpressionSyntax node)
{
var updatedNode = (DefaultExpressionSyntax)base.VisitDefaultExpression(node)!;
updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, this.semanticModel, this.discoveredTypes);
// A default expression becomes (T)0 in HLSL
return CastExpression(updatedNode.Type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)));
}
/// <inheritdoc/>
public override SyntaxNode? VisitLiteralExpression(LiteralExpressionSyntax node)
{
var updatedNode = (LiteralExpressionSyntax)base.VisitLiteralExpression(node)!;
if (updatedNode.IsKind(SyntaxKind.DefaultLiteralExpression))
{
TypeSyntax type = node.TrackType(this.semanticModel, this.discoveredTypes);
// Same HLSL-style expression in the form (T)0
return CastExpression(type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)));
}
else if (updatedNode.IsKind(SyntaxKind.NumericLiteralExpression) &&
this.semanticModel.GetOperation(node) is ILiteralOperation operation &&
operation.Type is INamedTypeSymbol type)
{
// If the expression is a literal floating point value, we need to ensure the proper suffixes are
// used in the HLSL representation. Floating point values accept either f or F, but they don't work
// when the literal doesn't contain a decimal point. Since 32 bit floating point values are the default
// in HLSL, we can remove the suffix entirely. As for 64 bit values, we simply use the 'L' suffix.
if (type.GetFullMetadataName().Equals(typeof(float).FullName))
{
string literal = updatedNode.Token.ValueText;
if (!literal.Contains('.')) literal += ".0";
return updatedNode.WithToken(Literal(literal, 0f));
}
else if (type.GetFullMetadataName().Equals(typeof(double).FullName))
{
return updatedNode.WithToken(Literal(updatedNode.Token.ValueText + "L", 0d));
}
}
else if (updatedNode.IsKind(SyntaxKind.StringLiteralExpression))
{
this.context.ReportDiagnostic(StringLiteralExpression, node);
}
return updatedNode;
return updatedNode.ReplaceAndTrackType(updatedNode.Declaration.Type, node.Declaration.Type, SemanticModel, DiscoveredTypes);
}
/// <inheritdoc/>
@@ -361,7 +193,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
{
var updatedNode = (DeclarationExpressionSyntax)base.VisitDeclarationExpression(node)!;
updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, this.semanticModel, this.discoveredTypes);
updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel, DiscoveredTypes);
// Add the variable to the list of implicit declarations
this.implicitVariables.Add(VariableDeclaration(updatedNode.Type).AddVariables(VariableDeclarator(updatedNode.Designation.ToString())));
@@ -390,16 +222,16 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
.WithAttributeLists(List<AttributeListSyntax>())
.WithIdentifier(Identifier($"__{this.currentMethod!.Identifier.Text}__{node.Identifier.Text}"));
updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, this.semanticModel, this.discoveredTypes);
updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel, DiscoveredTypes);
if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword)))
{
this.context.ReportDiagnostic(AsyncModifierOnMethodOrFunction, node);
Context.ReportDiagnostic(AsyncModifierOnMethodOrFunction, node);
}
if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword)))
{
this.context.ReportDiagnostic(UnsafeModifierOnMethodOrFunction, node);
Context.ReportDiagnostic(UnsafeModifierOnMethodOrFunction, node);
}
this.localFunctionDepth--;
@@ -419,14 +251,14 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
var updatedNode = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node)!;
if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) &&
this.semanticModel.GetOperation(node) is IMemberReferenceOperation operation)
SemanticModel.GetOperation(node) is IMemberReferenceOperation operation)
{
// 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 &&
fieldOperation.Type.TypeKind != TypeKind.Enum)
{
this.constantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture);
ConstantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture);
var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().Replace(".", "__");
var constantName = $"__{ownerTypeName}__{fieldOperation.Field.Name}";
@@ -452,16 +284,16 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
{
DiagnosticDescriptor? descriptor = typeName switch
{
_ when typeName == typeof(ThreadIds).FullName => DiagnosticDescriptors.InvalidThreadIdsUsage,
_ when typeName == typeof(GroupIds).FullName => DiagnosticDescriptors.InvalidGroupIdsUsage,
_ when typeName == typeof(GroupSize).FullName => DiagnosticDescriptors.InvalidGroupSizeUsage,
_ when typeName == typeof(WarpIds).FullName => DiagnosticDescriptors.InvalidWarpIdsUsage,
_ when typeName == typeof(ThreadIds).FullName => InvalidThreadIdsUsage,
_ when typeName == typeof(GroupIds).FullName => InvalidGroupIdsUsage,
_ when typeName == typeof(GroupSize).FullName => InvalidGroupSizeUsage,
_ when typeName == typeof(WarpIds).FullName => InvalidWarpIdsUsage,
_ => null
};
if (descriptor is not null)
{
this.context.ReportDiagnostic(descriptor, node);
Context.ReportDiagnostic(descriptor, node);
}
}
}
@@ -490,7 +322,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
if (!this.staticMethods.TryGetValue(key, out MethodDeclarationSyntax? methodSyntax))
{
INamedTypeSymbol resourceType = (INamedTypeSymbol)this.semanticModel.GetTypeInfo(node.Expression).Type!;
INamedTypeSymbol resourceType = (INamedTypeSymbol)SemanticModel.GetTypeInfo(node.Expression).Type!;
string resourceName = HlslKnownTypes.GetMappedName(resourceType);
// Create a static method to get a specified dimension for a target resource type.
@@ -538,7 +370,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
{
var updatedNode = (InvocationExpressionSyntax)base.VisitInvocationExpression(node)!;
if (this.semanticModel.GetOperation(node) is IInvocationOperation operation &&
if (SemanticModel.GetOperation(node) is IInvocationOperation operation &&
operation.TargetMethod is IMethodSymbol method &&
method.IsStatic)
{
@@ -569,7 +401,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
if (!this.staticMethods.ContainsKey(method))
{
ShaderSourceRewriter shaderSourceRewriter = new(this.semanticModel, this.discoveredTypes, this.staticMethods, this.constantDefinitions, this.context);
ShaderSourceRewriter shaderSourceRewriter = new(SemanticModel, DiscoveredTypes, this.staticMethods, ConstantDefinitions, Context);
MethodDeclarationSyntax
methodNode = (MethodDeclarationSyntax)method.DeclaringSyntaxReferences[0].GetSyntax(),
processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace().WithoutTrivia();
@@ -584,64 +416,6 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxNode? VisitElementAccessExpression(ElementAccessExpressionSyntax node)
{
var updatedNode = (ElementAccessExpressionSyntax)base.VisitElementAccessExpression(node)!;
if (this.semanticModel.GetOperation(node) is IPropertyReferenceOperation operation)
{
string propertyName = operation.Property.GetFullMetadataName();
// Rewrite texture resource indices taking vectors into individual indices as per HLSL spec.
// For instance: texture[ThreadIds.XY] will be rewritten as texture[ThreadIds.X, ThreadIds.Y].
if (HlslKnownMembers.TryGetMappedResourceIndexerTypeName(propertyName, out string? mapping))
{
var index = InvocationExpression(IdentifierName(mapping!), ArgumentList(updatedNode.ArgumentList.Arguments));
return updatedNode.WithArgumentList(BracketedArgumentList(SingletonSeparatedList(Argument(index))));
}
// If the current property is a swizzled matrix indexer, ensure all the arguments are constants, and rewrite
// the property access to the corresponding HLSL syntax. For instance, m[M11, M12] will become m._m00_m01.
if (HlslKnownMembers.IsKnownMatrixIndexer(propertyName))
{
bool isValid = true;
// Validate the arguments
foreach (ArgumentSyntax argument in node.ArgumentList.Arguments)
{
if (this.semanticModel.GetOperation(argument.Expression) is not IFieldReferenceOperation fieldReference ||
!HlslKnownMembers.IsKnownMatrixIndex(fieldReference.Field.GetFullMetadataName()))
{
this.context.ReportDiagnostic(NonConstantMatrixSwizzledIndex, argument);
isValid = false;
}
}
if (isValid)
{
// Rewrite the indexer as a property access
string hlslPropertyName = string.Join("",
from argument in node.ArgumentList.Arguments
let fieldReference = (IFieldReferenceOperation)this.semanticModel.GetOperation(argument.Expression)!
let fieldName = fieldReference.Field.Name
let row = (char)(fieldName[1] - 1)
let column = (char)(fieldName[2] - 1)
select $"_m{row}{column}");
return MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
updatedNode.Expression,
IdentifierName(hlslPropertyName));
}
}
}
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxNode? VisitArgument(ArgumentSyntax node)
{
@@ -651,9 +425,9 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
updatedNode = updatedNode.WithRefKindKeyword(Token(SyntaxKind.None));
// Track and rewrite the discarded declaration
if (this.semanticModel.GetOperation(node.Expression) is IDiscardOperation operation)
if (SemanticModel.GetOperation(node.Expression) is IDiscardOperation operation)
{
TypeSyntax typeSyntax = operation.Type!.TrackType(this.discoveredTypes);
TypeSyntax typeSyntax = operation.Type!.TrackType(DiscoveredTypes);
string identifier = $"__implicit{this.implicitVariables.Count}";
// Add the variable to the list of implicit declarations
@@ -664,239 +438,5 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node)
{
var updatedNode = (IdentifierNameSyntax)base.VisitIdentifierName(node)!;
if (this.semanticModel.GetOperation(node) is IFieldReferenceOperation operation &&
operation.Field.IsConst &&
operation.Type.TypeKind != TypeKind.Enum)
{
this.constantDefinitions[operation.Field] = ((IFormattable)operation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture);
var ownerTypeName = ((INamedTypeSymbol)operation.Field.ContainingSymbol).ToDisplayString().Replace(".", "__");
var constantName = $"__{ownerTypeName}__{operation.Field.Name}";
return IdentifierName(constantName);
}
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxNode? VisitAwaitExpression(AwaitExpressionSyntax node)
{
this.context.ReportDiagnostic(DiagnosticDescriptors.AwaitExpression, node);
return base.VisitAwaitExpression(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitCheckedExpression(CheckedExpressionSyntax node)
{
this.context.ReportDiagnostic(DiagnosticDescriptors.CheckedExpression, node);
return base.VisitCheckedExpression(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitCheckedStatement(CheckedStatementSyntax node)
{
this.context.ReportDiagnostic(DiagnosticDescriptors.CheckedStatement, node);
return base.VisitCheckedStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitFixedStatement(FixedStatementSyntax node)
{
this.context.ReportDiagnostic(DiagnosticDescriptors.FixedStatement, node);
return base.VisitFixedStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitForEachStatement(ForEachStatementSyntax node)
{
this.context.ReportDiagnostic(DiagnosticDescriptors.ForEachStatement, node);
return base.VisitForEachStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitForEachVariableStatement(ForEachVariableStatementSyntax node)
{
this.context.ReportDiagnostic(DiagnosticDescriptors.ForEachStatement, node);
return base.VisitForEachVariableStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitLockStatement(LockStatementSyntax node)
{
this.context.ReportDiagnostic(DiagnosticDescriptors.LockStatement, node);
return base.VisitLockStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitQueryExpression(QueryExpressionSyntax node)
{
this.context.ReportDiagnostic(DiagnosticDescriptors.QueryExpression, node);
return base.VisitQueryExpression(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitRangeExpression(RangeExpressionSyntax node)
{
this.context.ReportDiagnostic(DiagnosticDescriptors.RangeExpression, node);
return base.VisitRangeExpression(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitRecursivePattern(RecursivePatternSyntax node)
{
this.context.ReportDiagnostic(DiagnosticDescriptors.RecursivePattern, node);
return base.VisitRecursivePattern(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitRefType(RefTypeSyntax node)
{
this.context.ReportDiagnostic(DiagnosticDescriptors.RefType, node);
return base.VisitRefType(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitRelationalPattern(RelationalPatternSyntax node)
{
this.context.ReportDiagnostic(DiagnosticDescriptors.RelationalPattern, node);
return base.VisitRelationalPattern(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitSizeOfExpression(SizeOfExpressionSyntax node)
{
this.context.ReportDiagnostic(DiagnosticDescriptors.SizeOfExpression, node);
return base.VisitSizeOfExpression(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node)
{
this.context.ReportDiagnostic(DiagnosticDescriptors.StackAllocArrayCreationExpression, node);
return base.VisitStackAllocArrayCreationExpression(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitThrowExpression(ThrowExpressionSyntax node)
{
this.context.ReportDiagnostic(DiagnosticDescriptors.ThrowExpressionOrStatement, node);
return base.VisitThrowExpression(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitThrowStatement(ThrowStatementSyntax node)
{
this.context.ReportDiagnostic(DiagnosticDescriptors.ThrowExpressionOrStatement, node);
return base.VisitThrowStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitTryStatement(TryStatementSyntax node)
{
this.context.ReportDiagnostic(DiagnosticDescriptors.TryStatement, node);
return base.VisitTryStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitTupleType(TupleTypeSyntax node)
{
this.context.ReportDiagnostic(DiagnosticDescriptors.TupleType, node);
return base.VisitTupleType(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitUsingStatement(UsingStatementSyntax node)
{
this.context.ReportDiagnostic(DiagnosticDescriptors.UsingStatementOrDeclaration, node);
return base.VisitUsingStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitVariableDeclarator(VariableDeclaratorSyntax node)
{
var updatedNode = (VariableDeclaratorSyntax)base.VisitVariableDeclarator(node)!;
if (node.Initializer is null &&
node.Parent is VariableDeclarationSyntax declaration &&
this.semanticModel.GetTypeInfo(declaration.Type).Type is ITypeSymbol { IsUnmanagedType: false } type)
{
this.context.ReportDiagnostic(InvalidObjectDeclaration, node, type);
}
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxNode? VisitYieldStatement(YieldStatementSyntax node)
{
this.context.ReportDiagnostic(DiagnosticDescriptors.YieldStatement, node);
return base.VisitYieldStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitFunctionPointerType(FunctionPointerTypeSyntax node)
{
this.context.ReportDiagnostic(DiagnosticDescriptors.FunctionPointer, node);
return base.VisitFunctionPointerType(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitPointerType(PointerTypeSyntax node)
{
this.context.ReportDiagnostic(DiagnosticDescriptors.PointerType, node);
return base.VisitPointerType(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitUnsafeStatement(UnsafeStatementSyntax node)
{
this.context.ReportDiagnostic(DiagnosticDescriptors.UnsafeStatement, node);
return base.VisitUnsafeStatement(node);
}
/// <inheritdoc/>
public override SyntaxToken VisitToken(SyntaxToken token)
{
SyntaxToken updatedToken = base.VisitToken(token);
// Replace all identifier tokens when needed, to avoid colliding with HLSL keywords
if (updatedToken.IsKind(SyntaxKind.IdentifierToken) &&
HlslKnownKeywords.TryGetMappedName(updatedToken.Text, out string? mapped))
{
return ParseToken(mapped!);
}
return updatedToken.WithoutTrivia();
}
}
}
+11 -3
ファイルの表示
@@ -24,6 +24,7 @@ namespace ComputeSharp.__Internals
/// <param name="args">The mapped collection of shader fields.</param>
/// <param name="executeMethod">The source code for the <see cref="IComputeShader.Execute"/> method.</param>
/// <param name="methods">The collection of processed methods.</param>
/// <param name="defines">The collection of discovered defines.</param>
/// <param name="constants">The collection of discovered constants.</param>
/// <param name="sharedBuffers">The collection of group shared buffers.</param>
public IComputeShaderSourceAttribute(
@@ -32,6 +33,7 @@ namespace ComputeSharp.__Internals
object[] args,
string executeMethod,
string[] methods,
object[] defines,
object[] constants,
object[] sharedBuffers)
{
@@ -40,7 +42,8 @@ namespace ComputeSharp.__Internals
Fields = args.Cast<string[]>().ToDictionary(static arg => arg[0], static arg => (arg[1], arg[2]));
ExecuteMethod = executeMethod;
Methods = methods;
Constants = constants.Cast<string[]>().ToDictionary(static c => c[0], static c => c[1]);
Defines = defines.Cast<string[]>().ToDictionary(static c => c[0], static c => c[1]);
Constants = constants.Cast<string[]>().ToDictionary(static arg => arg[0], static arg => (arg[1], arg[2]));
SharedBuffers = sharedBuffers.Cast<object[]>().ToDictionary(static t => (string)t[0], static t => ((string)t[1], (int?)t[2]));
}
@@ -70,13 +73,18 @@ namespace ComputeSharp.__Internals
internal IReadOnlyCollection<string> Methods { get; }
/// <summary>
/// Gets the collection of discovered constants.
/// Gets the collection of discovered define declarations.
/// </summary>
internal IReadOnlyDictionary<string, string> Constants { get; }
internal IReadOnlyDictionary<string, string> Defines { get; }
/// <summary>
/// Gets the collection of discovered constants.
/// </summary>
internal IReadOnlyDictionary<string, (string Type, string Assignment)> Constants { get; }
/// <summary>
/// Gets the collection of discovered shared buffers.
/// </summary>
internal IReadOnlyDictionary<string, (string Type, int? Count)> SharedBuffers { get; }
/// <summary>
+21 -4
ファイルの表示
@@ -42,13 +42,30 @@ namespace ComputeSharp.Shaders.Renderer
builder.Append("#define __GroupSize__get_Z ");
builder.AppendLine(threadsZ.ToString());
// User defined onstants
foreach (var constant in info.ConstantsInfo)
// Define declarations
foreach (var define in info.DefinesInfo)
{
builder.Append("#define ");
builder.Append(constant.Key);
builder.Append(define.Key);
builder.Append(' ');
builder.AppendLine(constant.Value);
builder.AppendLine(define.Value);
}
// Static constants
if (info.ConstantsInfo.Count > 0)
{
builder.AppendLine();
foreach (var constant in info.ConstantsInfo)
{
builder.Append("static const ");
builder.Append(constant.Value.Type);
builder.Append(' ');
builder.Append(constant.Key);
builder.Append(" = ");
builder.Append(constant.Value.Assignment);
builder.AppendLine(";");
}
}
// Declared types
+8 -3
ファイルの表示
@@ -29,9 +29,14 @@ namespace ComputeSharp.Shaders.Translation
IReadOnlyCollection<string> MethodsInfo { get; }
/// <summary>
/// Gets the collection of constants to be declared in the shader.
/// Gets the collection of define declarations to be added to the shader.
/// </summary>
IReadOnlyDictionary<string, string> ConstantsInfo { get; }
IReadOnlyDictionary<string, string> DefinesInfo { get; }
/// <summary>
/// Gets the collection of discovered constants.
/// </summary>
IReadOnlyDictionary<string, (string Type, string Assignment)> ConstantsInfo { get; }
/// <summary>
/// Gets the collection of declared types for the shader.
@@ -39,7 +44,7 @@ namespace ComputeSharp.Shaders.Translation
IReadOnlyCollection<string> DeclaredTypes { get; }
/// <summary>
/// Gets the collection of discovered constants.
/// Gets the collection of discovered group shared buffers.
/// </summary>
IReadOnlyDictionary<string, (string Type, int? Count)> SharedBuffers { get; }
}
+10 -6
ファイルの表示
@@ -66,9 +66,9 @@ namespace ComputeSharp.Shaders.Translation
private readonly List<string> methodsInfo = new();
/// <summary>
/// The <see cref="Dictionary{TKey,TValue}"/> with the discovered constants for the shader.
/// The <see cref="Dictionary{TKey,TValue}"/> with the discovered define declarations for the shader.
/// </summary>
private readonly Dictionary<string, string> constantsInfo = new();
private readonly Dictionary<string, string> definesInfo = new();
/// <summary>
/// The <see cref="List{T}"/> with the collected declared types for the shader.
@@ -108,11 +108,14 @@ namespace ComputeSharp.Shaders.Translation
public IReadOnlyCollection<string> MethodsInfo => this.methodsInfo;
/// <inheritdoc/>
public IReadOnlyDictionary<string, string> ConstantsInfo => this.constantsInfo;
public IReadOnlyDictionary<string, string> DefinesInfo => this.definesInfo;
/// <inheritdoc/>
public IReadOnlyCollection<string> DeclaredTypes => this.declaredTypes;
/// <inheritdoc/>
public IReadOnlyDictionary<string, (string Type, string Assignment)> ConstantsInfo { get; private set; }
/// <inheritdoc/>
public IReadOnlyDictionary<string, (string Type, int? Count)> SharedBuffers { get; private set; }
@@ -143,14 +146,15 @@ namespace ComputeSharp.Shaders.Translation
private void LoadMethodMetadata()
{
EntryPoint = Attribute.ExecuteMethod;
ConstantsInfo = Attribute.Constants;
SharedBuffers = Attribute.SharedBuffers;
this.declaredTypes.AddRange(Attribute.Types);
this.methodsInfo.AddRange(Attribute.Methods);
foreach (var pair in Attribute.Constants)
foreach (var pair in Attribute.Defines)
{
this.constantsInfo.Add(pair.Key, pair.Value);
this.definesInfo.Add(pair.Key, pair.Value);
}
}
@@ -233,7 +237,7 @@ namespace ComputeSharp.Shaders.Translation
foreach (var pair in methodSource.Constants)
{
this.constantsInfo[pair.Key] = pair.Value;
this.definesInfo[pair.Key] = pair.Value;
}
}
else ThrowHelper.ThrowArgumentException("Invalid captured variable");
+143
ファイルの表示
@@ -1138,6 +1138,149 @@ namespace ComputeSharp.Tests.Internals
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0042");
}
[TestMethod]
public void InvalidShaderConstantPropertyType()
{
string source = @"
using ComputeSharp;
namespace ComputeSharp
{
public class ReadWriteBuffer<T> { }
}
namespace MyFancyApp.Sample
{
public struct MyShader : IComputeShader
{
public ReadWriteBuffer<float> buffer;
private static string Pi => ""Hello"";
public void Execute()
{
}
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0043");
}
[TestMethod]
public void InvalidShaderConstantPropertyDeclaration_AutoProp()
{
string source = @"
using ComputeSharp;
namespace ComputeSharp
{
public class ReadWriteBuffer<T> { }
}
namespace MyFancyApp.Sample
{
public struct MyShader : IComputeShader
{
public ReadWriteBuffer<float> buffer;
private static float Pi { get; } = 3.14f;
public void Execute()
{
}
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0044");
}
[TestMethod]
public void InvalidShaderConstantPropertyDeclaration_GetterBlock()
{
string source = @"
using ComputeSharp;
namespace ComputeSharp
{
public class ReadWriteBuffer<T> { }
}
namespace MyFancyApp.Sample
{
public struct MyShader : IComputeShader
{
public ReadWriteBuffer<float> buffer;
private static float Pi
{
get => 3.14f;
}
public void Execute()
{
}
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0044");
}
[TestMethod]
public void NonReadonlyShaderPropertyDeclaration()
{
string source = @"
using ComputeSharp;
namespace ComputeSharp
{
public class ReadWriteBuffer<T> { }
}
namespace MyFancyApp.Sample
{
public struct MyShader : IComputeShader
{
public ReadWriteBuffer<float> buffer;
private static float Pi { get; set; } = 3.14f;
public void Execute()
{
}
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0045");
}
[TestMethod]
public void InstanceShaderPropertyDeclaration()
{
string source = @"
using ComputeSharp;
namespace ComputeSharp
{
public class ReadWriteBuffer<T> { }
}
namespace MyFancyApp.Sample
{
public struct MyShader : IComputeShader
{
public ReadWriteBuffer<float> buffer;
private float Pi => 3.14f;
public void Execute()
{
}
}
}";
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0046");
}
/// <summary>
/// Verifies the output of a source generator.
/// </summary>
+56
ファイルの表示
@@ -0,0 +1,56 @@
using System;
using System.Linq;
using ComputeSharp.Resources;
using ComputeSharp.Tests.Attributes;
using ComputeSharp.Tests.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ComputeSharp.Tests
{
[TestClass]
[TestCategory("ShaderMembers")]
public partial class ShaderMembersTests
{
[CombinatorialTestMethod]
[AllDevices]
public void StaticConstants(Device device)
{
using ReadWriteBuffer<float> buffer = device.Get().AllocateReadWriteBuffer<float>(8);
device.Get().For(1, new StaticConstantsShader(buffer));
float[] results = buffer.ToArray();
Assert.IsTrue(Math.Abs(3.14f - results[0]) < 0.00001f);
Assert.IsTrue(Math.Abs(results[1] - results[2]) < 0.00001f);
Assert.IsTrue(Math.Abs(1 - results[3]) < 0.00001f);
Assert.IsTrue(Math.Abs(2 - results[4]) < 0.00001f);
Assert.IsTrue(Math.Abs(3 - results[5]) < 0.00001f);
Assert.IsTrue(Math.Abs(4 - results[6]) < 0.00001f);
Assert.IsTrue(Math.Abs(3.14f - results[7]) < 0.00001f);
}
[AutoConstructor]
internal readonly partial struct StaticConstantsShader : IComputeShader
{
public readonly ReadWriteBuffer<float> buffer;
static float Pi => 3.14f;
static float SinPi => Hlsl.Sin(Pi);
static Int2x2 Mat => new(1, 2, 3, 4);
static float Combo => Hlsl.Abs(Hlsl.Clamp(Hlsl.Min(Hlsl.Max(3.14f, 2), 10), 0, 42));
public void Execute()
{
buffer[0] = Pi;
buffer[1] = SinPi;
buffer[2] = Hlsl.Sin(3.14f);
buffer[3] = Mat.M11;
buffer[4] = Mat.M12;
buffer[5] = Mat.M21;
buffer[6] = Mat.M22;
buffer[7] = Combo;
}
}
}
}