Merge pull request #88 from Sergio0694/feature/constants-support

Constants support
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2021-01-11 18:07:45 +01:00
コミット d3b2889078
11ファイル変更
+218 -79

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

+14 -1
ファイルの表示
@@ -24,13 +24,21 @@ 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>
public IComputeShaderSourceAttribute(string shaderTypeName, string[] types, object[] args, string executeMethod, string[] methods)
/// <param name="constants">The collection of discovered constants.</param>
public IComputeShaderSourceAttribute(
string shaderTypeName,
string[] types,
object[] args,
string executeMethod,
string[] methods,
object[] constants)
{
ShaderTypeName = shaderTypeName;
Types = types;
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]);
}
/// <summary>
@@ -58,6 +66,11 @@ namespace ComputeSharp.__Internals
/// </summary>
internal IReadOnlyCollection<string> Methods { get; }
/// <summary>
/// Gets the collection of discovered constants.
/// </summary>
internal IReadOnlyDictionary<string, string> Constants { get; }
/// <summary>
/// Gets the associated <see cref="IComputeShaderSourceAttribute"/> instance for a specified type.
/// </summary>
+9 -1
ファイルの表示
@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using ComputeSharp.Core.Extensions;
using ComputeSharp.Exceptions;
@@ -35,13 +36,15 @@ namespace ComputeSharp.__Internals
/// <param name="types">The collection of custom types.</param>
/// <param name="invokeMethod">The source code for the target entry point method.</param>
/// <param name="methods">The collection of processed methods.</param>
public ShaderMethodSourceAttribute(string methodName, string[] types, string invokeMethod, string[] methods)
/// <param name="constants">The collection of discovered constants.</param>
public ShaderMethodSourceAttribute(string methodName, string[] types, string invokeMethod, string[] methods, object[] constants)
{
this.invokeMethod = invokeMethod;
MethodName = methodName;
Types = types;
Methods = methods;
Constants = constants.Cast<string[]>().ToDictionary(static c => c[0], static c => c[1]);
}
/// <summary>
@@ -59,6 +62,11 @@ namespace ComputeSharp.__Internals
/// </summary>
internal IReadOnlyCollection<string> Methods { get; }
/// <summary>
/// Gets the collection of discovered constants.
/// </summary>
internal IReadOnlyDictionary<string, string> Constants { get; }
/// <summary>
/// Gets the mapped source code for the current method.
/// </summary>
+15 -1
ファイルの表示
@@ -31,7 +31,21 @@ namespace ComputeSharp.Shaders.Renderer
builder.AppendLine("// AUTO GENERATED");
builder.AppendLine("// ================================================");
builder.AppendLine("// This shader was created by ComputeSharp.");
builder.AppendLine("// See: https://github.com/Sergio0694/ComputeSharp.");
builder.AppendLine("// See: https://github.com/Sergio0694/ComputeSharp.");
// Constants
if (info.ConstantsInfo.Count > 0)
{
builder.AppendLine();
foreach (var constant in info.ConstantsInfo)
{
builder.Append("#define ");
builder.Append(constant.Key);
builder.Append(' ');
builder.AppendLine(constant.Value);
}
}
// Declared types
foreach (var type in info.DeclaredTypes)
+5
ファイルの表示
@@ -28,6 +28,11 @@ namespace ComputeSharp.Shaders.Translation
/// </summary>
public IReadOnlyCollection<string> MethodsInfo { get; }
/// <summary>
/// Gets the collection of constants to be declared in the shader.
/// </summary>
public IReadOnlyDictionary<string, string> ConstantsInfo { get; }
/// <summary>
/// Gets the collection of declared types for the shader.
/// </summary>
+31 -12
ファイルの表示
@@ -61,6 +61,11 @@ namespace ComputeSharp.Shaders.Translation
/// </summary>
private readonly List<string> methodsInfo = new();
/// <summary>
/// The <see cref="Dictionary{TKey,TValue}"/> with the discovered constants for the shader.
/// </summary>
private readonly Dictionary<string, string> constantsInfo = new();
/// <summary>
/// The <see cref="List{T}"/> with the collected declared types for the shader.
/// </summary>
@@ -93,6 +98,9 @@ namespace ComputeSharp.Shaders.Translation
/// <inheritdoc/>
public IReadOnlyCollection<string> MethodsInfo => this.methodsInfo;
/// <inheritdoc/>
public IReadOnlyDictionary<string, string> ConstantsInfo => this.constantsInfo;
/// <inheritdoc/>
public IReadOnlyCollection<string> DeclaredTypes => this.declaredTypes;
@@ -106,16 +114,33 @@ namespace ComputeSharp.Shaders.Translation
{
ShaderLoader<T> @this = new();
@this.LoadMethodMetadata();
// Reading members through reflection requires an object parameter, so here we're just boxing
// the input shader once to avoid allocating it multiple times while processing the shader.
@this.d3D12DescriptorRanges1 = @this.LoadFieldsInfo(shader);
@this.LoadMethodMetadata();
@this.InitializeDispatchDataLoader();
return @this;
}
/// <summary>
/// Loads the metadata info for the current shader.
/// </summary>
private void LoadMethodMetadata()
{
EntryPoint = Attribute.ExecuteMethod;
this.declaredTypes.AddRange(Attribute.Types);
this.methodsInfo.AddRange(Attribute.Methods);
foreach (var pair in Attribute.Constants)
{
this.constantsInfo.Add(pair.Key, pair.Value);
}
}
/// <summary>
/// Loads the fields info for the current shader being loaded.
/// </summary>
@@ -197,19 +222,13 @@ namespace ComputeSharp.Shaders.Translation
this.declaredTypes.AddRange(methodSource.Types);
this.methodsInfo.Add(methodSource.GetMappedInvokeMethod(hlslName));
this.methodsInfo.AddRange(methodSource.Methods);
foreach (var pair in methodSource.Constants)
{
this.constantsInfo[pair.Key] = pair.Value;
}
}
else ThrowHelper.ThrowArgumentException("Invalid captured variable");
}
/// <summary>
/// Loads the metadata info for the current shader.
/// </summary>
private void LoadMethodMetadata()
{
EntryPoint = Attribute.ExecuteMethod;
this.methodsInfo.AddRange(Attribute.Methods);
this.declaredTypes.AddRange(Attribute.Types);
}
}
}
+4 -5
ファイルの表示
@@ -42,12 +42,11 @@ namespace ComputeSharp.SourceGenerators
var structName = structDeclaration.Identifier.Text;
var structModifiers = structDeclaration.Modifiers;
var fields = (
from fieldDeclaration in structDeclaration.Members.OfType<FieldDeclarationSyntax>()
let fieldType = fieldDeclaration.Declaration.Type
let typeName = semanticModel.GetTypeInfo(fieldType).Type!.ToDisplayString()
from fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>()
where !fieldSymbol.IsConst
let typeName = fieldSymbol.Type!.ToDisplayString()
let fieldFullType = ParseTypeName(typeName)
from fieldVariable in fieldDeclaration.Declaration.Variables
select (Type: fieldFullType, fieldVariable.Identifier)).ToImmutableArray();
select (Type: fieldFullType, Identifier: Identifier(fieldSymbol.Name))).ToImmutableArray();
// Create the constructor declaration for the type. This will
// produce a constructor with simple initialization of all variables:
+61
ファイルの表示
@@ -0,0 +1,61 @@
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.SourceGenerators.Helpers
{
/// <summary>
/// A class containing additional factory methods for constructing syntax nodes, tokens and trivia.
/// </summary>
internal static class SyntaxFactoryHelper
{
/// <summary>
/// Creates a <see cref="string"/>[] array expression from the given sequence of <see cref="string"/> instances.
/// <para>
/// That it, it applies the following transformation:
/// <code>
/// { "S1", "S2" } => new string[] { "S1", "S2" }
/// </code>
/// </para>
/// </summary>
/// <param name="values">The input sequence of <see cref="string"/> instances.</param>
/// <returns>An <see cref="ArrayCreationExpression"/> instance with the described contents.</returns>
[Pure]
public static ArrayCreationExpressionSyntax ArrayExpression(IEnumerable<string> values)
{
return
ArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword)))
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
.WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression)
.AddExpressions(values.Select(static value => LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(value))).ToArray()));
}
/// <summary>
/// Creates an <see cref="object"/>[] array expression with the nested groups in the input sequence.
/// <para>
/// That it, it applies the following transformation:
/// <code>
/// { ("K1", "V1"), ("K2", "V2") } => new object[] { new[] { "K1", "V1" }, new[] { "K2", "V2" } }
/// </code>
/// </para>
/// </summary>
/// <param name="values">The input sequence of <see cref="string"/> groups.</param>
/// <returns>An <see cref="ArrayCreationExpression"/> instance with the described contents.</returns>
[Pure]
public static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable<IEnumerable<string>> groups)
{
return
ArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.ObjectKeyword)))
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
.WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression)
.AddExpressions(groups.Select(static group =>
ImplicitArrayCreationExpression(InitializerExpression(SyntaxKind.ArrayInitializerExpression).AddExpressions(
group.Select(static item => LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item))).ToArray()))).ToArray()));
}
}
}
+2
ファイルの表示
@@ -141,6 +141,8 @@ namespace ComputeSharp.SourceGenerators
}
else if (HlslKnownTypes.IsScalarOrVectorType(typeName))
{
if (fieldSymbol.IsConst) continue;
var (fieldSize, fieldPack) = HlslKnownSizes.GetTypeInfo(typeName);
// Calculate the right offset with 16-bytes padding (HLSL constant buffer).
+27 -32
ファイルの表示
@@ -12,6 +12,7 @@ using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using static ComputeSharp.SourceGenerators.Helpers.SyntaxFactoryHelper;
#pragma warning disable CS0618
@@ -45,40 +46,14 @@ namespace ComputeSharp.SourceGenerators
// We need to sets to track all discovered custom types and static methods
HashSet<INamedTypeSymbol> discoveredTypes = new(SymbolEqualityComparer.Default);
Dictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods = new(SymbolEqualityComparer.Default);
// Helper that converts a sequence of string sequences into a nested array expression.
// That is, this applies the following transformation:
// - { ("K1", "V1"), ("K2", "V2") } => new object[] { new[] { "K1", "V1" }, new[] { "K2", "V2" } }
static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable<IEnumerable<string>> groups)
{
return
ArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.ObjectKeyword)))
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
.WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression)
.AddExpressions(groups.Select(static group =>
ImplicitArrayCreationExpression(InitializerExpression(SyntaxKind.ArrayInitializerExpression).AddExpressions(
group.Select(static item => LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item))).ToArray()))).ToArray()));
}
// Helper that converts a sequence of strings into an array expression.
// That is, this applies the following transformation:
// - { "S1", "S2" } => new string[] { "S1", "S2" }
static ArrayCreationExpressionSyntax ArrayExpression(IEnumerable<string> values)
{
return
ArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword)))
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
.WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression)
.AddExpressions(values.Select(static value => LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(value))).ToArray()));
}
Dictionary<IFieldSymbol, string> constantDefinitions = new(SymbolEqualityComparer.Default);
// Explore the syntax tree and extract the processed info
var processedMembers = GetProcessedMembers(structDeclarationSymbol, discoveredTypes).ToArray();
var (entryPoint, localFunctions) = GetProcessedMethods(structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods);
var (entryPoint, localFunctions) = GetProcessedMethods(structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions);
var processedTypes = GetProcessedTypes(discoveredTypes).ToArray();
var processedMethods = localFunctions.Concat(staticMethods.Values).Select(static method => method.NormalizeWhitespace().ToFullString()).ToArray();
var processedConstants = GetProcessedConstants(constantDefinitions);
// Create the compilation unit with the source attribute
var source =
@@ -90,7 +65,8 @@ namespace ComputeSharp.SourceGenerators
AttributeArgument(ArrayExpression(processedTypes)),
AttributeArgument(NestedArrayExpression(processedMembers)),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(entryPoint))),
AttributeArgument(ArrayExpression(processedMethods)))))
AttributeArgument(ArrayExpression(processedMethods)),
AttributeArgument(NestedArrayExpression(processedConstants)))))
.WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList()))
.WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword))))
.NormalizeWhitespace()
@@ -138,6 +114,7 @@ namespace ComputeSharp.SourceGenerators
/// <param name="semanticModel">The <see cref="SemanticModel"/> instance for the type to process.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <returns>A sequence of processed methods in <paramref name="structDeclaration"/>, and the entry point.</returns>
[Pure]
private static (string EntryPoint, IEnumerable<SyntaxNode> Methods) GetProcessedMethods(
@@ -145,7 +122,8 @@ namespace ComputeSharp.SourceGenerators
INamedTypeSymbol structDeclarationSymbol,
SemanticModel semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods)
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IFieldSymbol, string> constantDefinitions)
{
// Find all declared methods in the type
ImmutableArray<MethodDeclarationSyntax> methodDeclarations = (
@@ -159,7 +137,7 @@ namespace ComputeSharp.SourceGenerators
foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations)
{
IMethodSymbol methodDeclarationSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration)!;
ShaderSourceRewriter shaderSourceRewriter = new(structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods);
ShaderSourceRewriter shaderSourceRewriter = new(structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions);
// Rewrite the method syntax tree
var processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia();
@@ -189,6 +167,23 @@ namespace ComputeSharp.SourceGenerators
return (entryPoint!, methods);
}
/// <summary>
/// Gets a sequence of discovered constants.
/// </summary>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <returns>A sequence of discovered constants to declare in the shader.</returns>
[Pure]
internal static IEnumerable<IEnumerable<string>> GetProcessedConstants(IReadOnlyDictionary<IFieldSymbol, string> constantDefinitions)
{
foreach (var constant in constantDefinitions)
{
var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().Replace(".", "__");
var constantName = $"__{ownerTypeName}__{constant.Key.Name}";
yield return new string[] { constantName, constant.Value };
}
}
/// <summary>
/// Gets the sequence of processed discovered custom types.
/// </summary>
+10 -17
ファイルの表示
@@ -11,6 +11,7 @@ using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using static ComputeSharp.SourceGenerators.Helpers.SyntaxFactoryHelper;
#pragma warning disable CS0618
@@ -44,23 +45,12 @@ namespace ComputeSharp.SourceGenerators
// We need to sets to track all discovered custom types and static methods
HashSet<INamedTypeSymbol> discoveredTypes = new(SymbolEqualityComparer.Default);
Dictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods = new(SymbolEqualityComparer.Default);
Dictionary<IFieldSymbol, string> constantDefinitions = new(SymbolEqualityComparer.Default);
// Explore the syntax tree and extract the processed info
var (invokeMethod, processedMethods) = GetProcessedMethods(methodDeclaration, semanticModel, discoveredTypes, staticMethods);
var (invokeMethod, processedMethods) = GetProcessedMethods(methodDeclaration, semanticModel, discoveredTypes, staticMethods, constantDefinitions);
var processedTypes = IComputeShaderSourceGenerator.GetProcessedTypes(discoveredTypes).ToArray();
// Helper that converts a sequence of strings into an array expression.
// That is, this applies the following transformation:
// - { "S1", "S2" } => new string[] { "S1", "S2" }
static ArrayCreationExpressionSyntax ArrayExpression(IEnumerable<string> values)
{
return
ArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword)))
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
.WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression)
.AddExpressions(values.Select(static value => LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(value))).ToArray()));
}
var processedConstants = IComputeShaderSourceGenerator.GetProcessedConstants(constantDefinitions);
// Create the compilation unit with the source attribute
var source =
@@ -70,7 +60,8 @@ namespace ComputeSharp.SourceGenerators
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodDeclarationSymbol.GetFullMetadataName(true)))),
AttributeArgument(ArrayExpression(processedTypes)),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(invokeMethod))),
AttributeArgument(ArrayExpression(processedMethods)))))
AttributeArgument(ArrayExpression(processedMethods)),
AttributeArgument(NestedArrayExpression(processedConstants)))))
.WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList()))
.WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword))))
.NormalizeWhitespace()
@@ -88,15 +79,17 @@ namespace ComputeSharp.SourceGenerators
/// <param name="semanticModel">The <see cref="SemanticModel"/> instance for the method to process.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <returns>A sequence of processed methods in <paramref name="methodDeclaration"/>.</returns>
[Pure]
private static (string InvokeMethod, IEnumerable<string> Methods) GetProcessedMethods(
MethodDeclarationSyntax methodDeclaration,
SemanticModel semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods)
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IFieldSymbol, string> constantDefinitions)
{
ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods);
ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, constantDefinitions);
// Rewrite the method syntax tree
var processedMethod = shaderSourceRewriter
+40 -10
ファイルの表示
@@ -37,6 +37,11 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
/// </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>
@@ -59,16 +64,19 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
/// <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="staticMethods">The set of discovered and processed static methods.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
public ShaderSourceRewriter(
INamedTypeSymbol shaderType,
SemanticModel semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods)
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IFieldSymbol, string> constantDefinitions)
{
this.shaderType = shaderType;
this.semanticModel = semanticModel;
this.discoveredTypes = discoveredTypes;
this.staticMethods = staticMethods;
this.constantDefinitions = constantDefinitions;
this.localFunctions = new();
this.implicitVariables = new();
}
@@ -79,14 +87,17 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
/// <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="staticMethods">The set of discovered and processed static methods.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
public ShaderSourceRewriter(
SemanticModel semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods)
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IFieldSymbol, string> constantDefinitions)
{
this.semanticModel = semanticModel;
this.discoveredTypes = discoveredTypes;
this.staticMethods = staticMethods;
this.constantDefinitions = constantDefinitions;
this.implicitVariables = new();
this.localFunctions = new();
}
@@ -282,14 +293,15 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) &&
this.semanticModel.GetOperation(node) is IMemberReferenceOperation operation)
{
// If the current member access is to a constant, hardcode the value in HLSL
if (operation.ConstantValue is { HasValue: true } and { Value: object value })
// If the member access is a constant, track it and replace the tree with the processed constant name
if (operation is IFieldReferenceOperation fieldOperation && fieldOperation.Field.IsConst)
{
return ParseExpression(value switch
{
IFormattable f => f.ToString(null, CultureInfo.InvariantCulture),
_ => value.ToString()
});
this.constantDefinitions[fieldOperation.Field] = fieldOperation.Field.ConstantValue!.ToString();
var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().Replace(".", "__");
var constantName = $"__{ownerTypeName}__{fieldOperation.Field.Name}";
return IdentifierName(constantName);
}
// If the current member access is a field or property access, check the lookup table
@@ -398,7 +410,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
if (!this.staticMethods.ContainsKey(method))
{
ShaderSourceRewriter shaderSourceRewriter = new(this.semanticModel, this.discoveredTypes, this.staticMethods);
ShaderSourceRewriter shaderSourceRewriter = new(this.semanticModel, this.discoveredTypes, this.staticMethods, this.constantDefinitions);
MethodDeclarationSyntax
methodNode = (MethodDeclarationSyntax)method.DeclaringSyntaxReferences[0].GetSyntax(),
processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace().WithoutTrivia();
@@ -452,6 +464,24 @@ 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)
{
this.constantDefinitions[operation.Field] = operation.Field.ConstantValue!.ToString();
var ownerTypeName = ((INamedTypeSymbol)operation.Field.ContainingSymbol).ToDisplayString().Replace(".", "__");
var constantName = $"__{ownerTypeName}__{operation.Field.Name}";
return IdentifierName(constantName);
}
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxToken VisitToken(SyntaxToken token)
{