Refactored code to use file scoped using declarations

このコミットが含まれているのは:
Sergio Pedri committed 2021-10-30 15:11:43 +02:00
1 親 52ec5a79b0
コミット d5e3114f7c
275ファイル変更
+91970 -92271

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

+38 -40
ファイルの表示
@@ -4,53 +4,51 @@ using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace ComputeSharp.SourceGenerators
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
public sealed partial class AutoConstructorGenerator
{
/// <inheritdoc/>
public sealed partial class AutoConstructorGenerator
/// <summary>
/// An <see cref="ISyntaxContextReceiver"/> that selects candidate nodes to process.
/// </summary>
private sealed class SyntaxReceiver : ISyntaxContextReceiver
{
/// <summary>
/// An <see cref="ISyntaxContextReceiver"/> that selects candidate nodes to process.
/// The list of info gathered during exploration.
/// </summary>
private sealed class SyntaxReceiver : ISyntaxContextReceiver
private readonly List<Item> gatheredInfo = new();
/// <summary>
/// Gets the collection of gathered info to process.
/// </summary>
public IReadOnlyCollection<Item> GatheredInfo => this.gatheredInfo;
/// <inheritdoc/>
public void OnVisitSyntaxNode(GeneratorSyntaxContext context)
{
/// <summary>
/// The list of info gathered during exploration.
/// </summary>
private readonly List<Item> gatheredInfo = new();
/// <summary>
/// Gets the collection of gathered info to process.
/// </summary>
public IReadOnlyCollection<Item> GatheredInfo => this.gatheredInfo;
/// <inheritdoc/>
public void OnVisitSyntaxNode(GeneratorSyntaxContext context)
if (context.Node is StructDeclarationSyntax { AttributeLists: { Count: > 0 } } structDeclaration &&
context.SemanticModel.GetDeclaredSymbol(structDeclaration) is INamedTypeSymbol structSymbol &&
context.SemanticModel.Compilation.GetTypeByMetadataName(typeof(AutoConstructorAttribute).FullName) is INamedTypeSymbol attributeSymbol &&
structSymbol.GetAttributes().FirstOrDefault(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, attributeSymbol)) is AttributeData attributeData &&
attributeData.ApplicationSyntaxReference is SyntaxReference syntaxReference &&
syntaxReference.GetSyntax() is AttributeSyntax attributeSyntax)
{
if (context.Node is StructDeclarationSyntax { AttributeLists: { Count: > 0 } } structDeclaration &&
context.SemanticModel.GetDeclaredSymbol(structDeclaration) is INamedTypeSymbol structSymbol &&
context.SemanticModel.Compilation.GetTypeByMetadataName(typeof(AutoConstructorAttribute).FullName) is INamedTypeSymbol attributeSymbol &&
structSymbol.GetAttributes().FirstOrDefault(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, attributeSymbol)) is AttributeData attributeData &&
attributeData.ApplicationSyntaxReference is SyntaxReference syntaxReference &&
syntaxReference.GetSyntax() is AttributeSyntax attributeSyntax)
{
this.gatheredInfo.Add(new Item(structDeclaration, structSymbol, attributeSyntax, attributeData));
}
this.gatheredInfo.Add(new Item(structDeclaration, structSymbol, attributeSyntax, attributeData));
}
/// <summary>
/// A model for a group of item representing a discovered type to process.
/// </summary>
/// <param name="StructDeclaration">The <see cref="StructDeclarationSyntax"/> instance for the target struct declaration.</param>
/// <param name="StructSymbol">The <see cref="INamedTypeSymbol"/> instance for <paramref name="StructDeclaration"/>.</param>
/// <param name="AttributeSyntax">The <see cref="AttributeSyntax"/> instance for the target attribute over <paramref name="StructDeclaration"/>.</param>
/// <param name="AttributeData">The <see cref="AttributeData"/> instance for <paramref name="AttributeSyntax"/>.</param>
public sealed record Item(
StructDeclarationSyntax StructDeclaration,
INamedTypeSymbol StructSymbol,
AttributeSyntax AttributeSyntax,
AttributeData AttributeData);
}
/// <summary>
/// A model for a group of item representing a discovered type to process.
/// </summary>
/// <param name="StructDeclaration">The <see cref="StructDeclarationSyntax"/> instance for the target struct declaration.</param>
/// <param name="StructSymbol">The <see cref="INamedTypeSymbol"/> instance for <paramref name="StructDeclaration"/>.</param>
/// <param name="AttributeSyntax">The <see cref="AttributeSyntax"/> instance for the target attribute over <paramref name="StructDeclaration"/>.</param>
/// <param name="AttributeData">The <see cref="AttributeData"/> instance for <paramref name="AttributeSyntax"/>.</param>
public sealed record Item(
StructDeclarationSyntax StructDeclaration,
INamedTypeSymbol StructSymbol,
AttributeSyntax AttributeSyntax,
AttributeData AttributeData);
}
}
+84 -86
ファイルの表示
@@ -11,102 +11,100 @@ using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle;
namespace ComputeSharp.SourceGenerators
namespace ComputeSharp.SourceGenerators;
/// <summary>
/// A source generator creating constructors for types annotated with <see cref="AutoConstructorAttribute"/>.
/// </summary>
[Generator]
public sealed partial class AutoConstructorGenerator : ISourceGenerator
{
/// <summary>
/// A source generator creating constructors for types annotated with <see cref="AutoConstructorAttribute"/>.
/// </summary>
[Generator]
public sealed partial class AutoConstructorGenerator : ISourceGenerator
/// <inheritdoc/>
public void Initialize(GeneratorInitializationContext context)
{
/// <inheritdoc/>
public void Initialize(GeneratorInitializationContext context)
context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver());
}
/// <inheritdoc/>
public void Execute(GeneratorExecutionContext context)
{
// Get the syntax receiver with the candidate nodes
if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver)
{
context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver());
return;
}
/// <inheritdoc/>
public void Execute(GeneratorExecutionContext context)
foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo)
{
// Get the syntax receiver with the candidate nodes
if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver)
try
{
return;
OnExecute(context, item.StructDeclaration, item.StructSymbol);
}
foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo)
catch
{
try
{
OnExecute(context, item.StructDeclaration, item.StructSymbol);
}
catch
{
context.ReportDiagnostic(AutoConstructorGeneratorError, item.AttributeSyntax, item.StructSymbol);
}
context.ReportDiagnostic(AutoConstructorGeneratorError, item.AttributeSyntax, item.StructSymbol);
}
}
/// <summary>
/// Processes a given target type.
/// </summary>
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to 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>
private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol)
{
// Extract the info on the type to process
var namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces));
var structName = structDeclaration.Identifier.Text;
var structModifiers = structDeclaration.Modifiers;
var fields = (
from fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>()
where !fieldSymbol.IsConst && !fieldSymbol.IsStatic && !fieldSymbol.IsFixedSizeBuffer
let typeName = fieldSymbol.Type!.ToDisplayString()
let fieldFullType = ParseTypeName(typeName)
select (Type: fieldFullType, Identifier: Identifier(fieldSymbol.Name))).ToImmutableArray();
// Create the constructor declaration for the type. This will
// produce a constructor with simple initialization of all variables:
//
// public MyType(Foo a, Bar b, Baz c, ...)
// {
// this.a = a;
// this.b = b;
// this.c = c;
// ...
// }
var structDeclarationSyntax =
StructDeclaration(structName).WithModifiers(structModifiers).AddMembers(
ConstructorDeclaration(structName)
.AddModifiers(Token(SyntaxKind.PublicKeyword))
.AddParameterListParameters(fields.Select(field => Parameter(field.Identifier).WithType(field.Type)).ToArray())
.AddBodyStatements(fields.Select(field => ParseStatement($"this.{field.Identifier} = {field.Identifier};")).ToArray()));
TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax;
// Add all parent types in ascending order, if any
foreach (var parentType in structDeclaration.Ancestors().OfType<TypeDeclarationSyntax>())
{
typeDeclarationSyntax = parentType
.WithMembers(SingletonList<MemberDeclarationSyntax>(typeDeclarationSyntax))
.WithConstraintClauses(List<TypeParameterConstraintClauseSyntax>())
.WithBaseList(null)
.WithAttributeLists(List<AttributeListSyntax>())
.WithoutTrivia();
}
// Create the compilation unit with the namespace and target member.
// From this, we can finally generate the source code to output.
var source =
CompilationUnit().AddMembers(
NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax))
.NormalizeWhitespace(eol: "\n")
.ToFullString();
// Add the partial type
context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8));
}
}
}
/// <summary>
/// Processes a given target type.
/// </summary>
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to 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>
private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol)
{
// Extract the info on the type to process
var namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces));
var structName = structDeclaration.Identifier.Text;
var structModifiers = structDeclaration.Modifiers;
var fields = (
from fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>()
where !fieldSymbol.IsConst && !fieldSymbol.IsStatic && !fieldSymbol.IsFixedSizeBuffer
let typeName = fieldSymbol.Type!.ToDisplayString()
let fieldFullType = ParseTypeName(typeName)
select (Type: fieldFullType, Identifier: Identifier(fieldSymbol.Name))).ToImmutableArray();
// Create the constructor declaration for the type. This will
// produce a constructor with simple initialization of all variables:
//
// public MyType(Foo a, Bar b, Baz c, ...)
// {
// this.a = a;
// this.b = b;
// this.c = c;
// ...
// }
var structDeclarationSyntax =
StructDeclaration(structName).WithModifiers(structModifiers).AddMembers(
ConstructorDeclaration(structName)
.AddModifiers(Token(SyntaxKind.PublicKeyword))
.AddParameterListParameters(fields.Select(field => Parameter(field.Identifier).WithType(field.Type)).ToArray())
.AddBodyStatements(fields.Select(field => ParseStatement($"this.{field.Identifier} = {field.Identifier};")).ToArray()));
TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax;
// Add all parent types in ascending order, if any
foreach (var parentType in structDeclaration.Ancestors().OfType<TypeDeclarationSyntax>())
{
typeDeclarationSyntax = parentType
.WithMembers(SingletonList<MemberDeclarationSyntax>(typeDeclarationSyntax))
.WithConstraintClauses(List<TypeParameterConstraintClauseSyntax>())
.WithBaseList(null)
.WithAttributeLists(List<AttributeListSyntax>())
.WithoutTrivia();
}
// Create the compilation unit with the namespace and target member.
// From this, we can finally generate the source code to output.
var source =
CompilationUnit().AddMembers(
NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax))
.NormalizeWhitespace(eol: "\n")
.ToFullString();
// Add the partial type
context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8));
}
}
+8 -9
ファイルの表示
@@ -1,14 +1,13 @@
using System;
using System.ComponentModel;
namespace ComputeSharp.__Internals
namespace ComputeSharp.__Internals;
/// <summary>
/// A base <see langword="interface"/> representing a given shader that can be dispatched.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This interface is not intended to be used directly by user code")]
public interface IShader
{
/// <summary>
/// A base <see langword="interface"/> representing a given shader that can be dispatched.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This interface is not intended to be used directly by user code")]
public interface IShader
{
}
}
ファイル差分が大きすぎるため表示されません。 差分を読み込み
+32 -33
ファイルの表示
@@ -1,43 +1,42 @@
using System.Linq;
using Microsoft.CodeAnalysis;
namespace ComputeSharp.SourceGenerators.Diagnostics
namespace ComputeSharp.SourceGenerators.Diagnostics;
/// <summary>
/// Extension methods for <see cref="GeneratorExecutionContext"/>, specifically for reporting diagnostics.
/// </summary>
internal static class DiagnosticsExtensions
{
/// <summary>
/// Extension methods for <see cref="GeneratorExecutionContext"/>, specifically for reporting diagnostics.
/// Adds a new diagnostics to the current compilation.
/// </summary>
internal static class DiagnosticsExtensions
/// <param name="context">The <see cref="GeneratorEditContext"/> instance currently in use.</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 ReportDiagnostic(
this GeneratorExecutionContext context,
DiagnosticDescriptor descriptor,
ISymbol symbol,
params object[] args)
{
/// <summary>
/// Adds a new diagnostics to the current compilation.
/// </summary>
/// <param name="context">The <see cref="GeneratorEditContext"/> instance currently in use.</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 ReportDiagnostic(
this GeneratorExecutionContext context,
DiagnosticDescriptor descriptor,
ISymbol symbol,
params object[] args)
{
context.ReportDiagnostic(Diagnostic.Create(descriptor, symbol.Locations.FirstOrDefault(), args));
}
context.ReportDiagnostic(Diagnostic.Create(descriptor, symbol.Locations.FirstOrDefault(), args));
}
/// <summary>
/// Adds a new diagnostics to the current compilation.
/// </summary>
/// <param name="context">The <see cref="GeneratorEditContext"/> instance currently in use.</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 ReportDiagnostic(
this GeneratorExecutionContext context,
DiagnosticDescriptor descriptor,
SyntaxNode node,
params object[] args)
{
context.ReportDiagnostic(Diagnostic.Create(descriptor, node.GetLocation(), args));
}
/// <summary>
/// Adds a new diagnostics to the current compilation.
/// </summary>
/// <param name="context">The <see cref="GeneratorEditContext"/> instance currently in use.</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 ReportDiagnostic(
this GeneratorExecutionContext context,
DiagnosticDescriptor descriptor,
SyntaxNode node,
params object[] args)
{
context.ReportDiagnostic(Diagnostic.Create(descriptor, node.GetLocation(), args));
}
}
+1 -1
ファイルの表示
@@ -92,4 +92,4 @@ global using uint3x4 = global::ComputeSharp.UInt3x4;
global using uint4x1 = global::ComputeSharp.UInt4x1;
global using uint4x2 = global::ComputeSharp.UInt4x2;
global using uint4x3 = global::ComputeSharp.UInt4x3;
global using uint4x4 = global::ComputeSharp.UInt4x4;
global using uint4x4 = global::ComputeSharp.UInt4x4;
+120 -121
ファイルの表示
@@ -7,145 +7,144 @@ using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.SourceGenerators.Extensions
namespace ComputeSharp.SourceGenerators.Extensions;
/// <summary>
/// Extension methods for <see cref="ISymbol"/> types.
/// </summary>
internal static class ISymbolExtensions
{
/// <summary>
/// Extension methods for <see cref="ISymbol"/> types.
/// A custom <see cref="SymbolDisplayFormat"/> instance with fully qualified style, without global::.
/// </summary>
internal static class ISymbolExtensions
public static readonly SymbolDisplayFormat FullyQualifiedWithoutGlobalFormat = new(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters);
/// <summary>
/// A custom <see cref="SymbolDisplayFormat"/> instance with fully qualified style, without global:: and parameters.
/// </summary>
private static readonly SymbolDisplayFormat FullyQualifiedWithoutGlobalAndParametersFormat =
FullyQualifiedWithoutGlobalFormat
.WithMemberOptions(SymbolDisplayMemberOptions.IncludeContainingType)
.WithParameterOptions(SymbolDisplayParameterOptions.None);
/// <summary>
/// Gets the full metadata name for a given <see cref="ITypeSymbol"/> instance.
/// </summary>
/// <param name="symbol">The input <see cref="ITypeSymbol"/> instance.</param>
/// <returns>The full metadata name for <paramref name="symbol"/>.</returns>
[Pure]
public static string GetFullMetadataName(this ITypeSymbol symbol)
{
/// <summary>
/// A custom <see cref="SymbolDisplayFormat"/> instance with fully qualified style, without global::.
/// </summary>
public static readonly SymbolDisplayFormat FullyQualifiedWithoutGlobalFormat = new(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters);
/// <summary>
/// A custom <see cref="SymbolDisplayFormat"/> instance with fully qualified style, without global:: and parameters.
/// </summary>
private static readonly SymbolDisplayFormat FullyQualifiedWithoutGlobalAndParametersFormat =
FullyQualifiedWithoutGlobalFormat
.WithMemberOptions(SymbolDisplayMemberOptions.IncludeContainingType)
.WithParameterOptions(SymbolDisplayParameterOptions.None);
/// <summary>
/// Gets the full metadata name for a given <see cref="ITypeSymbol"/> instance.
/// </summary>
/// <param name="symbol">The input <see cref="ITypeSymbol"/> instance.</param>
/// <returns>The full metadata name for <paramref name="symbol"/>.</returns>
[Pure]
public static string GetFullMetadataName(this ITypeSymbol symbol)
static StringBuilder BuildFrom(ISymbol? symbol, StringBuilder builder)
{
static StringBuilder BuildFrom(ISymbol? symbol, StringBuilder builder)
return symbol switch
{
return symbol switch
{
INamespaceSymbol ns when ns.IsGlobalNamespace => builder,
INamespaceSymbol ns when ns.ContainingNamespace is { IsGlobalNamespace: false }
=> BuildFrom(ns.ContainingNamespace, builder.Insert(0, $".{ns.MetadataName}")),
ITypeSymbol ts when ts.ContainingType is ISymbol pt => BuildFrom(pt, builder.Insert(0, $"+{ts.MetadataName}")),
ITypeSymbol ts when ts.ContainingNamespace is ISymbol pn => BuildFrom(pn, builder.Insert(0, $".{ts.MetadataName}")),
ISymbol => BuildFrom(symbol.ContainingSymbol, builder.Insert(0, symbol.MetadataName)),
_ => builder
};
}
return BuildFrom(symbol, new StringBuilder(256)).ToString();
INamespaceSymbol ns when ns.IsGlobalNamespace => builder,
INamespaceSymbol ns when ns.ContainingNamespace is { IsGlobalNamespace: false }
=> BuildFrom(ns.ContainingNamespace, builder.Insert(0, $".{ns.MetadataName}")),
ITypeSymbol ts when ts.ContainingType is ISymbol pt => BuildFrom(pt, builder.Insert(0, $"+{ts.MetadataName}")),
ITypeSymbol ts when ts.ContainingNamespace is ISymbol pn => BuildFrom(pn, builder.Insert(0, $".{ts.MetadataName}")),
ISymbol => BuildFrom(symbol.ContainingSymbol, builder.Insert(0, symbol.MetadataName)),
_ => builder
};
}
/// <summary>
/// Gets the full metadata name for a given <see cref="IMethodSymbol"/> instance.
/// </summary>
/// <param name="symbol">The input <see cref="IMethodSymbol"/> instance.</param>
/// <param name="includeParameters">Whether or not to also include parameter types.</param>
/// <returns>The full metadata name for <paramref name="symbol"/>.</returns>
[Pure]
public static string GetFullMetadataName(this IMethodSymbol symbol, bool includeParameters = false)
return BuildFrom(symbol, new StringBuilder(256)).ToString();
}
/// <summary>
/// Gets the full metadata name for a given <see cref="IMethodSymbol"/> instance.
/// </summary>
/// <param name="symbol">The input <see cref="IMethodSymbol"/> instance.</param>
/// <param name="includeParameters">Whether or not to also include parameter types.</param>
/// <returns>The full metadata name for <paramref name="symbol"/>.</returns>
[Pure]
public static string GetFullMetadataName(this IMethodSymbol symbol, bool includeParameters = false)
{
if (includeParameters)
{
if (includeParameters)
{
var parameters = string.Join(", ", symbol.Parameters.Select(static p => ((INamedTypeSymbol)p.Type).GetFullMetadataName()));
var parameters = string.Join(", ", symbol.Parameters.Select(static p => ((INamedTypeSymbol)p.Type).GetFullMetadataName()));
return $"{symbol.ToDisplayString(FullyQualifiedWithoutGlobalAndParametersFormat)}({parameters})";
}
return symbol.ToDisplayString(FullyQualifiedWithoutGlobalAndParametersFormat);
return $"{symbol.ToDisplayString(FullyQualifiedWithoutGlobalAndParametersFormat)}({parameters})";
}
/// <summary>
/// Gets the full metadata name for a given <see cref="IPropertySymbol"/> instance.
/// </summary>
/// <param name="symbol">The input <see cref="IPropertySymbol"/> instance.</param>
/// <returns>The full metadata name for <paramref name="symbol"/>.</returns>
[Pure]
public static string GetFullMetadataName(this IPropertySymbol symbol)
return symbol.ToDisplayString(FullyQualifiedWithoutGlobalAndParametersFormat);
}
/// <summary>
/// Gets the full metadata name for a given <see cref="IPropertySymbol"/> instance.
/// </summary>
/// <param name="symbol">The input <see cref="IPropertySymbol"/> instance.</param>
/// <returns>The full metadata name for <paramref name="symbol"/>.</returns>
[Pure]
public static string GetFullMetadataName(this IPropertySymbol symbol)
{
string declaringTypeName = symbol.ContainingType.GetFullMetadataName();
if (symbol.IsIndexer)
{
string declaringTypeName = symbol.ContainingType.GetFullMetadataName();
var parameters = string.Join(", ", symbol.Parameters.Select(static p => ((INamedTypeSymbol)p.Type).GetFullMetadataName()));
if (symbol.IsIndexer)
{
var parameters = string.Join(", ", symbol.Parameters.Select(static p => ((INamedTypeSymbol)p.Type).GetFullMetadataName()));
return $"{declaringTypeName}.this[{parameters}]";
}
return $"{declaringTypeName}.{symbol.Name}";
return $"{declaringTypeName}.this[{parameters}]";
}
/// <summary>
/// Gets the full metadata name for a given <see cref="IFieldSymbol"/> instance.
/// </summary>
/// <param name="symbol">The input <see cref="IFieldSymbol"/> instance.</param>
/// <returns>The full metadata name for <paramref name="symbol"/>.</returns>
[Pure]
public static string GetFullMetadataName(this IFieldSymbol symbol)
return $"{declaringTypeName}.{symbol.Name}";
}
/// <summary>
/// Gets the full metadata name for a given <see cref="IFieldSymbol"/> instance.
/// </summary>
/// <param name="symbol">The input <see cref="IFieldSymbol"/> instance.</param>
/// <returns>The full metadata name for <paramref name="symbol"/>.</returns>
[Pure]
public static string GetFullMetadataName(this IFieldSymbol symbol)
{
return $"{symbol.ContainingType.GetFullMetadataName()}.{symbol.Name}";
}
/// <summary>
/// Gets a valid filename for a target symbol and generator type.
/// </summary>
/// <param name="symbol">The symbol being processed.</param>
/// <returns>A filename in the form "&lt;SYMBOL_FULLNAME&gt;"</returns>
[Pure]
public static string GetGeneratedFileName(this INamedTypeSymbol symbol)
{
return symbol.GetFullMetadataName().Replace('`', '-').Replace('+', '.');
}
/// <summary>
/// Gets a valid filename for a target symbol and generator type.
/// </summary>
/// <param name="symbol">The symbol being processed.</param>
/// <returns>A filename in the form "&lt;SYMBOL_FULLNAME&gt;"</returns>
[Pure]
public static string GetGeneratedFileName(this IMethodSymbol symbol)
{
return symbol.GetFullMetadataName(true).Replace('`', '-').Replace('+', '.');
}
/// <summary>
/// Tracks an <see cref="ITypeSymbol"/> instance and returns an HLSL compatible <see cref="TypeSyntax"/> object.
/// </summary>
/// <param name="typeSymbol">The input <see cref="ITypeSymbol"/> instance to process.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <returns>A <see cref="SyntaxNode"/> instance that represents a type compatible with HLSL.</returns>
[Pure]
public static TypeSyntax TrackType(this ITypeSymbol typeSymbol, ICollection<INamedTypeSymbol> discoveredTypes)
{
string typeName = typeSymbol.ToDisplayString(FullyQualifiedWithoutGlobalFormat);
discoveredTypes.Add((INamedTypeSymbol)typeSymbol);
if (HlslKnownTypes.TryGetMappedName(typeName, out string? mappedName))
{
return $"{symbol.ContainingType.GetFullMetadataName()}.{symbol.Name}";
return ParseTypeName(mappedName!);
}
/// <summary>
/// Gets a valid filename for a target symbol and generator type.
/// </summary>
/// <param name="symbol">The symbol being processed.</param>
/// <returns>A filename in the form "&lt;SYMBOL_FULLNAME&gt;"</returns>
[Pure]
public static string GetGeneratedFileName(this INamedTypeSymbol symbol)
{
return symbol.GetFullMetadataName().Replace('`', '-').Replace('+', '.');
}
/// <summary>
/// Gets a valid filename for a target symbol and generator type.
/// </summary>
/// <param name="symbol">The symbol being processed.</param>
/// <returns>A filename in the form "&lt;SYMBOL_FULLNAME&gt;"</returns>
[Pure]
public static string GetGeneratedFileName(this IMethodSymbol symbol)
{
return symbol.GetFullMetadataName(true).Replace('`', '-').Replace('+', '.');
}
/// <summary>
/// Tracks an <see cref="ITypeSymbol"/> instance and returns an HLSL compatible <see cref="TypeSyntax"/> object.
/// </summary>
/// <param name="typeSymbol">The input <see cref="ITypeSymbol"/> instance to process.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <returns>A <see cref="SyntaxNode"/> instance that represents a type compatible with HLSL.</returns>
[Pure]
public static TypeSyntax TrackType(this ITypeSymbol typeSymbol, ICollection<INamedTypeSymbol> discoveredTypes)
{
string typeName = typeSymbol.ToDisplayString(FullyQualifiedWithoutGlobalFormat);
discoveredTypes.Add((INamedTypeSymbol)typeSymbol);
if (HlslKnownTypes.TryGetMappedName(typeName, out string? mappedName))
{
return ParseTypeName(mappedName!);
}
return ParseTypeName(typeName.ToHlslIdentifierName());
}
return ParseTypeName(typeName.ToHlslIdentifierName());
}
}
+12 -13
ファイルの表示
@@ -1,21 +1,20 @@
using System.Diagnostics.Contracts;
namespace ComputeSharp.SourceGenerators.Extensions
namespace ComputeSharp.SourceGenerators.Extensions;
/// <summary>
/// Extension methods for <see cref="string"/> types.
/// </summary>
internal static class StringExtensions
{
/// <summary>
/// Extension methods for <see cref="string"/> types.
/// Converts a given <see cref="string"/> instance to a valid HLSL identifier name.
/// </summary>
internal static class StringExtensions
/// <param name="text">The input <see cref="string"/> instance to convert.</param>
/// <returns>An valid HLSL identifier name from <paramref name="text"/>.</returns>
[Pure]
public static string ToHlslIdentifierName(this string text)
{
/// <summary>
/// Converts a given <see cref="string"/> instance to a valid HLSL identifier name.
/// </summary>
/// <param name="text">The input <see cref="string"/> instance to convert.</param>
/// <returns>An valid HLSL identifier name from <paramref name="text"/>.</returns>
[Pure]
public static string ToHlslIdentifierName(this string text)
{
return text.Replace('.', '_').Replace('+', '_');
}
return text.Replace('.', '_').Replace('+', '_');
}
}
+170 -171
ファイルの表示
@@ -7,202 +7,201 @@ using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.SourceGenerators.Extensions
namespace ComputeSharp.SourceGenerators.Extensions;
/// <summary>
/// A <see langword="class"/> with some extension methods for C# syntax nodes.
/// </summary>
internal static class SyntaxNodeExtensions
{
/// <summary>
/// A <see langword="class"/> with some extension methods for C# syntax nodes.
/// Checks a <see cref="SyntaxNode"/> value and replaces the value type to be HLSL compatible, if needed.
/// </summary>
internal static class SyntaxNodeExtensions
/// <typeparam name="TRoot">The type of the input <see cref="TypeSyntax"/> instance.</typeparam>
/// <param name="node">The input <see cref="SyntaxNode"/> to check and modify if needed.</param>
/// <param name="sourceType">The source <see cref="SyntaxNode"/> to use to get type into from <paramref name="semanticModel"/>.</param>
/// <param name="semanticModel">The <see cref="SemanticModel"/> instance with info on the input tree.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <returns>A <see cref="SyntaxNode"/> instance that represents a type compatible with HLSL.</returns>
[Pure]
public static TRoot ReplaceAndTrackType<TRoot>(this TRoot node, SyntaxNode sourceType, SemanticModel semanticModel, ICollection<INamedTypeSymbol> discoveredTypes)
where TRoot : TypeSyntax
{
/// <summary>
/// Checks a <see cref="SyntaxNode"/> value and replaces the value type to be HLSL compatible, if needed.
/// </summary>
/// <typeparam name="TRoot">The type of the input <see cref="TypeSyntax"/> instance.</typeparam>
/// <param name="node">The input <see cref="SyntaxNode"/> to check and modify if needed.</param>
/// <param name="sourceType">The source <see cref="SyntaxNode"/> to use to get type into from <paramref name="semanticModel"/>.</param>
/// <param name="semanticModel">The <see cref="SemanticModel"/> instance with info on the input tree.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <returns>A <see cref="SyntaxNode"/> instance that represents a type compatible with HLSL.</returns>
[Pure]
public static TRoot ReplaceAndTrackType<TRoot>(this TRoot node, SyntaxNode sourceType, SemanticModel semanticModel, ICollection<INamedTypeSymbol> discoveredTypes)
where TRoot : TypeSyntax
return node.ReplaceAndTrackType(node, sourceType, semanticModel, discoveredTypes);
}
/// <summary>
/// Checks a <see cref="SyntaxNode"/> value and replaces the value type to be HLSL compatible, if needed.
/// </summary>
/// <typeparam name="TRoot">The type of the input <see cref="SyntaxNode"/> instance.</typeparam>
/// <param name="node">The input <see cref="SyntaxNode"/> to check and modify if needed.</param>
/// <param name="targetType">The target <see cref="TypeSyntax"/> node to replace.</param>
/// <param name="sourceType">The source <see cref="SyntaxNode"/> to use to get type into from <paramref name="semanticModel"/>.</param>
/// <param name="semanticModel">The <see cref="SemanticModel"/> instance with info on the input tree.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <returns>A <see cref="SyntaxNode"/> instance that represents a type compatible with HLSL.</returns>
[Pure]
public static TRoot ReplaceAndTrackType<TRoot>(this TRoot node, TypeSyntax targetType, SyntaxNode sourceType, SemanticModel semanticModel, ICollection<INamedTypeSymbol> discoveredTypes)
where TRoot : SyntaxNode
{
// Skip immediately for function pointers
if (sourceType is FunctionPointerTypeSyntax)
{
return node.ReplaceAndTrackType(node, sourceType, semanticModel, discoveredTypes);
return node.ReplaceNode(targetType, ParseTypeName("void*"));
}
/// <summary>
/// Checks a <see cref="SyntaxNode"/> value and replaces the value type to be HLSL compatible, if needed.
/// </summary>
/// <typeparam name="TRoot">The type of the input <see cref="SyntaxNode"/> instance.</typeparam>
/// <param name="node">The input <see cref="SyntaxNode"/> to check and modify if needed.</param>
/// <param name="targetType">The target <see cref="TypeSyntax"/> node to replace.</param>
/// <param name="sourceType">The source <see cref="SyntaxNode"/> to use to get type into from <paramref name="semanticModel"/>.</param>
/// <param name="semanticModel">The <see cref="SemanticModel"/> instance with info on the input tree.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <returns>A <see cref="SyntaxNode"/> instance that represents a type compatible with HLSL.</returns>
[Pure]
public static TRoot ReplaceAndTrackType<TRoot>(this TRoot node, TypeSyntax targetType, SyntaxNode sourceType, SemanticModel semanticModel, ICollection<INamedTypeSymbol> discoveredTypes)
where TRoot : SyntaxNode
// Handle the various possible type kinds
ITypeSymbol typeSymbol = sourceType switch
{
// Skip immediately for function pointers
if (sourceType is FunctionPointerTypeSyntax)
{
return node.ReplaceNode(targetType, ParseTypeName("void*"));
}
RefTypeSyntax refType => semanticModel.GetTypeInfo(refType.Type).Type!,
PointerTypeSyntax pointerType => semanticModel.GetTypeInfo(pointerType.ElementType).Type!,
_ => semanticModel.GetTypeInfo(sourceType).Type!
};
// Handle the various possible type kinds
ITypeSymbol typeSymbol = sourceType switch
// Do nothing if the type is just void
if (typeSymbol.SpecialType == SpecialType.System_Void)
{
return node;
}
string typeName = typeSymbol.ToDisplayString(ISymbolExtensions.FullyQualifiedWithoutGlobalFormat);
discoveredTypes.Add((INamedTypeSymbol)typeSymbol);
if (HlslKnownTypes.TryGetMappedName(typeName, out string? mappedName))
{
TypeSyntax newType = ParseTypeName(mappedName!);
return node.ReplaceNode(targetType, newType);
}
return node.ReplaceNode(targetType, ParseTypeName(typeName.ToHlslIdentifierName()));
}
/// <summary>
/// Tracks the associated type for a <see cref="SyntaxNode"/> value and returns the HLSL compatible <see cref="TypeSyntax"/>.
/// </summary>
/// <param name="node">The input <see cref="SyntaxNode"/> to check.</param>
/// <param name="semanticModel">The <see cref="SemanticModel"/> instance with info on the input tree.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <returns>A <see cref="SyntaxNode"/> instance that represents a type compatible with HLSL.</returns>
[Pure]
public static TypeSyntax TrackType(this SyntaxNode node, SemanticModel semanticModel, ICollection<INamedTypeSymbol> discoveredTypes)
{
ITypeSymbol typeSymbol = semanticModel.GetTypeInfo(node).Type!;
string typeName = typeSymbol.ToDisplayString(ISymbolExtensions.FullyQualifiedWithoutGlobalFormat);
discoveredTypes.Add((INamedTypeSymbol)typeSymbol);
if (HlslKnownTypes.TryGetMappedName(typeName, out string? mappedName))
{
return ParseTypeName(mappedName!);
}
return ParseTypeName(typeName.ToHlslIdentifierName());
}
/// <summary>
/// Returns a <see cref="MethodDeclarationSyntax"/> with a block body.
/// </summary>
/// <param name="node">The input <see cref="MethodDeclarationSyntax"/> node.</param>
/// <returns>A node like the one in input, but always with a block body.</returns>
[Pure]
public static MethodDeclarationSyntax WithBlockBody(this MethodDeclarationSyntax node)
{
if (node.ExpressionBody is ArrowExpressionClauseSyntax arrow)
{
StatementSyntax statement = node.ReturnType switch
{
RefTypeSyntax refType => semanticModel.GetTypeInfo(refType.Type).Type!,
PointerTypeSyntax pointerType => semanticModel.GetTypeInfo(pointerType.ElementType).Type!,
_ => semanticModel.GetTypeInfo(sourceType).Type!
PredefinedTypeSyntax pts when pts.Keyword.IsKind(SyntaxKind.VoidKeyword) => ExpressionStatement(arrow.Expression),
_ => ReturnStatement(arrow.Expression)
};
// Do nothing if the type is just void
if (typeSymbol.SpecialType == SpecialType.System_Void)
{
return node;
}
string typeName = typeSymbol.ToDisplayString(ISymbolExtensions.FullyQualifiedWithoutGlobalFormat);
discoveredTypes.Add((INamedTypeSymbol)typeSymbol);
if (HlslKnownTypes.TryGetMappedName(typeName, out string? mappedName))
{
TypeSyntax newType = ParseTypeName(mappedName!);
return node.ReplaceNode(targetType, newType);
}
return node.ReplaceNode(targetType, ParseTypeName(typeName.ToHlslIdentifierName()));
return node
.WithBody(Block(statement))
.WithExpressionBody(null)
.WithSemicolonToken(MissingToken(SyntaxKind.SemicolonToken));
}
/// <summary>
/// Tracks the associated type for a <see cref="SyntaxNode"/> value and returns the HLSL compatible <see cref="TypeSyntax"/>.
/// </summary>
/// <param name="node">The input <see cref="SyntaxNode"/> to check.</param>
/// <param name="semanticModel">The <see cref="SemanticModel"/> instance with info on the input tree.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <returns>A <see cref="SyntaxNode"/> instance that represents a type compatible with HLSL.</returns>
[Pure]
public static TypeSyntax TrackType(this SyntaxNode node, SemanticModel semanticModel, ICollection<INamedTypeSymbol> discoveredTypes)
return node;
}
/// <summary>
/// Returns a <see cref="MethodDeclarationSyntax"/> as a method definition.
/// </summary>
/// <param name="node">The input <see cref="MethodDeclarationSyntax"/> node.</param>
/// <returns>A node like the one in input, but just as a definition.</returns>
[Pure]
public static MethodDeclarationSyntax AsDefinition(this MethodDeclarationSyntax node)
{
if (node.ExpressionBody is ArrowExpressionClauseSyntax)
{
ITypeSymbol typeSymbol = semanticModel.GetTypeInfo(node).Type!;
string typeName = typeSymbol.ToDisplayString(ISymbolExtensions.FullyQualifiedWithoutGlobalFormat);
discoveredTypes.Add((INamedTypeSymbol)typeSymbol);
if (HlslKnownTypes.TryGetMappedName(typeName, out string? mappedName))
{
return ParseTypeName(mappedName!);
}
return ParseTypeName(typeName.ToHlslIdentifierName());
return node.WithExpressionBody(null).WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
}
/// <summary>
/// Returns a <see cref="MethodDeclarationSyntax"/> with a block body.
/// </summary>
/// <param name="node">The input <see cref="MethodDeclarationSyntax"/> node.</param>
/// <returns>A node like the one in input, but always with a block body.</returns>
[Pure]
public static MethodDeclarationSyntax WithBlockBody(this MethodDeclarationSyntax node)
return node.WithBody(null).WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
}
/// <summary>
/// Returns a <see cref="LocalFunctionStatementSyntax"/> with a block body.
/// </summary>
/// <param name="node">The input <see cref="LocalFunctionStatementSyntax"/> node.</param>
/// <returns>A node like the one in input, but always with a block body.</returns>
/// <remarks>
/// This method is the same as <see cref="WithBlockBody(MethodDeclarationSyntax)"/>, but it is necessary to
/// duplicate the code because the two types don't have a common base type or interface that can be leveraged.
/// </remarks>
[Pure]
public static LocalFunctionStatementSyntax WithBlockBody(this LocalFunctionStatementSyntax node)
{
if (node.ExpressionBody is ArrowExpressionClauseSyntax arrow)
{
if (node.ExpressionBody is ArrowExpressionClauseSyntax arrow)
StatementSyntax statement = node.ReturnType switch
{
StatementSyntax statement = node.ReturnType switch
{
PredefinedTypeSyntax pts when pts.Keyword.IsKind(SyntaxKind.VoidKeyword) => ExpressionStatement(arrow.Expression),
_ => ReturnStatement(arrow.Expression)
};
PredefinedTypeSyntax pts when pts.Keyword.IsKind(SyntaxKind.VoidKeyword) => ExpressionStatement(arrow.Expression),
_ => ReturnStatement(arrow.Expression)
};
return node
.WithBody(Block(statement))
.WithExpressionBody(null)
.WithSemicolonToken(MissingToken(SyntaxKind.SemicolonToken));
}
return node;
return node
.WithBody(Block(statement))
.WithExpressionBody(null)
.WithSemicolonToken(MissingToken(SyntaxKind.SemicolonToken));
}
/// <summary>
/// Returns a <see cref="MethodDeclarationSyntax"/> as a method definition.
/// </summary>
/// <param name="node">The input <see cref="MethodDeclarationSyntax"/> node.</param>
/// <returns>A node like the one in input, but just as a definition.</returns>
[Pure]
public static MethodDeclarationSyntax AsDefinition(this MethodDeclarationSyntax node)
return node;
}
/// <summary>
/// Returns a <see cref="LocalFunctionStatementSyntax"/> as a method definition.
/// </summary>
/// <param name="node">The input <see cref="LocalFunctionStatementSyntax"/> node.</param>
/// <returns>A node like the one in input, but just as a definition.</returns>
[Pure]
public static LocalFunctionStatementSyntax AsDefinition(this LocalFunctionStatementSyntax node)
{
if (node.ExpressionBody is ArrowExpressionClauseSyntax)
{
if (node.ExpressionBody is ArrowExpressionClauseSyntax)
{
return node.WithExpressionBody(null).WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
}
return node.WithBody(null).WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
return node.WithExpressionBody(null).WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
}
/// <summary>
/// Returns a <see cref="LocalFunctionStatementSyntax"/> with a block body.
/// </summary>
/// <param name="node">The input <see cref="LocalFunctionStatementSyntax"/> node.</param>
/// <returns>A node like the one in input, but always with a block body.</returns>
/// <remarks>
/// This method is the same as <see cref="WithBlockBody(MethodDeclarationSyntax)"/>, but it is necessary to
/// duplicate the code because the two types don't have a common base type or interface that can be leveraged.
/// </remarks>
[Pure]
public static LocalFunctionStatementSyntax WithBlockBody(this LocalFunctionStatementSyntax node)
return node.WithBody(null).WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
}
/// <summary>
/// Returns a <see cref="MethodDeclarationSyntax"/> instance with no accessibility modifiers.
/// </summary>
/// <param name="node">The input <see cref="MethodDeclarationSyntax"/> node.</param>
/// <returns>A node just like <paramref name="node"/> but with no accessibility modifiers.</returns>
[Pure]
public static MethodDeclarationSyntax WithoutAccessibilityModifiers(this MethodDeclarationSyntax node)
{
return node.WithModifiers(TokenList(node.Modifiers.Where(static modifier => modifier.Kind() switch
{
if (node.ExpressionBody is ArrowExpressionClauseSyntax arrow)
{
StatementSyntax statement = node.ReturnType switch
{
PredefinedTypeSyntax pts when pts.Keyword.IsKind(SyntaxKind.VoidKeyword) => ExpressionStatement(arrow.Expression),
_ => ReturnStatement(arrow.Expression)
};
return node
.WithBody(Block(statement))
.WithExpressionBody(null)
.WithSemicolonToken(MissingToken(SyntaxKind.SemicolonToken));
}
return node;
}
/// <summary>
/// Returns a <see cref="LocalFunctionStatementSyntax"/> as a method definition.
/// </summary>
/// <param name="node">The input <see cref="LocalFunctionStatementSyntax"/> node.</param>
/// <returns>A node like the one in input, but just as a definition.</returns>
[Pure]
public static LocalFunctionStatementSyntax AsDefinition(this LocalFunctionStatementSyntax node)
{
if (node.ExpressionBody is ArrowExpressionClauseSyntax)
{
return node.WithExpressionBody(null).WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
}
return node.WithBody(null).WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
}
/// <summary>
/// Returns a <see cref="MethodDeclarationSyntax"/> instance with no accessibility modifiers.
/// </summary>
/// <param name="node">The input <see cref="MethodDeclarationSyntax"/> node.</param>
/// <returns>A node just like <paramref name="node"/> but with no accessibility modifiers.</returns>
[Pure]
public static MethodDeclarationSyntax WithoutAccessibilityModifiers(this MethodDeclarationSyntax node)
{
return node.WithModifiers(TokenList(node.Modifiers.Where(static modifier => modifier.Kind() switch
{
SyntaxKind.PublicKeyword => false,
SyntaxKind.PrivateKeyword => false,
SyntaxKind.ProtectedKeyword => false,
SyntaxKind.InternalKeyword => false,
_ => true
}).ToArray()));
}
SyntaxKind.PublicKeyword => false,
SyntaxKind.PrivateKeyword => false,
SyntaxKind.ProtectedKeyword => false,
SyntaxKind.InternalKeyword => false,
_ => true
}).ToArray()));
}
}
+20 -22
ファイルの表示
@@ -4,34 +4,32 @@ using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
namespace ComputeSharp.SourceGenerators
namespace ComputeSharp.SourceGenerators;
/// <summary>
/// A source generator to create global using directives for the HLSL primitive types.
/// </summary>
[Generator]
public sealed class GlobalUsingDirectivesGenerator : ISourceGenerator
{
/// <summary>
/// A source generator to create global using directives for the HLSL primitive types.
/// </summary>
[Generator]
public sealed class GlobalUsingDirectivesGenerator : ISourceGenerator
/// <inheritdoc/>
public void Initialize(GeneratorInitializationContext context)
{
/// <inheritdoc/>
public void Initialize(GeneratorInitializationContext context)
context.RegisterForPostInitialization(static context =>
{
context.RegisterForPostInitialization(static context =>
{
const string filename = "ComputeSharp.SourceGenerators.EmbeddedResources.GlobalUsingDirectives.cs";
const string filename = "ComputeSharp.SourceGenerators.EmbeddedResources.GlobalUsingDirectives.cs";
using Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(filename);
using StreamReader reader = new(stream);
using Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(filename);
using StreamReader reader = new(stream);
string globalUsingDirectives = reader.ReadToEnd();
string globalUsingDirectives = reader.ReadToEnd();
context.AddSource("GlobalUsingDirectives.cs", SourceText.From(globalUsingDirectives, Encoding.UTF8));
});
}
context.AddSource("GlobalUsingDirectives.cs", SourceText.From(globalUsingDirectives, Encoding.UTF8));
});
}
/// <inheritdoc/>
public void Execute(GeneratorExecutionContext context)
{
}
/// <inheritdoc/>
public void Execute(GeneratorExecutionContext context)
{
}
}
+19 -20
ファイルの表示
@@ -1,25 +1,24 @@
using System;
namespace ComputeSharp.SourceGenerators.Helpers
{
/// <summary>
/// A polyfill type that mirrors some methods from <see cref="System.Runtime.InteropServices.MemoryMarshal"/> on .NET 5.
/// </summary>
internal static class MemoryMarshal
{
/// <inheritdoc cref="System.Runtime.InteropServices.MemoryMarshal.GetReference{T}(Span{T})"/>
public static ref T GetReference<T>(Span<T> span)
{
return ref System.Runtime.InteropServices.MemoryMarshal.GetReference(span);
}
namespace ComputeSharp.SourceGenerators.Helpers;
/// <summary>
/// Creates a new <see cref="Span{T}"/> from a given reference.
/// </summary>
/// <typeparam name="T">The type of reference to wrap.</typeparam>
/// <param name="value">The target reference.</param>
/// <param name="length">The length of the <see cref="Span{T}"/> to create.</param>
/// <returns>A new <see cref="Span{T}"/> wrapping <paramref name="value"/>.</returns>
public static Span<T> CreateSpan<T>(ref T value, int length) => default;
/// <summary>
/// A polyfill type that mirrors some methods from <see cref="System.Runtime.InteropServices.MemoryMarshal"/> on .NET 5.
/// </summary>
internal static class MemoryMarshal
{
/// <inheritdoc cref="System.Runtime.InteropServices.MemoryMarshal.GetReference{T}(Span{T})"/>
public static ref T GetReference<T>(Span<T> span)
{
return ref System.Runtime.InteropServices.MemoryMarshal.GetReference(span);
}
/// <summary>
/// Creates a new <see cref="Span{T}"/> from a given reference.
/// </summary>
/// <typeparam name="T">The type of reference to wrap.</typeparam>
/// <param name="value">The target reference.</param>
/// <param name="length">The length of the <see cref="Span{T}"/> to create.</param>
/// <returns>A new <see cref="Span{T}"/> wrapping <paramref name="value"/>.</returns>
public static Span<T> CreateSpan<T>(ref T value, int length) => default;
}
+11 -12
ファイルの表示
@@ -1,18 +1,17 @@
using System;
namespace ComputeSharp.SourceGenerators.Helpers
namespace ComputeSharp.SourceGenerators.Helpers;
/// <summary>
/// A polyfill type that mirrors some methods from <see cref="System.Runtime.CompilerServices.RuntimeHelpers"/> on .NET 5.
/// </summary>
internal static class RuntimeHelpers
{
/// <summary>
/// A polyfill type that mirrors some methods from <see cref="System.Runtime.CompilerServices.RuntimeHelpers"/> on .NET 5.
/// Allocates some memory tied to the lifetime of a specific type.
/// </summary>
internal static class RuntimeHelpers
{
/// <summary>
/// Allocates some memory tied to the lifetime of a specific type.
/// </summary>
/// <param name="type">The type to associate the memory to.</param>
/// <param name="size">The size in byte of the memory to allocate.</param>
/// <returns>A pointer to the allocated memory.</returns>
public static IntPtr AllocateTypeAssociatedMemory(Type type, int size) => default;
}
/// <param name="type">The type to associate the memory to.</param>
/// <param name="size">The size in byte of the memory to allocate.</param>
/// <returns>A pointer to the allocated memory.</returns>
public static IntPtr AllocateTypeAssociatedMemory(Type type, int size) => default;
}
+34 -35
ファイルの表示
@@ -1,48 +1,47 @@
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
namespace ComputeSharp.SourceGenerators.Helpers
namespace ComputeSharp.SourceGenerators.Helpers;
/// <summary>
/// A type providing <see cref="SemanticModel"/> instances for nodes.
/// </summary>
internal sealed class SemanticModelProvider
{
/// <summary>
/// A type providing <see cref="SemanticModel"/> instances for nodes.
/// The source <see cref="Compilation"/> instance.
/// </summary>
internal sealed class SemanticModelProvider
private readonly Compilation compilation;
/// <summary>
/// The map of loaded <see cref="SemanticModel"/> instances.
/// </summary>
private readonly Dictionary<SyntaxTree, SemanticModel> semanticModelsMap;
/// <summary>
/// Creates a new <see cref="SemanticModelProvider"/> instance with the specified parameters.
/// </summary>
/// <param name="compilation">The source <see cref="Compilation"/> instance.</param>
public SemanticModelProvider(Compilation compilation)
{
/// <summary>
/// The source <see cref="Compilation"/> instance.
/// </summary>
private readonly Compilation compilation;
this.compilation = compilation;
this.semanticModelsMap = new Dictionary<SyntaxTree, SemanticModel>();
}
/// <summary>
/// The map of loaded <see cref="SemanticModel"/> instances.
/// </summary>
private readonly Dictionary<SyntaxTree, SemanticModel> semanticModelsMap;
/// <summary>
/// Creates a new <see cref="SemanticModelProvider"/> instance with the specified parameters.
/// </summary>
/// <param name="compilation">The source <see cref="Compilation"/> instance.</param>
public SemanticModelProvider(Compilation compilation)
/// <summary>
/// Gets a <see cref="SemanticModel"/> instance with info on a given <see cref="SyntaxNode"/>.
/// </summary>
/// <param name="syntaxNode">The input <see cref="SyntaxNode"/> to get info for.</param>
/// <returns>A <see cref="SemanticModel"/> instance containing info on <paramref name="syntaxNode"/>.</returns>
public SemanticModel For(SyntaxNode syntaxNode)
{
if (!this.semanticModelsMap.TryGetValue(syntaxNode.SyntaxTree, out SemanticModel semanticModel))
{
this.compilation = compilation;
this.semanticModelsMap = new Dictionary<SyntaxTree, SemanticModel>();
semanticModel = this.compilation.GetSemanticModel(syntaxNode.SyntaxTree);
this.semanticModelsMap.Add(syntaxNode.SyntaxTree, semanticModel);
}
/// <summary>
/// Gets a <see cref="SemanticModel"/> instance with info on a given <see cref="SyntaxNode"/>.
/// </summary>
/// <param name="syntaxNode">The input <see cref="SyntaxNode"/> to get info for.</param>
/// <returns>A <see cref="SemanticModel"/> instance containing info on <paramref name="syntaxNode"/>.</returns>
public SemanticModel For(SyntaxNode syntaxNode)
{
if (!this.semanticModelsMap.TryGetValue(syntaxNode.SyntaxTree, out SemanticModel semanticModel))
{
semanticModel = this.compilation.GetSemanticModel(syntaxNode.SyntaxTree);
this.semanticModelsMap.Add(syntaxNode.SyntaxTree, semanticModel);
}
return semanticModel;
}
return semanticModel;
}
}
+27 -28
ファイルの表示
@@ -5,40 +5,39 @@ using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.SourceGenerators.Helpers
namespace ComputeSharp.SourceGenerators.Helpers;
/// <summary>
/// A class containing additional factory methods for constructing syntax nodes, tokens and trivia.
/// </summary>
internal static class SyntaxFactoryHelper
{
/// <summary>
/// A class containing additional factory methods for constructing syntax nodes, tokens and trivia.
/// Creates an <see cref="object"/>[] array expression with the nested groups in the input sequence.
/// <para>
/// That it, it applies the following transformation:
/// <code>
/// { ("K1", "V1"), ("K2", "V2") } => new object[] { new string[] { "K1", "V1" }, new string[] { "K2", "V2" } }
/// </code>
/// </para>
/// </summary>
internal static class SyntaxFactoryHelper
/// <param name="values">The input sequence of <see cref="string"/> groups.</param>
/// <returns>An <see cref="ArrayCreationExpressionSyntax"/> instance with the described contents.</returns>
[Pure]
public static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable<(string A, string B)> groups)
{
/// <summary>
/// Creates an <see cref="object"/>[] array expression with the nested groups in the input sequence.
/// <para>
/// That it, it applies the following transformation:
/// <code>
/// { ("K1", "V1"), ("K2", "V2") } => new object[] { new string[] { "K1", "V1" }, new string[] { "K2", "V2" } }
/// </code>
/// </para>
/// </summary>
/// <param name="values">The input sequence of <see cref="string"/> groups.</param>
/// <returns>An <see cref="ArrayCreationExpressionSyntax"/> instance with the described contents.</returns>
[Pure]
public static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable<(string A, string B)> groups)
{
return
return
ArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.ObjectKeyword)))
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
.WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression)
.AddExpressions(groups.Select(static group =>
ArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.ObjectKeyword)))
ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword)))
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
.WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression)
.AddExpressions(groups.Select(static group =>
ArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword)))
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
.WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression)
.AddExpressions(
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(group.A)),
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(group.B))))).ToArray()));
}
.AddExpressions(
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(group.A)),
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(group.B))))).ToArray()));
}
}
ファイル差分が大きすぎるため表示されません。 差分を読み込み
+69 -71
ファイルの表示
@@ -10,91 +10,89 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
public sealed partial class IShaderGenerator
{
/// <inheritdoc/>
public sealed partial class IShaderGenerator
private static partial MethodDeclarationSyntax CreateGetDispatchIdMethod(INamedTypeSymbol structDeclarationSymbol)
{
/// <inheritdoc/>
private static partial MethodDeclarationSyntax CreateGetDispatchIdMethod(INamedTypeSymbol structDeclarationSymbol)
// This code produces a method declaration as follows:
//
// readonly int IShader.GetDispatchId()
// {
// <BODY>
// }
return
MethodDeclaration(
PredefinedType(Token(SyntaxKind.IntKeyword)),
Identifier("GetDispatchId"))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName(nameof(IShader))))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.WithBody(GetShaderHashCodeBody(structDeclarationSymbol));
}
/// <summary>
/// Gets a <see cref="BlockSyntax"/> instance with the logic to compute the hashcode of a given shader type.
/// </summary>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <returns>The <see cref="BlockSyntax"/> instance to hash the input shader.</returns>
[Pure]
private static BlockSyntax GetShaderHashCodeBody(INamedTypeSymbol structDeclarationSymbol)
{
var delegateFields = structDeclarationSymbol
.GetMembers()
.OfType<IFieldSymbol>()
.Where(static m => m.Type is INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false })
.ToImmutableArray();
if (delegateFields.Length == 0)
{
// This code produces a method declaration as follows:
//
// readonly int IShader.GetDispatchId()
// {
// <BODY>
// }
// return 0;
return
MethodDeclaration(
PredefinedType(Token(SyntaxKind.IntKeyword)),
Identifier("GetDispatchId"))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName(nameof(IShader))))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.WithBody(GetShaderHashCodeBody(structDeclarationSymbol));
Block(ReturnStatement(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))));
}
/// <summary>
/// Gets a <see cref="BlockSyntax"/> instance with the logic to compute the hashcode of a given shader type.
/// </summary>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <returns>The <see cref="BlockSyntax"/> instance to hash the input shader.</returns>
[Pure]
private static BlockSyntax GetShaderHashCodeBody(INamedTypeSymbol structDeclarationSymbol)
{
var delegateFields = structDeclarationSymbol
.GetMembers()
.OfType<IFieldSymbol>()
.Where(static m => m.Type is INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false })
.ToImmutableArray();
List<StatementSyntax> blockStatements = new(4);
if (delegateFields.Length == 0)
{
// return 0;
return
Block(ReturnStatement(
// HashCode hashCode = default;
blockStatements.Add(LocalDeclarationStatement(
VariableDeclaration(IdentifierName("HashCode"))
.AddVariables(
VariableDeclarator(Identifier("hashCode"))
.WithInitializer(EqualsValueClause(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))));
}
SyntaxKind.DefaultLiteralExpression,
Token(SyntaxKind.DefaultKeyword)))))));
List<StatementSyntax> blockStatements = new(4);
// HashCode hashCode = default;
blockStatements.Add(LocalDeclarationStatement(
VariableDeclaration(IdentifierName("HashCode"))
.AddVariables(
VariableDeclarator(Identifier("hashCode"))
.WithInitializer(EqualsValueClause(
LiteralExpression(
SyntaxKind.DefaultLiteralExpression,
Token(SyntaxKind.DefaultKeyword)))))));
foreach (IFieldSymbol fieldSymbol in delegateFields)
{
// hashCode.Add(delegateField.Method);
blockStatements.Add(ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("hashCode"),
IdentifierName("Add")))
.AddArgumentListArguments(Argument(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName(fieldSymbol.Name),
IdentifierName("Method"))))));
}
// return hashCode.ToHashCode();
blockStatements.Add(ReturnStatement(
foreach (IFieldSymbol fieldSymbol in delegateFields)
{
// hashCode.Add(delegateField.Method);
blockStatements.Add(ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("hashCode"),
IdentifierName("ToHashCode")))));
return Block(blockStatements);
IdentifierName("Add")))
.AddArgumentListArguments(Argument(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName(fieldSymbol.Name),
IdentifierName("Method"))))));
}
// return hashCode.ToHashCode();
blockStatements.Add(ReturnStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("hashCode"),
IdentifierName("ToHashCode")))));
return Block(blockStatements);
}
}
+268 -270
ファイルの表示
@@ -14,327 +14,325 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
public sealed partial class IShaderGenerator
{
/// <inheritdoc/>
public sealed partial class IShaderGenerator
private static partial MethodDeclarationSyntax CreateLoadDispatchDataMethod(
GeneratorExecutionContext context,
INamedTypeSymbol structDeclarationSymbol,
out IReadOnlyCollection<string> discoveredResources,
out int root32BitConstantsCount)
{
/// <inheritdoc/>
private static partial MethodDeclarationSyntax CreateLoadDispatchDataMethod(
GeneratorExecutionContext context,
INamedTypeSymbol structDeclarationSymbol,
out IReadOnlyCollection<string> discoveredResources,
out int root32BitConstantsCount)
// This code produces a method declaration as follows:
//
// readonly void IShader.LoadDispatchData<TDataLoader>(ref TDataLoader loader, GraphicsDevice device, int x, int y, int z)
// {
// <BODY>
// }
return
MethodDeclaration(
PredefinedType(Token(SyntaxKind.VoidKeyword)),
Identifier("LoadDispatchData"))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName(nameof(IShader))))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.AddTypeParameterListParameters(TypeParameter(Identifier("TDataLoader")))
.AddParameterListParameters(
Parameter(Identifier("loader"))
.AddModifiers(Token(SyntaxKind.RefKeyword))
.WithType(IdentifierName("TDataLoader")),
Parameter(Identifier("device")).WithType(IdentifierName("GraphicsDevice")),
Parameter(Identifier("x")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("y")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("z")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))))
.WithBody(Block(GetDispatchDataLoadingStatements(context, structDeclarationSymbol, out discoveredResources, out root32BitConstantsCount)));
}
/// <summary>
/// Gets a sequence of statements to load the dispatch data for a given shader.
/// </summary>
/// <param name="context">The current generator context in use.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="discoveredResources">The collection of discovered resources in the current shader type.</param>
/// <param name="root32BitConstantsCount">The total number of 32 bit root constants being loaded for the current shader type.</param>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
private static IEnumerable<StatementSyntax> GetDispatchDataLoadingStatements(GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol, out IReadOnlyCollection<string> discoveredResources, out int root32BitConstantsCount)
{
List<StatementSyntax> statements = new();
List<string> resources = new();
discoveredResources = resources;
var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) });
var isComputeShader = pixelShaderSymbol is null;
int
resourceOffset = 0,
rawDataOffset = sizeof(int) * (isComputeShader ? 3 : 2);
// Append the statements for the dispatch ranges:
//
// span0[0] = (uint)x;
// span0[1] = (uint)y;
// span0[2] = (uint)z;
statements.Add(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))),
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("x")))));
statements.Add(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1)))),
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("y")))));
if (isComputeShader)
{
// This code produces a method declaration as follows:
//
// readonly void IShader.LoadDispatchData<TDataLoader>(ref TDataLoader loader, GraphicsDevice device, int x, int y, int z)
// {
// <BODY>
// }
return
MethodDeclaration(
PredefinedType(Token(SyntaxKind.VoidKeyword)),
Identifier("LoadDispatchData"))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName(nameof(IShader))))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.AddTypeParameterListParameters(TypeParameter(Identifier("TDataLoader")))
.AddParameterListParameters(
Parameter(Identifier("loader"))
.AddModifiers(Token(SyntaxKind.RefKeyword))
.WithType(IdentifierName("TDataLoader")),
Parameter(Identifier("device")).WithType(IdentifierName("GraphicsDevice")),
Parameter(Identifier("x")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("y")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("z")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))))
.WithBody(Block(GetDispatchDataLoadingStatements(context, structDeclarationSymbol, out discoveredResources, out root32BitConstantsCount)));
statements.Add(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(2)))),
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("z")))));
}
/// <summary>
/// Gets a sequence of statements to load the dispatch data for a given shader.
/// </summary>
/// <param name="context">The current generator context in use.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="discoveredResources">The collection of discovered resources in the current shader type.</param>
/// <param name="root32BitConstantsCount">The total number of 32 bit root constants being loaded for the current shader type.</param>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
private static IEnumerable<StatementSyntax> GetDispatchDataLoadingStatements(GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol, out IReadOnlyCollection<string> discoveredResources, out int root32BitConstantsCount)
// Append the statements to load all fields (both resources and other captured values)
AppendFields(structDeclarationSymbol, Array.Empty<string>(), ref resourceOffset, ref rawDataOffset, resources, statements);
// After all the captured fields have been processed, ansure the reported byte size for
// the local variables is padded to a multiple of a 32 bit value. This is necessary to
// enable loading all the dispatch data after reinterpreting it to a sequence of values
// of size 32 bits (via SetComputeRoot32BitConstants), without reading out of bounds.
rawDataOffset = AlignmentHelper.Pad(rawDataOffset, sizeof(int));
root32BitConstantsCount = rawDataOffset / sizeof(int);
// A shader root signature has a maximum size of 64 DWORDs, so 256 bytes.
// Loaded values in the root signature have the following costs:
// - Root constants cost 1 DWORD each, since they are 32-bit values.
// - Descriptor tables cost 1 DWORD each.
// - Root descriptors (64-bit GPU virtual addresses) cost 2 DWORDs each.
// So here we check whether the current signature respects that constraint,
// and emit a build error otherwise. For more info on this, see the docs here:
// https://docs.microsoft.com/windows/win32/direct3d12/root-signature-limits.
int rootSignatureDwordSize = root32BitConstantsCount + resourceOffset;
if (rootSignatureDwordSize > 64)
{
List<StatementSyntax> statements = new();
List<string> resources = new();
context.ReportDiagnostic(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol);
}
discoveredResources = resources;
// Span<uint> span0 = stackalloc uint[<VARIABLES>];
statements.Insert(0,
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("Span"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.UIntKeyword))))
.AddVariables(
VariableDeclarator(Identifier("span0"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.UIntKeyword)))
.AddRankSpecifiers(
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(root32BitConstantsCount)))))))))));
var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) });
var isComputeShader = pixelShaderSymbol is null;
int
resourceOffset = 0,
rawDataOffset = sizeof(int) * (isComputeShader ? 3 : 2);
// ref uint r0 = ref span0[0];
statements.Insert(1,
LocalDeclarationStatement(
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.UIntKeyword))))
.AddVariables(
VariableDeclarator(Identifier("r0"))
.WithInitializer(EqualsValueClause(
RefExpression(
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))))))))));
// Append the statements for the dispatch ranges:
//
// span0[0] = (uint)x;
// span0[1] = (uint)y;
// span0[2] = (uint)z;
statements.Add(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))),
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("x")))));
// loader.LoadCapturedValues(span0);
statements.Add(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("loader"),
IdentifierName("LoadCapturedValues")))
.AddArgumentListArguments(Argument(IdentifierName("span0")))));
statements.Add(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1)))),
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("y")))));
if (isComputeShader)
{
statements.Add(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(2)))),
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("z")))));
}
// Append the statements to load all fields (both resources and other captured values)
AppendFields(structDeclarationSymbol, Array.Empty<string>(), ref resourceOffset, ref rawDataOffset, resources, statements);
// After all the captured fields have been processed, ansure the reported byte size for
// the local variables is padded to a multiple of a 32 bit value. This is necessary to
// enable loading all the dispatch data after reinterpreting it to a sequence of values
// of size 32 bits (via SetComputeRoot32BitConstants), without reading out of bounds.
rawDataOffset = AlignmentHelper.Pad(rawDataOffset, sizeof(int));
root32BitConstantsCount = rawDataOffset / sizeof(int);
// A shader root signature has a maximum size of 64 DWORDs, so 256 bytes.
// Loaded values in the root signature have the following costs:
// - Root constants cost 1 DWORD each, since they are 32-bit values.
// - Descriptor tables cost 1 DWORD each.
// - Root descriptors (64-bit GPU virtual addresses) cost 2 DWORDs each.
// So here we check whether the current signature respects that constraint,
// and emit a build error otherwise. For more info on this, see the docs here:
// https://docs.microsoft.com/windows/win32/direct3d12/root-signature-limits.
int rootSignatureDwordSize = root32BitConstantsCount + resourceOffset;
if (rootSignatureDwordSize > 64)
{
context.ReportDiagnostic(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol);
}
// Span<uint> span0 = stackalloc uint[<VARIABLES>];
statements.Insert(0,
if (resourceOffset > 0)
{
// Span<ulong> span1 = stackalloc ulong[<RESOURCES>];
statements.Insert(1,
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("Span"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.UIntKeyword))))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ULongKeyword))))
.AddVariables(
VariableDeclarator(Identifier("span0"))
VariableDeclarator(Identifier("span1"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.UIntKeyword)))
ArrayType(PredefinedType(Token(SyntaxKind.ULongKeyword)))
.AddRankSpecifiers(
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(root32BitConstantsCount)))))))))));
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(resourceOffset)))))))))));
// ref uint r0 = ref span0[0];
statements.Insert(1,
// ref ulong r1 = ref span1[0];
statements.Insert(3,
LocalDeclarationStatement(
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.UIntKeyword))))
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ULongKeyword))))
.AddVariables(
VariableDeclarator(Identifier("r0"))
VariableDeclarator(Identifier("r1"))
.WithInitializer(EqualsValueClause(
RefExpression(
ElementAccessExpression(IdentifierName("span0"))
ElementAccessExpression(IdentifierName("span1"))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))))))))));
// loader.LoadCapturedValues(span0);
// loader.LoadCapturedResources(span1);
statements.Add(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("loader"),
IdentifierName("LoadCapturedValues")))
.AddArgumentListArguments(Argument(IdentifierName("span0")))));
if (resourceOffset > 0)
{
// Span<ulong> span1 = stackalloc ulong[<RESOURCES>];
statements.Insert(1,
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("Span"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ULongKeyword))))
.AddVariables(
VariableDeclarator(Identifier("span1"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.ULongKeyword)))
.AddRankSpecifiers(
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(resourceOffset)))))))))));
// ref ulong r1 = ref span1[0];
statements.Insert(3,
LocalDeclarationStatement(
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ULongKeyword))))
.AddVariables(
VariableDeclarator(Identifier("r1"))
.WithInitializer(EqualsValueClause(
RefExpression(
ElementAccessExpression(IdentifierName("span1"))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))))))))));
// loader.LoadCapturedResources(span1);
statements.Add(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("loader"),
IdentifierName("LoadCapturedResources")))
.AddArgumentListArguments(Argument(IdentifierName("span1")))));
}
return statements;
IdentifierName("LoadCapturedResources")))
.AddArgumentListArguments(Argument(IdentifierName("span1")))));
}
/// <summary>
/// Explores a given type hierarchy and generates statements to load fields.
/// </summary>
/// <param name="currentTypeSymbol">The current type being explored.</param>
/// <param name="fieldPath">The current path of the field with respect to the shader instance.</param>
/// <param name="resourceOffset">The current offset in the root table of loaded resources.</param>
/// <param name="rawDataOffset">The current offset within the loaded data buffer.</param>
/// <param name="resources">The target list of resources in the current shader type.</param>
/// <param name="statements">The target list of statements being generated.</param>
private static void AppendFields(ITypeSymbol currentTypeSymbol, IReadOnlyCollection<string> fieldPath, ref int resourceOffset, ref int rawDataOffset, ICollection<string> resources, ICollection<StatementSyntax> statements)
return statements;
}
/// <summary>
/// Explores a given type hierarchy and generates statements to load fields.
/// </summary>
/// <param name="currentTypeSymbol">The current type being explored.</param>
/// <param name="fieldPath">The current path of the field with respect to the shader instance.</param>
/// <param name="resourceOffset">The current offset in the root table of loaded resources.</param>
/// <param name="rawDataOffset">The current offset within the loaded data buffer.</param>
/// <param name="resources">The target list of resources in the current shader type.</param>
/// <param name="statements">The target list of statements being generated.</param>
private static void AppendFields(ITypeSymbol currentTypeSymbol, IReadOnlyCollection<string> fieldPath, ref int resourceOffset, ref int rawDataOffset, ICollection<string> resources, ICollection<StatementSyntax> statements)
{
bool isFirstField = true;
foreach (
IFieldSymbol fieldSymbol in
from fieldSymbol in currentTypeSymbol.GetMembers().OfType<IFieldSymbol>()
where fieldSymbol.Type is INamedTypeSymbol { IsStatic: false } &&
!fieldSymbol.IsConst && !fieldSymbol.IsStatic && !fieldSymbol.IsFixedSizeBuffer
select fieldSymbol)
{
bool isFirstField = true;
string
fieldName = fieldSymbol.Name,
typeName = fieldSymbol.Type.GetFullMetadataName();
foreach (
IFieldSymbol fieldSymbol in
from fieldSymbol in currentTypeSymbol.GetMembers().OfType<IFieldSymbol>()
where fieldSymbol.Type is INamedTypeSymbol { IsStatic: false } &&
!fieldSymbol.IsConst && !fieldSymbol.IsStatic && !fieldSymbol.IsFixedSizeBuffer
select fieldSymbol)
// Disambiguates the name of target fields against the current input parameters
if (fieldName is "loader" or "device" or "x" or "y" or "z")
{
string
fieldName = fieldSymbol.Name,
typeName = fieldSymbol.Type.GetFullMetadataName();
// Disambiguates the name of target fields against the current input parameters
if (fieldName is "loader" or "device" or "x" or "y" or "z")
{
fieldName = $"this.{fieldName}";
}
// The first item in each nested struct needs to be aligned to 16 bytes
if (isFirstField && fieldPath.Count > 0)
{
rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
isFirstField = false;
}
if (HlslKnownTypes.IsTypedResourceType(typeName))
{
resources.Add(typeName);
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"Unsafe.Add(ref r1, {resourceOffset++})"),
ParseExpression($"GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({fieldName}, device)"))));
}
else if (HlslKnownTypes.IsKnownHlslType(typeName))
{
AppendHlslKnownTypeField(fieldPath.Concat(new[] { fieldName }), typeName, ref rawDataOffset, statements);
}
else if (fieldSymbol.Type.IsUnmanagedType)
{
// Custom struct type defined by the user
AppendFields(fieldSymbol.Type, fieldPath.Concat(new[] { fieldName }).ToArray(), ref resourceOffset, ref rawDataOffset, resources, statements);
}
fieldName = $"this.{fieldName}";
}
}
/// <summary>
/// Generates a loading statement for a known HLSL primitive type field (scalar, vector or matrix).
/// </summary>
/// <param name="fieldPath">The current path of the field with respect to the shader instance.</param>
/// <param name="typeName">The type name currently being read.</param>
/// <param name="rawDataOffset">The current offset within the loaded data buffer.</param>
/// <param name="statements">The target list of statements being generated.</param>
private static void AppendHlslKnownTypeField(IEnumerable<string> fieldPath, string typeName, ref int rawDataOffset, ICollection<StatementSyntax> statements)
{
// For scalar, vector and linear matrix types, serialize the value normally.
// Only the initial alignment needs to be considered, while data is packed.
var (fieldSize, fieldPack) = HlslKnownSizes.GetTypeInfo(typeName);
// Check if the current type is a matrix type with more than one row. In this
// case, each row is aligned as if it was a separate array, so the start of
// each row needs to be at a multiple of 16 bytes (a float4 register).
if (HlslKnownTypes.IsNonLinearMatrixType(typeName, out string? elementName, out int rows, out int columns))
// The first item in each nested struct needs to be aligned to 16 bytes
if (isFirstField && fieldPath.Count > 0)
{
string
rowTypeName = $"ComputeSharp.{elementName}{columns}",
rowLocalName = $"__{string.Join("_", fieldPath)}__row0";
rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref Unsafe.As<{typeName}, {rowTypeName}>(ref Unsafe.AsRef(in {string.Join(".", fieldPath)}));"));
// Generate the loading code for each individual row, with proper alignment.
// This will result in the following (assuming Float2x3 m):
//
// ref Float3 __m__row0 = ref Unsafe.As<Float2x3, Float3>(ref Unsafe.AsRef(in m));
// Unsafe.As<uint, Float3>(ref Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) =, Unsafe.Add(ref __m__row0, 0);
// Unsafe.As<uint, Float3>(ref Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = Unsafe.Add(ref __m__row0, 1);
for (int j = 0; j < rows; j++)
{
rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"Unsafe.As<uint, {rowTypeName}>(ref Unsafe.AddByteOffset(ref r0, (nint){rawDataOffset}))"),
ParseExpression($"Unsafe.Add(ref {rowLocalName}, {j})"))));
rawDataOffset += fieldPack * columns;
}
isFirstField = false;
}
else
if (HlslKnownTypes.IsTypedResourceType(typeName))
{
// Calculate the right offset with 16-bytes padding (HLSL constant buffer).
// Since we're in a constant buffer, we need to both pad the starting offset
// to be aligned to the packing size of the type, and also to align the initial
// offset to ensure that values do not cross 16 bytes boundaries either.
rawDataOffset = AlignmentHelper.AlignToBoundary(
AlignmentHelper.Pad(rawDataOffset, fieldPack),
fieldSize,
16);
resources.Add(typeName);
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"Unsafe.As<uint, {typeName}>(ref Unsafe.AddByteOffset(ref r0, (nint){rawDataOffset}))"),
ParseExpression($"{string.Join(".", fieldPath)}"))));
rawDataOffset += fieldSize;
ParseExpression($"Unsafe.Add(ref r1, {resourceOffset++})"),
ParseExpression($"GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({fieldName}, device)"))));
}
else if (HlslKnownTypes.IsKnownHlslType(typeName))
{
AppendHlslKnownTypeField(fieldPath.Concat(new[] { fieldName }), typeName, ref rawDataOffset, statements);
}
else if (fieldSymbol.Type.IsUnmanagedType)
{
// Custom struct type defined by the user
AppendFields(fieldSymbol.Type, fieldPath.Concat(new[] { fieldName }).ToArray(), ref resourceOffset, ref rawDataOffset, resources, statements);
}
}
}
}
/// <summary>
/// Generates a loading statement for a known HLSL primitive type field (scalar, vector or matrix).
/// </summary>
/// <param name="fieldPath">The current path of the field with respect to the shader instance.</param>
/// <param name="typeName">The type name currently being read.</param>
/// <param name="rawDataOffset">The current offset within the loaded data buffer.</param>
/// <param name="statements">The target list of statements being generated.</param>
private static void AppendHlslKnownTypeField(IEnumerable<string> fieldPath, string typeName, ref int rawDataOffset, ICollection<StatementSyntax> statements)
{
// For scalar, vector and linear matrix types, serialize the value normally.
// Only the initial alignment needs to be considered, while data is packed.
var (fieldSize, fieldPack) = HlslKnownSizes.GetTypeInfo(typeName);
// Check if the current type is a matrix type with more than one row. In this
// case, each row is aligned as if it was a separate array, so the start of
// each row needs to be at a multiple of 16 bytes (a float4 register).
if (HlslKnownTypes.IsNonLinearMatrixType(typeName, out string? elementName, out int rows, out int columns))
{
string
rowTypeName = $"ComputeSharp.{elementName}{columns}",
rowLocalName = $"__{string.Join("_", fieldPath)}__row0";
statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref Unsafe.As<{typeName}, {rowTypeName}>(ref Unsafe.AsRef(in {string.Join(".", fieldPath)}));"));
// Generate the loading code for each individual row, with proper alignment.
// This will result in the following (assuming Float2x3 m):
//
// ref Float3 __m__row0 = ref Unsafe.As<Float2x3, Float3>(ref Unsafe.AsRef(in m));
// Unsafe.As<uint, Float3>(ref Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) =, Unsafe.Add(ref __m__row0, 0);
// Unsafe.As<uint, Float3>(ref Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = Unsafe.Add(ref __m__row0, 1);
for (int j = 0; j < rows; j++)
{
rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"Unsafe.As<uint, {rowTypeName}>(ref Unsafe.AddByteOffset(ref r0, (nint){rawDataOffset}))"),
ParseExpression($"Unsafe.Add(ref {rowLocalName}, {j})"))));
rawDataOffset += fieldPack * columns;
}
}
else
{
// Calculate the right offset with 16-bytes padding (HLSL constant buffer).
// Since we're in a constant buffer, we need to both pad the starting offset
// to be aligned to the packing size of the type, and also to align the initial
// offset to ensure that values do not cross 16 bytes boundaries either.
rawDataOffset = AlignmentHelper.AlignToBoundary(
AlignmentHelper.Pad(rawDataOffset, fieldPack),
fieldSize,
16);
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"Unsafe.As<uint, {typeName}>(ref Unsafe.AddByteOffset(ref r0, (nint){rawDataOffset}))"),
ParseExpression($"{string.Join(".", fieldPath)}"))));
rawDataOffset += fieldSize;
}
}
}
+134 -136
ファイルの表示
@@ -8,152 +8,150 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
public sealed partial class IShaderGenerator
{
/// <inheritdoc/>
public sealed partial class IShaderGenerator
private static partial MethodDeclarationSyntax CreateLoadDispatchMetadataMethod(
string? implicitTextureType,
IReadOnlyCollection<string> discoveredResources,
int root32BitConstantsCount,
bool isSamplerUsed)
{
/// <inheritdoc/>
private static partial MethodDeclarationSyntax CreateLoadDispatchMetadataMethod(
string? implicitTextureType,
IReadOnlyCollection<string> discoveredResources,
int root32BitConstantsCount,
bool isSamplerUsed)
// This code produces a method declaration as follows:
//
// readonly void IShader.LoadDispatchMetadata<TMetadataLoader>(ref TMetadataLoader loader, out IntPtr result)
// {
// <BODY>
// }
return
MethodDeclaration(
PredefinedType(Token(SyntaxKind.VoidKeyword)),
Identifier("LoadDispatchMetadata"))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName(nameof(IShader))))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.AddTypeParameterListParameters(TypeParameter(Identifier("TMetadataLoader")))
.AddParameterListParameters(
Parameter(Identifier("loader"))
.AddModifiers(Token(SyntaxKind.RefKeyword))
.WithType(IdentifierName("TMetadataLoader")),
Parameter(Identifier("result"))
.AddModifiers(Token(SyntaxKind.OutKeyword))
.WithType(IdentifierName(typeof(IntPtr).Name)))
.WithBody(Block(GetDispatchMetadataLoadingStatements(implicitTextureType, discoveredResources, root32BitConstantsCount, isSamplerUsed)));
}
/// <summary>
/// Gets a sequence of statements to load the dispatch metadata for a given shader type.
/// </summary>
/// <param name="implicitTextureType">The implicit texture type, if available (if the shader is a pixel shader).</param>
/// <param name="discoveredResources">The collection of resources used by the shader.</param>
/// <param name="root32BitConstantsCount">The total number of 32 bit root constants being loaded for the shader.</param>
/// <param name="isSamplerUsed">Whether or not the shader requires a static sampler to be available.</param>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
private static IEnumerable<StatementSyntax> GetDispatchMetadataLoadingStatements(
string? implicitTextureType,
IReadOnlyCollection<string> discoveredResources,
int root32BitConstantsCount,
bool isSamplerUsed)
{
// Span<byte> span0 = stackalloc byte[5];
yield return
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("Span"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))))
.AddVariables(
VariableDeclarator(Identifier("span0"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
.AddRankSpecifiers(
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(5))))))))));
// Compute the total number of resources (discovered ones and the implicit target texture, if present)
int totalResourcesCount = discoveredResources.Count + (implicitTextureType is not null ? 1 : 0);
// Span<ResourceDescriptor> span1 = stackalloc ResourceDescriptor[<ADJUSTED_COUNT>];
yield return
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("Span"))
.AddTypeArgumentListArguments(IdentifierName("ResourceDescriptor")))
.AddVariables(
VariableDeclarator(Identifier("span1"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(IdentifierName("ResourceDescriptor"))
.AddRankSpecifiers(
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(totalResourcesCount))))))))));
// ref byte r0 = ref span0[0];
yield return
LocalDeclarationStatement(
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword))))
.AddVariables(
VariableDeclarator(Identifier("r0"))
.WithInitializer(EqualsValueClause(
RefExpression(
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0)))))))));
// ref ResourceDescriptor r1 = ref span1[0];
yield return
LocalDeclarationStatement(
VariableDeclaration(RefType(IdentifierName("ResourceDescriptor")))
.AddVariables(
VariableDeclarator(Identifier("r1"))
.WithInitializer(EqualsValueClause(
RefExpression(
ElementAccessExpression(IdentifierName("span1"))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0)))))))));
// Serialized shader metadata
yield return ParseStatement($"Unsafe.WriteUnaligned<int>(ref Unsafe.Add(ref r0, 0), {root32BitConstantsCount});");
yield return ParseStatement($"Unsafe.WriteUnaligned<bool>(ref Unsafe.Add(ref r0, 4), {isSamplerUsed.ToString().ToLowerInvariant()});");
int
constantBufferOffset = 1,
readOnlyResourceOffset = 0,
readWriteResourceOffset = 0,
resourceOffset = 0;
// Add the implicit texture descriptor, if needed
if (implicitTextureType is not null)
{
// This code produces a method declaration as follows:
//
// readonly void IShader.LoadDispatchMetadata<TMetadataLoader>(ref TMetadataLoader loader, out IntPtr result)
// {
// <BODY>
// }
return
MethodDeclaration(
PredefinedType(Token(SyntaxKind.VoidKeyword)),
Identifier("LoadDispatchMetadata"))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName(nameof(IShader))))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.AddTypeParameterListParameters(TypeParameter(Identifier("TMetadataLoader")))
.AddParameterListParameters(
Parameter(Identifier("loader"))
.AddModifiers(Token(SyntaxKind.RefKeyword))
.WithType(IdentifierName("TMetadataLoader")),
Parameter(Identifier("result"))
.AddModifiers(Token(SyntaxKind.OutKeyword))
.WithType(IdentifierName(typeof(IntPtr).Name)))
.WithBody(Block(GetDispatchMetadataLoadingStatements(implicitTextureType, discoveredResources, root32BitConstantsCount, isSamplerUsed)));
yield return ParseStatement($"ResourceDescriptor.Create(1, {readWriteResourceOffset++}, out Unsafe.Add(ref r1, {resourceOffset++}));");
}
/// <summary>
/// Gets a sequence of statements to load the dispatch metadata for a given shader type.
/// </summary>
/// <param name="implicitTextureType">The implicit texture type, if available (if the shader is a pixel shader).</param>
/// <param name="discoveredResources">The collection of resources used by the shader.</param>
/// <param name="root32BitConstantsCount">The total number of 32 bit root constants being loaded for the shader.</param>
/// <param name="isSamplerUsed">Whether or not the shader requires a static sampler to be available.</param>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
private static IEnumerable<StatementSyntax> GetDispatchMetadataLoadingStatements(
string? implicitTextureType,
IReadOnlyCollection<string> discoveredResources,
int root32BitConstantsCount,
bool isSamplerUsed)
// Populate the sequence of resource descriptors
foreach (var resource in discoveredResources)
{
// Span<byte> span0 = stackalloc byte[5];
yield return
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("Span"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))))
.AddVariables(
VariableDeclarator(Identifier("span0"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
.AddRankSpecifiers(
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(5))))))))));
// Compute the total number of resources (discovered ones and the implicit target texture, if present)
int totalResourcesCount = discoveredResources.Count + (implicitTextureType is not null ? 1 : 0);
// Span<ResourceDescriptor> span1 = stackalloc ResourceDescriptor[<ADJUSTED_COUNT>];
yield return
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("Span"))
.AddTypeArgumentListArguments(IdentifierName("ResourceDescriptor")))
.AddVariables(
VariableDeclarator(Identifier("span1"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(IdentifierName("ResourceDescriptor"))
.AddRankSpecifiers(
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(totalResourcesCount))))))))));
// ref byte r0 = ref span0[0];
yield return
LocalDeclarationStatement(
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword))))
.AddVariables(
VariableDeclarator(Identifier("r0"))
.WithInitializer(EqualsValueClause(
RefExpression(
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0)))))))));
// ref ResourceDescriptor r1 = ref span1[0];
yield return
LocalDeclarationStatement(
VariableDeclaration(RefType(IdentifierName("ResourceDescriptor")))
.AddVariables(
VariableDeclarator(Identifier("r1"))
.WithInitializer(EqualsValueClause(
RefExpression(
ElementAccessExpression(IdentifierName("span1"))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0)))))))));
// Serialized shader metadata
yield return ParseStatement($"Unsafe.WriteUnaligned<int>(ref Unsafe.Add(ref r0, 0), {root32BitConstantsCount});");
yield return ParseStatement($"Unsafe.WriteUnaligned<bool>(ref Unsafe.Add(ref r0, 4), {isSamplerUsed.ToString().ToLowerInvariant()});");
int
constantBufferOffset = 1,
readOnlyResourceOffset = 0,
readWriteResourceOffset = 0,
resourceOffset = 0;
// Add the implicit texture descriptor, if needed
if (implicitTextureType is not null)
if (HlslKnownTypes.IsConstantBufferType(resource))
{
yield return ParseStatement($"ResourceDescriptor.Create(2, {constantBufferOffset++}, out Unsafe.Add(ref r1, {resourceOffset++}));");
}
else if (HlslKnownTypes.IsReadOnlyTypedResourceType(resource))
{
yield return ParseStatement($"ResourceDescriptor.Create(0, {readOnlyResourceOffset++}, out Unsafe.Add(ref r1, {resourceOffset++}));");
}
else
{
yield return ParseStatement($"ResourceDescriptor.Create(1, {readWriteResourceOffset++}, out Unsafe.Add(ref r1, {resourceOffset++}));");
}
// Populate the sequence of resource descriptors
foreach (var resource in discoveredResources)
{
if (HlslKnownTypes.IsConstantBufferType(resource))
{
yield return ParseStatement($"ResourceDescriptor.Create(2, {constantBufferOffset++}, out Unsafe.Add(ref r1, {resourceOffset++}));");
}
else if (HlslKnownTypes.IsReadOnlyTypedResourceType(resource))
{
yield return ParseStatement($"ResourceDescriptor.Create(0, {readOnlyResourceOffset++}, out Unsafe.Add(ref r1, {resourceOffset++}));");
}
else
{
yield return ParseStatement($"ResourceDescriptor.Create(1, {readWriteResourceOffset++}, out Unsafe.Add(ref r1, {resourceOffset++}));");
}
}
// Invoke the value delegate to create the opaque root signature handle
yield return ParseStatement("loader.LoadMetadataHandle(span0, span1, out result);");
}
// Invoke the value delegate to create the opaque root signature handle
yield return ParseStatement("loader.LoadMetadataHandle(span0, span1, out result);");
}
}
+31 -33
ファイルの表示
@@ -4,46 +4,44 @@ using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace ComputeSharp.SourceGenerators
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
public sealed partial class IShaderGenerator
{
/// <inheritdoc/>
public sealed partial class IShaderGenerator
/// <summary>
/// An <see cref="ISyntaxContextReceiver"/> that selects candidate nodes to process.
/// </summary>
private sealed class SyntaxReceiver : ISyntaxContextReceiver
{
/// <summary>
/// An <see cref="ISyntaxContextReceiver"/> that selects candidate nodes to process.
/// The list of info gathered during exploration.
/// </summary>
private sealed class SyntaxReceiver : ISyntaxContextReceiver
private readonly List<Item> gatheredInfo = new();
/// <summary>
/// Gets the collection of gathered info to process.
/// </summary>
public IReadOnlyCollection<Item> GatheredInfo => this.gatheredInfo;
/// <inheritdoc/>
public void OnVisitSyntaxNode(GeneratorSyntaxContext context)
{
/// <summary>
/// The list of info gathered during exploration.
/// </summary>
private readonly List<Item> gatheredInfo = new();
/// <summary>
/// Gets the collection of gathered info to process.
/// </summary>
public IReadOnlyCollection<Item> GatheredInfo => this.gatheredInfo;
/// <inheritdoc/>
public void OnVisitSyntaxNode(GeneratorSyntaxContext context)
if (context.Node is StructDeclarationSyntax structDeclaration &&
context.SemanticModel.GetDeclaredSymbol(structDeclaration) is INamedTypeSymbol structSymbol &&
structSymbol.Interfaces.Any(static interfaceSymbol =>
interfaceSymbol.Name == nameof(IComputeShader) ||
interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) }))
{
if (context.Node is StructDeclarationSyntax structDeclaration &&
context.SemanticModel.GetDeclaredSymbol(structDeclaration) is INamedTypeSymbol structSymbol &&
structSymbol.Interfaces.Any(static interfaceSymbol =>
interfaceSymbol.Name == nameof(IComputeShader) ||
interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) }))
{
this.gatheredInfo.Add(new Item(structDeclaration, structSymbol));
}
this.gatheredInfo.Add(new Item(structDeclaration, structSymbol));
}
/// <summary>
/// A model for a group of item representing a discovered type to process.
/// </summary>
/// <param name="StructDeclaration">The <see cref="StructDeclarationSyntax"/> instance for the target struct declaration.</param>
/// <param name="StructSymbol">The <see cref="INamedTypeSymbol"/> instance for <paramref name="StructDeclaration"/>.</param>
public sealed record Item(StructDeclarationSyntax StructDeclaration, INamedTypeSymbol StructSymbol);
}
/// <summary>
/// A model for a group of item representing a discovered type to process.
/// </summary>
/// <param name="StructDeclaration">The <see cref="StructDeclarationSyntax"/> instance for the target struct declaration.</param>
/// <param name="StructSymbol">The <see cref="INamedTypeSymbol"/> instance for <paramref name="StructDeclaration"/>.</param>
public sealed record Item(StructDeclarationSyntax StructDeclaration, INamedTypeSymbol StructSymbol);
}
}
+209 -211
ファイルの表示
@@ -11,218 +11,216 @@ using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle;
namespace ComputeSharp.SourceGenerators
namespace ComputeSharp.SourceGenerators;
/// <summary>
/// A source generator creating data loaders for <see cref="IComputeShader"/> and <see cref="IPixelShader{TPixel}"/> types.
/// </summary>
[Generator]
public sealed partial class IShaderGenerator : ISourceGenerator
{
/// <summary>
/// A source generator creating data loaders for <see cref="IComputeShader"/> and <see cref="IPixelShader{TPixel}"/> types.
/// </summary>
[Generator]
public sealed partial class IShaderGenerator : ISourceGenerator
/// <inheritdoc/>
public void Initialize(GeneratorInitializationContext context)
{
/// <inheritdoc/>
public void Initialize(GeneratorInitializationContext context)
{
context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver());
}
/// <inheritdoc/>
public void Execute(GeneratorExecutionContext context)
{
// Get the syntax receiver with the candidate nodes
if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver)
{
return;
}
foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo)
{
try
{
OnExecute(context, item.StructDeclaration, item.StructSymbol);
}
catch
{
context.ReportDiagnostic(IShaderGeneratorError, item.StructDeclaration, item.StructSymbol);
}
}
}
/// <summary>
/// Processes a given target type.
/// </summary>
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to 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>
private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol)
{
// Create the required interface methods for the current shader type
MethodDeclarationSyntax
getDispatchIdMethod = CreateGetDispatchIdMethod(structDeclarationSymbol),
loadDispatchDataMethod = CreateLoadDispatchDataMethod(context, structDeclarationSymbol, out var discoveredResources, out int root32BitConstants),
buildHlslStringMethod = CreateBuildHlslStringMethod(context, structDeclaration, structDeclarationSymbol, out string? implicitTextureType, out bool isSamplerUsed, out bool isHashSetDirectiveNeeded),
loadDispatchMetadataMethod = CreateLoadDispatchMetadataMethod(implicitTextureType, discoveredResources, root32BitConstants, isSamplerUsed);
// Reorder the method declarations to respect the order in the interface definition
MethodDeclarationSyntax[] methods =
{
getDispatchIdMethod,
loadDispatchDataMethod,
loadDispatchMetadataMethod,
buildHlslStringMethod
};
// Method attributes
List<AttributeListSyntax> attributes = new()
{
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("GeneratedCode")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).FullName))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).Assembly.GetName().Version.ToString())))))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("DebuggerNonUserCode")))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("ExcludeFromCodeCoverage")))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments(
AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("Obsolete")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(
SyntaxKind.StringLiteralExpression,
Literal("This method is not intended to be used directly by user code"))))))
};
// Add [SkipLocalsInit] if the target project allows it
if (context.Compilation.Options is CSharpCompilationOptions { AllowUnsafe: true })
{
attributes.Add(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("SkipLocalsInit")))));
}
string namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces));
string structName = structDeclaration.Identifier.Text;
SyntaxTokenList structModifiers = structDeclaration.Modifiers;
// Create the partial shader type declaration with the hashcode interface method implementation.
// This code produces a struct declaration as follows:
//
// public <MODIFIERS> struct ShaderType
// {
// <METHODS_LIST>
// }
var structDeclarationSyntax =
StructDeclaration(structName)
.WithModifiers(structModifiers)
.AddMembers(methods.Select(m => m.AddAttributeLists(attributes.ToArray())).ToArray());
TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax;
// Add all parent types in ascending order, if any
foreach (var parentType in structDeclaration.Ancestors().OfType<TypeDeclarationSyntax>())
{
typeDeclarationSyntax = parentType
.WithMembers(SingletonList<MemberDeclarationSyntax>(typeDeclarationSyntax))
.WithConstraintClauses(List<TypeParameterConstraintClauseSyntax>())
.WithBaseList(null)
.WithAttributeLists(List<AttributeListSyntax>())
.WithoutTrivia();
}
// Prepare the necessary using directives
List<UsingDirectiveSyntax> usingDirectives = new()
{
UsingDirective(IdentifierName("System")),
UsingDirective(IdentifierName("System.CodeDom.Compiler")),
UsingDirective(IdentifierName("System.ComponentModel")),
UsingDirective(IdentifierName("System.Diagnostics")),
UsingDirective(IdentifierName("System.Diagnostics.CodeAnalysis")),
UsingDirective(IdentifierName("System.Runtime.CompilerServices")),
UsingDirective(IdentifierName("ComputeSharp")),
UsingDirective(IdentifierName("ComputeSharp.__Internals"))
};
if (isHashSetDirectiveNeeded)
{
usingDirectives.Insert(2, UsingDirective(IdentifierName("System.Collections.Generic")));
}
// Create a static method to create the combined hashcode for a given shader type.
// This code takes a block syntax and produces a compilation unit as follows:
//
// using System;
// using System.CodeDom.Compiler;
// using System.ComponentModel;
// using System.Diagnostics;
// using System.Diagnostics.CodeAnalysis;
// using System.Runtime.CompilerServices;
// using ComputeSharp.__Internals;
//
// #pragma warning disable
//
// namespace <SHADER_NAMESPACE>
// {
// <SHADER_DECLARATION>
// }
var source =
CompilationUnit().AddUsings(usingDirectives.ToArray()).AddMembers(
NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax)
.WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList())))
.NormalizeWhitespace(eol: "\n")
.ToFullString();
// Add the method source attribute
context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8));
}
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>GetDispatchId</c> method.
/// </summary>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for <paramref name="structDeclaration"/>.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>GetDispatchId</c> method.</returns>
private static partial MethodDeclarationSyntax CreateGetDispatchIdMethod(INamedTypeSymbol structDeclarationSymbol);
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.
/// </summary>
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to use.</param>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for <paramref name="structDeclaration"/>.</param>
/// <param name="discoveredResources">The collection of discovered resources in the current shader type.</param>
/// <param name="root32BitConstantsCount">The total number of 32 bit root constants being loaded for the current shader type.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.</returns>
private static partial MethodDeclarationSyntax CreateLoadDispatchDataMethod(
GeneratorExecutionContext context,
INamedTypeSymbol structDeclarationSymbol,
out IReadOnlyCollection<string> discoveredResources,
out int root32BitConstantsCount);
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.
/// </summary>
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to 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>
/// <param name="implicitTextureType">The implicit texture type, if available (if the shader is a pixel shader).</param>
/// <param name="isSamplerUsed">Whether or not the current shader type requires a static sampler to be available.</param>
/// <param name="isHashSetDirectiveNeeded">Indicates whether or not the <see langword="using"/> directive for <see cref="HashSet{T}"/> is needed.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.</returns>
private static partial MethodDeclarationSyntax CreateBuildHlslStringMethod(
GeneratorExecutionContext context,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
out string? implicitTextureType,
out bool isSamplerUsed,
out bool isHashSetDirectiveNeeded);
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchMetadata</c> method.
/// </summary>
/// <param name="implicitTextureType">The implicit texture type, if available (if the shader is a pixel shader).</param>
/// <param name="discoveredResources">The collection of resources used by the shader.</param>
/// <param name="root32BitConstantsCount">The total number of 32 bit root constants being loaded for the shader.</param>
/// <param name="isSamplerUsed">Whether or not the shader requires a static sampler to be available.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchMetadata</c> method.</returns>
private static partial MethodDeclarationSyntax CreateLoadDispatchMetadataMethod(
string? implicitTextureType,
IReadOnlyCollection<string> discoveredResources,
int root32BitConstantsCount,
bool isSamplerUsed);
context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver());
}
}
/// <inheritdoc/>
public void Execute(GeneratorExecutionContext context)
{
// Get the syntax receiver with the candidate nodes
if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver)
{
return;
}
foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo)
{
try
{
OnExecute(context, item.StructDeclaration, item.StructSymbol);
}
catch
{
context.ReportDiagnostic(IShaderGeneratorError, item.StructDeclaration, item.StructSymbol);
}
}
}
/// <summary>
/// Processes a given target type.
/// </summary>
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to 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>
private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol)
{
// Create the required interface methods for the current shader type
MethodDeclarationSyntax
getDispatchIdMethod = CreateGetDispatchIdMethod(structDeclarationSymbol),
loadDispatchDataMethod = CreateLoadDispatchDataMethod(context, structDeclarationSymbol, out var discoveredResources, out int root32BitConstants),
buildHlslStringMethod = CreateBuildHlslStringMethod(context, structDeclaration, structDeclarationSymbol, out string? implicitTextureType, out bool isSamplerUsed, out bool isHashSetDirectiveNeeded),
loadDispatchMetadataMethod = CreateLoadDispatchMetadataMethod(implicitTextureType, discoveredResources, root32BitConstants, isSamplerUsed);
// Reorder the method declarations to respect the order in the interface definition
MethodDeclarationSyntax[] methods =
{
getDispatchIdMethod,
loadDispatchDataMethod,
loadDispatchMetadataMethod,
buildHlslStringMethod
};
// Method attributes
List<AttributeListSyntax> attributes = new()
{
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("GeneratedCode")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).FullName))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).Assembly.GetName().Version.ToString())))))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("DebuggerNonUserCode")))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("ExcludeFromCodeCoverage")))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments(
AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("Obsolete")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(
SyntaxKind.StringLiteralExpression,
Literal("This method is not intended to be used directly by user code"))))))
};
// Add [SkipLocalsInit] if the target project allows it
if (context.Compilation.Options is CSharpCompilationOptions { AllowUnsafe: true })
{
attributes.Add(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("SkipLocalsInit")))));
}
string namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces));
string structName = structDeclaration.Identifier.Text;
SyntaxTokenList structModifiers = structDeclaration.Modifiers;
// Create the partial shader type declaration with the hashcode interface method implementation.
// This code produces a struct declaration as follows:
//
// public <MODIFIERS> struct ShaderType
// {
// <METHODS_LIST>
// }
var structDeclarationSyntax =
StructDeclaration(structName)
.WithModifiers(structModifiers)
.AddMembers(methods.Select(m => m.AddAttributeLists(attributes.ToArray())).ToArray());
TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax;
// Add all parent types in ascending order, if any
foreach (var parentType in structDeclaration.Ancestors().OfType<TypeDeclarationSyntax>())
{
typeDeclarationSyntax = parentType
.WithMembers(SingletonList<MemberDeclarationSyntax>(typeDeclarationSyntax))
.WithConstraintClauses(List<TypeParameterConstraintClauseSyntax>())
.WithBaseList(null)
.WithAttributeLists(List<AttributeListSyntax>())
.WithoutTrivia();
}
// Prepare the necessary using directives
List<UsingDirectiveSyntax> usingDirectives = new()
{
UsingDirective(IdentifierName("System")),
UsingDirective(IdentifierName("System.CodeDom.Compiler")),
UsingDirective(IdentifierName("System.ComponentModel")),
UsingDirective(IdentifierName("System.Diagnostics")),
UsingDirective(IdentifierName("System.Diagnostics.CodeAnalysis")),
UsingDirective(IdentifierName("System.Runtime.CompilerServices")),
UsingDirective(IdentifierName("ComputeSharp")),
UsingDirective(IdentifierName("ComputeSharp.__Internals"))
};
if (isHashSetDirectiveNeeded)
{
usingDirectives.Insert(2, UsingDirective(IdentifierName("System.Collections.Generic")));
}
// Create a static method to create the combined hashcode for a given shader type.
// This code takes a block syntax and produces a compilation unit as follows:
//
// using System;
// using System.CodeDom.Compiler;
// using System.ComponentModel;
// using System.Diagnostics;
// using System.Diagnostics.CodeAnalysis;
// using System.Runtime.CompilerServices;
// using ComputeSharp.__Internals;
//
// #pragma warning disable
//
// namespace <SHADER_NAMESPACE>
// {
// <SHADER_DECLARATION>
// }
var source =
CompilationUnit().AddUsings(usingDirectives.ToArray()).AddMembers(
NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax)
.WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList())))
.NormalizeWhitespace(eol: "\n")
.ToFullString();
// Add the method source attribute
context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8));
}
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>GetDispatchId</c> method.
/// </summary>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for <paramref name="structDeclaration"/>.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>GetDispatchId</c> method.</returns>
private static partial MethodDeclarationSyntax CreateGetDispatchIdMethod(INamedTypeSymbol structDeclarationSymbol);
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.
/// </summary>
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to use.</param>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for <paramref name="structDeclaration"/>.</param>
/// <param name="discoveredResources">The collection of discovered resources in the current shader type.</param>
/// <param name="root32BitConstantsCount">The total number of 32 bit root constants being loaded for the current shader type.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.</returns>
private static partial MethodDeclarationSyntax CreateLoadDispatchDataMethod(
GeneratorExecutionContext context,
INamedTypeSymbol structDeclarationSymbol,
out IReadOnlyCollection<string> discoveredResources,
out int root32BitConstantsCount);
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.
/// </summary>
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to 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>
/// <param name="implicitTextureType">The implicit texture type, if available (if the shader is a pixel shader).</param>
/// <param name="isSamplerUsed">Whether or not the current shader type requires a static sampler to be available.</param>
/// <param name="isHashSetDirectiveNeeded">Indicates whether or not the <see langword="using"/> directive for <see cref="HashSet{T}"/> is needed.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.</returns>
private static partial MethodDeclarationSyntax CreateBuildHlslStringMethod(
GeneratorExecutionContext context,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
out string? implicitTextureType,
out bool isSamplerUsed,
out bool isHashSetDirectiveNeeded);
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchMetadata</c> method.
/// </summary>
/// <param name="implicitTextureType">The implicit texture type, if available (if the shader is a pixel shader).</param>
/// <param name="discoveredResources">The collection of resources used by the shader.</param>
/// <param name="root32BitConstantsCount">The total number of 32 bit root constants being loaded for the shader.</param>
/// <param name="isSamplerUsed">Whether or not the shader requires a static sampler to be available.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchMetadata</c> method.</returns>
private static partial MethodDeclarationSyntax CreateLoadDispatchMetadataMethod(
string? implicitTextureType,
IReadOnlyCollection<string> discoveredResources,
int root32BitConstantsCount,
bool isSamplerUsed);
}
+53 -54
ファイルの表示
@@ -4,70 +4,69 @@ using System.Linq;
using System.Reflection;
using ComputeSharp.Core.Intrinsics.Attributes;
namespace ComputeSharp.SourceGenerators.Mappings
namespace ComputeSharp.SourceGenerators.Mappings;
/// <summary>
/// A <see langword="class"/> that contains and maps known HLSL identifier names valid HLSL names.
/// </summary>
internal static class HlslKnownKeywords
{
/// <summary>
/// A <see langword="class"/> that contains and maps known HLSL identifier names valid HLSL names.
/// The mapping of known HLSL keywords.
/// </summary>
internal static class HlslKnownKeywords
private static readonly IReadOnlyCollection<string> KnownKeywords = BuildKnownKeywordsMap();
/// <summary>
/// Builds the mapping of all known HLSL keywords.
/// </summary>
[Pure]
private static IReadOnlyCollection<string> BuildKnownKeywordsMap()
{
/// <summary>
/// The mapping of known HLSL keywords.
/// </summary>
private static readonly IReadOnlyCollection<string> KnownKeywords = BuildKnownKeywordsMap();
/// <summary>
/// Builds the mapping of all known HLSL keywords.
/// </summary>
[Pure]
private static IReadOnlyCollection<string> BuildKnownKeywordsMap()
// HLSL keywords
HashSet<string> knownKeywords = new(new[]
{
// HLSL keywords
HashSet<string> knownKeywords = new(new[]
{
"asm", "asm_fragment", "cbuffer", "centroid", "column_major",
"compile", "discard", "dword", "export", "fxgroup", "groupshared",
"half", "inline", "inout", "line", "lineadj", "linear", "matrix",
"nointerpolation", "noperspective", "NULL", "packoffset", "pass",
"pixelfragment", "point", "precise", "register", "row_major", "sample",
"sampler", "shared", "snorm", "stateblock", "stateblock_state", "tbuffer",
"technique", "typedef", "triangle", "triangleadj", "uniform", "unorm",
"unsigned", "vector", "vertexfragment", "zero"
});
"asm", "asm_fragment", "cbuffer", "centroid", "column_major",
"compile", "discard", "dword", "export", "fxgroup", "groupshared",
"half", "inline", "inout", "line", "lineadj", "linear", "matrix",
"nointerpolation", "noperspective", "NULL", "packoffset", "pass",
"pixelfragment", "point", "precise", "register", "row_major", "sample",
"sampler", "shared", "snorm", "stateblock", "stateblock_state", "tbuffer",
"technique", "typedef", "triangle", "triangleadj", "uniform", "unorm",
"unsigned", "vector", "vertexfragment", "zero"
});
// Dispatch type names
knownKeywords.Add(nameof(ThreadIds));
knownKeywords.Add(nameof(GroupIds));
knownKeywords.Add(nameof(GroupSize));
knownKeywords.Add(nameof(GridIds));
// Dispatch type names
knownKeywords.Add(nameof(ThreadIds));
knownKeywords.Add(nameof(GroupIds));
knownKeywords.Add(nameof(GroupSize));
knownKeywords.Add(nameof(GridIds));
// HLSL intrinsics method names
foreach (var method in typeof(Hlsl).GetMethods(BindingFlags.Public | BindingFlags.Static))
{
string name = method.GetCustomAttribute<HlslIntrinsicNameAttribute>()?.Name ?? method.Name;
// HLSL intrinsics method names
foreach (var method in typeof(Hlsl).GetMethods(BindingFlags.Public | BindingFlags.Static))
{
string name = method.GetCustomAttribute<HlslIntrinsicNameAttribute>()?.Name ?? method.Name;
knownKeywords.Add(name);
}
return knownKeywords;
knownKeywords.Add(name);
}
/// <summary>
/// Tries to get the mapped HLSL-compatible identifier name for the input identifier name.
/// </summary>
/// <param name="name">The input identifier name.</param>
/// <param name="mapped">The mapped identifier name, if a replacement is needed.</param>
/// <returns>The HLSL-compatible identifier name that can be used in an HLSL shader.</returns>
[Pure]
public static bool TryGetMappedName(string name, out string? mapped)
{
mapped = KnownKeywords.Contains(name) switch
{
true => $"__reserved__{name}",
false => null
};
return knownKeywords;
}
return mapped is not null;
}
/// <summary>
/// Tries to get the mapped HLSL-compatible identifier name for the input identifier name.
/// </summary>
/// <param name="name">The input identifier name.</param>
/// <param name="mapped">The mapped identifier name, if a replacement is needed.</param>
/// <returns>The HLSL-compatible identifier name that can be used in an HLSL shader.</returns>
[Pure]
public static bool TryGetMappedName(string name, out string? mapped)
{
mapped = KnownKeywords.Contains(name) switch
{
true => $"__reserved__{name}",
false => null
};
return mapped is not null;
}
}
+390 -391
ファイルの表示
@@ -7,434 +7,433 @@ using System.Numerics;
using System.Reflection;
using System.Text.RegularExpressions;
namespace ComputeSharp.SourceGenerators.Mappings
namespace ComputeSharp.SourceGenerators.Mappings;
/// <summary>
/// A <see langword="class"/> that contains and maps known HLSL member names to common .NET members.
/// </summary>
internal static class HlslKnownMembers
{
/// <summary>
/// A <see langword="class"/> that contains and maps known HLSL member names to common .NET members.
/// The mapping of supported known indexers to HLSL resource type names.
/// </summary>
internal static class HlslKnownMembers
private static readonly IReadOnlyDictionary<string, string> KnownResourceIndexers = new Dictionary<string, string>
{
/// <summary>
/// The mapping of supported known indexers to HLSL resource type names.
/// </summary>
private static readonly IReadOnlyDictionary<string, string> KnownResourceIndexers = new Dictionary<string, string>
[$"ComputeSharp.ReadOnlyTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.ReadWriteTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.ReadWriteTexture2D`2.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.IReadWriteTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.ReadOnlyTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3",
[$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3",
[$"ComputeSharp.ReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3",
[$"ComputeSharp.ReadWriteTexture3D`2.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3",
[$"ComputeSharp.IReadOnlyTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3",
[$"ComputeSharp.IReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3"
};
/// <summary>
/// The mapping of supported known samplers to HLSL resource type names.
/// </summary>
private static readonly IReadOnlyDictionary<string, string?> KnownResourceSamplers = new Dictionary<string, string?>
{
[$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2",
[$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(Float2).FullName}]"] = null,
[$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2",
[$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(Float2).FullName}]"] = null,
[$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3",
[$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(Float3).FullName}]"] = null,
[$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3",
[$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(Float3).FullName}]"] = null
};
/// <summary>
/// The mapping of supported known size accessors for HLSL resource types.
/// </summary>
private static readonly IReadOnlyDictionary<string, (int Rank, int Axis)> KnownSizeAccessors = new Dictionary<string, (int, int)>
{
["ComputeSharp.Resources.Buffer`1.Length"] = (2, 0),
["ComputeSharp.Resources.Texture2D`1.Width"] = (2, 0),
["ComputeSharp.Resources.Texture2D`1.Height"] = (2, 1),
["ComputeSharp.Resources.Texture3D`1.Width"] = (3, 0),
["ComputeSharp.Resources.Texture3D`1.Height"] = (3, 1),
["ComputeSharp.Resources.Texture3D`1.Depth"] = (3, 2),
["ComputeSharp.IReadOnlyTexture2D`1.Width"] = (2, 0),
["ComputeSharp.IReadOnlyTexture2D`1.Height"] = (2, 1),
["ComputeSharp.IReadOnlyTexture3D`1.Width"] = (3, 0),
["ComputeSharp.IReadOnlyTexture3D`1.Height"] = (3, 1),
["ComputeSharp.IReadOnlyTexture3D`1.Depth"] = (3, 2),
["ComputeSharp.IReadWriteTexture2D`1.Width"] = (2, 0),
["ComputeSharp.IReadWriteTexture2D`1.Height"] = (2, 1),
["ComputeSharp.IReadWriteTexture3D`1.Width"] = (3, 0),
["ComputeSharp.IReadWriteTexture3D`1.Height"] = (3, 1),
["ComputeSharp.IReadWriteTexture3D`1.Depth"] = (3, 2)
};
/// <summary>
/// The mapping of supported known members to HLSL names.
/// </summary>
private static readonly IReadOnlyDictionary<string, string> KnownMembers = BuildKnownMembersMap();
/// <summary>
/// Builds the mapping of supported known members to HLSL names.
/// </summary>
[Pure]
private static IReadOnlyDictionary<string, string> BuildKnownMembersMap()
{
Dictionary<string, string> knownMembers = new()
{
[$"ComputeSharp.ReadOnlyTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.ReadWriteTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.ReadWriteTexture2D`2.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.IReadWriteTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.ReadOnlyTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3",
[$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3",
[$"ComputeSharp.ReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3",
[$"ComputeSharp.ReadWriteTexture3D`2.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3",
[$"ComputeSharp.IReadOnlyTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3",
[$"ComputeSharp.IReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3"
[$"{typeof(Vector2).FullName}.{nameof(Vector2.X)}"] = "x",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Y)}"] = "y",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Zero)}"] = "(float2)0",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.One)}"] = "float2(1.0f, 1.0f)",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.UnitX)}"] = "float2(1.0f, 0.0f)",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.UnitY)}"] = "float2(0.0f, 1.0f)",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.X)}"] = "x",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Y)}"] = "y",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Z)}"] = "z",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Zero)}"] = "(float3)0",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.One)}"] = "float3(1.0f, 1.0f, 1.0f)",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.UnitX)}"] = "float3(1.0f, 0.0f, 0.0f)",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.UnitY)}"] = "float3(0.0f, 1.0f, 0.0f)",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.UnitZ)}"] = "float3(0.0f, 0.0f, 1.0f)",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.X)}"] = "x",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Y)}"] = "y",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Z)}"] = "z",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.W)}"] = "w",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Zero)}"] = "(float4)0",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.One)}"] = "float4(1.0f, 1.0f, 1.0f, 1.0f)",
[$"{typeof(Bool2).FullName}.{nameof(Bool2.False)}"] = "(bool2)0",
[$"{typeof(Bool2).FullName}.{nameof(Bool2.True)}"] = "bool2(true, true)",
[$"{typeof(Bool2).FullName}.{nameof(Bool2.TrueX)}"] = "bool2(true, false)",
[$"{typeof(Bool2).FullName}.{nameof(Bool2.TrueY)}"] = "bool2(false, true)",
[$"{typeof(Bool3).FullName}.{nameof(Bool3.False)}"] = "(bool3)0",
[$"{typeof(Bool3).FullName}.{nameof(Bool3.True)}"] = "bool3(true, true, true)",
[$"{typeof(Bool3).FullName}.{nameof(Bool3.TrueX)}"] = "bool3(true, false, false)",
[$"{typeof(Bool3).FullName}.{nameof(Bool3.TrueY)}"] = "bool3(false, true, false)",
[$"{typeof(Bool3).FullName}.{nameof(Bool3.TrueZ)}"] = "bool3(false, false, true)",
[$"{typeof(Bool4).FullName}.{nameof(Bool4.False)}"] = "(bool4)0",
[$"{typeof(Bool4).FullName}.{nameof(Bool4.True)}"] = "bool4(true, true, true, true)",
[$"{typeof(Bool4).FullName}.{nameof(Bool4.TrueX)}"] = "bool4(true, false, false, false)",
[$"{typeof(Bool4).FullName}.{nameof(Bool4.TrueY)}"] = "bool4(false, true, false, false)",
[$"{typeof(Bool4).FullName}.{nameof(Bool4.TrueZ)}"] = "bool4(false, false, true, false)",
[$"{typeof(Bool4).FullName}.{nameof(Bool4.TrueW)}"] = "bool4(false, false, false, true)",
[$"{typeof(Int2).FullName}.{nameof(Int2.Zero)}"] = "(int2)0",
[$"{typeof(Int2).FullName}.{nameof(Int2.One)}"] = "int2(1, 1)",
[$"{typeof(Int2).FullName}.{nameof(Int2.UnitX)}"] = "int2(1, 0)",
[$"{typeof(Int2).FullName}.{nameof(Int2.UnitY)}"] = "int2(0, 1)",
[$"{typeof(Int3).FullName}.{nameof(Int3.Zero)}"] = "(int3)0",
[$"{typeof(Int3).FullName}.{nameof(Int3.One)}"] = "int3(1, 1, 1)",
[$"{typeof(Int3).FullName}.{nameof(Int3.UnitX)}"] = "int3(1, 0, 0)",
[$"{typeof(Int3).FullName}.{nameof(Int3.UnitY)}"] = "int3(0, 1, 0)",
[$"{typeof(Int3).FullName}.{nameof(Int3.UnitZ)}"] = "int3(0, 0, 1)",
[$"{typeof(Int4).FullName}.{nameof(Int4.Zero)}"] = "(int4)0",
[$"{typeof(Int4).FullName}.{nameof(Int4.One)}"] = "int4(1, 1, 1, 1)",
[$"{typeof(Int4).FullName}.{nameof(Int4.UnitX)}"] = "int4(1, 0, 0, 0)",
[$"{typeof(Int4).FullName}.{nameof(Int4.UnitY)}"] = "int4(0, 1, 0, 0)",
[$"{typeof(Int4).FullName}.{nameof(Int4.UnitZ)}"] = "int4(0, 0, 1, 0)",
[$"{typeof(Int4).FullName}.{nameof(Int4.UnitW)}"] = "int4(0, 0, 0, 1)",
[$"{typeof(UInt2).FullName}.{nameof(UInt2.Zero)}"] = "(uint2)0",
[$"{typeof(UInt2).FullName}.{nameof(UInt2.One)}"] = "uint2(1u, 1u)",
[$"{typeof(UInt2).FullName}.{nameof(UInt2.UnitX)}"] = "uint2(1u, 0u)",
[$"{typeof(UInt2).FullName}.{nameof(UInt2.UnitY)}"] = "uint2(0u, 1u)",
[$"{typeof(UInt3).FullName}.{nameof(UInt3.Zero)}"] = "(uint3)0",
[$"{typeof(UInt3).FullName}.{nameof(UInt3.One)}"] = "uint3(1u, 1u, 1u)",
[$"{typeof(UInt3).FullName}.{nameof(UInt3.UnitX)}"] = "uint3(1u, 0u, 0u)",
[$"{typeof(UInt3).FullName}.{nameof(UInt3.UnitY)}"] = "uint3(0u, 1u, 0u)",
[$"{typeof(UInt3).FullName}.{nameof(UInt3.UnitZ)}"] = "uint3(0u, 0u, 1u)",
[$"{typeof(UInt4).FullName}.{nameof(UInt4.Zero)}"] = "(uint4)0",
[$"{typeof(UInt4).FullName}.{nameof(UInt4.One)}"] = "uint4(1u, 1u, 1u, 1u)",
[$"{typeof(UInt4).FullName}.{nameof(UInt4.UnitX)}"] = "uint4(1u, 0u, 0u, 0u)",
[$"{typeof(UInt4).FullName}.{nameof(UInt4.UnitY)}"] = "uint4(0u, 1u, 0u, 0u)",
[$"{typeof(UInt4).FullName}.{nameof(UInt4.UnitZ)}"] = "uint4(0u, 0u, 1u, 0u)",
[$"{typeof(UInt4).FullName}.{nameof(UInt4.UnitW)}"] = "uint4(0u, 0u, 0u, 1u)",
[$"{typeof(Float2).FullName}.{nameof(Float2.Zero)}"] = "(float2)0",
[$"{typeof(Float2).FullName}.{nameof(Float2.One)}"] = "float2(1.0f, 1.0f)",
[$"{typeof(Float2).FullName}.{nameof(Float2.UnitX)}"] = "float2(1.0f, 0.0f)",
[$"{typeof(Float2).FullName}.{nameof(Float2.UnitY)}"] = "float2(0.0f, 1.0f)",
[$"{typeof(Float3).FullName}.{nameof(Float3.Zero)}"] = "(float3)0",
[$"{typeof(Float3).FullName}.{nameof(Float3.One)}"] = "float3(1.0f, 1.0f, 1.0f)",
[$"{typeof(Float3).FullName}.{nameof(Float3.UnitX)}"] = "float3(1.0f, 0.0f, 0.0f)",
[$"{typeof(Float3).FullName}.{nameof(Float3.UnitY)}"] = "float3(0.0f, 1.0f, 0.0f)",
[$"{typeof(Float3).FullName}.{nameof(Float3.UnitZ)}"] = "float3(0.0f, 0.0f, 1.0f)",
[$"{typeof(Float4).FullName}.{nameof(Float4.Zero)}"] = "(float4)0",
[$"{typeof(Float4).FullName}.{nameof(Float4.One)}"] = "float4(1.0f, 1.0f, 1.0f, 1.0f)",
[$"{typeof(Float4).FullName}.{nameof(Float4.UnitX)}"] = "float4(1.0f, 0.0f, 0.0f, 0.0f)",
[$"{typeof(Float4).FullName}.{nameof(Float4.UnitY)}"] = "float4(0.0f, 1.0f, 0.0f, 0.0f)",
[$"{typeof(Float4).FullName}.{nameof(Float4.UnitZ)}"] = "float4(0.0f, 0.0f, 1.0f, 0.0f)",
[$"{typeof(Float4).FullName}.{nameof(Float4.UnitW)}"] = "float4(0.0f, 0.0f, 0.0f, 1.0f)",
[$"{typeof(Double2).FullName}.{nameof(Double2.Zero)}"] = "(double2)0",
[$"{typeof(Double2).FullName}.{nameof(Double2.One)}"] = "double2(1.0, 1.0)",
[$"{typeof(Double2).FullName}.{nameof(Double2.UnitX)}"] = "double2(1.0, 0.0)",
[$"{typeof(Double2).FullName}.{nameof(Double2.UnitY)}"] = "double2(0.0, 1.0)",
[$"{typeof(Double3).FullName}.{nameof(Double3.Zero)}"] = "(double3)0",
[$"{typeof(Double3).FullName}.{nameof(Double3.One)}"] = "double3(1.0, 1.0, 1.0)",
[$"{typeof(Double3).FullName}.{nameof(Double3.UnitX)}"] = "double3(1.0, 0.0, 0.0)",
[$"{typeof(Double3).FullName}.{nameof(Double3.UnitY)}"] = "double3(0.0, 1.0, 0.0)",
[$"{typeof(Double3).FullName}.{nameof(Double3.UnitZ)}"] = "double3(0.0, 0.0, 1.0)",
[$"{typeof(Double4).FullName}.{nameof(Double4.Zero)}"] = "(double4)0",
[$"{typeof(Double4).FullName}.{nameof(Double4.One)}"] = "double4(1.0, 1.0, 1.0, 1.0)",
[$"{typeof(Double4).FullName}.{nameof(Double4.UnitX)}"] = "double4(1.0, 0.0, 0.0, 0.0)",
[$"{typeof(Double4).FullName}.{nameof(Double4.UnitY)}"] = "double4(0.0, 1.0, 0.0, 0.0)",
[$"{typeof(Double4).FullName}.{nameof(Double4.UnitZ)}"] = "double4(0.0, 0.0, 1.0, 0.0)",
[$"{typeof(Double4).FullName}.{nameof(Double4.UnitW)}"] = "double4(0.0, 0.0, 0.0, 1.0)"
};
/// <summary>
/// The mapping of supported known samplers to HLSL resource type names.
/// </summary>
private static readonly IReadOnlyDictionary<string, string?> KnownResourceSamplers = new Dictionary<string, string?>
// Programmatically load mappings for the instance members of the HLSL vector types
foreach (var item in
from type in HlslKnownTypes.KnownVectorTypes
from property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public)
select (Type: type, Property: property))
{
[$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2",
[$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(Float2).FullName}]"] = null,
[$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2",
[$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(Float2).FullName}]"] = null,
[$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3",
[$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(Float3).FullName}]"] = null,
[$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3",
[$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(Float3).FullName}]"] = null
};
knownMembers.Add($"{item.Type.FullName}{Type.Delimiter}{item.Property.Name}", $"{item.Property.Name.ToLower()}");
}
/// <summary>
/// The mapping of supported known size accessors for HLSL resource types.
/// </summary>
private static readonly IReadOnlyDictionary<string, (int Rank, int Axis)> KnownSizeAccessors = new Dictionary<string, (int, int)>
// Load mappings for the matrix properties as well
foreach (var item in
from type in HlslKnownTypes.KnownMatrixTypes
from property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public)
where Regex.IsMatch(property.Name, "^M[1-4]{2}$")
select (Type: type, Property: property))
{
["ComputeSharp.Resources.Buffer`1.Length"] = (2, 0),
["ComputeSharp.Resources.Texture2D`1.Width"] = (2, 0),
["ComputeSharp.Resources.Texture2D`1.Height"] = (2, 1),
["ComputeSharp.Resources.Texture3D`1.Width"] = (3, 0),
["ComputeSharp.Resources.Texture3D`1.Height"] = (3, 1),
["ComputeSharp.Resources.Texture3D`1.Depth"] = (3, 2),
["ComputeSharp.IReadOnlyTexture2D`1.Width"] = (2, 0),
["ComputeSharp.IReadOnlyTexture2D`1.Height"] = (2, 1),
["ComputeSharp.IReadOnlyTexture3D`1.Width"] = (3, 0),
["ComputeSharp.IReadOnlyTexture3D`1.Height"] = (3, 1),
["ComputeSharp.IReadOnlyTexture3D`1.Depth"] = (3, 2),
["ComputeSharp.IReadWriteTexture2D`1.Width"] = (2, 0),
["ComputeSharp.IReadWriteTexture2D`1.Height"] = (2, 1),
["ComputeSharp.IReadWriteTexture3D`1.Width"] = (3, 0),
["ComputeSharp.IReadWriteTexture3D`1.Height"] = (3, 1),
["ComputeSharp.IReadWriteTexture3D`1.Depth"] = (3, 2)
};
char
row = (char)(item.Property.Name[1] - 1),
column = (char)(item.Property.Name[2] - 1);
/// <summary>
/// The mapping of supported known members to HLSL names.
/// </summary>
private static readonly IReadOnlyDictionary<string, string> KnownMembers = BuildKnownMembersMap();
knownMembers.Add($"{item.Type.FullName}{Type.Delimiter}{item.Property.Name}", $"_m{row}{column}");
}
/// <summary>
/// Builds the mapping of supported known members to HLSL names.
/// </summary>
[Pure]
private static IReadOnlyDictionary<string, string> BuildKnownMembersMap()
// Store GroupIds.Index for a quicker comparison afterwards
PropertyInfo groupindexProperty = typeof(GroupIds).GetProperty(nameof(GroupIds.Index), BindingFlags.Static | BindingFlags.Public);
// Programmatically load mappings for the dispatch types
foreach (var item in
from type in HlslKnownTypes.HlslDispatchTypes
from property in type.GetProperties(BindingFlags.Static | BindingFlags.Public)
select (Type: type, Property: property))
{
Dictionary<string, string> knownMembers = new()
if (item.Property == groupindexProperty)
{
[$"{typeof(Vector2).FullName}.{nameof(Vector2.X)}"] = "x",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Y)}"] = "y",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Zero)}"] = "(float2)0",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.One)}"] = "float2(1.0f, 1.0f)",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.UnitX)}"] = "float2(1.0f, 0.0f)",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.UnitY)}"] = "float2(0.0f, 1.0f)",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.X)}"] = "x",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Y)}"] = "y",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Z)}"] = "z",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Zero)}"] = "(float3)0",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.One)}"] = "float3(1.0f, 1.0f, 1.0f)",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.UnitX)}"] = "float3(1.0f, 0.0f, 0.0f)",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.UnitY)}"] = "float3(0.0f, 1.0f, 0.0f)",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.UnitZ)}"] = "float3(0.0f, 0.0f, 1.0f)",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.X)}"] = "x",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Y)}"] = "y",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Z)}"] = "z",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.W)}"] = "w",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Zero)}"] = "(float4)0",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.One)}"] = "float4(1.0f, 1.0f, 1.0f, 1.0f)",
[$"{typeof(Bool2).FullName}.{nameof(Bool2.False)}"] = "(bool2)0",
[$"{typeof(Bool2).FullName}.{nameof(Bool2.True)}"] = "bool2(true, true)",
[$"{typeof(Bool2).FullName}.{nameof(Bool2.TrueX)}"] = "bool2(true, false)",
[$"{typeof(Bool2).FullName}.{nameof(Bool2.TrueY)}"] = "bool2(false, true)",
[$"{typeof(Bool3).FullName}.{nameof(Bool3.False)}"] = "(bool3)0",
[$"{typeof(Bool3).FullName}.{nameof(Bool3.True)}"] = "bool3(true, true, true)",
[$"{typeof(Bool3).FullName}.{nameof(Bool3.TrueX)}"] = "bool3(true, false, false)",
[$"{typeof(Bool3).FullName}.{nameof(Bool3.TrueY)}"] = "bool3(false, true, false)",
[$"{typeof(Bool3).FullName}.{nameof(Bool3.TrueZ)}"] = "bool3(false, false, true)",
[$"{typeof(Bool4).FullName}.{nameof(Bool4.False)}"] = "(bool4)0",
[$"{typeof(Bool4).FullName}.{nameof(Bool4.True)}"] = "bool4(true, true, true, true)",
[$"{typeof(Bool4).FullName}.{nameof(Bool4.TrueX)}"] = "bool4(true, false, false, false)",
[$"{typeof(Bool4).FullName}.{nameof(Bool4.TrueY)}"] = "bool4(false, true, false, false)",
[$"{typeof(Bool4).FullName}.{nameof(Bool4.TrueZ)}"] = "bool4(false, false, true, false)",
[$"{typeof(Bool4).FullName}.{nameof(Bool4.TrueW)}"] = "bool4(false, false, false, true)",
[$"{typeof(Int2).FullName}.{nameof(Int2.Zero)}"] = "(int2)0",
[$"{typeof(Int2).FullName}.{nameof(Int2.One)}"] = "int2(1, 1)",
[$"{typeof(Int2).FullName}.{nameof(Int2.UnitX)}"] = "int2(1, 0)",
[$"{typeof(Int2).FullName}.{nameof(Int2.UnitY)}"] = "int2(0, 1)",
[$"{typeof(Int3).FullName}.{nameof(Int3.Zero)}"] = "(int3)0",
[$"{typeof(Int3).FullName}.{nameof(Int3.One)}"] = "int3(1, 1, 1)",
[$"{typeof(Int3).FullName}.{nameof(Int3.UnitX)}"] = "int3(1, 0, 0)",
[$"{typeof(Int3).FullName}.{nameof(Int3.UnitY)}"] = "int3(0, 1, 0)",
[$"{typeof(Int3).FullName}.{nameof(Int3.UnitZ)}"] = "int3(0, 0, 1)",
[$"{typeof(Int4).FullName}.{nameof(Int4.Zero)}"] = "(int4)0",
[$"{typeof(Int4).FullName}.{nameof(Int4.One)}"] = "int4(1, 1, 1, 1)",
[$"{typeof(Int4).FullName}.{nameof(Int4.UnitX)}"] = "int4(1, 0, 0, 0)",
[$"{typeof(Int4).FullName}.{nameof(Int4.UnitY)}"] = "int4(0, 1, 0, 0)",
[$"{typeof(Int4).FullName}.{nameof(Int4.UnitZ)}"] = "int4(0, 0, 1, 0)",
[$"{typeof(Int4).FullName}.{nameof(Int4.UnitW)}"] = "int4(0, 0, 0, 1)",
[$"{typeof(UInt2).FullName}.{nameof(UInt2.Zero)}"] = "(uint2)0",
[$"{typeof(UInt2).FullName}.{nameof(UInt2.One)}"] = "uint2(1u, 1u)",
[$"{typeof(UInt2).FullName}.{nameof(UInt2.UnitX)}"] = "uint2(1u, 0u)",
[$"{typeof(UInt2).FullName}.{nameof(UInt2.UnitY)}"] = "uint2(0u, 1u)",
[$"{typeof(UInt3).FullName}.{nameof(UInt3.Zero)}"] = "(uint3)0",
[$"{typeof(UInt3).FullName}.{nameof(UInt3.One)}"] = "uint3(1u, 1u, 1u)",
[$"{typeof(UInt3).FullName}.{nameof(UInt3.UnitX)}"] = "uint3(1u, 0u, 0u)",
[$"{typeof(UInt3).FullName}.{nameof(UInt3.UnitY)}"] = "uint3(0u, 1u, 0u)",
[$"{typeof(UInt3).FullName}.{nameof(UInt3.UnitZ)}"] = "uint3(0u, 0u, 1u)",
[$"{typeof(UInt4).FullName}.{nameof(UInt4.Zero)}"] = "(uint4)0",
[$"{typeof(UInt4).FullName}.{nameof(UInt4.One)}"] = "uint4(1u, 1u, 1u, 1u)",
[$"{typeof(UInt4).FullName}.{nameof(UInt4.UnitX)}"] = "uint4(1u, 0u, 0u, 0u)",
[$"{typeof(UInt4).FullName}.{nameof(UInt4.UnitY)}"] = "uint4(0u, 1u, 0u, 0u)",
[$"{typeof(UInt4).FullName}.{nameof(UInt4.UnitZ)}"] = "uint4(0u, 0u, 1u, 0u)",
[$"{typeof(UInt4).FullName}.{nameof(UInt4.UnitW)}"] = "uint4(0u, 0u, 0u, 1u)",
[$"{typeof(Float2).FullName}.{nameof(Float2.Zero)}"] = "(float2)0",
[$"{typeof(Float2).FullName}.{nameof(Float2.One)}"] = "float2(1.0f, 1.0f)",
[$"{typeof(Float2).FullName}.{nameof(Float2.UnitX)}"] = "float2(1.0f, 0.0f)",
[$"{typeof(Float2).FullName}.{nameof(Float2.UnitY)}"] = "float2(0.0f, 1.0f)",
[$"{typeof(Float3).FullName}.{nameof(Float3.Zero)}"] = "(float3)0",
[$"{typeof(Float3).FullName}.{nameof(Float3.One)}"] = "float3(1.0f, 1.0f, 1.0f)",
[$"{typeof(Float3).FullName}.{nameof(Float3.UnitX)}"] = "float3(1.0f, 0.0f, 0.0f)",
[$"{typeof(Float3).FullName}.{nameof(Float3.UnitY)}"] = "float3(0.0f, 1.0f, 0.0f)",
[$"{typeof(Float3).FullName}.{nameof(Float3.UnitZ)}"] = "float3(0.0f, 0.0f, 1.0f)",
[$"{typeof(Float4).FullName}.{nameof(Float4.Zero)}"] = "(float4)0",
[$"{typeof(Float4).FullName}.{nameof(Float4.One)}"] = "float4(1.0f, 1.0f, 1.0f, 1.0f)",
[$"{typeof(Float4).FullName}.{nameof(Float4.UnitX)}"] = "float4(1.0f, 0.0f, 0.0f, 0.0f)",
[$"{typeof(Float4).FullName}.{nameof(Float4.UnitY)}"] = "float4(0.0f, 1.0f, 0.0f, 0.0f)",
[$"{typeof(Float4).FullName}.{nameof(Float4.UnitZ)}"] = "float4(0.0f, 0.0f, 1.0f, 0.0f)",
[$"{typeof(Float4).FullName}.{nameof(Float4.UnitW)}"] = "float4(0.0f, 0.0f, 0.0f, 1.0f)",
[$"{typeof(Double2).FullName}.{nameof(Double2.Zero)}"] = "(double2)0",
[$"{typeof(Double2).FullName}.{nameof(Double2.One)}"] = "double2(1.0, 1.0)",
[$"{typeof(Double2).FullName}.{nameof(Double2.UnitX)}"] = "double2(1.0, 0.0)",
[$"{typeof(Double2).FullName}.{nameof(Double2.UnitY)}"] = "double2(0.0, 1.0)",
[$"{typeof(Double3).FullName}.{nameof(Double3.Zero)}"] = "(double3)0",
[$"{typeof(Double3).FullName}.{nameof(Double3.One)}"] = "double3(1.0, 1.0, 1.0)",
[$"{typeof(Double3).FullName}.{nameof(Double3.UnitX)}"] = "double3(1.0, 0.0, 0.0)",
[$"{typeof(Double3).FullName}.{nameof(Double3.UnitY)}"] = "double3(0.0, 1.0, 0.0)",
[$"{typeof(Double3).FullName}.{nameof(Double3.UnitZ)}"] = "double3(0.0, 0.0, 1.0)",
[$"{typeof(Double4).FullName}.{nameof(Double4.Zero)}"] = "(double4)0",
[$"{typeof(Double4).FullName}.{nameof(Double4.One)}"] = "double4(1.0, 1.0, 1.0, 1.0)",
[$"{typeof(Double4).FullName}.{nameof(Double4.UnitX)}"] = "double4(1.0, 0.0, 0.0, 0.0)",
[$"{typeof(Double4).FullName}.{nameof(Double4.UnitY)}"] = "double4(0.0, 1.0, 0.0, 0.0)",
[$"{typeof(Double4).FullName}.{nameof(Double4.UnitZ)}"] = "double4(0.0, 0.0, 1.0, 0.0)",
[$"{typeof(Double4).FullName}.{nameof(Double4.UnitW)}"] = "double4(0.0, 0.0, 0.0, 1.0)"
};
// Programmatically load mappings for the instance members of the HLSL vector types
foreach (var item in
from type in HlslKnownTypes.KnownVectorTypes
from property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public)
select (Type: type, Property: property))
{
knownMembers.Add($"{item.Type.FullName}{Type.Delimiter}{item.Property.Name}", $"{item.Property.Name.ToLower()}");
// The thread group index is a standalone parameter, so if this property is used, we
// just map the access directly to that implicit and hidden parameter name instead.
knownMembers.Add($"{item.Type.FullName}{Type.Delimiter}{item.Property.Name}", $"__{nameof(GroupIds)}__get_Index");
}
// Load mappings for the matrix properties as well
foreach (var item in
from type in HlslKnownTypes.KnownMatrixTypes
from property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public)
where Regex.IsMatch(property.Name, "^M[1-4]{2}$")
select (Type: type, Property: property))
else
{
char
row = (char)(item.Property.Name[1] - 1),
column = (char)(item.Property.Name[2] - 1);
knownMembers.Add($"{item.Type.FullName}{Type.Delimiter}{item.Property.Name}", $"_m{row}{column}");
knownMembers.Add($"{item.Type.FullName}{Type.Delimiter}{item.Property.Name}", $"{item.Type.Name}.{item.Property.Name.ToLower()}");
}
}
// Store GroupIds.Index for a quicker comparison afterwards
PropertyInfo groupindexProperty = typeof(GroupIds).GetProperty(nameof(GroupIds.Index), BindingFlags.Static | BindingFlags.Public);
// Programmatically load mappings for the normalized thread ids
foreach (var property in typeof(ThreadIds.Normalized).GetProperties(BindingFlags.Static | BindingFlags.Public))
{
string key = $"{typeof(ThreadIds).FullName}{Type.Delimiter}{typeof(ThreadIds.Normalized).Name}{Type.Delimiter}{property.Name}";
// Programmatically load mappings for the dispatch types
foreach (var item in
from type in HlslKnownTypes.HlslDispatchTypes
from property in type.GetProperties(BindingFlags.Static | BindingFlags.Public)
select (Type: type, Property: property))
switch (property.Name)
{
if (item.Property == groupindexProperty)
case string name when name.Length == 1:
knownMembers.Add(key, $"{typeof(ThreadIds).Name}.{char.ToLower(name[0])} / (float)__{char.ToLower(name[0])}");
break;
case string name when name.Length == 2:
{
// The thread group index is a standalone parameter, so if this property is used, we
// just map the access directly to that implicit and hidden parameter name instead.
knownMembers.Add($"{item.Type.FullName}{Type.Delimiter}{item.Property.Name}", $"__{nameof(GroupIds)}__get_Index");
string
numerator = $"float2({typeof(ThreadIds).Name}.{char.ToLower(name[0])}, {typeof(ThreadIds).Name}.{char.ToLower(name[1])})",
denominator = $"float2(__{char.ToLower(name[0])}, __{char.ToLower(name[1])})";
knownMembers.Add(key, $"{numerator} / {denominator}");
break;
}
else
case string name when name.Length == 3:
{
knownMembers.Add($"{item.Type.FullName}{Type.Delimiter}{item.Property.Name}", $"{item.Type.Name}.{item.Property.Name.ToLower()}");
string
numerator = $"float3({typeof(ThreadIds).Name}.{char.ToLower(name[0])}, {typeof(ThreadIds).Name}.{char.ToLower(name[1])}, {typeof(ThreadIds).Name}.{char.ToLower(name[2])})",
denominator = $"float3(__{char.ToLower(name[0])}, __{char.ToLower(name[1])}, __{char.ToLower(name[2])})";
knownMembers.Add(key, $"{numerator} / {denominator}");
break;
}
}
}
// Programmatically load mappings for the normalized thread ids
foreach (var property in typeof(ThreadIds.Normalized).GetProperties(BindingFlags.Static | BindingFlags.Public))
// Programmatically load mappings for the group size
foreach (var property in typeof(GroupSize).GetProperties(BindingFlags.Static | BindingFlags.Public))
{
string key = $"{typeof(GroupSize).FullName}{Type.Delimiter}{property.Name}";
switch (property.Name)
{
string key = $"{typeof(ThreadIds).FullName}{Type.Delimiter}{typeof(ThreadIds.Normalized).Name}{Type.Delimiter}{property.Name}";
switch (property.Name)
{
case string name when name.Length == 1:
knownMembers.Add(key, $"{typeof(ThreadIds).Name}.{char.ToLower(name[0])} / (float)__{char.ToLower(name[0])}");
break;
case string name when name.Length == 2:
{
string
numerator = $"float2({typeof(ThreadIds).Name}.{char.ToLower(name[0])}, {typeof(ThreadIds).Name}.{char.ToLower(name[1])})",
denominator = $"float2(__{char.ToLower(name[0])}, __{char.ToLower(name[1])})";
knownMembers.Add(key, $"{numerator} / {denominator}");
break;
}
case string name when name.Length == 3:
{
string
numerator = $"float3({typeof(ThreadIds).Name}.{char.ToLower(name[0])}, {typeof(ThreadIds).Name}.{char.ToLower(name[1])}, {typeof(ThreadIds).Name}.{char.ToLower(name[2])})",
denominator = $"float3(__{char.ToLower(name[0])}, __{char.ToLower(name[1])}, __{char.ToLower(name[2])})";
knownMembers.Add(key, $"{numerator} / {denominator}");
break;
}
}
case nameof(GroupSize.Count):
knownMembers.Add(key, "__GroupSize__get_X * __GroupSize__get_Y * __GroupSize__get_Z");
break;
case string name when name.Length == 1:
knownMembers.Add(key, $"__GroupSize__get_{name}");
break;
case string name when name.Length == 2:
knownMembers.Add(key, $"int2(__GroupSize__get_{name[0]}, __GroupSize__get_{name[1]})");
break;
case string name when name.Length == 3:
knownMembers.Add(key, $"int3(__GroupSize__get_{name[0]}, __GroupSize__get_{name[1]}, __GroupSize__get_{name[2]})");
break;
}
}
// Programmatically load mappings for the group size
foreach (var property in typeof(GroupSize).GetProperties(BindingFlags.Static | BindingFlags.Public))
// Programmatically load mappings for the dispatch size
foreach (var property in typeof(DispatchSize).GetProperties(BindingFlags.Static | BindingFlags.Public))
{
string key = $"{typeof(DispatchSize).FullName}{Type.Delimiter}{property.Name}";
switch (property.Name)
{
string key = $"{typeof(GroupSize).FullName}{Type.Delimiter}{property.Name}";
switch (property.Name)
{
case nameof(GroupSize.Count):
knownMembers.Add(key, "__GroupSize__get_X * __GroupSize__get_Y * __GroupSize__get_Z");
break;
case string name when name.Length == 1:
knownMembers.Add(key, $"__GroupSize__get_{name}");
break;
case string name when name.Length == 2:
knownMembers.Add(key, $"int2(__GroupSize__get_{name[0]}, __GroupSize__get_{name[1]})");
break;
case string name when name.Length == 3:
knownMembers.Add(key, $"int3(__GroupSize__get_{name[0]}, __GroupSize__get_{name[1]}, __GroupSize__get_{name[2]})");
break;
}
case nameof(DispatchSize.Count):
knownMembers.Add(key, "__x * __y * __z");
break;
case string name when name.Length == 1:
knownMembers.Add(key, $"__{char.ToLower(name[0])}");
break;
case string name when name.Length == 2:
knownMembers.Add(key, $"int2(__{char.ToLower(name[0])}, __{char.ToLower(name[1])})");
break;
case string name when name.Length == 3:
knownMembers.Add(key, $"int3(__{char.ToLower(name[0])}, __{char.ToLower(name[1])}, __{char.ToLower(name[2])})");
break;
}
// Programmatically load mappings for the dispatch size
foreach (var property in typeof(DispatchSize).GetProperties(BindingFlags.Static | BindingFlags.Public))
{
string key = $"{typeof(DispatchSize).FullName}{Type.Delimiter}{property.Name}";
switch (property.Name)
{
case nameof(DispatchSize.Count):
knownMembers.Add(key, "__x * __y * __z");
break;
case string name when name.Length == 1:
knownMembers.Add(key, $"__{char.ToLower(name[0])}");
break;
case string name when name.Length == 2:
knownMembers.Add(key, $"int2(__{char.ToLower(name[0])}, __{char.ToLower(name[1])})");
break;
case string name when name.Length == 3:
knownMembers.Add(key, $"int3(__{char.ToLower(name[0])}, __{char.ToLower(name[1])}, __{char.ToLower(name[2])})");
break;
}
}
return knownMembers;
}
/// <summary>
/// The mapping of supported known members to HLSL names.
/// </summary>
private static readonly IReadOnlyCollection<string> KnownMatrixIndexers = BuildKnownMatrixIndexers();
return knownMembers;
}
/// <summary>
/// Builds the mapping of swizzled matrix indexer properties.
/// </summary>
[Pure]
private static IReadOnlyCollection<string> BuildKnownMatrixIndexers()
/// <summary>
/// The mapping of supported known members to HLSL names.
/// </summary>
private static readonly IReadOnlyCollection<string> KnownMatrixIndexers = BuildKnownMatrixIndexers();
/// <summary>
/// Builds the mapping of swizzled matrix indexer properties.
/// </summary>
[Pure]
private static IReadOnlyCollection<string> BuildKnownMatrixIndexers()
{
return (
from type in Assembly.GetExecutingAssembly().ExportedTypes
where Regex.IsMatch(type.FullName, @"ComputeSharp\.(Bool|Double|Float|Int|UInt)[1-4]x[1-4]")
from property in type.GetProperties()
let indices = property.GetIndexParameters()
where indices.Length > 0 &&
indices.All(static index => index.ParameterType == typeof(MatrixIndex))
let metadataName = $"{type.FullName}.this[{string.Join(", ", indices.Select(index => index.ParameterType))}]"
select metadataName).ToImmutableHashSet();
}
/// <summary>
/// The mapping of supported known members to HLSL names.
/// </summary>
private static readonly IReadOnlyCollection<string> KnownMatrixIndices = BuildKnownMatrixIndices();
/// <summary>
/// Builds the mapping of swizzled matrix indices.
/// </summary>
[Pure]
private static IReadOnlyCollection<string> BuildKnownMatrixIndices()
{
return (
from name in Enum.GetNames(typeof(MatrixIndex))
select $"{typeof(MatrixIndex).FullName}.{name}").ToImmutableHashSet();
}
/// <summary>
/// Checks whether or not a given property fullname matches a matrix swizzled indexer.
/// </summary>
/// <param name="name">The input fully qualified member name.</param>
/// <returns>Whether or not <paramref name="name"/> is a matrix swizzled indexer.</returns>
[Pure]
public static bool IsKnownMatrixIndexer(string name)
{
return KnownMatrixIndexers.Contains(name);
}
/// <summary>
/// Checks whether or not a given property fullname matches a matrix swizzled index.
/// </summary>
/// <param name="name">The input fully qualified member name.</param>
/// <returns>Whether or not <paramref name="name"/> is a matrix swizzled index.</returns>
[Pure]
public static bool IsKnownMatrixIndex(string name)
{
return KnownMatrixIndices.Contains(name);
}
/// <summary>
/// Tries to get the mapped HLSL-compatible member name for the input member name.
/// </summary>
/// <param name="name">The input fully qualified member name.</param>
/// <param name="mapped">The mapped name, if one is found.</param>
/// <returns>The HLSL-compatible member name that can be used in an HLSL shader.</returns>
[Pure]
public static bool TryGetMappedName(string name, out string? mapped)
{
return KnownMembers.TryGetValue(name, out mapped);
}
/// <summary>
/// Tries to get the mapped HLSL-compatible indexer resource type name for the input indexer name.
/// </summary>
/// <param name="name">The input fully qualified indexer name.</param>
/// <param name="mapped">The mapped type name, if one is found.</param>
/// <returns>The HLSL-compatible type name that can be used in an HLSL shader for the given indexer.</returns>
[Pure]
public static bool TryGetMappedResourceIndexerTypeName(string name, out string? mapped)
{
return KnownResourceIndexers.TryGetValue(name, out mapped);
}
/// <summary>
/// Tries to get the mapped HLSL-compatible sampler resource type name for the input indexer name.
/// </summary>
/// <param name="name">The input fully qualified indexer name.</param>
/// <param name="mapped">The mapped type name, if one is found.</param>
/// <returns>The HLSL-compatible type name that can be used in an HLSL shader for the given sampler.</returns>
[Pure]
public static bool TryGetMappedResourceSamplerAccessType(string name, out string? mapped)
{
return KnownResourceSamplers.TryGetValue(name, out mapped);
}
/// <summary>
/// Tries to get the mapped HLSL-compatible indexer vector type name for the input indexer name.
/// </summary>
/// <param name="name">The input fully qualified indexer name.</param>
/// <param name="mapped">The mapped type name, if one is found.</param>
/// <returns>The HLSL-compatible type name that can be used in an HLSL shader for the given indexer.</returns>
[Pure]
public static bool TryGetAccessorRankAndAxis(string name, out int rank, out int axis)
{
if (KnownSizeAccessors.TryGetValue(name, out var info))
{
return (
from type in Assembly.GetExecutingAssembly().ExportedTypes
where Regex.IsMatch(type.FullName, @"ComputeSharp\.(Bool|Double|Float|Int|UInt)[1-4]x[1-4]")
from property in type.GetProperties()
let indices = property.GetIndexParameters()
where indices.Length > 0 &&
indices.All(static index => index.ParameterType == typeof(MatrixIndex))
let metadataName = $"{type.FullName}.this[{string.Join(", ", indices.Select(index => index.ParameterType))}]"
select metadataName).ToImmutableHashSet();
(rank, axis) = info;
return true;
}
/// <summary>
/// The mapping of supported known members to HLSL names.
/// </summary>
private static readonly IReadOnlyCollection<string> KnownMatrixIndices = BuildKnownMatrixIndices();
(rank, axis) = default((int, int));
/// <summary>
/// Builds the mapping of swizzled matrix indices.
/// </summary>
[Pure]
private static IReadOnlyCollection<string> BuildKnownMatrixIndices()
{
return (
from name in Enum.GetNames(typeof(MatrixIndex))
select $"{typeof(MatrixIndex).FullName}.{name}").ToImmutableHashSet();
}
/// <summary>
/// Checks whether or not a given property fullname matches a matrix swizzled indexer.
/// </summary>
/// <param name="name">The input fully qualified member name.</param>
/// <returns>Whether or not <paramref name="name"/> is a matrix swizzled indexer.</returns>
[Pure]
public static bool IsKnownMatrixIndexer(string name)
{
return KnownMatrixIndexers.Contains(name);
}
/// <summary>
/// Checks whether or not a given property fullname matches a matrix swizzled index.
/// </summary>
/// <param name="name">The input fully qualified member name.</param>
/// <returns>Whether or not <paramref name="name"/> is a matrix swizzled index.</returns>
[Pure]
public static bool IsKnownMatrixIndex(string name)
{
return KnownMatrixIndices.Contains(name);
}
/// <summary>
/// Tries to get the mapped HLSL-compatible member name for the input member name.
/// </summary>
/// <param name="name">The input fully qualified member name.</param>
/// <param name="mapped">The mapped name, if one is found.</param>
/// <returns>The HLSL-compatible member name that can be used in an HLSL shader.</returns>
[Pure]
public static bool TryGetMappedName(string name, out string? mapped)
{
return KnownMembers.TryGetValue(name, out mapped);
}
/// <summary>
/// Tries to get the mapped HLSL-compatible indexer resource type name for the input indexer name.
/// </summary>
/// <param name="name">The input fully qualified indexer name.</param>
/// <param name="mapped">The mapped type name, if one is found.</param>
/// <returns>The HLSL-compatible type name that can be used in an HLSL shader for the given indexer.</returns>
[Pure]
public static bool TryGetMappedResourceIndexerTypeName(string name, out string? mapped)
{
return KnownResourceIndexers.TryGetValue(name, out mapped);
}
/// <summary>
/// Tries to get the mapped HLSL-compatible sampler resource type name for the input indexer name.
/// </summary>
/// <param name="name">The input fully qualified indexer name.</param>
/// <param name="mapped">The mapped type name, if one is found.</param>
/// <returns>The HLSL-compatible type name that can be used in an HLSL shader for the given sampler.</returns>
[Pure]
public static bool TryGetMappedResourceSamplerAccessType(string name, out string? mapped)
{
return KnownResourceSamplers.TryGetValue(name, out mapped);
}
/// <summary>
/// Tries to get the mapped HLSL-compatible indexer vector type name for the input indexer name.
/// </summary>
/// <param name="name">The input fully qualified indexer name.</param>
/// <param name="mapped">The mapped type name, if one is found.</param>
/// <returns>The HLSL-compatible type name that can be used in an HLSL shader for the given indexer.</returns>
[Pure]
public static bool TryGetAccessorRankAndAxis(string name, out int rank, out int axis)
{
if (KnownSizeAccessors.TryGetValue(name, out var info))
{
(rank, axis) = info;
return true;
}
(rank, axis) = default((int, int));
return false;
}
return false;
}
}
+132 -133
ファイルの表示
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
@@ -6,152 +6,151 @@ using System.Numerics;
using System.Reflection;
using ComputeSharp.Core.Intrinsics.Attributes;
namespace ComputeSharp.SourceGenerators.Mappings
namespace ComputeSharp.SourceGenerators.Mappings;
/// <summary>
/// A <see langword="class"/> that contains and maps known HLSL method names to common .NET methods.
/// </summary>
internal static class HlslKnownMethods
{
/// <summary>
/// A <see langword="class"/> that contains and maps known HLSL method names to common .NET methods.
/// The mapping of supported known methods to HLSL names.
/// </summary>
internal static class HlslKnownMethods
private static readonly IReadOnlyDictionary<string, string> KnownMethods = BuildKnownMethodsMap();
/// <summary>
/// Builds the mapping of supported known methods to HLSL names.
/// </summary>
[Pure]
private static IReadOnlyDictionary<string, string> BuildKnownMethodsMap()
{
/// <summary>
/// The mapping of supported known methods to HLSL names.
/// </summary>
private static readonly IReadOnlyDictionary<string, string> KnownMethods = BuildKnownMethodsMap();
/// <summary>
/// Builds the mapping of supported known methods to HLSL names.
/// </summary>
[Pure]
private static IReadOnlyDictionary<string, string> BuildKnownMethodsMap()
Dictionary<string, string> knownMethods = new()
{
Dictionary<string, string> knownMethods = new()
{
[$"{typeof(Math).FullName}.{nameof(Math.Abs)}"] = "abs",
[$"{typeof(Math).FullName}.{nameof(Math.Max)}"] = "max",
[$"{typeof(Math).FullName}.{nameof(Math.Min)}"] = "min",
[$"{typeof(Math).FullName}.{nameof(Math.Pow)}"] = "pow",
[$"{typeof(Math).FullName}.{nameof(Math.Sin)}"] = "sin",
[$"{typeof(Math).FullName}.{nameof(Math.Sinh)}"] = "sinh",
[$"{typeof(Math).FullName}.{nameof(Math.Asin)}"] = "asin",
[$"{typeof(Math).FullName}.{nameof(Math.Cos)}"] = "cos",
[$"{typeof(Math).FullName}.{nameof(Math.Cosh)}"] = "cosh",
[$"{typeof(Math).FullName}.{nameof(Math.Acos)}"] = "acos",
[$"{typeof(Math).FullName}.{nameof(Math.Tan)}"] = "tan",
[$"{typeof(Math).FullName}.{nameof(Math.Tanh)}"] = "tanh",
[$"{typeof(Math).FullName}.{nameof(Math.Atan)}"] = "atan",
[$"{typeof(Math).FullName}.{nameof(Math.Atan2)}"] = "atan2",
[$"{typeof(Math).FullName}.{nameof(Math.Ceiling)}"] = "ceil",
[$"{typeof(Math).FullName}.{nameof(Math.Floor)}"] = "floor",
[$"{typeof(Math).FullName}.Clamp"] = "clamp",
[$"{typeof(Math).FullName}.{nameof(Math.Exp)}"] = "exp",
[$"{typeof(Math).FullName}.{nameof(Math.Log)}"] = "log",
[$"{typeof(Math).FullName}.{nameof(Math.Log10)}"] = "log10",
[$"{typeof(Math).FullName}.{nameof(Math.Max)}"] = "max",
[$"{typeof(Math).FullName}.{nameof(Math.Min)}"] = "min",
[$"{typeof(Math).FullName}.{nameof(Math.Round)}"] = "round",
[$"{typeof(Math).FullName}.{nameof(Math.Sqrt)}"] = "sqrt",
[$"{typeof(Math).FullName}.{nameof(Math.Sign)}"] = "sign",
[$"{typeof(Math).FullName}.{nameof(Math.Truncate)}"] = "trunc",
[$"{typeof(Math).FullName}.{nameof(Math.Abs)}"] = "abs",
[$"{typeof(Math).FullName}.{nameof(Math.Max)}"] = "max",
[$"{typeof(Math).FullName}.{nameof(Math.Min)}"] = "min",
[$"{typeof(Math).FullName}.{nameof(Math.Pow)}"] = "pow",
[$"{typeof(Math).FullName}.{nameof(Math.Sin)}"] = "sin",
[$"{typeof(Math).FullName}.{nameof(Math.Sinh)}"] = "sinh",
[$"{typeof(Math).FullName}.{nameof(Math.Asin)}"] = "asin",
[$"{typeof(Math).FullName}.{nameof(Math.Cos)}"] = "cos",
[$"{typeof(Math).FullName}.{nameof(Math.Cosh)}"] = "cosh",
[$"{typeof(Math).FullName}.{nameof(Math.Acos)}"] = "acos",
[$"{typeof(Math).FullName}.{nameof(Math.Tan)}"] = "tan",
[$"{typeof(Math).FullName}.{nameof(Math.Tanh)}"] = "tanh",
[$"{typeof(Math).FullName}.{nameof(Math.Atan)}"] = "atan",
[$"{typeof(Math).FullName}.{nameof(Math.Atan2)}"] = "atan2",
[$"{typeof(Math).FullName}.{nameof(Math.Ceiling)}"] = "ceil",
[$"{typeof(Math).FullName}.{nameof(Math.Floor)}"] = "floor",
[$"{typeof(Math).FullName}.Clamp"] = "clamp",
[$"{typeof(Math).FullName}.{nameof(Math.Exp)}"] = "exp",
[$"{typeof(Math).FullName}.{nameof(Math.Log)}"] = "log",
[$"{typeof(Math).FullName}.{nameof(Math.Log10)}"] = "log10",
[$"{typeof(Math).FullName}.{nameof(Math.Max)}"] = "max",
[$"{typeof(Math).FullName}.{nameof(Math.Min)}"] = "min",
[$"{typeof(Math).FullName}.{nameof(Math.Round)}"] = "round",
[$"{typeof(Math).FullName}.{nameof(Math.Sqrt)}"] = "sqrt",
[$"{typeof(Math).FullName}.{nameof(Math.Sign)}"] = "sign",
[$"{typeof(Math).FullName}.{nameof(Math.Truncate)}"] = "trunc",
["System.MathF.Abs"] = "abs",
["System.MathF.Max"] = "max",
["System.MathF.Min"] = "min",
["System.MathF.Pow"] = "pow",
["System.MathF.Sin"] = "sin",
["System.MathF.Sinh"] = "sinh",
["System.MathF.Asin"] = "asin",
["System.MathF.Cos"] = "cos",
["System.MathF.Cosh"] = "cosh",
["System.MathF.Acos"] = "acos",
["System.MathF.Tan"] = "tan",
["System.MathF.Tanh"] = "tanh",
["System.MathF.Atan"] = "atan",
["System.MathF.Atan2"] = "atan2",
["System.MathF.Ceiling"] = "ceil",
["System.MathF.Floor"] = "floor",
["System.MathF.Clamp"] = "clamp",
["System.MathF.Exp"] = "exp",
["System.MathF.Log"] = "log",
["System.MathF.Log10"] = "log10",
["System.MathF.Max"] = "max",
["System.MathF.Min"] = "min",
["System.MathF.Round"] = "round",
["System.MathF.Sqrt"] = "sqrt",
["System.MathF.Sign"] = "sign",
["System.MathF.Truncate"] = "trunc",
["System.MathF.Abs"] = "abs",
["System.MathF.Max"] = "max",
["System.MathF.Min"] = "min",
["System.MathF.Pow"] = "pow",
["System.MathF.Sin"] = "sin",
["System.MathF.Sinh"] = "sinh",
["System.MathF.Asin"] = "asin",
["System.MathF.Cos"] = "cos",
["System.MathF.Cosh"] = "cosh",
["System.MathF.Acos"] = "acos",
["System.MathF.Tan"] = "tan",
["System.MathF.Tanh"] = "tanh",
["System.MathF.Atan"] = "atan",
["System.MathF.Atan2"] = "atan2",
["System.MathF.Ceiling"] = "ceil",
["System.MathF.Floor"] = "floor",
["System.MathF.Clamp"] = "clamp",
["System.MathF.Exp"] = "exp",
["System.MathF.Log"] = "log",
["System.MathF.Log10"] = "log10",
["System.MathF.Max"] = "max",
["System.MathF.Min"] = "min",
["System.MathF.Round"] = "round",
["System.MathF.Sqrt"] = "sqrt",
["System.MathF.Sign"] = "sign",
["System.MathF.Truncate"] = "trunc",
[$"{typeof(float).FullName}.IsFinite"] = "isfinite",
[$"{typeof(float).FullName}.{nameof(float.IsInfinity)}"] = "isinf",
[$"{typeof(float).FullName}.{nameof(float.IsNaN)}"] = "isnan",
[$"{typeof(float).FullName}.IsFinite"] = "isfinite",
[$"{typeof(float).FullName}.{nameof(float.IsInfinity)}"] = "isinf",
[$"{typeof(float).FullName}.{nameof(float.IsNaN)}"] = "isnan",
[$"{typeof(double).FullName}.IsFinite"] = "isfinite",
[$"{typeof(double).FullName}.{nameof(double.IsInfinity)}"] = "isinf",
[$"{typeof(double).FullName}.{nameof(double.IsNaN)}"] = "isnan",
[$"{typeof(double).FullName}.IsFinite"] = "isfinite",
[$"{typeof(double).FullName}.{nameof(double.IsInfinity)}"] = "isinf",
[$"{typeof(double).FullName}.{nameof(double.IsNaN)}"] = "isnan",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Abs)}"] = "abs",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Clamp)}"] = "clamp",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Distance)}"] = "distance",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Dot)}"] = "dot",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Lerp)}"] = "lerp",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Max)}"] = "max",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Min)}"] = "min",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Reflect)}"] = "reflect",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Transform)}"] = "mul",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.TransformNormal)}"] = "mul",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Normalize)}"] = "normalize",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Abs)}"] = "abs",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Clamp)}"] = "clamp",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Distance)}"] = "distance",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Dot)}"] = "dot",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Lerp)}"] = "lerp",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Max)}"] = "max",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Min)}"] = "min",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Reflect)}"] = "reflect",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Transform)}"] = "mul",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.TransformNormal)}"] = "mul",
[$"{typeof(Vector2).FullName}.{nameof(Vector2.Normalize)}"] = "normalize",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Abs)}"] = "abs",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Clamp)}"] = "clamp",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Cross)}"] = "cross",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Distance)}"] = "distance",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Dot)}"] = "dot",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Lerp)}"] = "lerp",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Max)}"] = "max",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Min)}"] = "min",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Reflect)}"] = "reflect",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Transform)}"] = "mul",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.TransformNormal)}"] = "mul",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Normalize)}"] = "normalize",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Abs)}"] = "abs",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Clamp)}"] = "clamp",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Cross)}"] = "cross",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Distance)}"] = "distance",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Dot)}"] = "dot",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Lerp)}"] = "lerp",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Max)}"] = "max",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Min)}"] = "min",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Reflect)}"] = "reflect",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Transform)}"] = "mul",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.TransformNormal)}"] = "mul",
[$"{typeof(Vector3).FullName}.{nameof(Vector3.Normalize)}"] = "normalize",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Abs)}"] = "abs",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Clamp)}"] = "clamp",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Distance)}"] = "distance",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Dot)}"] = "dot",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Lerp)}"] = "lerp",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Max)}"] = "max",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Min)}"] = "min",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Transform)}"] = "mul",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Normalize)}"] = "normalize"
};
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Abs)}"] = "abs",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Clamp)}"] = "clamp",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Distance)}"] = "distance",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Dot)}"] = "dot",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Lerp)}"] = "lerp",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Max)}"] = "max",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Min)}"] = "min",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Transform)}"] = "mul",
[$"{typeof(Vector4).FullName}.{nameof(Vector4.Normalize)}"] = "normalize"
};
// Programmatically load mappings from the Hlsl class as well
foreach (var method in
from method in typeof(Hlsl).GetMethods(BindingFlags.Public | BindingFlags.Static)
group method by method.Name
into groups
select groups.First())
{
// Check whether the current method should be translated with the original name
// or with the lowercase version. This is needed because all C# methods are exposed
// with the upper camel case format, while HLSL intrinsics use multiple different formats.
string hlslName = method.GetCustomAttribute<HlslIntrinsicNameAttribute>()?.Name ?? method.Name;
// Programmatically load mappings from the Hlsl class as well
foreach (var method in
from method in typeof(Hlsl).GetMethods(BindingFlags.Public | BindingFlags.Static)
group method by method.Name
into groups
select groups.First())
{
// Check whether the current method should be translated with the original name
// or with the lowercase version. This is needed because all C# methods are exposed
// with the upper camel case format, while HLSL intrinsics use multiple different formats.
string hlslName = method.GetCustomAttribute<HlslIntrinsicNameAttribute>()?.Name ?? method.Name;
knownMethods.Add($"{typeof(Hlsl).FullName}{Type.Delimiter}{method.Name}", hlslName);
}
return knownMethods;
knownMethods.Add($"{typeof(Hlsl).FullName}{Type.Delimiter}{method.Name}", hlslName);
}
/// <summary>
/// Tries to get the mapped HLSL-compatible method name for the input method name.
/// </summary>
/// <param name="name">The input fully qualified method name.</param>
/// <param name="mapped">The mapped name, if one is found.</param>
/// <returns>The HLSL-compatible member name that can be used in an HLSL shader.</returns>
[Pure]
public static bool TryGetMappedName(string name, out string? mapped)
{
return KnownMethods.TryGetValue(name, out mapped);
}
return knownMethods;
}
/// <summary>
/// Tries to get the mapped HLSL-compatible method name for the input method name.
/// </summary>
/// <param name="name">The input fully qualified method name.</param>
/// <param name="mapped">The mapped name, if one is found.</param>
/// <returns>The HLSL-compatible member name that can be used in an HLSL shader.</returns>
[Pure]
public static bool TryGetMappedName(string name, out string? mapped)
{
return KnownMethods.TryGetValue(name, out mapped);
}
}
+43 -44
ファイルの表示
@@ -5,58 +5,57 @@ using System.Numerics;
using System.Reflection;
using System.Text.RegularExpressions;
namespace ComputeSharp.SourceGenerators.Mappings
namespace ComputeSharp.SourceGenerators.Mappings;
/// <summary>
/// A <see langword="class"/> that contains and maps known HLSL types to their alignment sizes.
/// </summary>
internal static class HlslKnownSizes
{
/// <summary>
/// A <see langword="class"/> that contains and maps known HLSL types to their alignment sizes.
/// The mapping of supported known sizes to HLSL type names.
/// </summary>
internal static class HlslKnownSizes
private static IReadOnlyDictionary<string, (int, int)> KnownSizes = BuildKnownSizesMap();
/// <summary>
/// Builds the mapping of known type sizes and alignments.
/// </summary>
[Pure]
private static IReadOnlyDictionary<string, (int, int)> BuildKnownSizesMap()
{
/// <summary>
/// The mapping of supported known sizes to HLSL type names.
/// </summary>
private static IReadOnlyDictionary<string, (int, int)> KnownSizes = BuildKnownSizesMap();
/// <summary>
/// Builds the mapping of known type sizes and alignments.
/// </summary>
[Pure]
private static IReadOnlyDictionary<string, (int, int)> BuildKnownSizesMap()
Dictionary<string, (int, int)> knownSizes = new()
{
Dictionary<string, (int, int)> knownSizes = new()
{
[typeof(bool).FullName] = (4, 4),
[typeof(int).FullName] = (4, 4),
[typeof(uint).FullName] = (4, 4),
[typeof(float).FullName] = (4, 4),
[typeof(double).FullName] = (8, 8),
[typeof(bool).FullName] = (4, 4),
[typeof(int).FullName] = (4, 4),
[typeof(uint).FullName] = (4, 4),
[typeof(float).FullName] = (4, 4),
[typeof(double).FullName] = (8, 8),
[typeof(Vector2).FullName] = (8, 4),
[typeof(Vector3).FullName] = (12, 4),
[typeof(Vector4).FullName] = (16, 4)
};
[typeof(Vector2).FullName] = (8, 4),
[typeof(Vector3).FullName] = (12, 4),
[typeof(Vector4).FullName] = (16, 4)
};
foreach (
var type in
from type in Assembly.GetExecutingAssembly().ExportedTypes
where Regex.IsMatch(type.FullName, @"^ComputeSharp\.(Bool|Double|Float|Int|UInt)")
select type)
{
knownSizes.Add(type.FullName, (type.StructLayoutAttribute.Size, type.StructLayoutAttribute.Pack));
}
return knownSizes;
foreach (
var type in
from type in Assembly.GetExecutingAssembly().ExportedTypes
where Regex.IsMatch(type.FullName, @"^ComputeSharp\.(Bool|Double|Float|Int|UInt)")
select type)
{
knownSizes.Add(type.FullName, (type.StructLayoutAttribute.Size, type.StructLayoutAttribute.Pack));
}
/// <summary>
/// Gets the size and alignment info for a specified primitive type.
/// </summary>
/// <param name="typeName">The type name to get info for.</param>
/// <returns>The size and and alignment for the input type.</returns>
[Pure]
public static (int Size, int Pack) GetTypeInfo(string typeName)
{
return KnownSizes[typeName];
}
return knownSizes;
}
/// <summary>
/// Gets the size and alignment info for a specified primitive type.
/// </summary>
/// <param name="typeName">The type name to get info for.</param>
/// <returns>The size and and alignment for the input type.</returns>
[Pure]
public static (int Size, int Pack) GetTypeInfo(string typeName)
{
return KnownSizes[typeName];
}
}
+364 -365
ファイルの表示
@@ -9,301 +9,253 @@ using Microsoft.CodeAnalysis;
#pragma warning disable RS1024
namespace ComputeSharp.SourceGenerators.Mappings
namespace ComputeSharp.SourceGenerators.Mappings;
/// <summary>
/// A <see langword="class"/> that contains and maps known HLSL type names to common .NET types.
/// </summary>
internal static class HlslKnownTypes
{
/// <summary>
/// A <see langword="class"/> that contains and maps known HLSL type names to common .NET types.
/// Gets the known HLSL dispatch types.
/// </summary>
internal static class HlslKnownTypes
public static IReadOnlyCollection<Type> HlslDispatchTypes { get; } = new[]
{
/// <summary>
/// Gets the known HLSL dispatch types.
/// </summary>
public static IReadOnlyCollection<Type> HlslDispatchTypes { get; } = new[]
typeof(ThreadIds),
typeof(GroupIds),
typeof(GridIds)
};
/// <summary>
/// Gets the set of HLSL vector types.
/// </summary>
public static IReadOnlyCollection<Type> KnownVectorTypes { get; } = new[]
{
typeof(Bool2), typeof(Bool3), typeof(Bool4),
typeof(Int2), typeof(Int3), typeof(Int4),
typeof(UInt2), typeof(UInt3), typeof(UInt4),
typeof(Float2), typeof(Float3), typeof(Float4),
typeof(Double2), typeof(Double3), typeof(Double4)
};
/// <summary>
/// Gets the set of HLSL matrix types.
/// </summary>
public static IReadOnlyCollection<Type> KnownMatrixTypes { get; } = new[]
{
typeof(Bool1x1), typeof(Bool1x2), typeof(Bool1x3), typeof(Bool1x4),
typeof(Bool2x1), typeof(Bool2x2), typeof(Bool2x3), typeof(Bool2x4),
typeof(Bool3x1), typeof(Bool3x2), typeof(Bool3x3), typeof(Bool3x4),
typeof(Bool4x1), typeof(Bool4x2), typeof(Bool4x3), typeof(Bool4x4),
typeof(Int1x1), typeof(Int1x2), typeof(Int1x3), typeof(Int1x4),
typeof(Int2x1), typeof(Int2x2), typeof(Int2x3), typeof(Int2x4),
typeof(Int3x1), typeof(Int3x2), typeof(Int3x3), typeof(Int3x4),
typeof(Int4x1), typeof(Int4x2), typeof(Int4x3), typeof(Int4x4),
typeof(UInt1x1), typeof(UInt1x2), typeof(UInt1x3), typeof(UInt1x4),
typeof(UInt2x1), typeof(UInt2x2), typeof(UInt2x3), typeof(UInt2x4),
typeof(UInt3x1), typeof(UInt3x2), typeof(UInt3x3), typeof(UInt3x4),
typeof(UInt4x1), typeof(UInt4x2), typeof(UInt4x3), typeof(UInt4x4),
typeof(Float1x1), typeof(Float1x2), typeof(Float1x3), typeof(Float1x4),
typeof(Float2x1), typeof(Float2x2), typeof(Float2x3), typeof(Float2x4),
typeof(Float3x1), typeof(Float3x2), typeof(Float3x3), typeof(Float3x4),
typeof(Float4x1), typeof(Float4x2), typeof(Float4x3), typeof(Float4x4),
typeof(Double1x1), typeof(Double1x2), typeof(Double1x3), typeof(Double1x4),
typeof(Double2x1), typeof(Double2x2), typeof(Double2x3), typeof(Double2x4),
typeof(Double3x1), typeof(Double3x2), typeof(Double3x3), typeof(Double3x4),
typeof(Double4x1), typeof(Double4x2), typeof(Double4x3), typeof(Double4x4)
};
/// <summary>
/// The mapping of supported known types to HLSL types.
/// </summary>
private static readonly IReadOnlyDictionary<string, string> KnownHlslTypes = BuildKnownHlslTypes();
/// <summary>
/// Builds the mapping of known primitive types.
/// </summary>
[Pure]
private static IReadOnlyDictionary<string, string> BuildKnownHlslTypes()
{
Dictionary<string, string> knownTypes = new()
{
typeof(ThreadIds),
typeof(GroupIds),
typeof(GridIds)
[typeof(bool).FullName] = "bool",
[typeof(int).FullName] = "int",
[typeof(uint).FullName] = "uint",
[typeof(float).FullName] = "float",
[typeof(Vector2).FullName] = "float2",
[typeof(Vector3).FullName] = "float3",
[typeof(Vector4).FullName] = "float4",
[typeof(double).FullName] = "double"
};
/// <summary>
/// Gets the set of HLSL vector types.
/// </summary>
public static IReadOnlyCollection<Type> KnownVectorTypes { get; } = new[]
// Add all the vector types
foreach (var type in KnownVectorTypes)
{
typeof(Bool2), typeof(Bool3), typeof(Bool4),
typeof(Int2), typeof(Int3), typeof(Int4),
typeof(UInt2), typeof(UInt3), typeof(UInt4),
typeof(Float2), typeof(Float3), typeof(Float4),
typeof(Double2), typeof(Double3), typeof(Double4)
knownTypes.Add(type.FullName, type.Name.ToLower());
}
// Add all the matrix types
foreach (var type in KnownMatrixTypes)
{
knownTypes.Add(type.FullName, type.Name.ToLower());
}
return knownTypes;
}
/// <summary>
/// Checks whether or not a given type name matches a constant buffer type.
/// </summary>
/// <param name="typeName">The input type name to check.</param>
/// <returns>Whether or not <paramref name="typeName"/> represents a constant buffer type.</returns>
public static bool IsConstantBufferType(string typeName)
{
return typeName == "ComputeSharp.ConstantBuffer`1";
}
/// <summary>
/// Checks whether or not a given type name matches a structured buffer type.
/// </summary>
/// <param name="typeName">The input type name to check.</param>
/// <returns>Whether or not <paramref name="typeName"/> represents a structured buffer type.</returns>
public static bool IsStructuredBufferType(string typeName)
{
return typeName switch
{
"ComputeSharp.ConstantBuffer`1" or
"ComputeSharp.ReadOnlyBuffer`1" or
"ComputeSharp.ReadWriteBuffer`1" => true,
_ => false,
};
}
/// <summary>
/// Gets the set of HLSL matrix types.
/// </summary>
public static IReadOnlyCollection<Type> KnownMatrixTypes { get; } = new[]
/// <summary>
/// Checks whether or not a given type name matches a readonly typed resource type.
/// </summary>
/// <param name="typeName">The input type name to check.</param>
/// <returns>Whether or not <paramref name="typeName"/> represents a readonly typed resource type.</returns>
public static bool IsReadOnlyTypedResourceType(string typeName)
{
return typeName switch
{
typeof(Bool1x1), typeof(Bool1x2), typeof(Bool1x3), typeof(Bool1x4),
typeof(Bool2x1), typeof(Bool2x2), typeof(Bool2x3), typeof(Bool2x4),
typeof(Bool3x1), typeof(Bool3x2), typeof(Bool3x3), typeof(Bool3x4),
typeof(Bool4x1), typeof(Bool4x2), typeof(Bool4x3), typeof(Bool4x4),
typeof(Int1x1), typeof(Int1x2), typeof(Int1x3), typeof(Int1x4),
typeof(Int2x1), typeof(Int2x2), typeof(Int2x3), typeof(Int2x4),
typeof(Int3x1), typeof(Int3x2), typeof(Int3x3), typeof(Int3x4),
typeof(Int4x1), typeof(Int4x2), typeof(Int4x3), typeof(Int4x4),
typeof(UInt1x1), typeof(UInt1x2), typeof(UInt1x3), typeof(UInt1x4),
typeof(UInt2x1), typeof(UInt2x2), typeof(UInt2x3), typeof(UInt2x4),
typeof(UInt3x1), typeof(UInt3x2), typeof(UInt3x3), typeof(UInt3x4),
typeof(UInt4x1), typeof(UInt4x2), typeof(UInt4x3), typeof(UInt4x4),
typeof(Float1x1), typeof(Float1x2), typeof(Float1x3), typeof(Float1x4),
typeof(Float2x1), typeof(Float2x2), typeof(Float2x3), typeof(Float2x4),
typeof(Float3x1), typeof(Float3x2), typeof(Float3x3), typeof(Float3x4),
typeof(Float4x1), typeof(Float4x2), typeof(Float4x3), typeof(Float4x4),
typeof(Double1x1), typeof(Double1x2), typeof(Double1x3), typeof(Double1x4),
typeof(Double2x1), typeof(Double2x2), typeof(Double2x3), typeof(Double2x4),
typeof(Double3x1), typeof(Double3x2), typeof(Double3x3), typeof(Double3x4),
typeof(Double4x1), typeof(Double4x2), typeof(Double4x3), typeof(Double4x4)
"ComputeSharp.ReadOnlyBuffer`1" or
"ComputeSharp.ReadOnlyTexture2D`1" or
"ComputeSharp.ReadOnlyTexture2D`2" or
"ComputeSharp.ReadOnlyTexture3D`1" or
"ComputeSharp.ReadOnlyTexture3D`2" or
"ComputeSharp.IReadOnlyTexture2D`1" or
"ComputeSharp.IReadOnlyTexture3D`1" => true,
_ => false,
};
}
/// <summary>
/// The mapping of supported known types to HLSL types.
/// </summary>
private static readonly IReadOnlyDictionary<string, string> KnownHlslTypes = BuildKnownHlslTypes();
/// <summary>
/// Builds the mapping of known primitive types.
/// </summary>
[Pure]
private static IReadOnlyDictionary<string, string> BuildKnownHlslTypes()
/// <summary>
/// Checks whether or not a given type name matches a typed resource type.
/// </summary>
/// <param name="typeName">The input type name to check.</param>
/// <returns>Whether or not <paramref name="typeName"/> represents a typed resource type.</returns>
public static bool IsTypedResourceType(string typeName)
{
return typeName switch
{
Dictionary<string, string> knownTypes = new()
{
[typeof(bool).FullName] = "bool",
[typeof(int).FullName] = "int",
[typeof(uint).FullName] = "uint",
[typeof(float).FullName] = "float",
[typeof(Vector2).FullName] = "float2",
[typeof(Vector3).FullName] = "float3",
[typeof(Vector4).FullName] = "float4",
[typeof(double).FullName] = "double"
};
"ComputeSharp.ConstantBuffer`1" or
"ComputeSharp.ReadOnlyBuffer`1" or
"ComputeSharp.ReadWriteBuffer`1" or
"ComputeSharp.ReadOnlyTexture2D`1" or
"ComputeSharp.ReadOnlyTexture2D`2" or
"ComputeSharp.ReadWriteTexture2D`1" or
"ComputeSharp.ReadWriteTexture2D`2" or
"ComputeSharp.ReadOnlyTexture3D`1" or
"ComputeSharp.ReadOnlyTexture3D`2" or
"ComputeSharp.ReadWriteTexture3D`1" or
"ComputeSharp.ReadWriteTexture3D`2" or
"ComputeSharp.IReadOnlyTexture2D`1" or
"ComputeSharp.IReadWriteTexture2D`1" or
"ComputeSharp.IReadOnlyTexture3D`1" or
"ComputeSharp.IReadWriteTexture3D`1" => true,
_ => false,
};
}
// Add all the vector types
foreach (var type in KnownVectorTypes)
/// <summary>
/// Checks whether or not a given type name matches a known HLSL primitive type (scalar, vector or matrix).
/// </summary>
/// <param name="typeName">The input type name to check.</param>
/// <returns>Whether or not <paramref name="typeName"/> represents a scalar, vector or matrix type.</returns>
public static bool IsKnownHlslType(string typeName)
{
return KnownHlslTypes.ContainsKey(typeName);
}
/// <summary>
/// Checks whether or not a given type name matches a vector type.
/// </summary>
/// <param name="typeName">The input type name to check.</param>
/// <returns>Whether or not <paramref name="typeName"/> represents a vector type.</returns>
public static bool IsVectorType(string typeName)
{
return KnownVectorTypes.Any(type => type.FullName == typeName);
}
/// <summary>
/// Checks whether or not a given type name matches a matrix type.
/// </summary>
/// <param name="typeName">The input type name to check.</param>
/// <returns>Whether or not <paramref name="typeName"/> represents a matrix type.</returns>
public static bool IsMatrixType(string typeName)
{
return KnownMatrixTypes.Any(type => type.FullName == typeName);
}
/// <summary>
/// Checks whether or not a given type name is a non linear matrix type.
/// That is, a matrix type with more than a single row (which affects the constant buffer alignment).
/// </summary>
/// <param name="typeName">The input type name to check.</param>
/// <param name="elementName">The element name of the matrix type.</param>
/// <param name="rows">The number of rows in the matrix type.</param>
/// <param name="columns">The number of columns in the matrix type.</param>
/// <returns>Whether or not <paramref name="typeName"/> represents a non linear matrix type.</returns>
public static bool IsNonLinearMatrixType(string typeName, out string? elementName, out int rows, out int columns)
{
if (KnownMatrixTypes.Any(type => type.FullName == typeName))
{
var match = Regex.Match(typeName, @"^ComputeSharp\.(Bool|Int|UInt|Float|Double)([2-4])x([1-4])$");
if (match.Success)
{
knownTypes.Add(type.FullName, type.Name.ToLower());
elementName = match.Groups[1].Value;
rows = int.Parse(match.Groups[2].Value);
columns = int.Parse(match.Groups[3].Value);
return true;
}
// Add all the matrix types
foreach (var type in KnownMatrixTypes)
{
knownTypes.Add(type.FullName, type.Name.ToLower());
}
return knownTypes;
}
/// <summary>
/// Checks whether or not a given type name matches a constant buffer type.
/// </summary>
/// <param name="typeName">The input type name to check.</param>
/// <returns>Whether or not <paramref name="typeName"/> represents a constant buffer type.</returns>
public static bool IsConstantBufferType(string typeName)
elementName = null;
rows = columns = 0;
return false;
}
/// <summary>
/// Gets the mapped HLSL-compatible type name for the input type symbol.
/// </summary>
/// <param name="typeSymbol">The input type to map.</param>
/// <returns>The HLSL-compatible type name that can be used in an HLSL shader.</returns>
[Pure]
public static string GetMappedName(INamedTypeSymbol typeSymbol)
{
// Delegate types just return an empty string, as they're not actually
// used in the generated shaders, but just mapped to a function at runtime.
if (typeSymbol.TypeKind == TypeKind.Delegate) return "";
string typeName = typeSymbol.GetFullMetadataName();
// Special case for the resource types
if (IsTypedResourceType(typeName))
{
return typeName == "ComputeSharp.ConstantBuffer`1";
}
/// <summary>
/// Checks whether or not a given type name matches a structured buffer type.
/// </summary>
/// <param name="typeName">The input type name to check.</param>
/// <returns>Whether or not <paramref name="typeName"/> represents a structured buffer type.</returns>
public static bool IsStructuredBufferType(string typeName)
{
return typeName switch
{
"ComputeSharp.ConstantBuffer`1" or
"ComputeSharp.ReadOnlyBuffer`1" or
"ComputeSharp.ReadWriteBuffer`1" => true,
_ => false,
};
}
/// <summary>
/// Checks whether or not a given type name matches a readonly typed resource type.
/// </summary>
/// <param name="typeName">The input type name to check.</param>
/// <returns>Whether or not <paramref name="typeName"/> represents a readonly typed resource type.</returns>
public static bool IsReadOnlyTypedResourceType(string typeName)
{
return typeName switch
{
"ComputeSharp.ReadOnlyBuffer`1" or
"ComputeSharp.ReadOnlyTexture2D`1" or
"ComputeSharp.ReadOnlyTexture2D`2" or
"ComputeSharp.ReadOnlyTexture3D`1" or
"ComputeSharp.ReadOnlyTexture3D`2" or
"ComputeSharp.IReadOnlyTexture2D`1" or
"ComputeSharp.IReadOnlyTexture3D`1" => true,
_ => false,
};
}
/// <summary>
/// Checks whether or not a given type name matches a typed resource type.
/// </summary>
/// <param name="typeName">The input type name to check.</param>
/// <returns>Whether or not <paramref name="typeName"/> represents a typed resource type.</returns>
public static bool IsTypedResourceType(string typeName)
{
return typeName switch
{
"ComputeSharp.ConstantBuffer`1" or
"ComputeSharp.ReadOnlyBuffer`1" or
"ComputeSharp.ReadWriteBuffer`1" or
"ComputeSharp.ReadOnlyTexture2D`1" or
"ComputeSharp.ReadOnlyTexture2D`2" or
"ComputeSharp.ReadWriteTexture2D`1" or
"ComputeSharp.ReadWriteTexture2D`2" or
"ComputeSharp.ReadOnlyTexture3D`1" or
"ComputeSharp.ReadOnlyTexture3D`2" or
"ComputeSharp.ReadWriteTexture3D`1" or
"ComputeSharp.ReadWriteTexture3D`2" or
"ComputeSharp.IReadOnlyTexture2D`1" or
"ComputeSharp.IReadWriteTexture2D`1" or
"ComputeSharp.IReadOnlyTexture3D`1" or
"ComputeSharp.IReadWriteTexture3D`1" => true,
_ => false,
};
}
/// <summary>
/// Checks whether or not a given type name matches a known HLSL primitive type (scalar, vector or matrix).
/// </summary>
/// <param name="typeName">The input type name to check.</param>
/// <returns>Whether or not <paramref name="typeName"/> represents a scalar, vector or matrix type.</returns>
public static bool IsKnownHlslType(string typeName)
{
return KnownHlslTypes.ContainsKey(typeName);
}
/// <summary>
/// Checks whether or not a given type name matches a vector type.
/// </summary>
/// <param name="typeName">The input type name to check.</param>
/// <returns>Whether or not <paramref name="typeName"/> represents a vector type.</returns>
public static bool IsVectorType(string typeName)
{
return KnownVectorTypes.Any(type => type.FullName == typeName);
}
/// <summary>
/// Checks whether or not a given type name matches a matrix type.
/// </summary>
/// <param name="typeName">The input type name to check.</param>
/// <returns>Whether or not <paramref name="typeName"/> represents a matrix type.</returns>
public static bool IsMatrixType(string typeName)
{
return KnownMatrixTypes.Any(type => type.FullName == typeName);
}
/// <summary>
/// Checks whether or not a given type name is a non linear matrix type.
/// That is, a matrix type with more than a single row (which affects the constant buffer alignment).
/// </summary>
/// <param name="typeName">The input type name to check.</param>
/// <param name="elementName">The element name of the matrix type.</param>
/// <param name="rows">The number of rows in the matrix type.</param>
/// <param name="columns">The number of columns in the matrix type.</param>
/// <returns>Whether or not <paramref name="typeName"/> represents a non linear matrix type.</returns>
public static bool IsNonLinearMatrixType(string typeName, out string? elementName, out int rows, out int columns)
{
if (KnownMatrixTypes.Any(type => type.FullName == typeName))
{
var match = Regex.Match(typeName, @"^ComputeSharp\.(Bool|Int|UInt|Float|Double)([2-4])x([1-4])$");
if (match.Success)
{
elementName = match.Groups[1].Value;
rows = int.Parse(match.Groups[2].Value);
columns = int.Parse(match.Groups[3].Value);
return true;
}
}
elementName = null;
rows = columns = 0;
return false;
}
/// <summary>
/// Gets the mapped HLSL-compatible type name for the input type symbol.
/// </summary>
/// <param name="typeSymbol">The input type to map.</param>
/// <returns>The HLSL-compatible type name that can be used in an HLSL shader.</returns>
[Pure]
public static string GetMappedName(INamedTypeSymbol typeSymbol)
{
// Delegate types just return an empty string, as they're not actually
// used in the generated shaders, but just mapped to a function at runtime.
if (typeSymbol.TypeKind == TypeKind.Delegate) return "";
string typeName = typeSymbol.GetFullMetadataName();
// Special case for the resource types
if (IsTypedResourceType(typeName))
{
string genericArgumentName = ((INamedTypeSymbol)typeSymbol.TypeArguments.Last()).GetFullMetadataName();
// If the current type is a custom type, format it as needed
if (!KnownHlslTypes.TryGetValue(genericArgumentName, out string? mappedElementType))
{
mappedElementType = genericArgumentName.ToHlslIdentifierName();
}
// Construct the HLSL type name
return typeName switch
{
"ComputeSharp.ConstantBuffer`1" => mappedElementType,
"ComputeSharp.ReadOnlyBuffer`1" => $"StructuredBuffer<{mappedElementType}>",
"ComputeSharp.ReadWriteBuffer`1" => $"RWStructuredBuffer<{mappedElementType}>",
"ComputeSharp.ReadOnlyTexture2D`1" => $"Texture2D<{mappedElementType}>",
"ComputeSharp.ReadOnlyTexture2D`2" => $"Texture2D<unorm {mappedElementType}>",
"ComputeSharp.ReadWriteTexture2D`1" => $"RWTexture2D<{mappedElementType}>",
"ComputeSharp.ReadWriteTexture2D`2" => $"RWTexture2D<unorm {mappedElementType}>",
"ComputeSharp.ReadOnlyTexture3D`1" => $"Texture3D<{mappedElementType}>",
"ComputeSharp.ReadOnlyTexture3D`2" => $"Texture3D<unorm {mappedElementType}>",
"ComputeSharp.ReadWriteTexture3D`1" => $"RWTexture3D<{mappedElementType}>",
"ComputeSharp.ReadWriteTexture3D`2" => $"RWTexture3D<unorm {mappedElementType}>",
"ComputeSharp.IReadOnlyTexture2D`1" => $"Texture2D<unorm {mappedElementType}>",
"ComputeSharp.IReadWriteTexture2D`1" => $"RWTexture2D<unorm {mappedElementType}>",
"ComputeSharp.IReadOnlyTexture3D`1" => $"Texture3D<unorm {mappedElementType}>",
"ComputeSharp.IReadWriteTexture3D`1" => $"RWTexture3D<unorm {mappedElementType}>",
_ => throw new ArgumentException()
};
}
// The captured field is of an HLSL primitive type
if (KnownHlslTypes.TryGetValue(typeName, out string? mappedType))
{
return mappedType;
}
// The captured field is of a custom struct type
return typeName.ToHlslIdentifierName();
}
/// <summary>
/// Gets the mapped HLSL-compatible type name for the output texture of a pixel shader.
/// </summary>
/// <param name="typeSymbol">The pixel shader type to map.</param>
/// <returns>The HLSL-compatible type name that can be used in an HLSL shader.</returns>
[Pure]
public static string GetMappedNameForPixelShaderType(INamedTypeSymbol typeSymbol)
{
string genericArgumentName = ((INamedTypeSymbol)typeSymbol.TypeArguments.First()).GetFullMetadataName();
string genericArgumentName = ((INamedTypeSymbol)typeSymbol.TypeArguments.Last()).GetFullMetadataName();
// If the current type is a custom type, format it as needed
if (!KnownHlslTypes.TryGetValue(genericArgumentName, out string? mappedElementType))
@@ -312,124 +264,171 @@ namespace ComputeSharp.SourceGenerators.Mappings
}
// Construct the HLSL type name
return $"RWTexture2D<unorm {mappedElementType}>";
return typeName switch
{
"ComputeSharp.ConstantBuffer`1" => mappedElementType,
"ComputeSharp.ReadOnlyBuffer`1" => $"StructuredBuffer<{mappedElementType}>",
"ComputeSharp.ReadWriteBuffer`1" => $"RWStructuredBuffer<{mappedElementType}>",
"ComputeSharp.ReadOnlyTexture2D`1" => $"Texture2D<{mappedElementType}>",
"ComputeSharp.ReadOnlyTexture2D`2" => $"Texture2D<unorm {mappedElementType}>",
"ComputeSharp.ReadWriteTexture2D`1" => $"RWTexture2D<{mappedElementType}>",
"ComputeSharp.ReadWriteTexture2D`2" => $"RWTexture2D<unorm {mappedElementType}>",
"ComputeSharp.ReadOnlyTexture3D`1" => $"Texture3D<{mappedElementType}>",
"ComputeSharp.ReadOnlyTexture3D`2" => $"Texture3D<unorm {mappedElementType}>",
"ComputeSharp.ReadWriteTexture3D`1" => $"RWTexture3D<{mappedElementType}>",
"ComputeSharp.ReadWriteTexture3D`2" => $"RWTexture3D<unorm {mappedElementType}>",
"ComputeSharp.IReadOnlyTexture2D`1" => $"Texture2D<unorm {mappedElementType}>",
"ComputeSharp.IReadWriteTexture2D`1" => $"RWTexture2D<unorm {mappedElementType}>",
"ComputeSharp.IReadOnlyTexture3D`1" => $"Texture3D<unorm {mappedElementType}>",
"ComputeSharp.IReadWriteTexture3D`1" => $"RWTexture3D<unorm {mappedElementType}>",
_ => throw new ArgumentException()
};
}
/// <summary>
/// Gets the mapped HLSL-compatible type name for the input element type symbol.
/// </summary>
/// <param name="typeSymbol">The input type to map.</param>
/// <returns>The HLSL-compatible type name that can be used in an HLSL shader.</returns>
[Pure]
public static string GetMappedElementName(IArrayTypeSymbol typeSymbol)
// The captured field is of an HLSL primitive type
if (KnownHlslTypes.TryGetValue(typeName, out string? mappedType))
{
string elementTypeName = ((INamedTypeSymbol)typeSymbol.ElementType).GetFullMetadataName();
return mappedType;
}
if (KnownHlslTypes.TryGetValue(elementTypeName, out string? mapped))
// The captured field is of a custom struct type
return typeName.ToHlslIdentifierName();
}
/// <summary>
/// Gets the mapped HLSL-compatible type name for the output texture of a pixel shader.
/// </summary>
/// <param name="typeSymbol">The pixel shader type to map.</param>
/// <returns>The HLSL-compatible type name that can be used in an HLSL shader.</returns>
[Pure]
public static string GetMappedNameForPixelShaderType(INamedTypeSymbol typeSymbol)
{
string genericArgumentName = ((INamedTypeSymbol)typeSymbol.TypeArguments.First()).GetFullMetadataName();
// If the current type is a custom type, format it as needed
if (!KnownHlslTypes.TryGetValue(genericArgumentName, out string? mappedElementType))
{
mappedElementType = genericArgumentName.ToHlslIdentifierName();
}
// Construct the HLSL type name
return $"RWTexture2D<unorm {mappedElementType}>";
}
/// <summary>
/// Gets the mapped HLSL-compatible type name for the input element type symbol.
/// </summary>
/// <param name="typeSymbol">The input type to map.</param>
/// <returns>The HLSL-compatible type name that can be used in an HLSL shader.</returns>
[Pure]
public static string GetMappedElementName(IArrayTypeSymbol typeSymbol)
{
string elementTypeName = ((INamedTypeSymbol)typeSymbol.ElementType).GetFullMetadataName();
if (KnownHlslTypes.TryGetValue(elementTypeName, out string? mapped))
{
return mapped;
}
return elementTypeName.ToHlslIdentifierName();
}
/// <summary>
/// Gets the mapped HLSL-compatible type name for the input type name.
/// </summary>
/// <param name="name">The input type name to map.</param>
/// <returns>The HLSL-compatible type name that can be used in an HLSL shader.</returns>
public static bool TryGetMappedName(string originalName, out string? mappedName)
{
return KnownHlslTypes.TryGetValue(originalName, out mappedName);
}
/// <summary>
/// Gets the sequence of unique custom types from a collection of discovered types.
/// </summary>
/// <param name="discoveredTypes">The input collection of discovered types.</param>
/// <returns>The list of unique custom types.</returns>
public static IEnumerable<INamedTypeSymbol> GetCustomTypes(IEnumerable<INamedTypeSymbol> discoveredTypes)
{
// Local function to recursively gather nested types
static void ExploreTypes(INamedTypeSymbol type, HashSet<INamedTypeSymbol> customTypes)
{
if (KnownHlslTypes.ContainsKey(type.GetFullMetadataName())) return;
if (!customTypes.Add(type)) return;
foreach (var field in type.GetMembers().OfType<IFieldSymbol>())
{
return mapped;
if (field.IsStatic) continue;
ExploreTypes((INamedTypeSymbol)field.Type, customTypes);
}
return elementTypeName.ToHlslIdentifierName();
}
/// <summary>
/// Gets the mapped HLSL-compatible type name for the input type name.
/// </summary>
/// <param name="name">The input type name to map.</param>
/// <returns>The HLSL-compatible type name that can be used in an HLSL shader.</returns>
public static bool TryGetMappedName(string originalName, out string? mappedName)
HashSet<INamedTypeSymbol> customTypes = new(SymbolEqualityComparer.Default);
// Explore all input types and their nested types
foreach (INamedTypeSymbol type in discoveredTypes)
{
return KnownHlslTypes.TryGetValue(originalName, out mappedName);
ExploreTypes(type, customTypes);
}
/// <summary>
/// Gets the sequence of unique custom types from a collection of discovered types.
/// </summary>
/// <param name="discoveredTypes">The input collection of discovered types.</param>
/// <returns>The list of unique custom types.</returns>
public static IEnumerable<INamedTypeSymbol> GetCustomTypes(IEnumerable<INamedTypeSymbol> discoveredTypes)
return OrderByDependency(customTypes);
}
/// <summary>
/// Orders the input sequence of types so that they can be declared in HLSL successfully.
/// </summary>
/// <param name="types">The input collection of types to declare.</param>
/// <returns>The same list as input, but in a valid HLSL declaration order.</returns>
[Pure]
private static IEnumerable<INamedTypeSymbol> OrderByDependency(IEnumerable<INamedTypeSymbol> types)
{
Queue<(INamedTypeSymbol Type, HashSet<INamedTypeSymbol> Fields)> queue = new();
// Build a mapping of type dependencies for all the captured types. A type depends on another
// when the latter is a field in the first type. HLSL requires custom types to be declared in
// order of usage, so we need to ensure that types are declared in an order that guarantees
// that no type will be referenced before being defined. To do so, we can create a mapping of
// types and their dependencies, and iteratively remove items from the map when they have no
// dependencies left. When one type is processed and removed, it is also removed from the list
// of dependencies of all other remaining types in the map, until there is none left.
foreach (var type in types)
{
// Local function to recursively gather nested types
static void ExploreTypes(INamedTypeSymbol type, HashSet<INamedTypeSymbol> customTypes)
HashSet<INamedTypeSymbol> dependencies = new(SymbolEqualityComparer.Default);
// Only add other custom types as dependencies, and ignore HLSL types
foreach (var field in type.GetMembers().OfType<IFieldSymbol>())
{
if (KnownHlslTypes.ContainsKey(type.GetFullMetadataName())) return;
if (field.IsStatic) continue;
if (!customTypes.Add(type)) return;
INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type;
foreach (var field in type.GetMembers().OfType<IFieldSymbol>())
if (!KnownHlslTypes.ContainsKey(fieldType.GetFullMetadataName()))
{
if (field.IsStatic) continue;
ExploreTypes((INamedTypeSymbol)field.Type, customTypes);
_ = dependencies.Add(fieldType);
}
}
HashSet<INamedTypeSymbol> customTypes = new(SymbolEqualityComparer.Default);
// Explore all input types and their nested types
foreach (INamedTypeSymbol type in discoveredTypes)
{
ExploreTypes(type, customTypes);
}
return OrderByDependency(customTypes);
queue.Enqueue((type, dependencies));
}
/// <summary>
/// Orders the input sequence of types so that they can be declared in HLSL successfully.
/// </summary>
/// <param name="types">The input collection of types to declare.</param>
/// <returns>The same list as input, but in a valid HLSL declaration order.</returns>
[Pure]
private static IEnumerable<INamedTypeSymbol> OrderByDependency(IEnumerable<INamedTypeSymbol> types)
while (queue.Count > 0)
{
Queue<(INamedTypeSymbol Type, HashSet<INamedTypeSymbol> Fields)> queue = new();
var entry = queue.Dequeue();
// Build a mapping of type dependencies for all the captured types. A type depends on another
// when the latter is a field in the first type. HLSL requires custom types to be declared in
// order of usage, so we need to ensure that types are declared in an order that guarantees
// that no type will be referenced before being defined. To do so, we can create a mapping of
// types and their dependencies, and iteratively remove items from the map when they have no
// dependencies left. When one type is processed and removed, it is also removed from the list
// of dependencies of all other remaining types in the map, until there is none left.
foreach (var type in types)
// No dependencies left, we can declare this type
if (entry.Fields.Count == 0)
{
HashSet<INamedTypeSymbol> dependencies = new(SymbolEqualityComparer.Default);
// Only add other custom types as dependencies, and ignore HLSL types
foreach (var field in type.GetMembers().OfType<IFieldSymbol>())
// Remove the current type from dependencies of others
foreach (var pair in queue)
{
if (field.IsStatic) continue;
INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type;
if (!KnownHlslTypes.ContainsKey(fieldType.GetFullMetadataName()))
{
_ = dependencies.Add(fieldType);
}
_ = pair.Fields.Remove(entry.Type);
}
queue.Enqueue((type, dependencies));
}
while (queue.Count > 0)
{
var entry = queue.Dequeue();
// No dependencies left, we can declare this type
if (entry.Fields.Count == 0)
{
// Remove the current type from dependencies of others
foreach (var pair in queue)
{
_ = pair.Fields.Remove(entry.Type);
}
yield return entry.Type;
}
else queue.Enqueue(entry);
yield return entry.Type;
}
else queue.Enqueue(entry);
}
}
}
+30 -32
ファイルの表示
@@ -4,45 +4,43 @@ using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace ComputeSharp.SourceGenerators
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
public sealed partial class ShaderMethodSourceGenerator
{
/// <inheritdoc/>
public sealed partial class ShaderMethodSourceGenerator
/// <summary>
/// An <see cref="ISyntaxContextReceiver"/> that selects candidate nodes to process.
/// </summary>
private sealed class SyntaxReceiver : ISyntaxContextReceiver
{
/// <summary>
/// An <see cref="ISyntaxContextReceiver"/> that selects candidate nodes to process.
/// The list of info gathered during exploration.
/// </summary>
private sealed class SyntaxReceiver : ISyntaxContextReceiver
private readonly List<Item> gatheredInfo = new();
/// <summary>
/// Gets the collection of gathered info to process.
/// </summary>
public IReadOnlyCollection<Item> GatheredInfo => this.gatheredInfo;
/// <inheritdoc/>
public void OnVisitSyntaxNode(GeneratorSyntaxContext context)
{
/// <summary>
/// The list of info gathered during exploration.
/// </summary>
private readonly List<Item> gatheredInfo = new();
/// <summary>
/// Gets the collection of gathered info to process.
/// </summary>
public IReadOnlyCollection<Item> GatheredInfo => this.gatheredInfo;
/// <inheritdoc/>
public void OnVisitSyntaxNode(GeneratorSyntaxContext context)
if (context.Node is MethodDeclarationSyntax { AttributeLists: { Count: > 0 } } methodDeclaration &&
context.SemanticModel.GetDeclaredSymbol(methodDeclaration) is IMethodSymbol methodSymbol &&
context.SemanticModel.Compilation.GetTypeByMetadataName(typeof(ShaderMethodAttribute).FullName) is INamedTypeSymbol attributeSymbol &&
methodSymbol.GetAttributes().Any(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, attributeSymbol)))
{
if (context.Node is MethodDeclarationSyntax { AttributeLists: { Count: > 0 } } methodDeclaration &&
context.SemanticModel.GetDeclaredSymbol(methodDeclaration) is IMethodSymbol methodSymbol &&
context.SemanticModel.Compilation.GetTypeByMetadataName(typeof(ShaderMethodAttribute).FullName) is INamedTypeSymbol attributeSymbol &&
methodSymbol.GetAttributes().Any(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, attributeSymbol)))
{
this.gatheredInfo.Add(new Item(methodDeclaration, methodSymbol));
}
this.gatheredInfo.Add(new Item(methodDeclaration, methodSymbol));
}
/// <summary>
/// A model for a group of item representing a discovered method to process.
/// </summary>
/// <param name="MethodDeclaration">The <see cref="MethodDeclarationSyntax"/> instance for the target method declaration.</param>
/// <param name="MethodSymbol">The <see cref="IMethodSymbol"/> instance for <paramref name="MethodDeclaration"/>.</param>
public sealed record Item(MethodDeclarationSyntax MethodDeclaration, IMethodSymbol MethodSymbol);
}
/// <summary>
/// A model for a group of item representing a discovered method to process.
/// </summary>
/// <param name="MethodDeclaration">The <see cref="MethodDeclarationSyntax"/> instance for the target method declaration.</param>
/// <param name="MethodSymbol">The <see cref="IMethodSymbol"/> instance for <paramref name="MethodDeclaration"/>.</param>
public sealed record Item(MethodDeclarationSyntax MethodDeclaration, IMethodSymbol MethodSymbol);
}
}
+112 -114
ファイルの表示
@@ -17,130 +17,128 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618, RS1024
namespace ComputeSharp.SourceGenerators
namespace ComputeSharp.SourceGenerators;
/// <summary>
/// A source generator for processing static methods referenced from compute shaders.
/// </summary>
[Generator]
public sealed partial class ShaderMethodSourceGenerator : ISourceGenerator
{
/// <summary>
/// A source generator for processing static methods referenced from compute shaders.
/// </summary>
[Generator]
public sealed partial class ShaderMethodSourceGenerator : ISourceGenerator
/// <inheritdoc/>
public void Initialize(GeneratorInitializationContext context)
{
/// <inheritdoc/>
public void Initialize(GeneratorInitializationContext context)
context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver());
}
/// <inheritdoc/>
public void Execute(GeneratorExecutionContext context)
{
// Get the syntax receiver with the candidate nodes
if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver)
{
context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver());
return;
}
/// <inheritdoc/>
public void Execute(GeneratorExecutionContext context)
foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo)
{
// Get the syntax receiver with the candidate nodes
if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver)
SemanticModelProvider semanticModel = new(context.Compilation);
try
{
return;
OnExecute(context, item.MethodDeclaration, semanticModel, item.MethodSymbol);
}
foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo)
catch
{
SemanticModelProvider semanticModel = new(context.Compilation);
try
{
OnExecute(context, item.MethodDeclaration, semanticModel, item.MethodSymbol);
}
catch
{
context.ReportDiagnostic(ShaderMethodSourceGeneratorError, item.MethodDeclaration, item.MethodSymbol);
}
context.ReportDiagnostic(ShaderMethodSourceGeneratorError, item.MethodDeclaration, item.MethodSymbol);
}
}
/// <summary>
/// Processes a given target method.
/// </summary>
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to use.</param>
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> node to process.</param>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> with metadata on the types being processed.</param>
/// <param name="methodDeclarationSymbol">The <see cref="IMethodSymbol"/> for <paramref name="methodDeclaration"/>.</param>
private static void OnExecute(GeneratorExecutionContext context, MethodDeclarationSyntax methodDeclaration, SemanticModelProvider semanticModel, IMethodSymbol methodDeclarationSymbol)
{
// We need to sets to track all discovered custom types and static methods
HashSet<INamedTypeSymbol> discoveredTypes = new(SymbolEqualityComparer.Default);
Dictionary<IFieldSymbol, string> constantDefinitions = new(SymbolEqualityComparer.Default);
// Explore the syntax tree and extract the processed info
var (invokeMethod, processedMethods) = GetProcessedMethods(context, methodDeclaration, semanticModel, discoveredTypes, constantDefinitions);
var processedTypes = IShaderGenerator.GetProcessedTypes(discoveredTypes).ToArray();
var processedConstants = IShaderGenerator.GetProcessedConstants(constantDefinitions);
// Create the compilation unit with the source attribute
var source =
CompilationUnit().AddAttributeLists(
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName(typeof(ShaderMethodSourceAttribute).FullName)).AddArgumentListArguments(
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodDeclarationSymbol.GetFullMetadataName(true)))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(invokeMethod))),
AttributeArgument(NestedArrayExpression(processedTypes)),
AttributeArgument(NestedArrayExpression(processedMethods)),
AttributeArgument(NestedArrayExpression(processedConstants)))))
.WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList()))
.WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword))))
.NormalizeWhitespace(eol: "\n")
.ToFullString();
// Add the method source attribute
context.AddSource(methodDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8));
}
/// <summary>
/// Gets a sequence of processed methods from a target method declaration.
/// </summary>
/// <param name="context">The current generator context in use.</param>
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> instance for the current method.</param>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the method to process.</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 processed methods in <paramref name="methodDeclaration"/> (main method and all captured methods).</returns>
[Pure]
private static (string TargetMethod, IEnumerable<(string Signature, string Definition)> ProcessedMethods) GetProcessedMethods(
GeneratorExecutionContext context,
MethodDeclarationSyntax methodDeclaration,
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions)
{
Dictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods = new(SymbolEqualityComparer.Default);
ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, constantDefinitions, context);
// Rewrite the method syntax tree
var targetMethod = shaderSourceRewriter
.Visit(methodDeclaration)!
.WithIdentifier(Identifier(ShaderMethodSourceAttribute.InvokeMethodIdentifier))
.WithoutTrivia()
.NormalizeWhitespace(eol: "\n")
.ToFullString();
List<(string, string)> processedMethods = new(shaderSourceRewriter.LocalFunctions.Count);
// Emit the extracted local functions
foreach (var localFunction in shaderSourceRewriter.LocalFunctions)
{
processedMethods.Add((
localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString()));
}
// Emit the discovered static methods
foreach (var staticMethod in staticMethods.Values)
{
processedMethods.Add((
staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
staticMethod.NormalizeWhitespace(eol: "\n").ToFullString()));
}
return (targetMethod, processedMethods);
}
}
}
/// <summary>
/// Processes a given target method.
/// </summary>
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to use.</param>
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> node to process.</param>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> with metadata on the types being processed.</param>
/// <param name="methodDeclarationSymbol">The <see cref="IMethodSymbol"/> for <paramref name="methodDeclaration"/>.</param>
private static void OnExecute(GeneratorExecutionContext context, MethodDeclarationSyntax methodDeclaration, SemanticModelProvider semanticModel, IMethodSymbol methodDeclarationSymbol)
{
// We need to sets to track all discovered custom types and static methods
HashSet<INamedTypeSymbol> discoveredTypes = new(SymbolEqualityComparer.Default);
Dictionary<IFieldSymbol, string> constantDefinitions = new(SymbolEqualityComparer.Default);
// Explore the syntax tree and extract the processed info
var (invokeMethod, processedMethods) = GetProcessedMethods(context, methodDeclaration, semanticModel, discoveredTypes, constantDefinitions);
var processedTypes = IShaderGenerator.GetProcessedTypes(discoveredTypes).ToArray();
var processedConstants = IShaderGenerator.GetProcessedConstants(constantDefinitions);
// Create the compilation unit with the source attribute
var source =
CompilationUnit().AddAttributeLists(
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName(typeof(ShaderMethodSourceAttribute).FullName)).AddArgumentListArguments(
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodDeclarationSymbol.GetFullMetadataName(true)))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(invokeMethod))),
AttributeArgument(NestedArrayExpression(processedTypes)),
AttributeArgument(NestedArrayExpression(processedMethods)),
AttributeArgument(NestedArrayExpression(processedConstants)))))
.WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList()))
.WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword))))
.NormalizeWhitespace(eol: "\n")
.ToFullString();
// Add the method source attribute
context.AddSource(methodDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8));
}
/// <summary>
/// Gets a sequence of processed methods from a target method declaration.
/// </summary>
/// <param name="context">The current generator context in use.</param>
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> instance for the current method.</param>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the method to process.</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 processed methods in <paramref name="methodDeclaration"/> (main method and all captured methods).</returns>
[Pure]
private static (string TargetMethod, IEnumerable<(string Signature, string Definition)> ProcessedMethods) GetProcessedMethods(
GeneratorExecutionContext context,
MethodDeclarationSyntax methodDeclaration,
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions)
{
Dictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods = new(SymbolEqualityComparer.Default);
ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, constantDefinitions, context);
// Rewrite the method syntax tree
var targetMethod = shaderSourceRewriter
.Visit(methodDeclaration)!
.WithIdentifier(Identifier(ShaderMethodSourceAttribute.InvokeMethodIdentifier))
.WithoutTrivia()
.NormalizeWhitespace(eol: "\n")
.ToFullString();
List<(string, string)> processedMethods = new(shaderSourceRewriter.LocalFunctions.Count);
// Emit the extracted local functions
foreach (var localFunction in shaderSourceRewriter.LocalFunctions)
{
processedMethods.Add((
localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString()));
}
// Emit the discovered static methods
foreach (var staticMethod in staticMethods.Values)
{
processedMethods.Add((
staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
staticMethod.NormalizeWhitespace(eol: "\n").ToFullString()));
}
return (targetMethod, processedMethods);
}
}
+153 -154
ファイルの表示
@@ -3,159 +3,90 @@ using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.SourceGenerators.SyntaxRewriters
namespace ComputeSharp.SourceGenerators.SyntaxRewriters;
/// <summary>
/// A custom <see cref="CSharpSyntaxRewriter"/> type that does postprocessing fixups on the shader main method.
/// </summary>
internal abstract class ExecuteMethodRewriter : CSharpSyntaxRewriter
{
/// <summary>
/// A custom <see cref="CSharpSyntaxRewriter"/> type that does postprocessing fixups on the shader main method.
/// Creates a new <see cref="Compute"/> instance with the specified parameters.
/// </summary>
internal abstract class ExecuteMethodRewriter : CSharpSyntaxRewriter
/// <param name="shaderSourceRewriter">The <see cref="ShaderSourceRewriter"/> instance used to process the input tree.</param>
public ExecuteMethodRewriter(ShaderSourceRewriter shaderSourceRewriter)
{
ShaderSourceRewriter = shaderSourceRewriter;
}
/// <summary>
/// Gets the <see cref="ShaderSourceRewriter"/> instance used to process the input tree.
/// </summary>
protected ShaderSourceRewriter ShaderSourceRewriter { 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 (ShaderSourceRewriter.IsGroupIdsUsed)
{
updatedNode = updatedNode.AddParameters(Parameter(Identifier($"uint3 {nameof(GroupIds)} : SV_GroupThreadID")));
}
if (ShaderSourceRewriter.IsGroupIdsIndexUsed)
{
updatedNode = updatedNode.AddParameters(Parameter(Identifier($"uint __{nameof(GroupIds)}__get_Index : SV_GroupIndex")));
}
if (ShaderSourceRewriter.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 : ExecuteMethodRewriter
{
/// <summary>
/// Creates a new <see cref="Compute"/> instance with the specified parameters.
/// </summary>
/// <param name="shaderSourceRewriter">The <see cref="ShaderSourceRewriter"/> instance used to process the input tree.</param>
public ExecuteMethodRewriter(ShaderSourceRewriter shaderSourceRewriter)
public Compute(ShaderSourceRewriter shaderSourceRewriter)
: base(shaderSourceRewriter)
{
ShaderSourceRewriter = shaderSourceRewriter;
}
/// <summary>
/// Gets the <see cref="ShaderSourceRewriter"/> instance used to process the input tree.
/// </summary>
protected ShaderSourceRewriter ShaderSourceRewriter { 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)
public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node)
{
var updatedNode = (ParameterListSyntax)base.VisitParameterList(node)!;
var updatedNode = ((MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!).WithModifiers(TokenList());
updatedNode = updatedNode.AddParameters(Parameter(Identifier($"uint3 {nameof(ThreadIds)} : SV_DispatchThreadID")));
if (ShaderSourceRewriter.IsGroupIdsUsed)
{
updatedNode = updatedNode.AddParameters(Parameter(Identifier($"uint3 {nameof(GroupIds)} : SV_GroupThreadID")));
}
if (ShaderSourceRewriter.IsGroupIdsIndexUsed)
{
updatedNode = updatedNode.AddParameters(Parameter(Identifier($"uint __{nameof(GroupIds)}__get_Index : SV_GroupIndex")));
}
if (ShaderSourceRewriter.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 : ExecuteMethodRewriter
{
/// <summary>
/// Creates a new <see cref="Compute"/> instance with the specified parameters.
/// </summary>
/// <param name="shaderSourceRewriter">The <see cref="ShaderSourceRewriter"/> instance used to process the input tree.</param>
public Compute(ShaderSourceRewriter 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 : ExecuteMethodRewriter
{
/// <summary>
/// Creates a new <see cref="Pixel"/> instance with the specified parameters.
/// </summary>
/// <param name="shaderSourceRewriter">The <see cref="ShaderSourceRewriter"/> instance used to process the input tree.</param>
public Pixel(ShaderSourceRewriter 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 =
// 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(
@@ -168,25 +99,93 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName(nameof(ThreadIds)),
IdentifierName("y")),
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!)));
}
return updatedNode.WithBody(Block(IfStatement(rangeCheckExpression, updatedNode.Body!)));
}
}
/// <inheritdoc/>
public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node)
/// <summary>
/// A custom <see cref="ExecuteMethodRewriter"/> type specialized for compute shaders.
/// </summary>
public sealed class Pixel : ExecuteMethodRewriter
{
/// <summary>
/// Creates a new <see cref="Pixel"/> instance with the specified parameters.
/// </summary>
/// <param name="shaderSourceRewriter">The <see cref="ShaderSourceRewriter"/> instance used to process the input tree.</param>
public Pixel(ShaderSourceRewriter 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")
{
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;
return LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1));
}
return updatedNode;
}
}
}
+147 -148
ファイルの表示
@@ -4,203 +4,202 @@ using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
namespace ComputeSharp.SourceGenerators.SyntaxRewriters
namespace ComputeSharp.SourceGenerators.SyntaxRewriters;
/// <inheritdoc cref="HlslSourceRewriter"/>
internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
{
/// <inheritdoc cref="HlslSourceRewriter"/>
internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
/// <inheritdoc/>
public override SyntaxNode? VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
{
/// <inheritdoc/>
public override SyntaxNode? VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
{
var updatedNode = (AnonymousObjectCreationExpressionSyntax)base.VisitAnonymousObjectCreationExpression(node)!;
var updatedNode = (AnonymousObjectCreationExpressionSyntax)base.VisitAnonymousObjectCreationExpression(node)!;
Context.ReportDiagnostic(AnonymousObjectCreationExpression, node);
Context.ReportDiagnostic(AnonymousObjectCreationExpression, node);
return updatedNode;
}
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxNode? VisitAwaitExpression(AwaitExpressionSyntax node)
{
Context.ReportDiagnostic(AwaitExpression, node);
/// <inheritdoc/>
public override SyntaxNode? VisitAwaitExpression(AwaitExpressionSyntax node)
{
Context.ReportDiagnostic(AwaitExpression, node);
return base.VisitAwaitExpression(node);
}
return base.VisitAwaitExpression(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitCheckedExpression(CheckedExpressionSyntax node)
{
Context.ReportDiagnostic(CheckedExpression, node);
/// <inheritdoc/>
public override SyntaxNode? VisitCheckedExpression(CheckedExpressionSyntax node)
{
Context.ReportDiagnostic(CheckedExpression, node);
return base.VisitCheckedExpression(node);
}
return base.VisitCheckedExpression(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitCheckedStatement(CheckedStatementSyntax node)
{
Context.ReportDiagnostic(CheckedStatement, node);
/// <inheritdoc/>
public override SyntaxNode? VisitCheckedStatement(CheckedStatementSyntax node)
{
Context.ReportDiagnostic(CheckedStatement, node);
return base.VisitCheckedStatement(node);
}
return base.VisitCheckedStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitFixedStatement(FixedStatementSyntax node)
{
Context.ReportDiagnostic(FixedStatement, node);
/// <inheritdoc/>
public override SyntaxNode? VisitFixedStatement(FixedStatementSyntax node)
{
Context.ReportDiagnostic(FixedStatement, node);
return base.VisitFixedStatement(node);
}
return base.VisitFixedStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitForEachStatement(ForEachStatementSyntax node)
{
Context.ReportDiagnostic(ForEachStatement, node);
/// <inheritdoc/>
public override SyntaxNode? VisitForEachStatement(ForEachStatementSyntax node)
{
Context.ReportDiagnostic(ForEachStatement, node);
return base.VisitForEachStatement(node);
}
return base.VisitForEachStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitForEachVariableStatement(ForEachVariableStatementSyntax node)
{
Context.ReportDiagnostic(ForEachStatement, node);
/// <inheritdoc/>
public override SyntaxNode? VisitForEachVariableStatement(ForEachVariableStatementSyntax node)
{
Context.ReportDiagnostic(ForEachStatement, node);
return base.VisitForEachVariableStatement(node);
}
return base.VisitForEachVariableStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitLockStatement(LockStatementSyntax node)
{
Context.ReportDiagnostic(LockStatement, node);
/// <inheritdoc/>
public override SyntaxNode? VisitLockStatement(LockStatementSyntax node)
{
Context.ReportDiagnostic(LockStatement, node);
return base.VisitLockStatement(node);
}
return base.VisitLockStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitQueryExpression(QueryExpressionSyntax node)
{
Context.ReportDiagnostic(QueryExpression, node);
/// <inheritdoc/>
public override SyntaxNode? VisitQueryExpression(QueryExpressionSyntax node)
{
Context.ReportDiagnostic(QueryExpression, node);
return base.VisitQueryExpression(node);
}
return base.VisitQueryExpression(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitRangeExpression(RangeExpressionSyntax node)
{
Context.ReportDiagnostic(RangeExpression, node);
/// <inheritdoc/>
public override SyntaxNode? VisitRangeExpression(RangeExpressionSyntax node)
{
Context.ReportDiagnostic(RangeExpression, node);
return base.VisitRangeExpression(node);
}
return base.VisitRangeExpression(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitRecursivePattern(RecursivePatternSyntax node)
{
Context.ReportDiagnostic(RecursivePattern, node);
/// <inheritdoc/>
public override SyntaxNode? VisitRecursivePattern(RecursivePatternSyntax node)
{
Context.ReportDiagnostic(RecursivePattern, node);
return base.VisitRecursivePattern(node);
}
return base.VisitRecursivePattern(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitRefType(RefTypeSyntax node)
{
Context.ReportDiagnostic(RefType, node);
/// <inheritdoc/>
public override SyntaxNode? VisitRefType(RefTypeSyntax node)
{
Context.ReportDiagnostic(RefType, node);
return base.VisitRefType(node);
}
return base.VisitRefType(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitRelationalPattern(RelationalPatternSyntax node)
{
Context.ReportDiagnostic(RelationalPattern, node);
/// <inheritdoc/>
public override SyntaxNode? VisitRelationalPattern(RelationalPatternSyntax node)
{
Context.ReportDiagnostic(RelationalPattern, node);
return base.VisitRelationalPattern(node);
}
return base.VisitRelationalPattern(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitSizeOfExpression(SizeOfExpressionSyntax node)
{
Context.ReportDiagnostic(SizeOfExpression, node);
/// <inheritdoc/>
public override SyntaxNode? VisitSizeOfExpression(SizeOfExpressionSyntax node)
{
Context.ReportDiagnostic(SizeOfExpression, node);
return base.VisitSizeOfExpression(node);
}
return base.VisitSizeOfExpression(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node)
{
Context.ReportDiagnostic(StackAllocArrayCreationExpression, node);
/// <inheritdoc/>
public override SyntaxNode? VisitStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node)
{
Context.ReportDiagnostic(StackAllocArrayCreationExpression, node);
return base.VisitStackAllocArrayCreationExpression(node);
}
return base.VisitStackAllocArrayCreationExpression(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitThrowExpression(ThrowExpressionSyntax node)
{
Context.ReportDiagnostic(ThrowExpressionOrStatement, node);
/// <inheritdoc/>
public override SyntaxNode? VisitThrowExpression(ThrowExpressionSyntax node)
{
Context.ReportDiagnostic(ThrowExpressionOrStatement, node);
return base.VisitThrowExpression(node);
}
return base.VisitThrowExpression(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitThrowStatement(ThrowStatementSyntax node)
{
Context.ReportDiagnostic(ThrowExpressionOrStatement, node);
/// <inheritdoc/>
public override SyntaxNode? VisitThrowStatement(ThrowStatementSyntax node)
{
Context.ReportDiagnostic(ThrowExpressionOrStatement, node);
return base.VisitThrowStatement(node);
}
return base.VisitThrowStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitTryStatement(TryStatementSyntax node)
{
Context.ReportDiagnostic(TryStatement, node);
/// <inheritdoc/>
public override SyntaxNode? VisitTryStatement(TryStatementSyntax node)
{
Context.ReportDiagnostic(TryStatement, node);
return base.VisitTryStatement(node);
}
return base.VisitTryStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitTupleType(TupleTypeSyntax node)
{
Context.ReportDiagnostic(TupleType, node);
/// <inheritdoc/>
public override SyntaxNode? VisitTupleType(TupleTypeSyntax node)
{
Context.ReportDiagnostic(TupleType, node);
return base.VisitTupleType(node);
}
return base.VisitTupleType(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitUsingStatement(UsingStatementSyntax node)
{
Context.ReportDiagnostic(UsingStatementOrDeclaration, node);
/// <inheritdoc/>
public override SyntaxNode? VisitUsingStatement(UsingStatementSyntax node)
{
Context.ReportDiagnostic(UsingStatementOrDeclaration, node);
return base.VisitUsingStatement(node);
}
return base.VisitUsingStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitYieldStatement(YieldStatementSyntax node)
{
Context.ReportDiagnostic(YieldStatement, node);
/// <inheritdoc/>
public override SyntaxNode? VisitYieldStatement(YieldStatementSyntax node)
{
Context.ReportDiagnostic(YieldStatement, node);
return base.VisitYieldStatement(node);
}
return base.VisitYieldStatement(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitFunctionPointerType(FunctionPointerTypeSyntax node)
{
Context.ReportDiagnostic(FunctionPointer, node);
/// <inheritdoc/>
public override SyntaxNode? VisitFunctionPointerType(FunctionPointerTypeSyntax node)
{
Context.ReportDiagnostic(FunctionPointer, node);
return base.VisitFunctionPointerType(node);
}
return base.VisitFunctionPointerType(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitPointerType(PointerTypeSyntax node)
{
Context.ReportDiagnostic(PointerType, node);
/// <inheritdoc/>
public override SyntaxNode? VisitPointerType(PointerTypeSyntax node)
{
Context.ReportDiagnostic(PointerType, node);
return base.VisitPointerType(node);
}
return base.VisitPointerType(node);
}
/// <inheritdoc/>
public override SyntaxNode? VisitUnsafeStatement(UnsafeStatementSyntax node)
{
Context.ReportDiagnostic(UnsafeStatement, node);
/// <inheritdoc/>
public override SyntaxNode? VisitUnsafeStatement(UnsafeStatementSyntax node)
{
Context.ReportDiagnostic(UnsafeStatement, node);
return base.VisitUnsafeStatement(node);
}
return base.VisitUnsafeStatement(node);
}
}
+278 -279
ファイルの表示
@@ -13,330 +13,329 @@ using Microsoft.CodeAnalysis.Operations;
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.SourceGenerators.SyntaxRewriters
namespace ComputeSharp.SourceGenerators.SyntaxRewriters;
/// <summary>
/// A base <see cref="CSharpSyntaxRewriter"/> type that processes C# source to convert to HLSL compliant code.
/// This class contains only the shared logic for all derived HLSL source rewriters.
/// </summary>
internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
{
/// <summary>
/// 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.
/// The <see cref="SemanticModelProvider"/> instance with semantic info on the target syntax tree.
/// </summary>
internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
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 current generator context in use.
/// </summary>
protected readonly GeneratorExecutionContext Context;
/// <summary>
/// Creates a new <see cref="HlslSourceRewriter"/> instance with the specified parameters.
/// </summary>
/// <param name="semanticModel">The <see cref="Microsoft.CodeAnalysis.SemanticModel"/> instance for the target syntax tree.</param>
/// <param name="discoveredTypes">The set of discovered custom types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="context">The current generator context in use.</param>
protected HlslSourceRewriter(
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions,
GeneratorExecutionContext context)
{
/// <summary>
/// The <see cref="SemanticModelProvider"/> instance with semantic info on the target syntax tree.
/// </summary>
protected readonly SemanticModelProvider SemanticModel;
SemanticModel = semanticModel;
DiscoveredTypes = discoveredTypes;
ConstantDefinitions = constantDefinitions;
Context = context;
}
/// <summary>
/// The collection of discovered custom types.
/// </summary>
protected readonly ICollection<INamedTypeSymbol> DiscoveredTypes;
/// <summary>
/// Gets whether or not the shader uses a texture sampler at least once.
/// </summary>
public bool IsSamplerUsed { get; private set; }
/// <summary>
/// The collection of discovered constant definitions.
/// </summary>
protected readonly IDictionary<IFieldSymbol, string> ConstantDefinitions;
/// <inheritdoc/>
public override SyntaxNode VisitCastExpression(CastExpressionSyntax node)
{
var updatedNode = (CastExpressionSyntax)base.VisitCastExpression(node)!;
/// <summary>
/// The current generator context in use.
/// </summary>
protected readonly GeneratorExecutionContext Context;
return updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes);
}
/// <summary>
/// Creates a new <see cref="HlslSourceRewriter"/> instance with the specified parameters.
/// </summary>
/// <param name="semanticModel">The <see cref="Microsoft.CodeAnalysis.SemanticModel"/> instance for the target syntax tree.</param>
/// <param name="discoveredTypes">The set of discovered custom types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="context">The current generator context in use.</param>
protected HlslSourceRewriter(
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions,
GeneratorExecutionContext context)
/// <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)
{
SemanticModel = semanticModel;
DiscoveredTypes = discoveredTypes;
ConstantDefinitions = constantDefinitions;
Context = context;
Context.ReportDiagnostic(InvalidObjectDeclaration, node, type);
}
/// <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)
// If var is used, replace it with the explicit type
if (updatedNode.Type is IdentifierNameSyntax { IsVar: true })
{
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)
{
Context.ReportDiagnostic(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)
{
Context.ReportDiagnostic(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)
{
Context.ReportDiagnostic(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 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)
{
Context.ReportDiagnostic(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)));
}
/// <inheritdoc/>
public override SyntaxNode? VisitLiteralExpression(LiteralExpressionSyntax node)
// 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()))
{
var updatedNode = (LiteralExpressionSyntax)base.VisitLiteralExpression(node)!;
if (updatedNode.IsKind(SyntaxKind.DefaultLiteralExpression))
for (int i = 0; i < node.ArgumentList!.Arguments.Count; i++)
{
TypeSyntax type = node.TrackType(SemanticModel.For(node), DiscoveredTypes);
IArgumentOperation argumentOperation = (IArgumentOperation)SemanticModel.For(node).GetOperation(node.ArgumentList.Arguments[i])!;
INamedTypeSymbol elementType = (INamedTypeSymbol)argumentOperation.Parameter!.Type;
// Same HLSL-style expression in the form (T)0
return CastExpression(type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)));
updatedNode = updatedNode.ReplaceNode(
updatedNode.ArgumentList!.Arguments[i].Expression,
CastExpression(IdentifierName(HlslKnownTypes.GetMappedName(elementType)), updatedNode.ArgumentList.Arguments[i].Expression));
}
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))
{
Context.ReportDiagnostic(StringLiteralExpression, node);
}
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxNode? VisitElementAccessExpression(ElementAccessExpressionSyntax node)
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)
{
var updatedNode = (ElementAccessExpressionSyntax)base.VisitElementAccessExpression(node)!;
Context.ReportDiagnostic(InvalidObjectCreationExpression, node, type);
}
if (SemanticModel.For(node).GetOperation(node) is IPropertyReferenceOperation operation)
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++)
{
string propertyName = operation.Property.GetFullMetadataName();
IArgumentOperation argumentOperation = (IArgumentOperation)SemanticModel.For(node).GetOperation(node.ArgumentList.Arguments[i])!;
INamedTypeSymbol elementType = (INamedTypeSymbol)argumentOperation.Parameter!.Type;
// 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))
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)
{
var index = InvocationExpression(IdentifierName(mapping!), ArgumentList(updatedNode.ArgumentList.Arguments));
return updatedNode.WithArgumentList(BracketedArgumentList(SingletonSeparatedList(Argument(index))));
literal += ".0";
}
// Rewrite texture resource sampled accesses, if needed
if (HlslKnownMembers.TryGetMappedResourceSamplerAccessType(propertyName, out mapping))
return updatedNode.WithToken(Literal(literal, 0f));
}
else if (type.GetFullMetadataName().Equals(typeof(double).FullName))
{
return updatedNode.WithToken(Literal(updatedNode.Token.ValueText + "L", 0d));
}
}
else if (updatedNode.IsKind(SyntaxKind.StringLiteralExpression))
{
Context.ReportDiagnostic(StringLiteralExpression, node);
}
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxNode? VisitElementAccessExpression(ElementAccessExpressionSyntax node)
{
var updatedNode = (ElementAccessExpressionSyntax)base.VisitElementAccessExpression(node)!;
if (SemanticModel.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
{
IsSamplerUsed = true;
not null => Argument(InvocationExpression(IdentifierName(mapping!), ArgumentList(updatedNode.ArgumentList.Arguments))),
null => updatedNode.ArgumentList.Arguments[0]
};
// 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()))
{
Context.ReportDiagnostic(NonConstantMatrixSwizzledIndex, argument);
isValid = false;
}
}
if (isValid)
{
// Rewrite the indexer as a property access
string hlslPropertyName = string.Join("",
from argument in node.ArgumentList.Arguments
let fieldReference = (IFieldReferenceOperation)SemanticModel.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(
// 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(hlslPropertyName));
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()))
{
Context.ReportDiagnostic(NonConstantMatrixSwizzledIndex, argument);
isValid = false;
}
}
}
return updatedNode;
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));
}
}
}
/// <inheritdoc/>
public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node)
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)
{
var updatedNode = (IdentifierNameSyntax)base.VisitIdentifierName(node)!;
ConstantDefinitions[operation.Field] = ((IFormattable)operation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture);
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}";
var ownerTypeName = ((INamedTypeSymbol)operation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName();
var constantName = $"__{ownerTypeName}__{operation.Field.Name}";
return IdentifierName(constantName);
}
return updatedNode;
return IdentifierName(constantName);
}
/// <inheritdoc/>
public override SyntaxToken VisitToken(SyntaxToken token)
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))
{
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();
return ParseToken(mapped!);
}
return updatedToken.WithoutTrivia();
}
}
+379 -380
ファイルの表示
@@ -13,432 +13,431 @@ using Microsoft.CodeAnalysis.Operations;
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.SourceGenerators.SyntaxRewriters
namespace ComputeSharp.SourceGenerators.SyntaxRewriters;
/// <summary>
/// A custom <see cref="CSharpSyntaxRewriter"/> type that processes C# methods to convert to HLSL compliant code.
/// </summary>
internal sealed class ShaderSourceRewriter : HlslSourceRewriter
{
/// <summary>
/// A custom <see cref="CSharpSyntaxRewriter"/> type that processes C# methods to convert to HLSL compliant code.
/// The type symbol for the shader type.
/// </summary>
internal sealed class ShaderSourceRewriter : HlslSourceRewriter
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="ShaderSourceRewriter"/> instance with the specified parameters.
/// </summary>
/// <param name="shaderType">The type symbol for the shader type.</param>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the target syntax tree.</param>
/// <param name="discoveredTypes">The set of discovered custom types.</param>
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="context">The current generator context in use.</param>
/// <param name="isEntryPoint">Whether or not the current instance is processing a shader entry point.</param>
public ShaderSourceRewriter(
INamedTypeSymbol shaderType,
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IFieldSymbol, string> constantDefinitions,
GeneratorExecutionContext context,
bool isEntryPoint)
: base(semanticModel, discoveredTypes, constantDefinitions, context)
{
/// <summary>
/// The type symbol for the shader type.
/// </summary>
private readonly INamedTypeSymbol? shaderType;
this.shaderType = shaderType;
this.staticMethods = staticMethods;
this.localFunctions = new();
this.implicitVariables = new();
this.isEntryPoint = isEntryPoint;
}
/// <summary>
/// The collection of discovered static methods.
/// </summary>
private readonly IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods;
/// <summary>
/// Creates a new <see cref="ShaderSourceRewriter"/> instance with the specified parameters.
/// </summary>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the target syntax tree.</param>
/// <param name="discoveredTypes">The set of discovered custom types.</param>
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="context">The current generator context in use.</param>
public ShaderSourceRewriter(
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IFieldSymbol, string> constantDefinitions,
GeneratorExecutionContext context)
: base(semanticModel, discoveredTypes, constantDefinitions, context)
{
this.staticMethods = staticMethods;
this.implicitVariables = new();
this.localFunctions = new();
}
/// <summary>
/// The collection of processed local functions in the current tree.
/// </summary>
private readonly Dictionary<string, LocalFunctionStatementSyntax> localFunctions;
/// <summary>
/// Gets the collection of processed local functions in the current tree.
/// </summary>
public IReadOnlyDictionary<string, LocalFunctionStatementSyntax> LocalFunctions => this.localFunctions;
/// <summary>
/// The list of implicit variables to declare at the start of the body.
/// </summary>
private readonly List<VariableDeclarationSyntax> implicitVariables;
/// <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>
/// Whether or not the current instance is processing a shader entry point.
/// </summary>
private readonly bool isEntryPoint;
/// <summary>
/// Gets whether or not the shader uses <see cref="GroupIds.Index/> at least once.
/// </summary>
public bool IsGroupIdsIndexUsed { get; private set; }
/// <summary>
/// The current <see cref="MethodDeclarationSyntax"/> tree being visited.
/// </summary>
private MethodDeclarationSyntax? currentMethod;
/// <summary>
/// Gets whether or not the shader uses <see cref="GridIds"/> at least once.
/// </summary>
public bool IsGridIdsUsed { get; set; }
/// <summary>
/// The current depth inside local declarations.
/// </summary>
private int localFunctionDepth;
/// <inheritdoc cref="CSharpSyntaxRewriter.Visit(SyntaxNode?)"/>
public MethodDeclarationSyntax? Visit(MethodDeclarationSyntax? node)
{
this.currentMethod = node;
/// <summary>
/// Creates a new <see cref="ShaderSourceRewriter"/> instance with the specified parameters.
/// </summary>
/// <param name="shaderType">The type symbol for the shader type.</param>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the target syntax tree.</param>
/// <param name="discoveredTypes">The set of discovered custom types.</param>
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="context">The current generator context in use.</param>
/// <param name="isEntryPoint">Whether or not the current instance is processing a shader entry point.</param>
public ShaderSourceRewriter(
INamedTypeSymbol shaderType,
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IFieldSymbol, string> constantDefinitions,
GeneratorExecutionContext context,
bool isEntryPoint)
: base(semanticModel, discoveredTypes, constantDefinitions, context)
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)))
{
this.shaderType = shaderType;
this.staticMethods = staticMethods;
this.localFunctions = new();
this.implicitVariables = new();
this.isEntryPoint = isEntryPoint;
Context.ReportDiagnostic(AsyncModifierOnMethodOrFunction, node);
}
/// <summary>
/// Creates a new <see cref="ShaderSourceRewriter"/> instance with the specified parameters.
/// </summary>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the target syntax tree.</param>
/// <param name="discoveredTypes">The set of discovered custom types.</param>
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="context">The current generator context in use.</param>
public ShaderSourceRewriter(
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IFieldSymbol, string> constantDefinitions,
GeneratorExecutionContext context)
: base(semanticModel, discoveredTypes, constantDefinitions, context)
if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword)))
{
this.staticMethods = staticMethods;
this.implicitVariables = new();
this.localFunctions = new();
Context.ReportDiagnostic(UnsafeModifierOnMethodOrFunction, node);
}
/// <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)
if (updatedNode is not null)
{
this.currentMethod = node;
var implicitBlock = Block(this.implicitVariables.Select(static v => LocalDeclarationStatement(v)).ToArray());
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)))
{
Context.ReportDiagnostic(AsyncModifierOnMethodOrFunction, node);
}
if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword)))
{
Context.ReportDiagnostic(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;
// Add the tracked implicit declarations (at the start of the body)
updatedNode = updatedNode.WithBody(implicitBlock).AddBodyStatements(updatedNode.Body!.Statements.ToArray());
}
/// <inheritdoc/>
public override SyntaxNode VisitParameter(ParameterSyntax node)
{
var updatedNode = (ParameterSyntax)base.VisitParameter(node)!;
return updatedNode;
}
// 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
/// <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 })
{
Context.ReportDiagnostic(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)))
{
Context.ReportDiagnostic(AsyncModifierOnMethodOrFunction, node);
}
if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword)))
{
Context.ReportDiagnostic(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)
{
SyntaxKind.OutKeyword => m,
SyntaxKind.InKeyword => m,
SyntaxKind.RefKeyword => ParseToken("inout"),
_ => Token(SyntaxKind.None)
}).FirstOrDefault();
string typeName = operation.Member.ContainingType.GetFullMetadataName();
return updatedNode
.WithAttributeLists(default)
.ReplaceAndTrackType(updatedNode.Type!, node.Type!, SemanticModel.For(node), DiscoveredTypes)
.WithModifiers(TokenList(modifier));
}
if (mapping == $"__{nameof(GroupIds)}__get_Index") IsGroupIdsIndexUsed = true;
else if (typeName == typeof(GroupIds).FullName) IsGroupIdsUsed = true;
else if (typeName == typeof(GridIds).FullName) IsGridIdsUsed = true;
/// <inheritdoc/>
public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node)
{
var updatedNode = ((LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node)!);
if (SemanticModel.For(node).GetOperation(node) is IOperation { Kind: OperationKind.UsingDeclaration })
{
Context.ReportDiagnostic(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)))
{
Context.ReportDiagnostic(AsyncModifierOnMethodOrFunction, node);
}
if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword)))
{
Context.ReportDiagnostic(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)
// Check that the dispatch info types are only used from the main shader body
if (!this.isEntryPoint || this.localFunctionDepth > 0)
{
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
{
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
};
_ 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)
{
Context.ReportDiagnostic(descriptor, node);
}
if (descriptor is not null)
{
Context.ReportDiagnostic(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))
// 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
{
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));
}
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)
// 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))
{
// 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))
IMethodSymbol key = propertyOperation.Property.GetMethod!;
if (!this.staticMethods.TryGetValue(key, out MethodDeclarationSyntax? methodSyntax))
{
return updatedNode.WithExpression(ParseExpression(mapping!));
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);
}
// 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))
{
ShaderSourceRewriter shaderSourceRewriter = new(SemanticModel, DiscoveredTypes, this.staticMethods, ConstantDefinitions, Context);
MethodDeclarationSyntax
methodNode = (MethodDeclarationSyntax)method.DeclaringSyntaxReferences[0].GetSyntax(),
processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace(eol: "\n").WithoutTrivia();
this.staticMethods.Add(method, processedMethod.WithIdentifier(Identifier(methodIdentifier)));
}
return updatedNode.WithExpression(ParseExpression(methodIdentifier));
}
return InvocationExpression(IdentifierName(methodSyntax.Identifier)).AddArgumentListArguments(Argument(updatedNode.Expression));
}
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxNode? VisitArgument(ArgumentSyntax node)
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)
{
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)
// 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))
{
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.WithExpression(ParseExpression(mapping!));
}
return updatedNode;
// 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))
{
ShaderSourceRewriter shaderSourceRewriter = new(SemanticModel, DiscoveredTypes, this.staticMethods, ConstantDefinitions, Context);
MethodDeclarationSyntax
methodNode = (MethodDeclarationSyntax)method.DeclaringSyntaxReferences[0].GetSyntax(),
processedMethod = shaderSourceRewriter.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;
}
}
+93 -94
ファイルの表示
@@ -12,123 +12,122 @@ using Microsoft.CodeAnalysis.Operations;
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.SourceGenerators.SyntaxRewriters
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 StaticFieldRewriter : HlslSourceRewriter
{
/// <summary>
/// A custom <see cref="CSharpSyntaxRewriter"/> type that processes C# static field to convert to HLSL static fields (possibly constant).
/// Creates a new <see cref="StaticFieldRewriter"/> instance with the specified parameters.
/// </summary>
internal sealed class StaticFieldRewriter : HlslSourceRewriter
/// <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="context">The current generator context in use.</param>
public StaticFieldRewriter(
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions,
GeneratorExecutionContext context)
: base(semanticModel, discoveredTypes, constantDefinitions, context)
{
/// <summary>
/// Creates a new <see cref="StaticFieldRewriter"/> 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="context">The current generator context in use.</param>
public StaticFieldRewriter(
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions,
GeneratorExecutionContext context)
: base(semanticModel, discoveredTypes, constantDefinitions, context)
}
/// <inheritdoc cref="CSharpSyntaxRewriter.Visit(SyntaxNode?)"/>
public ExpressionSyntax? Visit(VariableDeclaratorSyntax? node)
{
if (node?.Initializer is EqualsValueClauseSyntax fieldInitializer)
{
return ((EqualsValueClauseSyntax)Visit(fieldInitializer))!.Value;
}
/// <inheritdoc cref="CSharpSyntaxRewriter.Visit(SyntaxNode?)"/>
public ExpressionSyntax? Visit(VariableDeclaratorSyntax? node)
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 (node?.Initializer is EqualsValueClauseSyntax fieldInitializer)
// Track and replace constants
if (operation is IFieldReferenceOperation fieldOperation &&
fieldOperation.Field.IsConst &&
fieldOperation.Type!.TypeKind != TypeKind.Enum)
{
return ((EqualsValueClauseSyntax)Visit(fieldInitializer))!.Value;
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);
}
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 (HlslKnownMembers.TryGetMappedName(operation.Member.ToDisplayString(), out string? mapping))
{
// Track and replace constants
if (operation is IFieldReferenceOperation fieldOperation &&
fieldOperation.Field.IsConst &&
fieldOperation.Type!.TypeKind != TypeKind.Enum)
if (operation.Member.IsStatic)
{
ConstantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture);
string typeName = operation.Member.ContainingType.GetFullMetadataName();
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)
// Special dispatch types are not supported from static constants
DiagnosticDescriptor? descriptor = typeName switch
{
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)
{
Context.ReportDiagnostic(descriptor, node);
}
}
// Rewrite static and instance mapped members
return operation.Member.IsStatic switch
{
true => ParseExpression(mapping!),
false => updatedNode.WithName(IdentifierName(mapping!))
_ 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)
{
Context.ReportDiagnostic(descriptor, node);
}
}
}
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))
// Rewrite static and instance mapped members
return operation.Member.IsStatic switch
{
return updatedNode.WithExpression(ParseExpression(mapping!));
}
true => ParseExpression(mapping!),
false => updatedNode.WithName(IdentifierName(mapping!))
};
}
return updatedNode;
}
/// <inheritdoc/>
public override SyntaxNode? VisitArgument(ArgumentSyntax node)
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)
{
var updatedNode = (ArgumentSyntax)base.VisitArgument(node)!;
updatedNode = updatedNode.WithRefKindKeyword(Token(SyntaxKind.None));
return updatedNode;
// 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;
}
}
+9 -10
ファイルの表示
@@ -4,14 +4,13 @@
using System.ComponentModel;
namespace System.Runtime.CompilerServices
namespace System.Runtime.CompilerServices;
/// <summary>
/// Reserved to be used by the compiler for tracking metadata.
/// This class should not be used by developers in source code.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
internal static class IsExternalInit
{
/// <summary>
/// Reserved to be used by the compiler for tracking metadata.
/// This class should not be used by developers in source code.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
internal static class IsExternalInit
{
}
}
}