diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs index 9342c22e..7986307b 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs @@ -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, diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.Syntax.cs deleted file mode 100644 index e55cccc9..00000000 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.Syntax.cs +++ /dev/null @@ -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; - -/// -partial class D2DPixelShaderSourceGenerator -{ - /// - partial class Execute - { - /// - /// Creates a instance for the TryGetBytecode method. - /// - /// The input bytecode info. - /// An opaque instance to transform the final tree into text. - /// The resulting instance for the target method. - public static MethodDeclarationSyntax GetSyntax(EmbeddedBytecodeMethodInfo bytecodeInfo, out Func fixup) - { - // Get the TypeSyntax for the return type (either ReadOnlySpan, 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(OmittedArraySizeExpression())))) - .WithInitializer( - InitializerExpression( - SyntaxKind.ArrayInitializerExpression, - SingletonSeparatedList(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: - // - // /// - // [global::System.CodeDom.Compiler.GeneratedCode("...", "...")] - // [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] - // () - // - 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( - $"/// ")), - SyntaxKind.OpenBracketToken, - TriviaList())), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage"))))) - .WithBody(methodBlock); - } - } -} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs index b46bcfd2..3a1e4bc1 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs @@ -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 } /// - /// Gets an instance with the compiled bytecode for the current shader. + /// Gets any diagnostics from a processed instance. /// - /// The source info for the shader to compile. - /// The used to cancel the operation, if needed. - /// The resulting diagnostic from the processing operation, if any. - /// The instance with the compiled shader bytecode. - public static unsafe ImmutableArray GetBytecode(HlslShaderMethodSourceInfo sourceInfo, CancellationToken token, out DeferredDiagnosticInfo? diagnostic) + /// The input instance to process. + /// The source instance. + /// The collection of produced instances. + public static void GetInfoDiagnostics( + IMethodSymbol methodSymbol, + HlslBytecodeInfo info, + ImmutableArrayBuilder diagnostics) { - ImmutableArray bytecode = ImmutableArray.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 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(buffer, length).ToArray(); - - bytecode = Unsafe.As>(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); + } + } + + /// + /// Writes the generated method for the compiled HLSL bytecode. + /// + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteSyntax(D2D1PixelShaderSourceInfo info, IndentedTextWriter writer) + { + writer.WriteLine("/// "); + 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 "); + } + + 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;"); + } + } } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs index af73afc5..fde55cf1 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs @@ -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 { + /// + private const string GeneratorName = "ComputeSharp.D2D1.D2DPixelShaderSourceGenerator"; + /// public void Initialize(IncrementalGeneratorInitializationContext context) { // Get all method declarations with the [D2DPixelShaderSource] attribute and gather all necessary info - IncrementalValuesProvider shaderInfoWithErrors = + IncrementalValuesProvider 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 diagnostics = ImmutableArrayBuilder.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 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> diagnosticInfo = methodInfo.Select(static (item, _) => item.Diagnostcs); + IncrementalValuesProvider 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 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 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 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.Empty, + memberCallbacks: new IndentedTextWriter.Callback[] { Execute.WriteSyntax }); + + context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{item.MethodName}.g.cs", writer.ToString()); }); } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1PixelShaderSourceInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1PixelShaderSourceInfo.cs index f355b6e6..058c383f 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1PixelShaderSourceInfo.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1PixelShaderSourceInfo.cs @@ -7,9 +7,17 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models; /// A model representing all necessary info for a full generation pass for a [D2D1PixelShaderSource] attribute. /// /// The hierarchy info for the shader type. -/// The processed HLSL source for the shader. +/// The modifiers for the annotated method (these are values, which can't be equated directly). +/// The name of the annotated method. +/// The fully qualified name of the return type, if invalid. +/// The key with processed info on the shader. +/// The value with processed info on the shader. /// The discovered diagnostics, if any. internal sealed record D2D1PixelShaderSourceInfo( HierarchyInfo Hierarchy, - HlslShaderMethodSourceInfo HlslShaderMethodSource, + EquatableArray Modifiers, + string MethodName, + string? InvalidReturnType, + HlslBytecodeInfoKey HlslInfoKey, + HlslBytecodeInfo HlslInfo, EquatableArray Diagnostcs); \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeMethodInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeMethodInfo.cs deleted file mode 100644 index 56ef702d..00000000 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeMethodInfo.cs +++ /dev/null @@ -1,18 +0,0 @@ -using ComputeSharp.SourceGeneration.Helpers; - -namespace ComputeSharp.D2D1.SourceGenerators.Models; - -/// -/// A model representing info on a shader method that has requested to be precompiled at build time. -/// -/// The modifiers for the annotated method (these are values, which can't be equated directly). -/// The name of the annotated method. -/// The fully qualified name of the return type, if invalid. -/// The HLSL source. -/// The compiled shader bytecode, if available. -internal sealed record EmbeddedBytecodeMethodInfo( - EquatableArray Modifiers, - string MethodName, - string? InvalidReturnType, - string HlslSource, - EquatableArray Bytecode); \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslShaderMethodSourceInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslShaderMethodSourceInfo.cs deleted file mode 100644 index 75ff95e0..00000000 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslShaderMethodSourceInfo.cs +++ /dev/null @@ -1,22 +0,0 @@ -using ComputeSharp.SourceGeneration.Helpers; - -namespace ComputeSharp.D2D1.SourceGenerators.Models; - -/// -/// A model for extracted info on a processed HLSL shader method. -/// -/// The modifiers for the annotated method (these are values, which can't be equated directly). -/// The name of the annotated method. -/// The fully qualified name of the return type, if invalid. -/// The HLSL source. -/// The shader profile to use to compile the shader. -/// The compile options to use to compile the shader. -/// Whether any errors have been detected, and therefore the shader compilation should be skipped. -internal sealed record HlslShaderMethodSourceInfo( - EquatableArray Modifiers, - string MethodName, - string? InvalidReturnType, - string HlslSource, - D2D1ShaderProfile ShaderProfile, - D2D1CompileOptions CompileOptions, - bool HasErrors); \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs b/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs index 9497cf23..dd28647d 100644 --- a/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs +++ b/src/ComputeSharp.SourceGeneration/Helpers/IndentedTextWriter.cs @@ -227,7 +227,7 @@ internal sealed class IndentedTextWriter : IDisposable /// public override string ToString() { - return this.builder.ToString(); + return this.builder.WrittenSpan.Trim().ToString(); } ///