Implement GetNonDynamicHlslSourceInfo() method
This includes the data gathering step for the HLSL rewrite pipeline
このコミットが含まれているのは:
1 親
1b465e7b9d
コミット
b912b4f076
9ファイル変更
+2161
-1
検索条件に一致するファイルはありません
@@ -1,4 +1,5 @@
|
||||
using System.Linq;
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace ComputeSharp.SourceGenerators.Diagnostics;
|
||||
@@ -39,4 +40,36 @@ internal static class DiagnosticsExtensions
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(descriptor, node.GetLocation(), args));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a new diagnostics to the target builder.
|
||||
/// </summary>
|
||||
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
|
||||
/// <param name="descriptor">The input <see cref="DiagnosticDescriptor"/> for the diagnostics to create.</param>
|
||||
/// <param name="symbol">The source <see cref="ISymbol"/> to attach the diagnostics to.</param>
|
||||
/// <param name="args">The optional arguments for the formatted message to include.</param>
|
||||
public static void Add(
|
||||
this ImmutableArray<Diagnostic>.Builder diagnostics,
|
||||
DiagnosticDescriptor descriptor,
|
||||
ISymbol symbol,
|
||||
params object[] args)
|
||||
{
|
||||
diagnostics.Add(Diagnostic.Create(descriptor, symbol.Locations.FirstOrDefault(), args));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a new diagnostics to the target builder.
|
||||
/// </summary>
|
||||
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
|
||||
/// <param name="descriptor">The input <see cref="DiagnosticDescriptor"/> for the diagnostics to create.</param>
|
||||
/// <param name="node">The source <see cref="SyntaxNode"/> to attach the diagnostics to.</param>
|
||||
/// <param name="args">The optional arguments for the formatted message to include.</param>
|
||||
public static void Add(
|
||||
this ImmutableArray<Diagnostic>.Builder diagnostics,
|
||||
DiagnosticDescriptor descriptor,
|
||||
SyntaxNode node,
|
||||
params object[] args)
|
||||
{
|
||||
diagnostics.Add(Diagnostic.Create(descriptor, node.GetLocation(), args));
|
||||
}
|
||||
}
|
||||
+705
@@ -0,0 +1,705 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using ComputeSharp.SourceGenerators.Diagnostics;
|
||||
using ComputeSharp.SourceGenerators.Extensions;
|
||||
using ComputeSharp.SourceGenerators.Helpers;
|
||||
using ComputeSharp.SourceGenerators.Mappings;
|
||||
using ComputeSharp.SourceGenerators.Models;
|
||||
using ComputeSharp.SourceGenerators.SyntaxRewriters;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
#pragma warning disable CS0618, RS1024
|
||||
|
||||
namespace ComputeSharp.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public sealed partial class IShaderGenerator2
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.
|
||||
/// </summary>
|
||||
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
|
||||
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> node to process.</param>
|
||||
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for <paramref name="structDeclaration"/>.</param>
|
||||
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.</returns>
|
||||
/// <inheritdoc/>
|
||||
private static ((NonDynamicHlslSourceInfo SourceInfo, string? ImplicitTextureType, bool IsSamplerUsed), ImmutableArray<Diagnostic> Diagnostics) GetNonDynamicHlslSourceInfo(
|
||||
Compilation compilation,
|
||||
StructDeclarationSyntax structDeclaration,
|
||||
INamedTypeSymbol structDeclarationSymbol)
|
||||
{
|
||||
ImmutableArray<Diagnostic>.Builder diagnostics = ImmutableArray.CreateBuilder<Diagnostic>();
|
||||
|
||||
// Properties are not supported
|
||||
DetectAndReportPropertyDeclarations(diagnostics, structDeclarationSymbol);
|
||||
|
||||
// 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);
|
||||
|
||||
// A given type can only represent a single shader type
|
||||
if (structDeclarationSymbol.AllInterfaces.Count(static interfaceSymbol => interfaceSymbol is { Name: nameof(IComputeShader) } or { IsGenericType: true, Name: nameof(IPixelShader<byte>) }) > 1)
|
||||
{
|
||||
diagnostics.Add(MultipleShaderTypesImplemented, structDeclarationSymbol, structDeclarationSymbol);
|
||||
}
|
||||
|
||||
// Explore the syntax tree and extract the processed info
|
||||
var semanticModelProvider = new SemanticModelProvider(compilation);
|
||||
var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) });
|
||||
var isComputeShader = pixelShaderSymbol is null;
|
||||
var implicitTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!);
|
||||
var instanceFields = GetInstanceFields(diagnostics, structDeclarationSymbol, discoveredTypes, isComputeShader);
|
||||
var sharedBuffers = GetSharedBuffers(diagnostics, structDeclarationSymbol, discoveredTypes);
|
||||
var (entryPoint, processedMethods, isSamplerUsed) = GetProcessedMethods(diagnostics, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, constantDefinitions, isComputeShader);
|
||||
var implicitSamplerField = isSamplerUsed ? ("SamplerState", "__sampler") : default((string, string)?);
|
||||
var declaredTypes = GetDeclaredTypes(discoveredTypes);
|
||||
var definedConstants = GetDefinedConstants(constantDefinitions);
|
||||
var staticFields = GetStaticFields(diagnostics, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions);
|
||||
|
||||
// Get the HLSL source data with the intermediate info
|
||||
NonDynamicHlslSourceInfo sourceInfo = GetNonDynamicHlslSourceInfo(
|
||||
definedConstants,
|
||||
declaredTypes,
|
||||
instanceFields,
|
||||
staticFields,
|
||||
sharedBuffers,
|
||||
processedMethods,
|
||||
isComputeShader,
|
||||
implicitTextureType,
|
||||
isSamplerUsed,
|
||||
entryPoint);
|
||||
|
||||
return ((sourceInfo, implicitTextureType, isSamplerUsed), diagnostics.ToImmutable());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a sequence of captured fields and their mapped names.
|
||||
/// </summary>
|
||||
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
|
||||
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
|
||||
/// <param name="types">The collection of currently discovered types.</param>
|
||||
/// <param name="isComputeShader">Indicates whether or not <paramref name="structDeclarationSymbol"/> represents a compute shader.</param>
|
||||
/// <returns>A sequence of captured fields in <paramref name="structDeclarationSymbol"/>.</returns>
|
||||
[Pure]
|
||||
private static ImmutableArray<(string MetadataName, string Name, string HlslType)> GetInstanceFields(
|
||||
ImmutableArray<Diagnostic>.Builder diagnostics,
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
ICollection<INamedTypeSymbol> types,
|
||||
bool isComputeShader)
|
||||
{
|
||||
ImmutableArray<(string, string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, string)>();
|
||||
bool hlslResourceFound = false;
|
||||
|
||||
foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>())
|
||||
{
|
||||
if (fieldSymbol.IsStatic)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) });
|
||||
|
||||
// Group shared fields must be static
|
||||
if (attribute is not null)
|
||||
{
|
||||
diagnostics.Add(InvalidGroupSharedFieldDeclaration, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name);
|
||||
}
|
||||
|
||||
// Captured fields must be named type symbols
|
||||
if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol)
|
||||
{
|
||||
diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
string metadataName = typeSymbol.GetFullMetadataName();
|
||||
|
||||
// Allowed fields must be either resources, unmanaged values or delegates
|
||||
if (HlslKnownTypes.IsTypedResourceType(metadataName))
|
||||
{
|
||||
hlslResourceFound = true;
|
||||
|
||||
// Track the type of items in the current buffer
|
||||
if (HlslKnownTypes.IsStructuredBufferType(metadataName))
|
||||
{
|
||||
types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]);
|
||||
}
|
||||
}
|
||||
else if (!typeSymbol.IsUnmanagedType &&
|
||||
typeSymbol.TypeKind != TypeKind.Delegate)
|
||||
{
|
||||
// Shaders can only capture valid HLSL resource types or unmanaged types
|
||||
diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, typeSymbol);
|
||||
|
||||
continue;
|
||||
}
|
||||
else if (typeSymbol.IsUnmanagedType &&
|
||||
!HlslKnownTypes.IsKnownHlslType(metadataName))
|
||||
{
|
||||
// Track the type if it's a custom struct
|
||||
types.Add(typeSymbol);
|
||||
}
|
||||
|
||||
string typeName = HlslKnownTypes.GetMappedName(typeSymbol);
|
||||
|
||||
_ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
|
||||
|
||||
// Yield back the current mapping for the name (if the name used a reserved keyword)
|
||||
builder.Add((metadataName, mapping ?? fieldSymbol.Name, typeName));
|
||||
}
|
||||
|
||||
// If the shader is a compute one (so no implicit output texture), it has to contain at least one resource
|
||||
if (!hlslResourceFound && isComputeShader)
|
||||
{
|
||||
diagnostics.Add(MissingShaderResources, structDeclarationSymbol, structDeclarationSymbol);
|
||||
}
|
||||
|
||||
return builder.ToImmutable();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a sequence of shader static fields and their mapped names.
|
||||
/// </summary>
|
||||
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
|
||||
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> 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 fields in <paramref name="structDeclarationSymbol"/>.</returns>
|
||||
[Pure]
|
||||
private static ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields(
|
||||
ImmutableArray<Diagnostic>.Builder diagnostics,
|
||||
SemanticModelProvider semanticModel,
|
||||
StructDeclarationSyntax structDeclaration,
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
ICollection<INamedTypeSymbol> discoveredTypes,
|
||||
IDictionary<IFieldSymbol, string> constantDefinitions)
|
||||
{
|
||||
ImmutableArray<(string, string, string?)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, string?)>();
|
||||
|
||||
foreach (var fieldDeclaration in structDeclaration.Members.OfType<FieldDeclarationSyntax>())
|
||||
{
|
||||
foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables)
|
||||
{
|
||||
IFieldSymbol fieldSymbol = (IFieldSymbol)semanticModel.For(variableDeclarator).GetDeclaredSymbol(variableDeclarator)!;
|
||||
|
||||
if (!fieldSymbol.IsStatic || fieldSymbol.IsConst)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) });
|
||||
|
||||
if (attribute is not null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Constant properties must be of a primitive, vector or matrix type
|
||||
if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol ||
|
||||
!HlslKnownTypes.IsKnownHlslType(typeSymbol.GetFullMetadataName()))
|
||||
{
|
||||
diagnostics.Add(InvalidShaderStaticFieldType, variableDeclarator, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
_ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
|
||||
|
||||
string typeDeclaration = fieldSymbol.IsReadOnly switch
|
||||
{
|
||||
true => $"static const {HlslKnownTypes.GetMappedName(typeSymbol)}",
|
||||
false => $"static {HlslKnownTypes.GetMappedName(typeSymbol)}"
|
||||
};
|
||||
|
||||
StaticFieldRewriter2 staticFieldRewriter = new(
|
||||
semanticModel,
|
||||
discoveredTypes,
|
||||
constantDefinitions,
|
||||
diagnostics);
|
||||
|
||||
string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace(eol: "\n").ToFullString();
|
||||
|
||||
builder.Add((mapping ?? fieldSymbol.Name, typeDeclaration, assignment));
|
||||
}
|
||||
}
|
||||
|
||||
return builder.ToImmutable();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a sequence of captured members and their mapped names.
|
||||
/// </summary>
|
||||
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</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>
|
||||
[Pure]
|
||||
private static ImmutableArray<(string Name, string Type, int? Count)> GetSharedBuffers(
|
||||
ImmutableArray<Diagnostic>.Builder diagnostics,
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
ICollection<INamedTypeSymbol> types)
|
||||
{
|
||||
ImmutableArray<(string, string, int?)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, int?)>();
|
||||
|
||||
foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>())
|
||||
{
|
||||
if (!fieldSymbol.IsStatic)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) });
|
||||
|
||||
if (attribute is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (fieldSymbol.Type is not IArrayTypeSymbol typeSymbol)
|
||||
{
|
||||
diagnostics.Add(InvalidGroupSharedFieldType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!typeSymbol.ElementType.IsUnmanagedType)
|
||||
{
|
||||
diagnostics.Add(InvalidGroupSharedFieldElementType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
int? bufferSize = (int?)attribute.ConstructorArguments.FirstOrDefault().Value;
|
||||
|
||||
string typeName = HlslKnownTypes.GetMappedElementName(typeSymbol);
|
||||
|
||||
_ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
|
||||
|
||||
builder.Add((mapping ?? fieldSymbol.Name, typeName, bufferSize));
|
||||
|
||||
types.Add((INamedTypeSymbol)typeSymbol.ElementType);
|
||||
}
|
||||
|
||||
return builder.ToImmutable();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a sequence of processed methods declared within a given type.
|
||||
/// </summary>
|
||||
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
|
||||
/// <param name="structDeclarationSymbol">The type symbol for the shader type.</param>
|
||||
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> instance for the current type.</param>
|
||||
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the type to process.</param>
|
||||
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
|
||||
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
|
||||
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
|
||||
/// <param name="isComputeShader">Indicates whether or not <paramref name="structDeclarationSymbol"/> represents a compute shader.</param>
|
||||
/// <returns>A sequence of processed methods in <paramref name="structDeclaration"/>, and the entry point.</returns>
|
||||
[Pure]
|
||||
private static (string EntryPoint, ImmutableArray<(string Signature, string Definition)> Methods, bool IsSamplerUser) GetProcessedMethods(
|
||||
ImmutableArray<Diagnostic>.Builder diagnostics,
|
||||
StructDeclarationSyntax structDeclaration,
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
SemanticModelProvider semanticModel,
|
||||
ICollection<INamedTypeSymbol> discoveredTypes,
|
||||
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
|
||||
IDictionary<IFieldSymbol, string> constantDefinitions,
|
||||
bool isComputeShader)
|
||||
{
|
||||
// Find all declared methods in the type
|
||||
ImmutableArray<MethodDeclarationSyntax> methodDeclarations = (
|
||||
from syntaxNode in structDeclaration.DescendantNodes()
|
||||
where syntaxNode.IsKind(SyntaxKind.MethodDeclaration)
|
||||
select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray();
|
||||
|
||||
string? entryPoint = null;
|
||||
ImmutableArray<(string, string)>.Builder methods = ImmutableArray.CreateBuilder<(string, string)>();
|
||||
bool isSamplerUsed = false;
|
||||
|
||||
foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations)
|
||||
{
|
||||
IMethodSymbol methodDeclarationSymbol = semanticModel.For(methodDeclaration).GetDeclaredSymbol(methodDeclaration)!;
|
||||
bool isShaderEntryPoint =
|
||||
(isComputeShader &&
|
||||
methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) &&
|
||||
methodDeclarationSymbol.ReturnsVoid &&
|
||||
methodDeclarationSymbol.TypeParameters.Length == 0 &&
|
||||
methodDeclarationSymbol.Parameters.Length == 0) ||
|
||||
(!isComputeShader &&
|
||||
methodDeclarationSymbol.Name == nameof(IPixelShader<byte>.Execute) &&
|
||||
methodDeclarationSymbol.ReturnType is not null && // TODO: match for pixel type
|
||||
methodDeclarationSymbol.TypeParameters.Length == 0 &&
|
||||
methodDeclarationSymbol.Parameters.Length == 0);
|
||||
|
||||
// Create the source rewriter for the current method
|
||||
ShaderSourceRewriter2 shaderSourceRewriter = new(
|
||||
structDeclarationSymbol,
|
||||
semanticModel,
|
||||
discoveredTypes,
|
||||
staticMethods,
|
||||
constantDefinitions,
|
||||
diagnostics,
|
||||
isShaderEntryPoint);
|
||||
|
||||
// Rewrite the method syntax tree
|
||||
MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia();
|
||||
|
||||
// Track the implicit sampler, if used
|
||||
isSamplerUsed = isSamplerUsed || shaderSourceRewriter.IsSamplerUsed;
|
||||
|
||||
// Emit the extracted local functions first
|
||||
foreach (var localFunction in shaderSourceRewriter.LocalFunctions)
|
||||
{
|
||||
methods.Add((
|
||||
localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
|
||||
localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString()));
|
||||
}
|
||||
|
||||
// If the method is the shader entry point, do additional processing
|
||||
if (isShaderEntryPoint)
|
||||
{
|
||||
processedMethod = isComputeShader switch
|
||||
{
|
||||
true => new ExecuteMethodRewriter2.Compute(shaderSourceRewriter).Visit(processedMethod)!,
|
||||
false => new ExecuteMethodRewriter2.Pixel(shaderSourceRewriter).Visit(processedMethod)!
|
||||
};
|
||||
|
||||
entryPoint = processedMethod.NormalizeWhitespace(eol: "\n").ToFullString();
|
||||
}
|
||||
else
|
||||
{
|
||||
methods.Add((
|
||||
processedMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
|
||||
processedMethod.NormalizeWhitespace(eol: "\n").ToFullString()));
|
||||
}
|
||||
}
|
||||
|
||||
// Process static methods as well
|
||||
foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values)
|
||||
{
|
||||
methods.Add((
|
||||
staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
|
||||
staticMethod.NormalizeWhitespace(eol: "\n").ToFullString()));
|
||||
}
|
||||
|
||||
return (entryPoint!, methods.ToImmutable(), isSamplerUsed);
|
||||
}
|
||||
|
||||
/// <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 ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary<IFieldSymbol, string> constantDefinitions)
|
||||
{
|
||||
ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(constantDefinitions.Count);
|
||||
|
||||
foreach (var constant in constantDefinitions)
|
||||
{
|
||||
var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName();
|
||||
var constantName = $"__{ownerTypeName}__{constant.Key.Name}";
|
||||
|
||||
builder.Add((constantName, constant.Value));
|
||||
}
|
||||
|
||||
return builder.MoveToImmutable();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the sequence of processed discovered custom types.
|
||||
/// </summary>
|
||||
/// <param name="types">The sequence of discovered custom types.</param>
|
||||
/// <returns>A sequence of custom type definitions to add to the shader source.</returns>
|
||||
internal static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes(IEnumerable<INamedTypeSymbol> types)
|
||||
{
|
||||
ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>();
|
||||
|
||||
foreach (var type in HlslKnownTypes.GetCustomTypes(types))
|
||||
{
|
||||
var structType = type.GetFullMetadataName().ToHlslIdentifierName();
|
||||
var structDeclaration = StructDeclaration(structType);
|
||||
|
||||
// Declare the fields of the current type
|
||||
foreach (var field in type.GetMembers().OfType<IFieldSymbol>())
|
||||
{
|
||||
if (field.IsStatic) continue;
|
||||
|
||||
INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type;
|
||||
|
||||
// Convert the name to the fully qualified HLSL version
|
||||
if (!HlslKnownTypes.TryGetMappedName(fieldType.GetFullMetadataName(), out string? mapped))
|
||||
{
|
||||
mapped = fieldType.GetFullMetadataName().ToHlslIdentifierName();
|
||||
}
|
||||
|
||||
structDeclaration = structDeclaration.AddMembers(
|
||||
FieldDeclaration(VariableDeclaration(
|
||||
IdentifierName(mapped!)).AddVariables(
|
||||
VariableDeclarator(Identifier(field.Name)))));
|
||||
}
|
||||
|
||||
// Insert the trailing ; right after the closing bracket (after normalization)
|
||||
builder.Add((
|
||||
structType,
|
||||
structDeclaration
|
||||
.NormalizeWhitespace(eol: "\n")
|
||||
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken))
|
||||
.ToFullString()));
|
||||
}
|
||||
|
||||
return builder.ToImmutable();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds and reports all declared properties in a shader.
|
||||
/// </summary>
|
||||
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
|
||||
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
|
||||
private static void DetectAndReportPropertyDeclarations(ImmutableArray<Diagnostic>.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol)
|
||||
{
|
||||
foreach (var propertySymbol in structDeclarationSymbol.GetMembers().OfType<IPropertySymbol>())
|
||||
{
|
||||
diagnostics.Add(DiagnosticDescriptors.PropertyDeclaration, propertySymbol);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Produces the series of statements to build the current HLSL source.
|
||||
/// </summary>
|
||||
/// <param name="definedConstants">The sequence of defined constants for the shader.</param>
|
||||
/// <param name="declaredTypes">The sequence of declared types used by the shader.</param>
|
||||
/// <param name="instanceFields">The sequence of instance fields for the current shader.</param>
|
||||
/// <param name="staticFields">The sequence of static fields referenced by the shader.</param>
|
||||
/// <param name="sharedBuffers">The sequence of shared buffers declared by the shader.</param>
|
||||
/// <param name="processedMethods">The sequence of processed methods used by the shader.</param>
|
||||
/// <param name="isComputeShader">Whether or not the current shader type is a compute shader.</param>
|
||||
/// <param name="implicitTextureType">The type of the implicit target texture, if present.</param>
|
||||
/// <param name="isSamplerUsed">Whether the static sampler is used by the shader.</param>
|
||||
/// <param name="executeMethod">The body of the entry point of the shader.</param>
|
||||
/// <returns>The series of statements to build the HLSL source to compile to execute the current shader.</returns>
|
||||
private static NonDynamicHlslSourceInfo GetNonDynamicHlslSourceInfo(
|
||||
ImmutableArray<(string Name, string Value)> definedConstants,
|
||||
ImmutableArray<(string Name, string Definition)> declaredTypes,
|
||||
ImmutableArray<(string MetadataName, string Name, string HlslType)> instanceFields,
|
||||
ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> staticFields,
|
||||
ImmutableArray<(string Name, string Type, int? Count)> sharedBuffers,
|
||||
ImmutableArray<(string Signature, string Definition)> processedMethods,
|
||||
bool isComputeShader,
|
||||
string? implicitTextureType,
|
||||
bool isSamplerUsed,
|
||||
|
||||
string executeMethod)
|
||||
{
|
||||
StringBuilder hlslBuilder = new();
|
||||
|
||||
void AppendLF()
|
||||
{
|
||||
hlslBuilder.Append('\n');
|
||||
}
|
||||
|
||||
void AppendLine(string text)
|
||||
{
|
||||
hlslBuilder.Append(text);
|
||||
}
|
||||
|
||||
void AppendLineAndLF(string text)
|
||||
{
|
||||
hlslBuilder.Append(text);
|
||||
hlslBuilder.Append('\n');
|
||||
}
|
||||
|
||||
void AppendCharacterAndLF(char c)
|
||||
{
|
||||
hlslBuilder.Append(c);
|
||||
hlslBuilder.Append('\n');
|
||||
}
|
||||
|
||||
string FlushText()
|
||||
{
|
||||
string text = hlslBuilder.ToString();
|
||||
|
||||
hlslBuilder.Clear();
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
// Header
|
||||
AppendLineAndLF("// ================================================");
|
||||
AppendLineAndLF("// AUTO GENERATED");
|
||||
AppendLineAndLF("// ================================================");
|
||||
AppendLineAndLF("// This shader was created by ComputeSharp.");
|
||||
AppendLineAndLF("// See: https://github.com/Sergio0694/ComputeSharp.");
|
||||
|
||||
// Group size constants
|
||||
AppendLF();
|
||||
AppendLine("#define __GroupSize__get_X ");
|
||||
|
||||
string headerAndThreadsX = FlushText();
|
||||
|
||||
AppendLF();
|
||||
AppendLine("#define __GroupSize__get_Y ");
|
||||
|
||||
string threadsY = FlushText();
|
||||
|
||||
AppendLF();
|
||||
AppendLine("#define __GroupSize__get_Z ");
|
||||
|
||||
string threadsZ = FlushText();
|
||||
|
||||
AppendLF();
|
||||
|
||||
// Define declarations
|
||||
foreach (var (name, value) in definedConstants)
|
||||
{
|
||||
AppendLineAndLF($"#define {name} {value}");
|
||||
}
|
||||
|
||||
string defines = FlushText();
|
||||
|
||||
// Static fields
|
||||
if (staticFields.Any())
|
||||
{
|
||||
AppendLF();
|
||||
|
||||
foreach (var field in staticFields)
|
||||
{
|
||||
if (field.Assignment is string assignment)
|
||||
{
|
||||
AppendLineAndLF($"{field.TypeDeclaration} {field.Name} = {assignment};");
|
||||
}
|
||||
else
|
||||
{
|
||||
AppendLineAndLF($"{field.TypeDeclaration} {field.Name};");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Declared types
|
||||
foreach (var (_, typeDefinition) in declaredTypes)
|
||||
{
|
||||
AppendLF();
|
||||
AppendLineAndLF(typeDefinition);
|
||||
}
|
||||
|
||||
string staticFieldsAndDeclaredTypes = FlushText();
|
||||
|
||||
// Captured variables
|
||||
AppendLF();
|
||||
AppendLineAndLF("cbuffer _ : register(b0)");
|
||||
AppendCharacterAndLF('{');
|
||||
AppendLineAndLF(" uint __x;");
|
||||
AppendLineAndLF(" uint __y;");
|
||||
|
||||
if (isComputeShader)
|
||||
{
|
||||
AppendLineAndLF(" uint __z;");
|
||||
}
|
||||
|
||||
// User-defined values
|
||||
foreach (var (_, fieldName, fieldType) in instanceFields.Where(static t => !HlslKnownTypes.IsTypedResourceType(t.MetadataName)))
|
||||
{
|
||||
AppendLineAndLF($" {fieldType} {fieldName};");
|
||||
}
|
||||
|
||||
AppendCharacterAndLF('}');
|
||||
|
||||
int constantBuffersCount = 1;
|
||||
int readOnlyBuffersCount = 0;
|
||||
int readWriteBuffersCount = 0;
|
||||
|
||||
// Optional implicit texture field
|
||||
if (!isComputeShader)
|
||||
{
|
||||
AppendLF();
|
||||
AppendLineAndLF($"{implicitTextureType} __outputTexture : register(u{readWriteBuffersCount++});");
|
||||
}
|
||||
|
||||
// Optional sampler field
|
||||
if (isSamplerUsed)
|
||||
{
|
||||
AppendLF();
|
||||
AppendLineAndLF("SamplerState __sampler : register(s);");
|
||||
}
|
||||
|
||||
// Resources
|
||||
foreach (var (metadataName, fieldName, fieldType) in instanceFields)
|
||||
{
|
||||
if (HlslKnownTypes.IsConstantBufferType(metadataName))
|
||||
{
|
||||
AppendLF();
|
||||
AppendLineAndLF($"cbuffer _{fieldName} : register(b{constantBuffersCount++})");
|
||||
AppendCharacterAndLF('{');
|
||||
AppendLineAndLF($" {fieldType} {fieldName}[2];");
|
||||
AppendCharacterAndLF('}');
|
||||
}
|
||||
else if (HlslKnownTypes.IsReadOnlyTypedResourceType(metadataName))
|
||||
{
|
||||
AppendLF();
|
||||
AppendLineAndLF($"{fieldType} {fieldName} : register(t{readOnlyBuffersCount++});");
|
||||
}
|
||||
else if (HlslKnownTypes.IsReadWriteTypedResourceType(metadataName))
|
||||
{
|
||||
AppendLF();
|
||||
AppendLineAndLF($"{fieldType} {fieldName} : register(u{readWriteBuffersCount++});");
|
||||
}
|
||||
}
|
||||
|
||||
// Shared buffers
|
||||
foreach (var (bufferName, bufferType, bufferCount) in sharedBuffers)
|
||||
{
|
||||
object count = (object?)bufferCount ?? "threadsX * threadsY * threadsZ";
|
||||
|
||||
AppendLF();
|
||||
AppendLineAndLF($"groupshared {bufferType} {bufferName} [{count}];");
|
||||
}
|
||||
|
||||
// Forward declarations
|
||||
foreach (var (forwardDeclaration, _) in processedMethods)
|
||||
{
|
||||
AppendLF();
|
||||
AppendLineAndLF(forwardDeclaration);
|
||||
}
|
||||
|
||||
string capturedFieldsAndResourcesAndForwardDeclarations = FlushText();
|
||||
|
||||
// Captured methods
|
||||
foreach (var (_, method) in processedMethods)
|
||||
{
|
||||
AppendLF();
|
||||
AppendLineAndLF(method);
|
||||
}
|
||||
|
||||
string capturedMethods = FlushText();
|
||||
|
||||
// Entry point
|
||||
AppendLF();
|
||||
AppendLineAndLF("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]");
|
||||
AppendLineAndLF(executeMethod);
|
||||
|
||||
string entryPoint = FlushText();
|
||||
|
||||
return new(
|
||||
headerAndThreadsX,
|
||||
threadsY,
|
||||
threadsZ,
|
||||
defines,
|
||||
staticFieldsAndDeclaredTypes,
|
||||
capturedFieldsAndResourcesAndForwardDeclarations,
|
||||
capturedMethods,
|
||||
entryPoint,
|
||||
processedMethods.Select(static m => m.Signature).ToImmutableArray());
|
||||
}
|
||||
}
|
||||
@@ -149,6 +149,26 @@ internal static class HlslKnownTypes
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether or not a given type name matches a writeable typed resource type.
|
||||
/// </summary>
|
||||
/// <param name="typeName">The input type name to check.</param>
|
||||
/// <returns>Whether or not <paramref name="typeName"/> represents a writeable typed resource type.</returns>
|
||||
public static bool IsReadWriteTypedResourceType(string typeName)
|
||||
{
|
||||
return typeName switch
|
||||
{
|
||||
"ComputeSharp.ReadWriteBuffer`1" or
|
||||
"ComputeSharp.ReadWriteTexture2D`1" or
|
||||
"ComputeSharp.ReadWriteTexture2D`2" or
|
||||
"ComputeSharp.ReadWriteTexture3D`1" or
|
||||
"ComputeSharp.ReadWriteTexture3D`2" or
|
||||
"ComputeSharp.IReadWriteTexture2D`1" or
|
||||
"ComputeSharp.IReadWriteTexture3D`1" => true,
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether or not a given type name matches a typed resource type.
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
|
||||
namespace ComputeSharp.SourceGenerators.Models;
|
||||
|
||||
/// <summary>
|
||||
/// A model for extracted info on a processed HLSL shader, excluding dynamic information.
|
||||
/// </summary>
|
||||
/// <param name="HeaderAndThreadsX">The shader generated header and <c>threadsX</c> count declaration.</param>
|
||||
/// <param name="ThreadsY">The <c>threadsY</c> count declaration.</param>
|
||||
/// <param name="ThreadsZ">The <c>threadsZ</c> count declaration.</param>
|
||||
/// <param name="Defines">The define statements, if any.</param>
|
||||
/// <param name="StaticFieldsAndDeclaredTypes">The static fields and declared types, if any.</param>
|
||||
/// <param name="CapturedFieldsAndResourcesAndForwardDeclarations">The captured fields, and method forward declarations.</param>
|
||||
/// <param name="CapturedMethods">The captured method implementations.</param>
|
||||
/// <param name="EntryPoint">The shader entry point.</param>
|
||||
/// <param name="MethodSignatures">The signatures for captured methods.</param>
|
||||
internal sealed record NonDynamicHlslSourceInfo(
|
||||
string HeaderAndThreadsX,
|
||||
string ThreadsY,
|
||||
string ThreadsZ,
|
||||
string Defines,
|
||||
string StaticFieldsAndDeclaredTypes,
|
||||
string CapturedFieldsAndResourcesAndForwardDeclarations,
|
||||
string CapturedMethods,
|
||||
string EntryPoint,
|
||||
ImmutableArray<string> MethodSignatures)
|
||||
{
|
||||
/// <summary>
|
||||
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="NonDynamicHlslSourceInfo"/>.
|
||||
/// </summary>
|
||||
public sealed class Comparer : IEqualityComparer<NonDynamicHlslSourceInfo>
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public bool Equals(NonDynamicHlslSourceInfo? x, NonDynamicHlslSourceInfo? y)
|
||||
{
|
||||
if (x is null && y is null)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (x is null || y is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (ReferenceEquals(x, y))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return
|
||||
x.HeaderAndThreadsX == y.HeaderAndThreadsX &&
|
||||
x.ThreadsY == y.ThreadsY &&
|
||||
x.ThreadsZ == y.ThreadsZ &&
|
||||
x.Defines == y.Defines &&
|
||||
x.StaticFieldsAndDeclaredTypes == y.StaticFieldsAndDeclaredTypes &&
|
||||
x.CapturedFieldsAndResourcesAndForwardDeclarations == y.CapturedFieldsAndResourcesAndForwardDeclarations &&
|
||||
x.CapturedMethods == y.CapturedMethods &&
|
||||
x.EntryPoint == y.EntryPoint &&
|
||||
x.MethodSignatures.AsSpan().SequenceEqual(y.MethodSignatures.AsSpan());
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public int GetHashCode(NonDynamicHlslSourceInfo obj)
|
||||
{
|
||||
HashCode hashCode = default;
|
||||
|
||||
hashCode.Add(obj.HeaderAndThreadsX);
|
||||
hashCode.Add(obj.ThreadsY);
|
||||
hashCode.Add(obj.ThreadsZ);
|
||||
hashCode.Add(obj.Defines);
|
||||
hashCode.Add(obj.StaticFieldsAndDeclaredTypes);
|
||||
hashCode.Add(obj.CapturedFieldsAndResourcesAndForwardDeclarations);
|
||||
hashCode.Add(obj.CapturedMethods);
|
||||
hashCode.Add(obj.EntryPoint);
|
||||
|
||||
foreach (string signature in obj.MethodSignatures)
|
||||
{
|
||||
hashCode.Add(signature);
|
||||
}
|
||||
|
||||
return hashCode.ToHashCode();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
namespace ComputeSharp.SourceGenerators.SyntaxRewriters;
|
||||
|
||||
/// <summary>
|
||||
/// A custom <see cref="CSharpSyntaxRewriter"/> type that does postprocessing fixups on the shader main method.
|
||||
/// </summary>
|
||||
internal abstract class ExecuteMethodRewriter2 : CSharpSyntaxRewriter
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="Compute"/> instance with the specified parameters.
|
||||
/// </summary>
|
||||
/// <param name="shaderSourceRewriter">The <see cref="ShaderSourceRewriter2"/> instance used to process the input tree.</param>
|
||||
public ExecuteMethodRewriter2(ShaderSourceRewriter2 shaderSourceRewriter)
|
||||
{
|
||||
ShaderSourceRewriter2 = shaderSourceRewriter;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the <see cref="ShaderSourceRewriter2"/> instance used to process the input tree.
|
||||
/// </summary>
|
||||
protected ShaderSourceRewriter2 ShaderSourceRewriter2 { get; }
|
||||
|
||||
/// <inheritdoc cref="CSharpSyntaxRewriter.Visit(SyntaxNode?)"/>
|
||||
public TNode? Visit<TNode>(TNode? node)
|
||||
where TNode : SyntaxNode
|
||||
{
|
||||
return (TNode?)base.Visit(node);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitParameterList(ParameterListSyntax node)
|
||||
{
|
||||
var updatedNode = (ParameterListSyntax)base.VisitParameterList(node)!;
|
||||
|
||||
updatedNode = updatedNode.AddParameters(Parameter(Identifier($"uint3 {nameof(ThreadIds)} : SV_DispatchThreadID")));
|
||||
|
||||
if (ShaderSourceRewriter2.IsGroupIdsUsed)
|
||||
{
|
||||
updatedNode = updatedNode.AddParameters(Parameter(Identifier($"uint3 {nameof(GroupIds)} : SV_GroupThreadID")));
|
||||
}
|
||||
|
||||
if (ShaderSourceRewriter2.IsGroupIdsIndexUsed)
|
||||
{
|
||||
updatedNode = updatedNode.AddParameters(Parameter(Identifier($"uint __{nameof(GroupIds)}__get_Index : SV_GroupIndex")));
|
||||
}
|
||||
|
||||
if (ShaderSourceRewriter2.IsGridIdsUsed)
|
||||
{
|
||||
updatedNode = updatedNode.AddParameters(Parameter(Identifier($"uint3 {nameof(GridIds)} : SV_GroupID")));
|
||||
}
|
||||
|
||||
return updatedNode;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A custom <see cref="ExecuteMethodRewriter"/> type specialized for compute shaders.
|
||||
/// </summary>
|
||||
public sealed class Compute : ExecuteMethodRewriter2
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="Compute"/> instance with the specified parameters.
|
||||
/// </summary>
|
||||
/// <param name="shaderSourceRewriter">The <see cref="ShaderSourceRewriter2"/> instance used to process the input tree.</param>
|
||||
public Compute(ShaderSourceRewriter2 shaderSourceRewriter)
|
||||
: base(shaderSourceRewriter)
|
||||
{
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node)
|
||||
{
|
||||
var updatedNode = ((MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!).WithModifiers(TokenList());
|
||||
|
||||
// When we're rewriting the main compute shader method, we need to insert a range
|
||||
// check to ensure that invocation outside of the requested range are discarded.
|
||||
// The following snippet creates this prologue before the user provided body:
|
||||
//
|
||||
// if (ThreadIds.x < __x &&
|
||||
// ThreadIds.y < __y &&
|
||||
// ThreadIds.z < __z)
|
||||
// {
|
||||
// <body>
|
||||
// }
|
||||
BinaryExpressionSyntax rangeCheckExpression =
|
||||
BinaryExpression(SyntaxKind.LogicalAndExpression,
|
||||
BinaryExpression(SyntaxKind.LogicalAndExpression,
|
||||
BinaryExpression(SyntaxKind.LessThanExpression,
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName(nameof(ThreadIds)),
|
||||
IdentifierName("x")),
|
||||
IdentifierName("__x")),
|
||||
BinaryExpression(SyntaxKind.LessThanExpression,
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName(nameof(ThreadIds)),
|
||||
IdentifierName("y")),
|
||||
IdentifierName("__y"))),
|
||||
BinaryExpression(SyntaxKind.LessThanExpression,
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName(nameof(ThreadIds)),
|
||||
IdentifierName("z")),
|
||||
IdentifierName("__z")));
|
||||
|
||||
return updatedNode.WithBody(Block(IfStatement(rangeCheckExpression, updatedNode.Body!)));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A custom <see cref="ExecuteMethodRewriter"/> type specialized for compute shaders.
|
||||
/// </summary>
|
||||
public sealed class Pixel : ExecuteMethodRewriter2
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="Pixel"/> instance with the specified parameters.
|
||||
/// </summary>
|
||||
/// <param name="shaderSourceRewriter">The <see cref="ShaderSourceRewriter2"/> instance used to process the input tree.</param>
|
||||
public Pixel(ShaderSourceRewriter2 shaderSourceRewriter)
|
||||
: base(shaderSourceRewriter)
|
||||
{
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitReturnStatement(ReturnStatementSyntax node)
|
||||
{
|
||||
var updatedNode = (ReturnStatementSyntax)base.VisitReturnStatement(node)!;
|
||||
|
||||
// __outputTexture[ThreadIds.xy] = <RETURN_EXPRESSION>;
|
||||
return
|
||||
ExpressionStatement(
|
||||
AssignmentExpression(
|
||||
SyntaxKind.SimpleAssignmentExpression,
|
||||
ElementAccessExpression(IdentifierName("__outputTexture"))
|
||||
.AddArgumentListArguments(
|
||||
Argument(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("ThreadIds"),
|
||||
IdentifierName("xy")))),
|
||||
updatedNode.Expression!));
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node)
|
||||
{
|
||||
var updatedNode = ((MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!).WithModifiers(TokenList());
|
||||
|
||||
// Change the return type to void
|
||||
updatedNode = updatedNode.WithReturnType(PredefinedType(Token(SyntaxKind.VoidKeyword)));
|
||||
|
||||
// Same as above, but skipping the third check for the Z axis.
|
||||
// This is because pixel shaders only ever run on 2D textures.
|
||||
BinaryExpressionSyntax rangeCheckExpression =
|
||||
BinaryExpression(SyntaxKind.LogicalAndExpression,
|
||||
BinaryExpression(SyntaxKind.LessThanExpression,
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName(nameof(ThreadIds)),
|
||||
IdentifierName("x")),
|
||||
IdentifierName("__x")),
|
||||
BinaryExpression(SyntaxKind.LessThanExpression,
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName(nameof(ThreadIds)),
|
||||
IdentifierName("y")),
|
||||
IdentifierName("__y")));
|
||||
|
||||
return updatedNode.WithBody(Block(IfStatement(rangeCheckExpression, updatedNode.Body!)));
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node)
|
||||
{
|
||||
IdentifierNameSyntax updatedNode = (IdentifierNameSyntax)base.VisitIdentifierName(node)!;
|
||||
|
||||
// Since pixel shaders are only ever executed on 2D textures, the special __z field can
|
||||
// be removed and replaced with just numeric literal expressions, where the value is 1.
|
||||
if (updatedNode.Identifier.Text == "__z")
|
||||
{
|
||||
return LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1));
|
||||
}
|
||||
|
||||
return updatedNode;
|
||||
}
|
||||
}
|
||||
}
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
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="HlslSourceRewriter2"/>
|
||||
internal abstract partial class HlslSourceRewriter2 : CSharpSyntaxRewriter
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
|
||||
{
|
||||
var updatedNode = (AnonymousObjectCreationExpressionSyntax)base.VisitAnonymousObjectCreationExpression(node)!;
|
||||
|
||||
Diagnostics.Add(AnonymousObjectCreationExpression, node);
|
||||
|
||||
return updatedNode;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitAwaitExpression(AwaitExpressionSyntax node)
|
||||
{
|
||||
Diagnostics.Add(AwaitExpression, node);
|
||||
|
||||
return base.VisitAwaitExpression(node);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitCheckedExpression(CheckedExpressionSyntax node)
|
||||
{
|
||||
Diagnostics.Add(CheckedExpression, node);
|
||||
|
||||
return base.VisitCheckedExpression(node);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitCheckedStatement(CheckedStatementSyntax node)
|
||||
{
|
||||
Diagnostics.Add(CheckedStatement, node);
|
||||
|
||||
return base.VisitCheckedStatement(node);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitFixedStatement(FixedStatementSyntax node)
|
||||
{
|
||||
Diagnostics.Add(FixedStatement, node);
|
||||
|
||||
return base.VisitFixedStatement(node);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitForEachStatement(ForEachStatementSyntax node)
|
||||
{
|
||||
Diagnostics.Add(ForEachStatement, node);
|
||||
|
||||
return base.VisitForEachStatement(node);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitForEachVariableStatement(ForEachVariableStatementSyntax node)
|
||||
{
|
||||
Diagnostics.Add(ForEachStatement, node);
|
||||
|
||||
return base.VisitForEachVariableStatement(node);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitLockStatement(LockStatementSyntax node)
|
||||
{
|
||||
Diagnostics.Add(LockStatement, node);
|
||||
|
||||
return base.VisitLockStatement(node);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitQueryExpression(QueryExpressionSyntax node)
|
||||
{
|
||||
Diagnostics.Add(QueryExpression, node);
|
||||
|
||||
return base.VisitQueryExpression(node);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitRangeExpression(RangeExpressionSyntax node)
|
||||
{
|
||||
Diagnostics.Add(RangeExpression, node);
|
||||
|
||||
return base.VisitRangeExpression(node);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitRecursivePattern(RecursivePatternSyntax node)
|
||||
{
|
||||
Diagnostics.Add(RecursivePattern, node);
|
||||
|
||||
return base.VisitRecursivePattern(node);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitRefType(RefTypeSyntax node)
|
||||
{
|
||||
Diagnostics.Add(RefType, node);
|
||||
|
||||
return base.VisitRefType(node);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitRelationalPattern(RelationalPatternSyntax node)
|
||||
{
|
||||
Diagnostics.Add(RelationalPattern, node);
|
||||
|
||||
return base.VisitRelationalPattern(node);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitSizeOfExpression(SizeOfExpressionSyntax node)
|
||||
{
|
||||
Diagnostics.Add(SizeOfExpression, node);
|
||||
|
||||
return base.VisitSizeOfExpression(node);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node)
|
||||
{
|
||||
Diagnostics.Add(StackAllocArrayCreationExpression, node);
|
||||
|
||||
return base.VisitStackAllocArrayCreationExpression(node);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitThrowExpression(ThrowExpressionSyntax node)
|
||||
{
|
||||
Diagnostics.Add(ThrowExpressionOrStatement, node);
|
||||
|
||||
return base.VisitThrowExpression(node);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitThrowStatement(ThrowStatementSyntax node)
|
||||
{
|
||||
Diagnostics.Add(ThrowExpressionOrStatement, node);
|
||||
|
||||
return base.VisitThrowStatement(node);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitTryStatement(TryStatementSyntax node)
|
||||
{
|
||||
Diagnostics.Add(TryStatement, node);
|
||||
|
||||
return base.VisitTryStatement(node);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitTupleType(TupleTypeSyntax node)
|
||||
{
|
||||
Diagnostics.Add(TupleType, node);
|
||||
|
||||
return base.VisitTupleType(node);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitUsingStatement(UsingStatementSyntax node)
|
||||
{
|
||||
Diagnostics.Add(UsingStatementOrDeclaration, node);
|
||||
|
||||
return base.VisitUsingStatement(node);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitYieldStatement(YieldStatementSyntax node)
|
||||
{
|
||||
Diagnostics.Add(YieldStatement, node);
|
||||
|
||||
return base.VisitYieldStatement(node);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitFunctionPointerType(FunctionPointerTypeSyntax node)
|
||||
{
|
||||
Diagnostics.Add(FunctionPointer, node);
|
||||
|
||||
return base.VisitFunctionPointerType(node);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitPointerType(PointerTypeSyntax node)
|
||||
{
|
||||
Diagnostics.Add(PointerType, node);
|
||||
|
||||
return base.VisitPointerType(node);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitUnsafeStatement(UnsafeStatementSyntax node)
|
||||
{
|
||||
Diagnostics.Add(UnsafeStatement, node);
|
||||
|
||||
return base.VisitUnsafeStatement(node);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using ComputeSharp.SourceGenerators.Diagnostics;
|
||||
using ComputeSharp.SourceGenerators.Extensions;
|
||||
using ComputeSharp.SourceGenerators.Helpers;
|
||||
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 HlslSourceRewriter2 : CSharpSyntaxRewriter
|
||||
{
|
||||
/// <summary>
|
||||
/// The <see cref="SemanticModelProvider"/> instance with semantic info on the target syntax tree.
|
||||
/// </summary>
|
||||
protected readonly SemanticModelProvider 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 collection of produced <see cref="Diagnostic"/> instances.
|
||||
/// </summary>
|
||||
protected readonly ImmutableArray<Diagnostic>.Builder Diagnostics;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="HlslSourceRewriter2"/> 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="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
|
||||
protected HlslSourceRewriter2(
|
||||
SemanticModelProvider semanticModel,
|
||||
ICollection<INamedTypeSymbol> discoveredTypes,
|
||||
IDictionary<IFieldSymbol, string> constantDefinitions,
|
||||
ImmutableArray<Diagnostic>.Builder diagnostics)
|
||||
{
|
||||
SemanticModel = semanticModel;
|
||||
DiscoveredTypes = discoveredTypes;
|
||||
ConstantDefinitions = constantDefinitions;
|
||||
Diagnostics = diagnostics;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether or not the shader uses a texture sampler at least once.
|
||||
/// </summary>
|
||||
public bool IsSamplerUsed { get; private set; }
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode VisitCastExpression(CastExpressionSyntax node)
|
||||
{
|
||||
var updatedNode = (CastExpressionSyntax)base.VisitCastExpression(node)!;
|
||||
|
||||
return updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitVariableDeclaration(VariableDeclarationSyntax node)
|
||||
{
|
||||
var updatedNode = (VariableDeclarationSyntax)base.VisitVariableDeclaration(node)!;
|
||||
|
||||
if (SemanticModel.For(node).GetTypeInfo(node.Type).Type is ITypeSymbol { IsUnmanagedType: false } type)
|
||||
{
|
||||
Diagnostics.Add(InvalidObjectDeclaration, node, type);
|
||||
}
|
||||
|
||||
// If var is used, replace it with the explicit type
|
||||
if (updatedNode.Type is IdentifierNameSyntax { IsVar: true })
|
||||
{
|
||||
updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes);
|
||||
}
|
||||
|
||||
return updatedNode;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode VisitObjectCreationExpression(ObjectCreationExpressionSyntax node)
|
||||
{
|
||||
var updatedNode = (ObjectCreationExpressionSyntax)base.VisitObjectCreationExpression(node)!;
|
||||
|
||||
if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type)
|
||||
{
|
||||
Diagnostics.Add(InvalidObjectCreationExpression, node, type);
|
||||
}
|
||||
|
||||
updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node, SemanticModel.For(node), 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.For(node).GetTypeInfo(node).Type is ITypeSymbol matrixType &&
|
||||
HlslKnownTypes.IsMatrixType(matrixType.GetFullMetadataName()))
|
||||
{
|
||||
for (int i = 0; i < node.ArgumentList!.Arguments.Count; i++)
|
||||
{
|
||||
IArgumentOperation argumentOperation = (IArgumentOperation)SemanticModel.For(node).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.For(node).GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type)
|
||||
{
|
||||
Diagnostics.Add(InvalidObjectCreationExpression, node, type);
|
||||
}
|
||||
|
||||
TypeSyntax explicitType = IdentifierName("").ReplaceAndTrackType(node, SemanticModel.For(node), 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.For(node).GetTypeInfo(node).Type is ITypeSymbol matrixType &&
|
||||
HlslKnownTypes.IsMatrixType(matrixType.GetFullMetadataName()))
|
||||
{
|
||||
for (int i = 0; i < node.ArgumentList.Arguments.Count; i++)
|
||||
{
|
||||
IArgumentOperation argumentOperation = (IArgumentOperation)SemanticModel.For(node).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.For(node), 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.For(node), 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.For(node).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 the numeric literal is neither a decimal nor an exponential, add the ".0" suffix
|
||||
if (literal.IndexOfAny(new[] { '.', 'E' }) == -1)
|
||||
{
|
||||
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))
|
||||
{
|
||||
Diagnostics.Add(StringLiteralExpression, node);
|
||||
}
|
||||
|
||||
return updatedNode;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitElementAccessExpression(ElementAccessExpressionSyntax node)
|
||||
{
|
||||
var updatedNode = (ElementAccessExpressionSyntax)base.VisitElementAccessExpression(node)!;
|
||||
|
||||
if (SemanticModel.For(node).GetOperation(node) is IPropertyReferenceOperation operation)
|
||||
{
|
||||
string propertyName = operation.Property.GetFullMetadataName();
|
||||
|
||||
// Rewrite texture resource indices taking individual indices a vector argument, as per HLSL spec.
|
||||
// For instance: texture[ThreadIds.X, ThreadIds.Y] will be rewritten as texture[int2(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))));
|
||||
}
|
||||
|
||||
// Rewrite texture resource sampled accesses, if needed
|
||||
if (HlslKnownMembers.TryGetMappedResourceSamplerAccessType(propertyName, out mapping))
|
||||
{
|
||||
IsSamplerUsed = true;
|
||||
|
||||
// Get the syntax for the argument syntax transformation as described above
|
||||
ArgumentSyntax coordinateSyntax = mapping switch
|
||||
{
|
||||
not null => Argument(InvocationExpression(IdentifierName(mapping!), ArgumentList(updatedNode.ArgumentList.Arguments))),
|
||||
null => updatedNode.ArgumentList.Arguments[0]
|
||||
};
|
||||
|
||||
// Transform an indexer syntax into a sampling call with the implicit static linear sampler.
|
||||
// For instance: texture[uv] will be rewritten as texture.SampleLevel(__sampler, uv, 0).
|
||||
return
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
updatedNode.Expression,
|
||||
IdentifierName("SampleLevel")))
|
||||
.AddArgumentListArguments(
|
||||
Argument(IdentifierName("__sampler")),
|
||||
coordinateSyntax,
|
||||
Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))));
|
||||
}
|
||||
|
||||
// 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.For(node).GetOperation(argument.Expression) is not IFieldReferenceOperation fieldReference ||
|
||||
!HlslKnownMembers.IsKnownMatrixIndex(fieldReference.Field.GetFullMetadataName()))
|
||||
{
|
||||
Diagnostics.Add(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.For(node).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.For(node).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().ToHlslIdentifierName();
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,443 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using ComputeSharp.SourceGenerators.Diagnostics;
|
||||
using ComputeSharp.SourceGenerators.Extensions;
|
||||
using ComputeSharp.SourceGenerators.Helpers;
|
||||
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# methods to convert to HLSL compliant code.
|
||||
/// </summary>
|
||||
internal sealed class ShaderSourceRewriter2 : HlslSourceRewriter2
|
||||
{
|
||||
/// <summary>
|
||||
/// The type symbol for the shader type.
|
||||
/// </summary>
|
||||
private readonly INamedTypeSymbol? shaderType;
|
||||
|
||||
/// <summary>
|
||||
/// The collection of discovered static methods.
|
||||
/// </summary>
|
||||
private readonly IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods;
|
||||
|
||||
/// <summary>
|
||||
/// The collection of processed local functions in the current tree.
|
||||
/// </summary>
|
||||
private readonly Dictionary<string, LocalFunctionStatementSyntax> localFunctions;
|
||||
|
||||
/// <summary>
|
||||
/// The list of implicit variables to declare at the start of the body.
|
||||
/// </summary>
|
||||
private readonly List<VariableDeclarationSyntax> implicitVariables;
|
||||
|
||||
/// <summary>
|
||||
/// Whether or not the current instance is processing a shader entry point.
|
||||
/// </summary>
|
||||
private readonly bool isEntryPoint;
|
||||
|
||||
/// <summary>
|
||||
/// The current <see cref="MethodDeclarationSyntax"/> tree being visited.
|
||||
/// </summary>
|
||||
private MethodDeclarationSyntax? currentMethod;
|
||||
|
||||
/// <summary>
|
||||
/// The current depth inside local declarations.
|
||||
/// </summary>
|
||||
private int localFunctionDepth;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ShaderSourceRewriter2"/> instance with the specified parameters.
|
||||
/// </summary>
|
||||
/// <param name="shaderType">The type symbol for the shader type.</param>
|
||||
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the target syntax tree.</param>
|
||||
/// <param name="discoveredTypes">The set of discovered custom types.</param>
|
||||
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
|
||||
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
|
||||
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
|
||||
/// <param name="isEntryPoint">Whether or not the current instance is processing a shader entry point.</param>
|
||||
public ShaderSourceRewriter2(
|
||||
INamedTypeSymbol shaderType,
|
||||
SemanticModelProvider semanticModel,
|
||||
ICollection<INamedTypeSymbol> discoveredTypes,
|
||||
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
|
||||
IDictionary<IFieldSymbol, string> constantDefinitions,
|
||||
ImmutableArray<Diagnostic>.Builder diagnostics,
|
||||
bool isEntryPoint)
|
||||
: base(semanticModel, discoveredTypes, constantDefinitions, diagnostics)
|
||||
{
|
||||
this.shaderType = shaderType;
|
||||
this.staticMethods = staticMethods;
|
||||
this.localFunctions = new();
|
||||
this.implicitVariables = new();
|
||||
this.isEntryPoint = isEntryPoint;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ShaderSourceRewriter2"/> instance with the specified parameters.
|
||||
/// </summary>
|
||||
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the target syntax tree.</param>
|
||||
/// <param name="discoveredTypes">The set of discovered custom types.</param>
|
||||
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
|
||||
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
|
||||
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
|
||||
public ShaderSourceRewriter2(
|
||||
SemanticModelProvider semanticModel,
|
||||
ICollection<INamedTypeSymbol> discoveredTypes,
|
||||
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
|
||||
IDictionary<IFieldSymbol, string> constantDefinitions,
|
||||
ImmutableArray<Diagnostic>.Builder diagnostics)
|
||||
: base(semanticModel, discoveredTypes, constantDefinitions, diagnostics)
|
||||
{
|
||||
this.staticMethods = staticMethods;
|
||||
this.implicitVariables = new();
|
||||
this.localFunctions = new();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the collection of processed local functions in the current tree.
|
||||
/// </summary>
|
||||
public IReadOnlyDictionary<string, LocalFunctionStatementSyntax> LocalFunctions => this.localFunctions;
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether or not the shader uses <see cref="GroupIds"/> at least once (except <see cref="GroupIds.Index"/>).
|
||||
/// </summary>
|
||||
public bool IsGroupIdsUsed { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether or not the shader uses <see cref="GroupIds.Index"/> at least once.
|
||||
/// </summary>
|
||||
public bool IsGroupIdsIndexUsed { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether or not the shader uses <see cref="GridIds"/> at least once.
|
||||
/// </summary>
|
||||
public bool IsGridIdsUsed { get; set; }
|
||||
|
||||
/// <inheritdoc cref="CSharpSyntaxRewriter.Visit(SyntaxNode?)"/>
|
||||
public MethodDeclarationSyntax? Visit(MethodDeclarationSyntax? node)
|
||||
{
|
||||
this.currentMethod = node;
|
||||
|
||||
var updatedNode = (MethodDeclarationSyntax?)base.Visit(node)!;
|
||||
|
||||
updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel.For(node), DiscoveredTypes);
|
||||
|
||||
if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword)))
|
||||
{
|
||||
Diagnostics.Add(AsyncModifierOnMethodOrFunction, node);
|
||||
}
|
||||
|
||||
if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword)))
|
||||
{
|
||||
Diagnostics.Add(UnsafeModifierOnMethodOrFunction, node);
|
||||
}
|
||||
|
||||
if (updatedNode is not null)
|
||||
{
|
||||
var implicitBlock = Block(this.implicitVariables.Select(static v => LocalDeclarationStatement(v)).ToArray());
|
||||
|
||||
// Add the tracked implicit declarations (at the start of the body)
|
||||
updatedNode = updatedNode.WithBody(implicitBlock).AddBodyStatements(updatedNode.Body!.Statements.ToArray());
|
||||
}
|
||||
|
||||
return updatedNode;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode VisitParameter(ParameterSyntax node)
|
||||
{
|
||||
var updatedNode = (ParameterSyntax)base.VisitParameter(node)!;
|
||||
|
||||
// Convert the C# parameter modifiers to the HLSL equivalent
|
||||
SyntaxToken modifier =
|
||||
node.Modifiers
|
||||
.Where(static m => m.Kind() is SyntaxKind.OutKeyword or SyntaxKind.RefKeyword or SyntaxKind.InKeyword)
|
||||
.Select(static m => m.Kind() switch
|
||||
{
|
||||
SyntaxKind.OutKeyword => m,
|
||||
SyntaxKind.InKeyword => m,
|
||||
SyntaxKind.RefKeyword => ParseToken("inout"),
|
||||
_ => Token(SyntaxKind.None)
|
||||
}).FirstOrDefault();
|
||||
|
||||
return updatedNode
|
||||
.WithAttributeLists(default)
|
||||
.ReplaceAndTrackType(updatedNode.Type!, node.Type!, SemanticModel.For(node), DiscoveredTypes)
|
||||
.WithModifiers(TokenList(modifier));
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node)
|
||||
{
|
||||
var updatedNode = ((LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node)!);
|
||||
|
||||
if (SemanticModel.For(node).GetOperation(node) is IOperation { Kind: OperationKind.UsingDeclaration })
|
||||
{
|
||||
Diagnostics.Add(UsingStatementOrDeclaration, node);
|
||||
}
|
||||
|
||||
return updatedNode.ReplaceAndTrackType(updatedNode.Declaration.Type, node.Declaration.Type, SemanticModel.For(node), DiscoveredTypes);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitDeclarationExpression(DeclarationExpressionSyntax node)
|
||||
{
|
||||
var updatedNode = (DeclarationExpressionSyntax)base.VisitDeclarationExpression(node)!;
|
||||
|
||||
updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes);
|
||||
|
||||
// Add the variable to the list of implicit declarations
|
||||
this.implicitVariables.Add(VariableDeclaration(updatedNode.Type).AddVariables(VariableDeclarator(updatedNode.Designation.ToString())));
|
||||
|
||||
return IdentifierName(updatedNode.Designation.ToString());
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node)
|
||||
{
|
||||
return
|
||||
((MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!)
|
||||
.WithBlockBody()
|
||||
.WithoutAccessibilityModifiers()
|
||||
.WithAttributeLists(List<AttributeListSyntax>());
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitLocalFunctionStatement(LocalFunctionStatementSyntax node)
|
||||
{
|
||||
this.localFunctionDepth++;
|
||||
|
||||
var updatedNode =
|
||||
((LocalFunctionStatementSyntax)base.VisitLocalFunctionStatement(node)!)
|
||||
.WithBlockBody()
|
||||
.WithAttributeLists(List<AttributeListSyntax>())
|
||||
.WithIdentifier(Identifier($"__{this.currentMethod!.Identifier.Text}__{node.Identifier.Text}"));
|
||||
|
||||
updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel.For(node), DiscoveredTypes);
|
||||
|
||||
if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword)))
|
||||
{
|
||||
Diagnostics.Add(AsyncModifierOnMethodOrFunction, node);
|
||||
}
|
||||
|
||||
if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword)))
|
||||
{
|
||||
Diagnostics.Add(UnsafeModifierOnMethodOrFunction, node);
|
||||
}
|
||||
|
||||
this.localFunctionDepth--;
|
||||
|
||||
// HLSL doesn't support local functions, so we first process them as usual and then remove
|
||||
// them from the current syntax tree completely. These will be added to the shader source
|
||||
// as external static method with a special name to avoid conflicts with other methods.
|
||||
// The name will simply be in the format: "__<MethodName>__<FunctionName>".
|
||||
this.localFunctions.Add(updatedNode.Identifier.Text, updatedNode);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node)
|
||||
{
|
||||
var updatedNode = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node)!;
|
||||
|
||||
if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) &&
|
||||
SemanticModel.For(node).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)
|
||||
{
|
||||
ConstantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture);
|
||||
|
||||
var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName();
|
||||
var constantName = $"__{ownerTypeName}__{fieldOperation.Field.Name}";
|
||||
|
||||
return IdentifierName(constantName);
|
||||
}
|
||||
|
||||
// If the current member access is a field or property access, check the lookup table
|
||||
// to see if the member should be rewritten for HLSL compliance, and rewrite if needed.
|
||||
if (HlslKnownMembers.TryGetMappedName(operation.Member.ToDisplayString(), out string? mapping))
|
||||
{
|
||||
// Mark which dispatch properties have been used, to optimize the declaration afterwards
|
||||
if (operation.Member.IsStatic)
|
||||
{
|
||||
string typeName = operation.Member.ContainingType.GetFullMetadataName();
|
||||
|
||||
if (mapping == $"__{nameof(GroupIds)}__get_Index") IsGroupIdsIndexUsed = true;
|
||||
else if (typeName == typeof(GroupIds).FullName) IsGroupIdsUsed = true;
|
||||
else if (typeName == typeof(GridIds).FullName) IsGridIdsUsed = true;
|
||||
|
||||
// Check that the dispatch info types are only used from the main shader body
|
||||
if (!this.isEntryPoint || this.localFunctionDepth > 0)
|
||||
{
|
||||
DiagnosticDescriptor? descriptor = typeName switch
|
||||
{
|
||||
_ when typeName == typeof(ThreadIds).FullName || typeName == typeof(ThreadIds.Normalized).FullName => InvalidThreadIdsUsage,
|
||||
_ when typeName == typeof(GroupIds).FullName => InvalidGroupIdsUsage,
|
||||
_ when typeName == typeof(GroupSize).FullName => InvalidGroupSizeUsage,
|
||||
_ when typeName == typeof(GridIds).FullName => InvalidGridIdsUsage,
|
||||
_ when typeName == typeof(DispatchSize).FullName => InvalidDispatchSizeUsage,
|
||||
_ => null
|
||||
};
|
||||
|
||||
if (descriptor is not null)
|
||||
{
|
||||
Diagnostics.Add(descriptor, node);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Static and instance members are handled differently, with static members being
|
||||
// converted into a literal expression, and instance getting an updated identifier.
|
||||
// For instance, consider these three cases:
|
||||
// - Vector3.One (static) => float3(1.0f, 1.0f, 1.0f)
|
||||
// - ThreadIds.X (custom) => ThreadIds.x
|
||||
// - uint3.X (instance) => [arg].x
|
||||
return operation.Member.IsStatic switch
|
||||
{
|
||||
true => ParseExpression(mapping!),
|
||||
false => updatedNode.WithName(IdentifierName(mapping!))
|
||||
};
|
||||
}
|
||||
|
||||
// If the current member access is an access to any of the size properties in the available
|
||||
// resource types (either buffer or texture types), then rewrite the subtree to transform the
|
||||
// property access into an invocation of an autogenerated static helper method to get the target
|
||||
// dimension for the buffer in use. The helper method is added to the list of static helpers.
|
||||
if (operation is IPropertyReferenceOperation propertyOperation &&
|
||||
HlslKnownMembers.TryGetAccessorRankAndAxis(propertyOperation.Property.GetFullMetadataName(), out int rank, out int axis))
|
||||
{
|
||||
IMethodSymbol key = propertyOperation.Property.GetMethod!;
|
||||
|
||||
if (!this.staticMethods.TryGetValue(key, out MethodDeclarationSyntax? methodSyntax))
|
||||
{
|
||||
INamedTypeSymbol resourceType = (INamedTypeSymbol)SemanticModel.For(node).GetTypeInfo(node.Expression).Type!;
|
||||
string resourceName = HlslKnownTypes.GetMappedName(resourceType);
|
||||
|
||||
// Create a static method to get a specified dimension for a target resource type.
|
||||
// The method will automatically create the necessary number of temporary variables
|
||||
// depending on the rank of the input resource (eg. 2 for Texture2D<T> resources).
|
||||
// For instance, this code will generate the following tree for Texture2D<float>.Width:
|
||||
//
|
||||
// static int __get_Dimension0(Texture2D<float> texture)
|
||||
// {
|
||||
// uint _0, _1;
|
||||
// texture.GetDimensions(_0, _1);
|
||||
//
|
||||
// return _0;
|
||||
// }
|
||||
methodSyntax =
|
||||
MethodDeclaration(PredefinedType(Token(SyntaxKind.IntKeyword)), $"__get_Dimension{axis}")
|
||||
.AddModifiers(Token(SyntaxKind.StaticKeyword))
|
||||
.AddParameterListParameters(
|
||||
Parameter(Identifier("resource"))
|
||||
.WithType(IdentifierName(resourceName)))
|
||||
.WithBody(Block(
|
||||
LocalDeclarationStatement(
|
||||
VariableDeclaration(PredefinedType(Token(SyntaxKind.UIntKeyword)))
|
||||
.AddVariables(Enumerable.Range(0, rank).Select(static i => VariableDeclarator(Identifier("_" + i))).ToArray())),
|
||||
ExpressionStatement(
|
||||
InvocationExpression(MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("resource"),
|
||||
IdentifierName("GetDimensions")))
|
||||
.AddArgumentListArguments(Enumerable.Range(0, rank).Select(static i => Argument(IdentifierName("_" + i))).ToArray())),
|
||||
ReturnStatement(IdentifierName("_" + axis))));
|
||||
|
||||
this.staticMethods.Add(key, methodSyntax);
|
||||
}
|
||||
|
||||
return InvocationExpression(IdentifierName(methodSyntax.Identifier)).AddArgumentListArguments(Argument(updatedNode.Expression));
|
||||
}
|
||||
}
|
||||
|
||||
return updatedNode;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node)
|
||||
{
|
||||
var updatedNode = (InvocationExpressionSyntax)base.VisitInvocationExpression(node)!;
|
||||
|
||||
if (SemanticModel.For(node).GetOperation(node) is IInvocationOperation operation &&
|
||||
operation.TargetMethod is IMethodSymbol method &&
|
||||
method.IsStatic)
|
||||
{
|
||||
// If the invocation consists of invoking a static method that has a direct
|
||||
// mapping to HLSL, rewrite the expression in the current invocation node.
|
||||
// For instance: Math.Abs(expr) => abs(expr).
|
||||
if (HlslKnownMethods.TryGetMappedName(method.GetFullMetadataName(), out string? mapping))
|
||||
{
|
||||
return updatedNode.WithExpression(ParseExpression(mapping!));
|
||||
}
|
||||
|
||||
// Update the name if the target is a local function. The exact schema for the
|
||||
// updated name is detailed in the override handling the local function statement.
|
||||
if (method.MethodKind == MethodKind.LocalFunction)
|
||||
{
|
||||
var functionIdentifier = $"__{this.currentMethod!.Identifier.Text}__{method.Name}";
|
||||
|
||||
return updatedNode.WithExpression(ParseExpression(functionIdentifier));
|
||||
}
|
||||
|
||||
// If the method is an external static method, import and rewrite it as well.
|
||||
// This assumes that the target method is actually part of the same compilation.
|
||||
// We need to check the declaring type to avoid rewriting static methods in the shader
|
||||
// type as well, as they will be processed by the generator in a different path.
|
||||
if (!SymbolEqualityComparer.Default.Equals(this.shaderType, method.ContainingType))
|
||||
{
|
||||
var methodIdentifier = method.GetFullMetadataName().ToHlslIdentifierName();
|
||||
|
||||
if (!this.staticMethods.ContainsKey(method))
|
||||
{
|
||||
ShaderSourceRewriter2 ShaderSourceRewriter2 = new(SemanticModel, DiscoveredTypes, this.staticMethods, ConstantDefinitions, Diagnostics);
|
||||
MethodDeclarationSyntax methodNode = (MethodDeclarationSyntax)method.DeclaringSyntaxReferences[0].GetSyntax();
|
||||
MethodDeclarationSyntax processedMethod = ShaderSourceRewriter2.Visit(methodNode)!.NormalizeWhitespace(eol: "\n").WithoutTrivia();
|
||||
|
||||
this.staticMethods.Add(method, processedMethod.WithIdentifier(Identifier(methodIdentifier)));
|
||||
}
|
||||
|
||||
return updatedNode.WithExpression(ParseExpression(methodIdentifier));
|
||||
}
|
||||
}
|
||||
|
||||
return updatedNode;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitArgument(ArgumentSyntax node)
|
||||
{
|
||||
var updatedNode = (ArgumentSyntax)base.VisitArgument(node)!;
|
||||
|
||||
// Strip the ref keywords from arguments
|
||||
updatedNode = updatedNode.WithRefKindKeyword(Token(SyntaxKind.None));
|
||||
|
||||
// Track and rewrite the discarded declaration
|
||||
if (SemanticModel.For(node).GetOperation(node.Expression) is IDiscardOperation operation)
|
||||
{
|
||||
TypeSyntax typeSyntax = operation.Type!.TrackType(DiscoveredTypes);
|
||||
string identifier = $"__implicit{this.implicitVariables.Count}";
|
||||
|
||||
// Add the variable to the list of implicit declarations
|
||||
this.implicitVariables.Add(VariableDeclaration(typeSyntax).AddVariables(VariableDeclarator(identifier)));
|
||||
|
||||
return updatedNode.WithExpression(IdentifierName(identifier));
|
||||
}
|
||||
|
||||
return updatedNode;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Globalization;
|
||||
using ComputeSharp.SourceGenerators.Diagnostics;
|
||||
using ComputeSharp.SourceGenerators.Extensions;
|
||||
using ComputeSharp.SourceGenerators.Helpers;
|
||||
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 field to convert to HLSL static fields (possibly constant).
|
||||
/// </summary>
|
||||
internal sealed class StaticFieldRewriter2 : HlslSourceRewriter2
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="StaticFieldRewriter2"/> instance with the specified parameters.
|
||||
/// </summary>
|
||||
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the target syntax tree.</param>
|
||||
/// <param name="discoveredTypes">The set of discovered custom types.</param>
|
||||
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
|
||||
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
|
||||
public StaticFieldRewriter2(
|
||||
SemanticModelProvider semanticModel,
|
||||
ICollection<INamedTypeSymbol> discoveredTypes,
|
||||
IDictionary<IFieldSymbol, string> constantDefinitions,
|
||||
ImmutableArray<Diagnostic>.Builder diagnostics)
|
||||
: base(semanticModel, discoveredTypes, constantDefinitions, diagnostics)
|
||||
{
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="CSharpSyntaxRewriter.Visit(SyntaxNode?)"/>
|
||||
public ExpressionSyntax? Visit(VariableDeclaratorSyntax? node)
|
||||
{
|
||||
if (node?.Initializer is EqualsValueClauseSyntax fieldInitializer)
|
||||
{
|
||||
return ((EqualsValueClauseSyntax)Visit(fieldInitializer))!.Value;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node)
|
||||
{
|
||||
var updatedNode = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node)!;
|
||||
|
||||
if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) &&
|
||||
SemanticModel.For(node).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().ToHlslIdentifierName();
|
||||
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 || typeName == typeof(ThreadIds.Normalized).FullName => InvalidThreadIdsUsage,
|
||||
_ when typeName == typeof(GroupIds).FullName => InvalidGroupIdsUsage,
|
||||
_ when typeName == typeof(GroupSize).FullName => InvalidGroupSizeUsage,
|
||||
_ when typeName == typeof(GridIds).FullName => InvalidGridIdsUsage,
|
||||
_ when typeName == typeof(DispatchSize).FullName => InvalidDispatchSizeUsage,
|
||||
_ => null
|
||||
};
|
||||
|
||||
if (descriptor is not null)
|
||||
{
|
||||
Diagnostics.Add(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.For(node).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;
|
||||
}
|
||||
}
|
||||
新しいイシューから参照
ユーザーをブロックする