Rewrite D2DPixelShaderSourceGenerator with new infra

このコミットが含まれているのは:
Sergio Pedri committed 2023-10-04 00:31:51 +02:00
1 親 1afd5a02d3
コミット 7679ae2d2b
8ファイル変更
+138 -271

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

+6 -1
ファイルの表示
@@ -163,8 +163,13 @@ public sealed partial class D2DPixelShaderDescriptorGenerator : IIncrementalGene
token.ThrowIfCancellationRequested();
// Finally, get the hierarchy too
HierarchyInfo hierarchyInfo = HierarchyInfo.From(typeSymbol);
token.ThrowIfCancellationRequested();
return new D2D1ShaderInfo(
Hierarchy: HierarchyInfo.From(typeSymbol),
Hierarchy: hierarchyInfo,
EffectId: effectId,
EffectDisplayName: effectDisplayName,
EffectDescription: effectDescription,
@@ -1,105 +0,0 @@
using System;
using System.Linq;
using System.Text;
using ComputeSharp.D2D1.SourceGenerators.Models;
using ComputeSharp.SourceGeneration.Helpers;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.D2D1.SourceGenerators;
/// <inheritdoc/>
partial class D2DPixelShaderSourceGenerator
{
/// <inheritdoc/>
partial class Execute
{
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>TryGetBytecode</c> method.
/// </summary>
/// <param name="bytecodeInfo">The input bytecode info.</param>
/// <param name="fixup">An opaque <see cref="Func{TResult}"/> instance to transform the final tree into text.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the target method.</returns>
public static MethodDeclarationSyntax GetSyntax(EmbeddedBytecodeMethodInfo bytecodeInfo, out Func<SyntaxNode, SourceText> fixup)
{
// Get the TypeSyntax for the return type (either ReadOnlySpan<byte>, or an invalid one).
// This is done so that if the user picks an invalid type, the code is still generated,
// just returning default, so that proper diagnostic can be generated, without also
// having hard to understand compiler errors due to the mismatched return type here.
TypeSyntax returnType = bytecodeInfo.InvalidReturnType is string invalidReturnType
? IdentifierName(invalidReturnType)
: GenericName(Identifier("global::System.ReadOnlySpan"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)));
BlockSyntax methodBlock;
if (bytecodeInfo.Bytecode.IsDefaultOrEmpty)
{
// This code generates the following block:
//
// {
// return default;
// }
methodBlock =
Block(ReturnStatement(
LiteralExpression(
SyntaxKind.DefaultLiteralExpression,
Token(SyntaxKind.DefaultKeyword))));
fixup = tree => tree.GetText(Encoding.UTF8);
}
else
{
// This code generates the following block:
//
// {
// return new byte[] { __EMBEDDED_SHADER_BYTECODE };
// }
//
// As in the ID2D1Shader generator, the __EMBEDDED_SHADER_BYTECODE identifier will be replaced with the bytecode
// after the full string for the syntax tree has been generated, to avoid every literal going through a token.
methodBlock =
Block(
ReturnStatement(
ArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
.WithInitializer(
InitializerExpression(
SyntaxKind.ArrayInitializerExpression,
SingletonSeparatedList<ExpressionSyntax>(IdentifierName("__EMBEDDED_SHADER_BYTECODE"))))));
string bytecodeLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(bytecodeInfo.Bytecode.AsSpan());
// Prepare the fixup function
fixup = tree => SourceText.From(tree.ToFullString().Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals), Encoding.UTF8);
}
// This code produces a branch as follows:
//
// /// <inheritdoc/>
// [global::System.CodeDom.Compiler.GeneratedCode("...", "...")]
// [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
// <MODIFIERS> <RETURN_TYPE> <METHOD_NAME>()
// <METHOD_BODY>
return
MethodDeclaration(returnType, Identifier(bytecodeInfo.MethodName))
.AddModifiers(bytecodeInfo.Modifiers.Select(static m => Token((SyntaxKind)m)).ToArray())
.AddAttributeLists(
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode"))
.AddArgumentListArguments(
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(D2DPixelShaderSourceAttribute).FullName))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(D2DPixelShaderSourceAttribute).Assembly.GetName().Version.ToString()))))))
.WithOpenBracketToken(Token(TriviaList(Comment(
$"/// <inheritdoc/>")),
SyntaxKind.OpenBracketToken,
TriviaList())),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))))
.WithBody(methodBlock);
}
}
}
+70 -54
ファイルの表示
@@ -1,17 +1,10 @@
using System;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Threading;
using ComputeSharp.D2D1.Exceptions;
using ComputeSharp.D2D1.Shaders.Translation;
using ComputeSharp.D2D1.SourceGenerators.Models;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGeneration.Models;
using Microsoft.CodeAnalysis;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
using Microsoft.CodeAnalysis.CSharp;
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
namespace ComputeSharp.D2D1.SourceGenerators;
@@ -130,62 +123,85 @@ partial class D2DPixelShaderSourceGenerator
}
/// <summary>
/// Gets an <see cref="ImmutableArray{T}"/> instance with the compiled bytecode for the current shader.
/// Gets any diagnostics from a processed <see cref="HlslBytecodeInfo"/> instance.
/// </summary>
/// <param name="sourceInfo">The source info for the shader to compile.</param>
/// <param name="token">The <see cref="CancellationToken"/> used to cancel the operation, if needed.</param>
/// <param name="diagnostic">The resulting diagnostic from the processing operation, if any.</param>
/// <returns>The <see cref="ImmutableArray{T}"/> instance with the compiled shader bytecode.</returns>
public static unsafe ImmutableArray<byte> GetBytecode(HlslShaderMethodSourceInfo sourceInfo, CancellationToken token, out DeferredDiagnosticInfo? diagnostic)
/// <param name="methodSymbol">The input <see cref="IMethodSymbol"/> instance to process.</param>
/// <param name="info">The source <see cref="HlslBytecodeInfo"/> instance.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
public static void GetInfoDiagnostics(
IMethodSymbol methodSymbol,
HlslBytecodeInfo info,
ImmutableArrayBuilder<DiagnosticInfo> diagnostics)
{
ImmutableArray<byte> bytecode = ImmutableArray<byte>.Empty;
DiagnosticInfo? diagnostic = null;
// Skip compilation if there are any errors
if (sourceInfo is { HasErrors: true })
if (info is HlslBytecodeInfo.Win32Error win32Error)
{
diagnostic = null;
goto End;
}
try
{
token.ThrowIfCancellationRequested();
// Compile the shader bytecode using the requested parameters
using ComPtr<ID3DBlob> dxcBlobBytecode = D3DCompiler.Compile(
sourceInfo.HlslSource.AsSpan(),
sourceInfo.ShaderProfile,
sourceInfo.CompileOptions);
token.ThrowIfCancellationRequested();
byte* buffer = (byte*)dxcBlobBytecode.Get()->GetBufferPointer();
int length = checked((int)dxcBlobBytecode.Get()->GetBufferSize());
byte[] array = new ReadOnlySpan<byte>(buffer, length).ToArray();
bytecode = Unsafe.As<byte[], ImmutableArray<byte>>(ref array);
diagnostic = null;
}
catch (Win32Exception e)
{
diagnostic = DeferredDiagnosticInfo.Create(
diagnostic = DiagnosticInfo.Create(
D2DPixelShaderSourceCompilationFailedWithWin32Exception,
sourceInfo.MethodName,
e.HResult,
D3DCompiler.PrettifyFxcErrorMessage(e.Message));
methodSymbol,
new object[] { methodSymbol, methodSymbol.ContainingType, win32Error.HResult, win32Error.Message });
}
catch (FxcCompilationException e)
else if (info is HlslBytecodeInfo.FxcError fxcError)
{
diagnostic = DeferredDiagnosticInfo.Create(
diagnostic = DiagnosticInfo.Create(
D2DPixelShaderSourceCompilationFailedWithFxcCompilationException,
sourceInfo.MethodName,
D3DCompiler.PrettifyFxcErrorMessage(e.Message));
methodSymbol,
new object[] { methodSymbol, methodSymbol.ContainingType, fxcError.Message });
}
End:
return bytecode;
if (diagnostic is not null)
{
diagnostics.Add(diagnostic);
}
}
/// <summary>
/// Writes the generated method for the compiled HLSL bytecode.
/// </summary>
/// <param name="info">The input <see cref="D2D1PixelShaderSourceInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteSyntax(D2D1PixelShaderSourceInfo info, IndentedTextWriter writer)
{
writer.WriteLine("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(GeneratorName);
// Write the modifiers, if any
foreach (uint modifier in info.Modifiers)
{
writer.Write(SyntaxFacts.GetText((SyntaxKind)modifier));
writer.Write(" ");
}
// Write the return type
if (info.InvalidReturnType is string invalidReturnType)
{
writer.Write(invalidReturnType);
writer.Write(" ");
}
else
{
writer.Write("global::System.ReadOnlySpan<byte> ");
}
writer.WriteLine($"{info.MethodName}()");
// Write the bytecode expression
using (writer.WriteBlock())
{
if (info.HlslInfo is HlslBytecodeInfo.Success success)
{
writer.Write("return new byte[] { ");
SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(success.Bytecode.AsSpan(), writer);
writer.WriteLine(" };");
}
else
{
writer.Write("return default;");
}
}
}
}
}
+51 -68
ファイルの表示
@@ -8,7 +8,7 @@ using ComputeSharp.SourceGeneration.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using static ComputeSharp.D2D1.SourceGenerators.D2DPixelShaderDescriptorGenerator;
namespace ComputeSharp.D2D1.SourceGenerators;
@@ -18,14 +18,17 @@ namespace ComputeSharp.D2D1.SourceGenerators;
[Generator(LanguageNames.CSharp)]
public sealed partial class D2DPixelShaderSourceGenerator : IIncrementalGenerator
{
/// <inheritdoc cref="D2DPixelShaderDescriptorGenerator.GeneratorName"/>
private const string GeneratorName = "ComputeSharp.D2D1.D2DPixelShaderSourceGenerator";
/// <inheritdoc/>
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// Get all method declarations with the [D2DPixelShaderSource] attribute and gather all necessary info
IncrementalValuesProvider<D2D1PixelShaderSourceInfo> shaderInfoWithErrors =
IncrementalValuesProvider<D2D1PixelShaderSourceInfo> methodInfo =
context.SyntaxProvider
.ForAttributeWithMetadataName(
typeof(D2DPixelShaderSourceAttribute).FullName,
"ComputeSharp.D2D1.D2DPixelShaderSourceAttribute",
static (node, _) => node is MethodDeclarationSyntax,
static (context, token) =>
{
@@ -34,87 +37,67 @@ public sealed partial class D2DPixelShaderSourceGenerator : IIncrementalGenerato
using ImmutableArrayBuilder<DiagnosticInfo> diagnostics = ImmutableArrayBuilder<DiagnosticInfo>.Rent();
// Get the processed HLSL first and check for cancellation
string hlslSource = Execute.GetHlslSource(diagnostics, methodSymbol);
token.ThrowIfCancellationRequested();
// Get the remaining info for the current shader
ImmutableArray<ushort> modifiers = methodDeclaration.Modifiers.Select(token => (ushort)token.Kind()).ToImmutableArray();
string methodName = methodSymbol.Name;
string? invalidReturnType = Execute.GetInvalidReturnType(diagnostics, methodSymbol);
string hlslSource = Execute.GetHlslSource(diagnostics, methodSymbol);
D2D1ShaderProfile shaderProfile = Execute.GetShaderProfile(diagnostics, methodSymbol);
D2D1CompileOptions compileOptions = Execute.GetCompileOptions(diagnostics, methodSymbol);
bool isCompilationEnabled = diagnostics.Count == 0;
token.ThrowIfCancellationRequested();
// Prepare the key to cache the bytecode (just like the main D2D1 generator)
HlslBytecodeInfoKey hlslInfoKey = new(
hlslSource,
shaderProfile,
compileOptions,
isCompilationEnabled);
// Get the existing compiled shader, or compile the processed HLSL code
HlslBytecodeInfo hlslInfo = HlslBytecode.GetInfo(ref hlslInfoKey, token);
token.ThrowIfCancellationRequested();
// Append any diagnostic for the shader compilation
Execute.GetInfoDiagnostics(methodSymbol, hlslInfo, diagnostics);
token.ThrowIfCancellationRequested();
// Finally, get the hierarchy too
HierarchyInfo hierarchyInfo = HierarchyInfo.From(methodSymbol.ContainingType!);
token.ThrowIfCancellationRequested();
return new D2D1PixelShaderSourceInfo(
Hierarchy: HierarchyInfo.From(methodSymbol.ContainingType!),
HlslShaderMethodSource: new HlslShaderMethodSourceInfo(
modifiers,
methodName,
invalidReturnType,
hlslSource,
shaderProfile,
compileOptions,
HasErrors: diagnostics.Count > 0),
Hierarchy: hierarchyInfo,
Modifiers: modifiers,
MethodName: methodName,
InvalidReturnType: invalidReturnType,
HlslInfoKey: hlslInfoKey,
HlslInfo: hlslInfo,
Diagnostcs: diagnostics.ToImmutable());
});
// Output the diagnostics
context.ReportDiagnostics(
shaderInfoWithErrors
.Select(static (item, _) => item.Diagnostcs));
IncrementalValuesProvider<EquatableArray<DiagnosticInfo>> diagnosticInfo = methodInfo.Select(static (item, _) => item.Diagnostcs);
IncrementalValuesProvider<D2D1PixelShaderSourceInfo> outputInfo = methodInfo.Select(static (item, _) => item with { Diagnostcs = default });
// Compile the requested shader bytecodes
IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeMethodInfo BytecodeInfo, DeferredDiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors =
shaderInfoWithErrors
.Select(static (item, token) =>
{
ImmutableArray<byte> bytecode = Execute.GetBytecode(
item.HlslShaderMethodSource,
token,
out DeferredDiagnosticInfo? diagnostic);
token.ThrowIfCancellationRequested();
EmbeddedBytecodeMethodInfo bytecodeInfo = new(
item.HlslShaderMethodSource.Modifiers,
item.HlslShaderMethodSource.MethodName,
item.HlslShaderMethodSource.InvalidReturnType,
item.HlslShaderMethodSource.HlslSource,
bytecode);
return (item.Hierarchy, bytecodeInfo, diagnostic);
});
// Gather the diagnostics
IncrementalValuesProvider<DiagnosticInfo> embeddedBytecodeDiagnostics =
embeddedBytecodeWithErrors
.Select(static (item, token) => (item.Hierarchy.FullyQualifiedMetadataName, item.Diagnostic))
.Where(static item => item.Diagnostic is not null)
.Combine(context.CompilationProvider)
.Select(static (item, token) =>
{
INamedTypeSymbol typeSymbol = item.Right.GetTypeByMetadataName(item.Left.FullyQualifiedMetadataName)!;
return DiagnosticInfo.Create(item.Left.Diagnostic!.Descriptor, typeSymbol, new object[] { typeSymbol }.Concat(item.Left.Diagnostic.Arguments).ToArray());
});
// Output the diagnostics
context.ReportDiagnostics(embeddedBytecodeDiagnostics);
// Get the filtered sequence to enable caching
IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeMethodInfo BytecodeInfo)> embeddedBytecode =
embeddedBytecodeWithErrors
.Select(static (item, token) => (item.Hierarchy, item.BytecodeInfo));
// Output the diagnostics, if any
context.ReportDiagnostics(diagnosticInfo);
// Generate the shader bytecode methods
context.RegisterSourceOutput(embeddedBytecode, static (context, item) =>
context.RegisterSourceOutput(outputInfo, static (context, item) =>
{
MethodDeclarationSyntax loadBytecodeMethod = Execute.GetSyntax(item.BytecodeInfo, out Func<SyntaxNode, SourceText> fixup);
CompilationUnitSyntax compilationUnit = item.Hierarchy.GetSyntax(loadBytecodeMethod);
SourceText text = fixup(compilationUnit);
using IndentedTextWriter writer = IndentedTextWriter.Rent();
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{item.BytecodeInfo.MethodName}.g.cs", text);
item.Hierarchy.WriteSyntax(
state: item,
writer: writer,
baseTypes: ReadOnlySpan<string>.Empty,
memberCallbacks: new IndentedTextWriter.Callback<D2D1PixelShaderSourceInfo>[] { Execute.WriteSyntax });
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{item.MethodName}.g.cs", writer.ToString());
});
}
}
+10 -2
ファイルの表示
@@ -7,9 +7,17 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// A model representing all necessary info for a full generation pass for a [D2D1PixelShaderSource] attribute.
/// </summary>
/// <param name="Hierarchy">The hierarchy info for the shader type.</param>
/// <param name="HlslShaderMethodSource">The processed HLSL source for the shader.</param>
/// <param name="Modifiers">The modifiers for the annotated method (these are <see cref="Microsoft.CodeAnalysis.CSharp.SyntaxKind"/> values, which can't be equated directly).</param>
/// <param name="MethodName">The name of the annotated method.</param>
/// <param name="InvalidReturnType">The fully qualified name of the return type, if invalid.</param>
/// <param name="HlslInfoKey">The key with processed info on the shader.</param>
/// <param name="HlslInfo">The value with processed info on the shader.</param>
/// <param name="Diagnostcs">The discovered diagnostics, if any.</param>
internal sealed record D2D1PixelShaderSourceInfo(
HierarchyInfo Hierarchy,
HlslShaderMethodSourceInfo HlslShaderMethodSource,
EquatableArray<ushort> Modifiers,
string MethodName,
string? InvalidReturnType,
HlslBytecodeInfoKey HlslInfoKey,
HlslBytecodeInfo HlslInfo,
EquatableArray<DiagnosticInfo> Diagnostcs);
-18
ファイルの表示
@@ -1,18 +0,0 @@
using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// <summary>
/// A model representing info on a shader method that has requested to be precompiled at build time.
/// </summary>
/// <param name="Modifiers">The modifiers for the annotated method (these are <see cref="Microsoft.CodeAnalysis.CSharp.SyntaxKind"/> values, which can't be equated directly).</param>
/// <param name="MethodName">The name of the annotated method.</param>
/// <param name="InvalidReturnType">The fully qualified name of the return type, if invalid.</param>
/// <param name="HlslSource">The HLSL source.</param>
/// <param name="Bytecode">The compiled shader bytecode, if available.</param>
internal sealed record EmbeddedBytecodeMethodInfo(
EquatableArray<ushort> Modifiers,
string MethodName,
string? InvalidReturnType,
string HlslSource,
EquatableArray<byte> Bytecode);
-22
ファイルの表示
@@ -1,22 +0,0 @@
using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// <summary>
/// A model for extracted info on a processed HLSL shader method.
/// </summary>
/// <param name="Modifiers">The modifiers for the annotated method (these are <see cref="Microsoft.CodeAnalysis.CSharp.SyntaxKind"/> values, which can't be equated directly).</param>
/// <param name="MethodName">The name of the annotated method.</param>
/// <param name="InvalidReturnType">The fully qualified name of the return type, if invalid.</param>
/// <param name="HlslSource">The HLSL source.</param>
/// <param name="ShaderProfile">The shader profile to use to compile the shader.</param>
/// <param name="CompileOptions">The compile options to use to compile the shader.</param>
/// <param name="HasErrors">Whether any errors have been detected, and therefore the shader compilation should be skipped.</param>
internal sealed record HlslShaderMethodSourceInfo(
EquatableArray<ushort> Modifiers,
string MethodName,
string? InvalidReturnType,
string HlslSource,
D2D1ShaderProfile ShaderProfile,
D2D1CompileOptions CompileOptions,
bool HasErrors);
+1 -1
ファイルの表示
@@ -227,7 +227,7 @@ internal sealed class IndentedTextWriter : IDisposable
/// <inheritdoc/>
public override string ToString()
{
return this.builder.ToString();
return this.builder.WrittenSpan.Trim().ToString();
}
/// <inheritdoc/>