Remove [ShaderMethod] support and infrastructure

このコミットが含まれているのは:
Sergio Pedri committed 2023-10-13 12:11:55 +02:00
1 親 2e020a1524
コミット 249c708466
10ファイル変更
+2 -531

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

-3
ファイルの表示
@@ -57,9 +57,6 @@
<!-- ComputeSharp APIs -->
<Compile Include="..\ComputeSharp\Core\Attributes\EmbeddedBytecodeAttribute.cs" Link="ComputeSharp\Core\Attributes\EmbeddedBytecodeAttribute.cs" />
<Compile Include="..\ComputeSharp\Core\Attributes\GroupSharedAttribute.cs" Link="ComputeSharp\Core\Attributes\GroupSharedAttribute.cs" />
<Compile Include="..\ComputeSharp.Dynamic\Attributes\ShaderMethodAttribute.cs" Link="ComputeSharp\Core\Attributes\ShaderMethodAttribute.cs" />
<Compile Include="..\ComputeSharp.Dynamic\Attributes\__Internals\ShaderMethodSourceAttribute.cs" Link="ComputeSharp\Core\Attributes\__Internals\ShaderMethodSourceAttribute.cs" />
<Compile Include="..\ComputeSharp.Dynamic\Attributes\Extensions\MethodInfoExtensions.cs" Link="ComputeSharp\Extensions\MethodInfoExtensions.cs" />
<Compile Include="..\ComputeSharp\Core\Dispatch\DispatchAxis.cs" Link="ComputeSharp\Core\Dispatch\DispatchAxis.cs" />
<Compile Include="..\ComputeSharp\Core\Dispatch\DispatchSize.cs" Link="ComputeSharp\Core\Dispatch\DispatchSize.cs" />
<Compile Include="..\ComputeSharp\Core\Dispatch\GridIds.cs" Link="ComputeSharp\Core\Dispatch\GridIds.cs" />
-41
ファイルの表示
@@ -1,41 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.SourceGenerators.Helpers;
/// <summary>
/// A class containing additional factory methods for constructing syntax nodes, tokens and trivia.
/// </summary>
internal static class SyntaxFactoryHelper
{
/// <summary>
/// Creates 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="groups">The input sequence of <see cref="string"/> groups.</param>
/// <returns>An <see cref="ArrayCreationExpressionSyntax"/> instance with the described contents.</returns>
public static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable<(string A, string B)> groups)
{
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.StringKeyword)))
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
.WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression)
.AddExpressions(
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(group.A)),
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(group.B))))).ToArray()));
}
}
+2 -2
ファイルの表示
@@ -421,7 +421,7 @@ partial class IShaderGenerator
/// </summary>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <returns>A sequence of discovered constants to declare in the shader.</returns>
internal static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary<IFieldSymbol, string> constantDefinitions)
private static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary<IFieldSymbol, string> constantDefinitions)
{
using ImmutableArrayBuilder<(string, string)> builder = new();
@@ -444,7 +444,7 @@ partial class IShaderGenerator
/// <param name="types">The sequence of discovered custom types.</param>
/// <param name="instanceMethods">The collection of discovered instance methods for custom struct types.</param>
/// <returns>A sequence of custom type definitions to add to the shader source.</returns>
internal static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes(
private static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes(
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
ISymbol sourceSymbol,
IEnumerable<INamedTypeSymbol> types,
-18
ファイルの表示
@@ -1,18 +0,0 @@
using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A model for extracted info on a processed HLSL method.
/// </summary>
/// <param name="MetadataName">The metadata name for the method.</param>
/// <param name="EntryPoint">The meethod entry point.</param>
/// <param name="DefinedTypes">The discovered declared types.</param>
/// <param name="DefinedConstants">The discovered defined constants.</param>
/// <param name="DependentMethods">The dependent captured methods.</param>
internal sealed record HlslMethodSourceInfo(
string MetadataName,
string EntryPoint,
EquatableArray<(string Name, string Definition)> DefinedTypes,
EquatableArray<(string Name, string Value)> DefinedConstants,
EquatableArray<(string Signature, string Definition)> DependentMethods);
-11
ファイルの表示
@@ -1,11 +0,0 @@
using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGeneration.Models;
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A model representing all necessary info for a full generation pass for a shader method.
/// </summary>
/// <param name="HlslMethodSource">The processed HLSL source for the shader method.</param>
/// <param name="Diagnostcs">The discovered diagnostics, if any.</param>
internal sealed record ShaderMethodInfo(HlslMethodSourceInfo HlslMethodSource, EquatableArray<DiagnosticInfo> Diagnostcs);
-190
ファイルの表示
@@ -1,190 +0,0 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using ComputeSharp.__Internals;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGeneration.Models;
using ComputeSharp.SourceGeneration.SyntaxRewriters;
using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static ComputeSharp.SourceGenerators.Helpers.SyntaxFactoryHelper;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators;
/// <summary>
/// A source generator for processing static methods referenced from compute shaders.
/// </summary>
[Generator(LanguageNames.CSharp)]
public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator
{
/// <inheritdoc/>
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// Get all declared methods (including global function declarations) with the [ShaderMethod] attribute, and their info
IncrementalValuesProvider<ShaderMethodInfo> methodInfoWithErrors =
context.SyntaxProvider
.ForAttributeWithMetadataName(
typeof(ShaderMethodAttribute).FullName,
static (node, _) => node is MethodDeclarationSyntax { AttributeLists.Count: > 0 } or LocalFunctionStatementSyntax { Parent: GlobalStatementSyntax { Parent: CompilationUnitSyntax } },
static (context, token) =>
{
HlslMethodSourceInfo hlslMethodSourceInfo = Execute.GetData(
context.SemanticModel.Compilation,
(CSharpSyntaxNode)context.TargetNode,
(IMethodSymbol)context.TargetSymbol,
out ImmutableArray<DiagnosticInfo> diagnostics);
return new ShaderMethodInfo(hlslMethodSourceInfo, diagnostics);
});
// Output the diagnostics, if any
context.ReportDiagnostics(
methodInfoWithErrors
.Select(static (item, _) => item.Diagnostcs));
// Generate the [ShaderMethodSource] attributes
context.RegisterSourceOutput(methodInfoWithErrors, static (context, item) =>
{
CompilationUnitSyntax compilationUnit = Execute.GetSyntax(item.HlslMethodSource);
string filename = item.HlslMethodSource.MetadataName.Replace('`', '-').Replace('+', '.');
context.AddSource($"{filename}.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
}
/// <summary>
/// A helper with all logic to generate the attribute declarations.
/// </summary>
private static class Execute
{
/// <summary>
/// Processes a given target method.
/// </summary>
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> or <see cref="LocalFunctionStatementSyntax"/> node to process.</param>
/// <param name="methodSymbol">The <see cref="IMethodSymbol"/> instance for the current method.</param>
/// <param name="diagnostics">The resulting diagnostics from the processing operation.</param>
public static HlslMethodSourceInfo GetData(
Compilation compilation,
CSharpSyntaxNode methodDeclaration,
IMethodSymbol methodSymbol,
out ImmutableArray<DiagnosticInfo> diagnostics)
{
using ImmutableArrayBuilder<DiagnosticInfo> builder = new();
// 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);
Dictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods = new(SymbolEqualityComparer.Default); // Unused in this generator
// Explore the syntax tree and extract the processed info
SemanticModelProvider semanticModel = new(compilation);
(string entryPoint, ImmutableArray<(string Signature, string Definition)> dependentMethods) = GetProcessedMethods(builder, methodDeclaration, semanticModel, discoveredTypes, constantDefinitions);
ImmutableArray<(string Name, string Definition)> definedTypes = IShaderGenerator.BuildHlslSource.GetDeclaredTypes(builder, methodSymbol, discoveredTypes, instanceMethods);
ImmutableArray<(string Name, string Value)> definedConstants = IShaderGenerator.BuildHlslSource.GetDefinedConstants(constantDefinitions);
diagnostics = builder.ToImmutable();
return new(
methodSymbol.GetFullyQualifiedMetadataName(includeParameters: true),
entryPoint,
definedTypes,
definedConstants,
dependentMethods);
}
/// <summary>
/// Gets a sequence of processed methods from a target method declaration.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> or <see cref="LocalFunctionStatementSyntax"/> 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>
private static (string TargetMethod, ImmutableArray<(string Signature, string Definition)> DependentMethods) GetProcessedMethods(
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
CSharpSyntaxNode methodDeclaration,
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions)
{
Dictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods = new(SymbolEqualityComparer.Default);
Dictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods = new(SymbolEqualityComparer.Default);
ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, instanceMethods, constantDefinitions, diagnostics);
// Process the possible syntax nodes
SyntaxNode visitedMethod = methodDeclaration switch
{
MethodDeclarationSyntax methodDeclarationSyntax => shaderSourceRewriter.Visit(methodDeclarationSyntax)!.WithIdentifier(Identifier(ShaderMethodSourceAttribute.InvokeMethodIdentifier)),
LocalFunctionStatementSyntax functionStatementSyntax => shaderSourceRewriter.Visit(functionStatementSyntax)!.WithIdentifier(Identifier(ShaderMethodSourceAttribute.InvokeMethodIdentifier)),
_ => throw new ArgumentException("Invalid method declaration syntax node type.")
};
// Rewrite the method syntax tree
string targetMethod = visitedMethod
.WithoutTrivia()
.NormalizeWhitespace(eol: "\n")
.ToFullString();
using ImmutableArrayBuilder<(string, string)> methods = new();
// Emit the extracted local functions
foreach (KeyValuePair<string, LocalFunctionStatementSyntax> localFunction in shaderSourceRewriter.LocalFunctions)
{
methods.Add((
localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString()));
}
// Emit the discovered static methods
foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values)
{
methods.Add((
staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
staticMethod.NormalizeWhitespace(eol: "\n").ToFullString()));
}
return (targetMethod, methods.ToImmutable());
}
/// <summary>
/// Creates a <see cref="CompilationUnitSyntax"/> instance with the processed attribute.
/// </summary>
/// <param name="methodSourceInfo">The input <see cref="HlslMethodSourceInfo"/> instance to use.</param>
public static CompilationUnitSyntax GetSyntax(HlslMethodSourceInfo methodSourceInfo)
{
// This produces an assembly attribute declaration as follows:
//
// // <auto-generated/>
// #pragma warning disable
// [assembly: global::ComputeSharp.ShaderMethodSourceAttribute(<ARGUMENTS>)]
return
CompilationUnit().AddAttributeLists(
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName($"global::{typeof(ShaderMethodSourceAttribute).FullName}")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodSourceInfo.MetadataName))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodSourceInfo.EntryPoint))),
AttributeArgument(NestedArrayExpression(methodSourceInfo.DefinedTypes)),
AttributeArgument(NestedArrayExpression(methodSourceInfo.DependentMethods)),
AttributeArgument(NestedArrayExpression(methodSourceInfo.DefinedConstants)))))
.WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList()))
.WithOpenBracketToken(Token(TriviaList(
Comment("// <auto-generated/>"),
Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))),
SyntaxKind.OpenBracketToken,
TriviaList()))
.WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword))))
.NormalizeWhitespace(eol: "\n");
}
}
}