diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs index 484d75dc..b46bcfd2 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs @@ -174,14 +174,14 @@ partial class D2DPixelShaderSourceGenerator D2DPixelShaderSourceCompilationFailedWithWin32Exception, sourceInfo.MethodName, e.HResult, - ID2D1ShaderGenerator.LoadBytecode.FixupExceptionMessage(e.Message)); + D3DCompiler.PrettifyFxcErrorMessage(e.Message)); } catch (FxcCompilationException e) { diagnostic = DeferredDiagnosticInfo.Create( D2DPixelShaderSourceCompilationFailedWithFxcCompilationException, sourceInfo.MethodName, - ID2D1ShaderGenerator.LoadBytecode.FixupExceptionMessage(e.Message)); + D3DCompiler.PrettifyFxcErrorMessage(e.Message)); } End: diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs index 40a3f440..061a20e5 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs @@ -1,12 +1,7 @@ -using System; -using System.Text; using ComputeSharp.D2D1.__Internals; -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; #pragma warning disable CS0618 @@ -22,14 +17,18 @@ partial class ID2D1ShaderGenerator /// /// Creates a instance for the EffectId property. /// - /// The input instance. - /// An opaque instance to transform the final tree into text. + /// The input instance with the effect GUID. /// The resulting instance for the EffectId property. - public static PropertyDeclarationSyntax GetSyntax(EffectIdInfo info, out Func fixup) + public static PropertyDeclarationSyntax GetSyntax(EquatableArray info) { + // Prepare the initialization text + string effectIdLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(info.AsSpan()); + + ExpressionSyntax effectIdExpression = ParseExpression($$"""new byte[] { {{effectIdLiterals}} }"""); + // Create the local declaration: // - // global::System.ReadOnlySpan bytes = new byte[] { __EMBEDDED_EFFECT_ID_BYTES }; + // global::System.ReadOnlySpan bytes = new byte[] { }; LocalDeclarationStatementSyntax guidBytesDeclaration = LocalDeclarationStatement( VariableDeclaration( @@ -38,20 +37,7 @@ partial class ID2D1ShaderGenerator .AddVariables( VariableDeclarator(Identifier("bytes")) .WithInitializer( - EqualsValueClause( - ArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) - .WithInitializer( - InitializerExpression( - SyntaxKind.ArrayInitializerExpression, - SingletonSeparatedList(IdentifierName("__EMBEDDED_EFFECT_ID_BYTES")))))))); - - // Prepare the initialization text - string effectIdLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(info.Bytes.AsSpan()); - - // Set the fixup function - fixup = tree => SourceText.From(tree.ToFullString().Replace("__EMBEDDED_EFFECT_ID_BYTES", effectIdLiterals), Encoding.UTF8); + EqualsValueClause(effectIdExpression)))); // Prepare the return statement: // diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs index 7ad7435a..6848e527 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs @@ -19,9 +19,9 @@ partial class ID2D1ShaderGenerator /// /// Creates a instance for the InitializeFromDispatchData method. /// - /// The dispatch info gathered for the current shader. + /// The discovered fields of the current shader. /// The resulting instance for the InitializeFromDispatchData method. - public static MethodDeclarationSyntax GetSyntax(DispatchDataInfo dispatchInfo) + public static MethodDeclarationSyntax GetSyntax(EquatableArray fields) { // This code produces a method declaration as follows: // @@ -35,7 +35,7 @@ partial class ID2D1ShaderGenerator .AddParameterListParameters(Parameter(Identifier("data")).WithType( GenericName(Identifier("global::System.ReadOnlySpan")) .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))))) - .WithBody(Block(GetDispatchDataUnloadingStatements(dispatchInfo.FieldInfos))); + .WithBody(Block(GetDispatchDataUnloadingStatements(fields))); } /// diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs index 53127aed..d5597ef5 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs @@ -20,19 +20,19 @@ partial class ID2D1ShaderGenerator /// /// Creates a instance for the InputDescriptions property. /// - /// The input descriptions info gathered for the current shader. - /// Any additional instances needed by the generated code, if needed. + /// The input descriptions info gathered for the current shader. + /// Any additional instances needed by the generated code, if needed. /// The resulting instance for the InputDescriptions property. - public static PropertyDeclarationSyntax GetSyntax(InputDescriptionsInfo inputDescriptionsInfo, out TypeDeclarationSyntax[] additionalTypes) + public static PropertyDeclarationSyntax GetSyntax(EquatableArray inputDescriptions, out MemberDeclarationSyntax[] additionalDataMembers) { ExpressionSyntax memoryExpression; // If there are no input descriptions, just return a default expression. // Otherwise, declare the shared array and return it from the property. - if (inputDescriptionsInfo.InputDescriptions.Length == 0) + if (inputDescriptions.Length == 0) { memoryExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)); - additionalTypes = Array.Empty(); + additionalDataMembers = Array.Empty(); } else { @@ -41,7 +41,7 @@ partial class ID2D1ShaderGenerator IdentifierName("Data"), IdentifierName(nameof(InputDescriptions))); - additionalTypes = new[] { GetArrayDeclaration(inputDescriptionsInfo) }; + additionalDataMembers = new[] { GetArrayDeclaration(inputDescriptions) }; } // This code produces a method declaration as follows: @@ -61,13 +61,13 @@ partial class ID2D1ShaderGenerator /// /// Gets the array declaration for the given input descriptions. /// - /// The input descriptions info gathered for the current shader. + /// The input descriptions info gathered for the current shader. /// The array declaration for the given input descriptions. - private static TypeDeclarationSyntax GetArrayDeclaration(InputDescriptionsInfo inputDescriptionsInfo) + private static MemberDeclarationSyntax GetArrayDeclaration(EquatableArray inputDescriptions) { using ImmutableArrayBuilder inputDescriptionExpressions = ImmutableArrayBuilder.Rent(); - foreach (InputDescription inputDescription in inputDescriptionsInfo.InputDescriptions) + foreach (InputDescription inputDescription in inputDescriptions) { // Create the description expression (excluding level of detail): // @@ -109,7 +109,7 @@ partial class ID2D1ShaderGenerator // // /// The singleton array instance. // public static readonly global::ComputeSharp.D2D1.Interop.D2D1InputDescription[] InputDescriptions = { }; - FieldDeclarationSyntax fieldDeclaration = + return FieldDeclaration( VariableDeclaration( ArrayType(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1InputDescription")) @@ -124,11 +124,24 @@ partial class ID2D1ShaderGenerator Token(SyntaxKind.StaticKeyword), Token(SyntaxKind.ReadOnlyKeyword)) .WithLeadingTrivia(Comment("""/// The singleton array instance.""")); + } + + /// + /// Gets any type declarations for additional members. + /// + /// The additional members that are needed. + /// Any type declarations for additional members. + public static TypeDeclarationSyntax[] GetDataTypeDeclarations(MemberDeclarationSyntax[] memberDeclarations) + { + if (memberDeclarations.Length == 0) + { + return Array.Empty(); + } // Create the container type declaration: // // /// - // /// A container type for input descriptions. + // /// A container type for additional data needed by the shader. // /// // [global::System.CodeDom.Compiler.GeneratedCode("...", "...")] // [global::System.Diagnostics.DebuggerNonUserCode] @@ -137,7 +150,7 @@ partial class ID2D1ShaderGenerator // { // // } - return + TypeDeclarationSyntax dataTypeDeclaration = ClassDeclaration("Data") .AddModifiers(Token(SyntaxKind.FileKeyword), Token(SyntaxKind.StaticKeyword)) .AddAttributeLists( @@ -147,11 +160,13 @@ partial class ID2D1ShaderGenerator AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).Assembly.GetName().Version.ToString())))))), AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))), AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage"))))) - .AddMembers(fieldDeclaration) + .AddMembers(memberDeclarations) .WithLeadingTrivia( Comment("/// "), Comment("/// A container type for input descriptions."), Comment("/// ")); + + return new[] { dataTypeDeclaration }; } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs index 0ac2d906..66af8d0a 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs @@ -24,9 +24,9 @@ partial class ID2D1ShaderGenerator /// /// Creates a instance for the ShaderProfile property. /// - /// The input bytecode info. + /// The input shader profile. /// The resulting instance for the ShaderProfile property. - public static PropertyDeclarationSyntax GetShaderProfileSyntax(EmbeddedBytecodeInfo bytecodeInfo) + public static PropertyDeclarationSyntax GetShaderProfileSyntax(D2D1ShaderProfile shaderProfile) { // This code produces a method declaration as follows: // @@ -39,21 +39,21 @@ partial class ID2D1ShaderGenerator MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, IdentifierName("global::ComputeSharp.D2D1.D2D1ShaderProfile"), - IdentifierName(bytecodeInfo.ShaderProfile.ToString(CultureInfo.InvariantCulture))))) + IdentifierName(shaderProfile.ToString(CultureInfo.InvariantCulture))))) .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); } /// /// Creates a instance for the CompileOptions property. /// - /// The input bytecode info. + /// The input compile options. /// The resulting instance for the CompileOptions property. - public static PropertyDeclarationSyntax GetCompileOptionsSyntax(EmbeddedBytecodeInfo bytecodeInfo) + public static PropertyDeclarationSyntax GetCompileOptionsSyntax(D2D1CompileOptions compileOptions) { // Get a formatted representation of the compile options being used ExpressionSyntax compileOptionsExpression = ParseExpression( - bytecodeInfo.CompileOptions + compileOptions .ToString(CultureInfo.InvariantCulture) .Split(',') .Select(static name => $"global::ComputeSharp.D2D1.D2D1CompileOptions.{name.Trim()}") @@ -78,7 +78,7 @@ partial class ID2D1ShaderGenerator /// Any additional instances needed by the generated code, if needed. /// The resulting instance for the HlslBytecode property. public static PropertyDeclarationSyntax GetHlslBytecodeSyntax( - EmbeddedBytecodeInfo bytecodeInfo, + HlslBytecodeInfo bytecodeInfo, out Func fixup, out TypeDeclarationSyntax[] additionalTypes) { @@ -86,7 +86,7 @@ partial class ID2D1ShaderGenerator // If there is no bytecode, simply return a default expression. // Otherwise, declare the memory manager and access it. - if (bytecodeInfo.Bytecode.Length == 0) + if (bytecodeInfo is not HlslBytecodeInfo.Success success) { memoryExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)); fixup = static tree => tree.GetText(Encoding.UTF8); @@ -106,8 +106,8 @@ partial class ID2D1ShaderGenerator IdentifierName("Instance")), IdentifierName("Memory")); - TypeDeclarationSyntax memoryManagerDeclaration = GetMemoryManagerDeclaration(bytecodeInfo); - string bytecodeLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(bytecodeInfo.Bytecode.AsSpan()); + TypeDeclarationSyntax memoryManagerDeclaration = GetMemoryManagerDeclaration(); + string bytecodeLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(success.Bytecode.AsSpan()); additionalTypes = new TypeDeclarationSyntax[] { memoryManagerDeclaration }; fixup = tree => SourceText.From(tree.ToFullString().Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals), Encoding.UTF8); @@ -130,9 +130,8 @@ partial class ID2D1ShaderGenerator /// /// Gets a instance with the logic to try to get a compiled shader bytecode. /// - /// The input bytecode info. /// The instance trying to retrieve the precompiled shader. - private static unsafe TypeDeclarationSyntax GetMemoryManagerDeclaration(EmbeddedBytecodeInfo bytecodeInfo) + private static unsafe TypeDeclarationSyntax GetMemoryManagerDeclaration() { // Create the MemoryManager declaration: // diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs index cc9a22f1..cb8a3946 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs @@ -3,7 +3,6 @@ using System.Collections.Immutable; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; -using System.Text.RegularExpressions; using System.Threading; using ComputeSharp.D2D1.Exceptions; using ComputeSharp.D2D1.Shaders.Translation; @@ -27,11 +26,11 @@ partial class ID2D1ShaderGenerator internal static partial class LoadBytecode { /// - /// Extracts the shader profile for the current shader. + /// Extracts the requested shader profile for the current shader. /// /// The input instance to process. - /// The shader profile to use to compile the shader, if present. - public static D2D1ShaderProfile? GetShaderProfile(INamedTypeSymbol structDeclarationSymbol) + /// The requested shader profile to use to compile the shader, if present. + public static D2D1ShaderProfile? GetRequestedShaderProfile(INamedTypeSymbol structDeclarationSymbol) { if (structDeclarationSymbol.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.D2D1.D2DShaderProfileAttribute", out AttributeData? attributeData)) { @@ -47,12 +46,12 @@ partial class ID2D1ShaderGenerator } /// - /// Extracts the compile options for the current shader. + /// Extracts the requested compile options for the current shader. /// /// The collection of produced instances. /// The input instance to process. - /// The compile options to use to compile the shader, if present. - public static D2D1CompileOptions? GetCompileOptions(ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol) + /// The requested compile options to use to compile the shader, if present. + public static D2D1CompileOptions? GetRequestedCompileOptions(ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol) { if (structDeclarationSymbol.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute", out AttributeData? attributeData)) { @@ -79,6 +78,30 @@ partial class ID2D1ShaderGenerator return null; } + /// + /// Gets the effective shader profile to use. + /// + /// The requested shader profile. + /// The effective shader profile. + public static D2D1ShaderProfile GetEffectiveShaderProfile(D2D1ShaderProfile? shaderProfile) + { + // The effective shader profile is either be the requested one, or the default value (which maps to PS5.0) + return shaderProfile ?? D2D1ShaderProfile.PixelShader50; + } + + /// + /// Gets the effective compile options to use. + /// + /// The requested compile options. + /// Whether the input shader supports linking. + /// The effective compile options. + public static D2D1CompileOptions GetEffectiveCompileOptions(D2D1CompileOptions? compileOptions, bool isLinkingSupported) + { + // If an explicit set of compile options is provided, use that directly. Otherwise, use the default + // options plus the option to enable linking only if the shader can potentially support it. + return compileOptions ?? (D2D1CompileOptions.Default | (isLinkingSupported ? D2D1CompileOptions.EnableLinking : 0)); + } + /// /// Extracts the metadata definition for the current shader. /// @@ -113,49 +136,31 @@ partial class ID2D1ShaderGenerator } /// - /// Gets an instance with the compiled bytecode for the current shader. + /// Gets the instance for the input shader info. /// - /// The source info for the shader to compile. + /// The instance for the shader to compile. /// The used to cancel the operation, if needed. - /// The effective shader profile used to create the shader bytecode, or the default profile to use. - /// The effective compile options used to create the shader bytecode, or the default options to use. - /// The resulting diagnostic from the processing operation, if any. - /// The instance with the compiled shader bytecode. - public static unsafe ImmutableArray GetBytecode( - HlslShaderSourceInfo sourceInfo, - CancellationToken token, - out D2D1ShaderProfile shaderProfile, - out D2D1CompileOptions compileOptions, - out DeferredDiagnosticInfo? diagnostic) + /// + public static unsafe HlslBytecodeInfo GetInfo(HlslBytecodeInfoKey key, CancellationToken token) { - // Set the shader profile to either be the requested one, or the default value (which maps to PS5.0) - shaderProfile = sourceInfo.ShaderProfile ?? D2D1ShaderProfile.PixelShader50; - - // If an explicit set of compile options is provided, use that directly. Otherwise, use the default - // options plus the option to enable linking only if the shader can potentially support it. - compileOptions = sourceInfo.CompileOptions ?? (D2D1CompileOptions.Default | (sourceInfo.IsLinkingSupported ? D2D1CompileOptions.EnableLinking : 0)); - - ImmutableArray bytecode = ImmutableArray.Empty; - // No embedded shader was requested, or there were some errors earlier in the pipeline. // In this case, skip the compilation, as diagnostic will be emitted for those anyway. // Compiling would just add overhead and result in more errors, as the HLSL would be invalid. - if (sourceInfo is { HasErrors: true } or { ShaderProfile: null }) + // We also skip compilation if no shader profile has been requested (we never just assume one). + if (key.HasErrors || key.RequestedShaderProfile is null) { - diagnostic = null; - - goto End; + return HlslBytecodeInfo.Missing.Instance; } try { token.ThrowIfCancellationRequested(); - // Compile the shader bytecode using the requested parameters + // Compile the shader bytecode using the effective parameters using ComPtr dxcBlobBytecode = D3DCompiler.Compile( - sourceInfo.HlslSource.AsSpan(), - sourceInfo.ShaderProfile.Value, - compileOptions); + key.HlslSource.AsSpan(), + key.EffectiveShaderProfile, + key.EffectiveCompileOptions); token.ThrowIfCancellationRequested(); @@ -164,35 +169,52 @@ partial class ID2D1ShaderGenerator byte[] array = new ReadOnlySpan(buffer, length).ToArray(); - bytecode = Unsafe.As>(ref array); - diagnostic = null; + ImmutableArray bytecode = Unsafe.As>(ref array); + + return new HlslBytecodeInfo.Success(bytecode); } catch (Win32Exception e) { - compileOptions = default; - diagnostic = DeferredDiagnosticInfo.Create(EmbeddedBytecodeFailedWithWin32Exception, e.HResult, FixupExceptionMessage(e.Message)); + return new HlslBytecodeInfo.Win32Error(e.NativeErrorCode, D3DCompiler.PrettifyFxcErrorMessage(e.Message)); } catch (FxcCompilationException e) { - compileOptions = default; - diagnostic = DeferredDiagnosticInfo.Create(EmbeddedBytecodeFailedWithFxcCompilationException, FixupExceptionMessage(e.Message)); + return new HlslBytecodeInfo.FxcError(D3DCompiler.PrettifyFxcErrorMessage(e.Message)); } - - End: - return bytecode; } /// - /// Fixes up an exception message to improve the way it's displayed in VS. + /// Gets any diagnostics from a processed instance. /// - /// The input exception message. - /// The updated exception message. - internal static string FixupExceptionMessage(string message) + /// The input instance to process. + /// The source instance. + /// The collection of produced instances. + public static void GetInfoDiagnostics( + INamedTypeSymbol structDeclarationSymbol, + HlslBytecodeInfo info, + ImmutableArrayBuilder diagnostics) { - // Add square brackets around error headers - message = Regex.Replace(message, @"((?:error|warning) \w+):", static m => $"[{m.Groups[1].Value}]:"); + DiagnosticInfo? diagnostic = null; - return message.NormalizeToSingleLine(); + if (info is HlslBytecodeInfo.Win32Error win32Error) + { + diagnostic = DiagnosticInfo.Create( + EmbeddedBytecodeFailedWithWin32Exception, + structDeclarationSymbol, + new object[] { structDeclarationSymbol, win32Error.HResult, win32Error.Message }); + } + else if (info is HlslBytecodeInfo.FxcError fxcError) + { + diagnostic = DiagnosticInfo.Create( + EmbeddedBytecodeFailedWithFxcCompilationException, + structDeclarationSymbol, + new object[] { structDeclarationSymbol, fxcError.Message }); + } + + if (diagnostic is not null) + { + diagnostics.Add(diagnostic); + } } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs index 0390b344..413d6342 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs @@ -24,19 +24,24 @@ partial class ID2D1ShaderGenerator /// Creates a instance for the LoadDispatchDataMethod method. /// /// The hiararchy info of the shader type. - /// The dispatch info gathered for the current shader. + /// The description on shader instance fields. + /// The size of the shader constant buffer. /// Any additional instances needed by the generated code, if needed. /// The resulting instance for the LoadDispatchDataMethod method. - public static MethodDeclarationSyntax GetSyntax(HierarchyInfo hierarchyInfo, DispatchDataInfo dispatchInfo, out TypeDeclarationSyntax[] additionalTypes) + public static MethodDeclarationSyntax GetSyntax( + HierarchyInfo hierarchyInfo, + EquatableArray fields, + int constantBufferSizeInBytes, + out TypeDeclarationSyntax[] additionalTypes) { // Declare the mapping constant buffer type, if needed (ie. if the shader has at least one field) - if (dispatchInfo.FieldInfos.Length == 0) + if (fields.Length == 0) { additionalTypes = Array.Empty(); } else { - additionalTypes = new[] { GetConstantBufferDeclaration(hierarchyInfo, dispatchInfo.FieldInfos, dispatchInfo.ConstantBufferSizeInBytes) }; + additionalTypes = new[] { GetConstantBufferDeclaration(hierarchyInfo, fields, constantBufferSizeInBytes) }; } // This code produces a method declaration as follows: @@ -51,7 +56,7 @@ partial class ID2D1ShaderGenerator .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword), Token(SyntaxKind.UnsafeKeyword)) .AddTypeParameterListParameters(TypeParameter(Identifier("TLoader"))) .AddParameterListParameters(Parameter(Identifier("loader")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(IdentifierName("TLoader"))) - .WithBody(Block(GetDispatchDataLoadingStatements(dispatchInfo.FieldInfos, dispatchInfo.ConstantBufferSizeInBytes))); + .WithBody(Block(GetDispatchDataLoadingStatements(fields, constantBufferSizeInBytes))); } /// diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateOutputBufferProperties.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateOutputBufferProperties.Syntax.cs index a7c73bf3..f36ce9ee 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateOutputBufferProperties.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateOutputBufferProperties.Syntax.cs @@ -1,6 +1,5 @@ using System; using ComputeSharp.D2D1.__Internals; -using ComputeSharp.D2D1.SourceGenerators.Models; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; @@ -18,20 +17,20 @@ partial class ID2D1ShaderGenerator /// /// Creates a instance for the BufferPrecision property. /// - /// The input info for the shader output buffer. + /// The buffer precision for the resulting output buffer. /// The resulting instance for the BufferPrecision property. - public static PropertyDeclarationSyntax GetBufferPrecisionSyntax(OutputBufferInfo info) + public static PropertyDeclarationSyntax GetBufferPrecisionSyntax(D2D1BufferPrecision bufferPrecision) { ExpressionSyntax bufferPrecisionExpression; // Set the right expression if the buffer options are valid - if (Enum.IsDefined(typeof(D2D1BufferPrecision), info.BufferPrecision)) + if (Enum.IsDefined(typeof(D2D1BufferPrecision), bufferPrecision)) { bufferPrecisionExpression = MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, IdentifierName("ComputeSharp.D2D1.D2D1BufferPrecision"), - IdentifierName(info.BufferPrecision.ToString())); + IdentifierName(bufferPrecision.ToString())); } else { @@ -53,20 +52,20 @@ partial class ID2D1ShaderGenerator /// /// Creates a instance for the ChannelDepth property. /// - /// The input info for the shader output buffer. + /// The channel depth for the resulting output buffer. /// The resulting instance for the ChannelDepth property. - public static PropertyDeclarationSyntax GetChannelDepthSyntax(OutputBufferInfo info) + public static PropertyDeclarationSyntax GetChannelDepthSyntax(D2D1ChannelDepth channelDepth) { ExpressionSyntax channelDepthExpression; // Set the right expression if the buffer options are valid - if (Enum.IsDefined(typeof(D2D1ChannelDepth), info.ChannelDepth)) + if (Enum.IsDefined(typeof(D2D1ChannelDepth), channelDepth)) { channelDepthExpression = MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, IdentifierName("ComputeSharp.D2D1.D2D1ChannelDepth"), - IdentifierName(info.ChannelDepth.ToString())); + IdentifierName(channelDepth.ToString())); } else { diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs index 9748945f..dc3fb916 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateResourceTextureDescriptionsProperty.Syntax.cs @@ -20,19 +20,19 @@ partial class ID2D1ShaderGenerator /// /// Creates a instance for the ResourceTextureDescriptions property. /// - /// The resource texture descriptions info gathered for the current shader. - /// Any additional instances needed by the generated code, if needed. + /// The resource texture descriptions info gathered for the current shader. + /// Any additional instances needed by the generated code, if needed. /// The resulting instance for the ResourceTextureDescriptions property. - public static PropertyDeclarationSyntax GetSyntax(ResourceTextureDescriptionsInfo resourceTextureDescriptionsInfo, out TypeDeclarationSyntax[] additionalTypes) + public static PropertyDeclarationSyntax GetSyntax(EquatableArray resourceTextureDescriptions, out MemberDeclarationSyntax[] additionalDataMembers) { ExpressionSyntax memoryExpression; // If there are no resource texture descriptions, just return a default expression. // Otherwise, declare the shared array and return it from the property. - if (resourceTextureDescriptionsInfo.ResourceTextureDescriptions.Length == 0) + if (resourceTextureDescriptions.Length == 0) { memoryExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)); - additionalTypes = Array.Empty(); + additionalDataMembers = Array.Empty(); } else { @@ -41,7 +41,7 @@ partial class ID2D1ShaderGenerator IdentifierName("Data"), IdentifierName(nameof(ResourceTextureDescriptions))); - additionalTypes = new[] { GetArrayDeclaration(resourceTextureDescriptionsInfo) }; + additionalDataMembers = new[] { GetArrayDeclaration(resourceTextureDescriptions) }; } // This code produces a method declaration as follows: @@ -61,13 +61,13 @@ partial class ID2D1ShaderGenerator /// /// Gets the array declaration for the given resource texture descriptions. /// - /// The resource texture descriptions info gathered for the current shader. + /// The resource texture descriptions info gathered for the current shader. /// The array declaration for the given resource texture descriptions. - private static TypeDeclarationSyntax GetArrayDeclaration(ResourceTextureDescriptionsInfo resourceTextureDescriptionsInfo) + private static MemberDeclarationSyntax GetArrayDeclaration(EquatableArray resourceTextureDescriptions) { using ImmutableArrayBuilder resourceTextureDescriptionExpressions = ImmutableArrayBuilder.Rent(); - foreach (ResourceTextureDescription resourceTextureDescription in resourceTextureDescriptionsInfo.ResourceTextureDescriptions) + foreach (ResourceTextureDescription resourceTextureDescription in resourceTextureDescriptions) { // Create the description expression: // @@ -87,7 +87,7 @@ partial class ID2D1ShaderGenerator // // /// The singleton array instance. // public static readonly global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription[] ResourceTextureDescriptions = { }; - FieldDeclarationSyntax fieldDeclaration = + return FieldDeclaration( VariableDeclaration( ArrayType(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription")) @@ -102,34 +102,6 @@ partial class ID2D1ShaderGenerator Token(SyntaxKind.StaticKeyword), Token(SyntaxKind.ReadOnlyKeyword)) .WithLeadingTrivia(Comment("""/// The singleton array instance.""")); - - // Create the container type declaration: - // - // /// - // /// A container type for input descriptions. - // /// - // [global::System.CodeDom.Compiler.GeneratedCode("...", "...")] - // [global::System.Diagnostics.DebuggerNonUserCode] - // [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] - // file static class Data - // { - // - // } - return - ClassDeclaration("Data") - .AddModifiers(Token(SyntaxKind.FileKeyword), Token(SyntaxKind.StaticKeyword)) - .AddAttributeLists( - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments( - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).FullName))), - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).Assembly.GetName().Version.ToString())))))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage"))))) - .AddMembers(fieldDeclaration) - .WithLeadingTrivia( - Comment("/// "), - Comment("/// A container type for resource texture descriptions."), - Comment("/// ")); } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs index 7632b4a9..b3d85420 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Immutable; using System.Linq; -using System.Text; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; @@ -23,7 +22,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator public void Initialize(IncrementalGeneratorInitializationContext context) { // Discover all shader types and extract all the necessary info from each of them - IncrementalValuesProvider shaderInfoWithErrors = + IncrementalValuesProvider shaderInfo = context.SyntaxProvider .CreateSyntaxProvider( static (node, _) => node.IsTypeDeclarationWithOrPotentiallyWithBaseTypes(), @@ -93,6 +92,8 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator out ImmutableArray inputComplexIndices, out ImmutableArray inputTypes); + token.ThrowIfCancellationRequested(); + // Get the resource texture info for ResourceTextureDescriptions ResourceTextureDescriptions.GetInfo( diagnostics, @@ -100,6 +101,8 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator inputCount, out ImmutableArray resourceTextureDescriptions); + token.ThrowIfCancellationRequested(); + // Get HLSL source for HlslSource string hlslSource = HlslSource.GetHlslSource( diagnostics, @@ -112,13 +115,6 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator token.ThrowIfCancellationRequested(); - // Get the shader profile and linking info for LoadBytecode() - D2D1ShaderProfile? shaderProfile = LoadBytecode.GetShaderProfile(typeSymbol); - D2D1CompileOptions? compileOptions = LoadBytecode.GetCompileOptions(diagnostics, typeSymbol); - bool isLinkingSupported = LoadBytecode.IsSimpleInputShader(typeSymbol, inputCount); - - token.ThrowIfCancellationRequested(); - // Get the info for the output buffer properties OutputBuffer.GetInfo(typeSymbol, out D2D1BufferPrecision bufferPrecision, out D2D1ChannelDepth channelDepth); @@ -137,293 +133,111 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator token.ThrowIfCancellationRequested(); + // Get the shader profile and linking info for LoadBytecode() + bool isLinkingSupported = LoadBytecode.IsSimpleInputShader(typeSymbol, inputCount); + D2D1ShaderProfile? requestedShaderProfile = LoadBytecode.GetRequestedShaderProfile(typeSymbol); + D2D1CompileOptions? requestedCompileOptions = LoadBytecode.GetRequestedCompileOptions(diagnostics, typeSymbol); + D2D1ShaderProfile effectiveShaderProfile = LoadBytecode.GetEffectiveShaderProfile(requestedShaderProfile); + D2D1CompileOptions effectiveCompileOptions = LoadBytecode.GetEffectiveCompileOptions(requestedCompileOptions, isLinkingSupported); + bool hasErrors = diagnostics.Count > 0; + + token.ThrowIfCancellationRequested(); + + // As the last steps in the pipeline, try to compile the shader if needed. + // This is done last so that it can be skipped if any errors happened before. + HlslBytecodeInfoKey hlslInfoKey = new( + hlslSource, + requestedShaderProfile, + requestedCompileOptions, + effectiveShaderProfile, + effectiveCompileOptions, + hasErrors); + + // TODO: cache this across transform runs + HlslBytecodeInfo hlslInfo = LoadBytecode.GetInfo(hlslInfoKey, token); + + token.ThrowIfCancellationRequested(); + + // Append any diagnostic for the shader compilation + LoadBytecode.GetInfoDiagnostics(typeSymbol, hlslInfo, diagnostics); + + token.ThrowIfCancellationRequested(); + return new D2D1ShaderInfo( Hierarchy: HierarchyInfo.From(typeSymbol), - EffectId: new EffectIdInfo(effectId), + EffectId: effectId, EffectDisplayName: effectDisplayName, EffectDescription: effectDescription, EffectCategory: effectCategory, EffectAuthor: effectAuthor, - DispatchData: new DispatchDataInfo(fieldInfos, constantBufferSizeInBytes), - InputTypes: new InputTypesInfo(inputTypes), - ResourceTextureDescriptions: new ResourceTextureDescriptionsInfo(resourceTextureDescriptions), - HlslShaderSource: new HlslShaderSourceInfo( - hlslSource, - shaderProfile, - compileOptions, - isLinkingSupported, - HasErrors: diagnostics.Count > 0), - OutputBuffer: new OutputBufferInfo(bufferPrecision, channelDepth), - InputDescriptions: new InputDescriptionsInfo(inputDescriptions), + ConstantBufferSizeInBytes: constantBufferSizeInBytes, + InputTypes: inputTypes, + InputDescriptions: inputDescriptions, + ResourceTextureDescriptions: resourceTextureDescriptions, + Fields: fieldInfos, + BufferPrecision: bufferPrecision, + ChannelDepth: channelDepth, PixelOptions: pixelOptions, + HlslInfoKey: hlslInfoKey, + HlslInfo: hlslInfo, Diagnostcs: diagnostics.ToImmutable()); }) .Where(static item => item is not null)!; + // We need to create two more incremental steps to ensure we correctly emit diagnostics and re-generate sources: + // - One with just the diagnostics, which will trigger every time any of them changes + // - One with just the shader info (and no diagnostics), so that changes there don't trigger generation unnecessarily + IncrementalValuesProvider> diagnosticInfo = shaderInfo.Select(static (item, _) => item.Diagnostcs); + IncrementalValuesProvider outputInfo = shaderInfo.Select(static (item, _) => item with { Diagnostcs = default }); + // Output the diagnostics, if any - context.ReportDiagnostics( - shaderInfoWithErrors - .Select(static (item, _) => item.Diagnostcs)); + context.ReportDiagnostics(diagnosticInfo); - // Get the EffectId info (hierarchy and effect id info) - IncrementalValuesProvider<(HierarchyInfo Hierarchy, EffectIdInfo EffectId)> effectIdInfo = - shaderInfoWithErrors - .Select(static (item, _) => (item.Hierarchy, item.EffectId)); - - // Generate the EffectId properties - context.RegisterSourceOutput(effectIdInfo, static (context, item) => - { - PropertyDeclarationSyntax effectDisplayNameProperty = EffectId.GetSyntax(item.EffectId, out Func fixup); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, effectDisplayNameProperty, skipLocalsInit: false); - SourceText text = fixup(compilationUnit); - - context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(EffectId)}.g.cs", text); - }); - - // Get the EffectDisplayName info (hierarchy and effect display name) - IncrementalValuesProvider<(HierarchyInfo Hierarchy, string? EffectDisplayName)> effectDisplayNameInfo = - shaderInfoWithErrors - .Select(static (item, _) => (item.Hierarchy, item.EffectDisplayName)); - - // Generate the EffectDisplayName properties - context.RegisterSourceOutput(effectDisplayNameInfo, static (context, item) => + // Generate the source files, if any + context.RegisterSourceOutput(outputInfo, static (context, item) => { + PropertyDeclarationSyntax effectIdProperty = EffectId.GetSyntax(item.EffectId); PropertyDeclarationSyntax effectDisplayNameProperty = EffectMetadata.GetEffectDisplayNameSyntax(item.EffectDisplayName); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, effectDisplayNameProperty, skipLocalsInit: false); - - context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.EffectDisplayName.g.cs", compilationUnit.GetText(Encoding.UTF8)); - }); - - // Get the EffectDescription info (hierarchy and effect description) - IncrementalValuesProvider<(HierarchyInfo Hierarchy, string? EffectDescription)> effectDescriptionInfo = - shaderInfoWithErrors - .Select(static (item, _) => (item.Hierarchy, item.EffectDescription)); - - // Generate the EffectDescription properties - context.RegisterSourceOutput(effectDescriptionInfo, static (context, item) => - { PropertyDeclarationSyntax effectDescriptionProperty = EffectMetadata.GetEffectDescriptionSyntax(item.EffectDescription); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, effectDescriptionProperty, skipLocalsInit: false); - - context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.EffectDescription.g.cs", compilationUnit.GetText(Encoding.UTF8)); - }); - - // Get the EffectCategory info (hierarchy and effect description) - IncrementalValuesProvider<(HierarchyInfo Hierarchy, string? EffectCategory)> effectCategoryInfo = - shaderInfoWithErrors - .Select(static (item, _) => (item.Hierarchy, item.EffectCategory)); - - // Generate the EffectCategory properties - context.RegisterSourceOutput(effectCategoryInfo, static (context, item) => - { PropertyDeclarationSyntax effectCategoryProperty = EffectMetadata.GetEffectCategorySyntax(item.EffectCategory); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, effectCategoryProperty, skipLocalsInit: false); - - context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.EffectCategory.g.cs", compilationUnit.GetText(Encoding.UTF8)); - }); - - // Get the EffectAuthor info (hierarchy and effect description) - IncrementalValuesProvider<(HierarchyInfo Hierarchy, string? EffectAuthor)> effectAuthorInfo = - shaderInfoWithErrors - .Select(static (item, _) => (item.Hierarchy, item.EffectAuthor)); - - // Generate the EffectAuthor properties - context.RegisterSourceOutput(effectAuthorInfo, static (context, item) => - { - PropertyDeclarationSyntax effectCategoryProperty = EffectMetadata.GetEffectAuthorSyntax(item.EffectAuthor); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, effectCategoryProperty, skipLocalsInit: false); - - context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.EffectAuthor.g.cs", compilationUnit.GetText(Encoding.UTF8)); - }); - - // Get the InputCount info (hierarchy and input count) - IncrementalValuesProvider<(HierarchyInfo Hierarchy, int InputCount)> inputCountInfo = - shaderInfoWithErrors - .Select(static (item, _) => (item.Hierarchy, item.InputTypes.InputTypes.Length)); - - // Generate the InputCount properties - context.RegisterSourceOutput(inputCountInfo, static (context, item) => - { - PropertyDeclarationSyntax inputCountProperty = InputCount.GetSyntax(item.InputCount); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, inputCountProperty, skipLocalsInit: false); - - context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(InputCount)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); - }); - - // Get the InputTypes info (hierarchy and input types) - IncrementalValuesProvider<(HierarchyInfo Hierarchy, InputTypesInfo InputTypes)> inputTypesInfo = - shaderInfoWithErrors - .Select(static (item, _) => (item.Hierarchy, item.InputTypes)); - - // Generate the InputTypes properties - context.RegisterSourceOutput(inputTypesInfo, static (context, item) => - { - PropertyDeclarationSyntax inputTypesProperty = InputTypes.GetSyntax(item.InputTypes.InputTypes, out TypeDeclarationSyntax[] additionalTypes); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, inputTypesProperty, skipLocalsInit: false, additionalMemberDeclarations: additionalTypes); - - context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(InputTypes)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); - }); - - // Get the ResourceTextureDescriptions info (hierarchy and resource texture descriptions) - IncrementalValuesProvider<(HierarchyInfo Hierarchy, ResourceTextureDescriptionsInfo ResourceTextureDescriptions)> resourceTextureDescriptionsInfo = - shaderInfoWithErrors - .Select(static (item, _) => (item.Hierarchy, item.ResourceTextureDescriptions)); - - // Generate the ResourceTextureDescriptions properties - context.RegisterSourceOutput(resourceTextureDescriptionsInfo, static (context, item) => - { - PropertyDeclarationSyntax resourceTextureDescriptionsProperty = ResourceTextureDescriptions.GetSyntax(item.ResourceTextureDescriptions, out TypeDeclarationSyntax[] additionalTypes); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, resourceTextureDescriptionsProperty, skipLocalsInit: false, additionalMemberDeclarations: additionalTypes); - - context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(ResourceTextureDescriptions)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); - }); - - // Get the info for InitializeFromDispatchData() and LoadDispatchData() (hierarchy and dispatch data) - IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch)> dispatchDataInfo = - shaderInfoWithErrors - .Select(static (item, _) => (item.Hierarchy, item.DispatchData)); - - // Generate the InitializeFromDispatchData() and LoadDispatchData() methods - context.RegisterSourceOutput(dispatchDataInfo, static (context, item) => - { - MethodDeclarationSyntax initializeFromDispatchDataMethod = InitializeFromDispatchData.GetSyntax(item.Dispatch); - MethodDeclarationSyntax loadDispatchDataMethod = LoadDispatchData.GetSyntax(item.Hierarchy, item.Dispatch, out TypeDeclarationSyntax[] additionalTypes); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMembers( - item.Hierarchy, - memberDeclarations: new (MemberDeclarationSyntax, bool)[] { (initializeFromDispatchDataMethod, false), (loadDispatchDataMethod, true) }, - additionalMemberDeclarations: additionalTypes); - - context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadDispatchData)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); - }); - - // Get the HlslSource info (hierarchy, HLSL source and parsing options) - IncrementalValuesProvider<(HierarchyInfo Hierarchy, string HlslSource)> hlslSourceInfo = - shaderInfoWithErrors - .Select(static (item, _) => (item.Hierarchy, item.HlslShaderSource.HlslSource)); - - // Generate the HlslSource properties - context.RegisterSourceOutput(hlslSourceInfo, static (context, item) => - { - PropertyDeclarationSyntax hlslStringProperty = HlslSource.GetSyntax(item.HlslSource, item.Hierarchy.Hierarchy.Length); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, hlslStringProperty, skipLocalsInit: false); - - context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(HlslSource)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); - }); - - // Get a filtered sequence to enable caching for the HLSL source info, before the shader compilation step - IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslShaderSourceInfo Source)> shaderBytecodeInfo = - shaderInfoWithErrors - .Select(static (item, _) => (item.Hierarchy, item.HlslShaderSource)); - - // Compile the requested shader bytecodes - IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo, DeferredDiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors = - shaderBytecodeInfo - .Select(static (item, token) => - { - ImmutableArray bytecode = LoadBytecode.GetBytecode( - item.Source, - token, - out D2D1ShaderProfile shaderProfile, - out D2D1CompileOptions compileOptions, - out DeferredDiagnosticInfo? diagnostic); - - token.ThrowIfCancellationRequested(); - - EmbeddedBytecodeInfo bytecodeInfo = new( - item.Source.HlslSource, - shaderProfile, - compileOptions, - bytecode); - - return (item.Hierarchy, bytecodeInfo, diagnostic); - }); - - // Gather the diagnostics - IncrementalValuesProvider embeddedBytecodeDiagnostics = - embeddedBytecodeWithErrors - .Select(static (item, _) => (item.Hierarchy.FullyQualifiedMetadataName, item.Diagnostic)) - .Where(static item => item.Diagnostic is not null) - .Combine(context.CompilationProvider) - .Select(static (item, _) => - { - 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 LoadBytecode() info (hierarchy and compiled bytecode) - IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo)> embeddedBytecode = - embeddedBytecodeWithErrors - .Select(static (item, _) => (item.Hierarchy, item.BytecodeInfo)); - - // Generate the LoadBytecode() methods - context.RegisterSourceOutput(embeddedBytecode, static (context, item) => - { - PropertyDeclarationSyntax hlslBytecodeProperty = LoadBytecode.GetHlslBytecodeSyntax(item.BytecodeInfo, out Func fixup, out TypeDeclarationSyntax[] additionalTypes); - CompilationUnitSyntax hlslBytecodeCompilationUnit = GetCompilationUnitFromMember(item.Hierarchy, hlslBytecodeProperty, skipLocalsInit: false, additionalMemberDeclarations: additionalTypes); - SourceText text = fixup(hlslBytecodeCompilationUnit); - - context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.HlslBytecode.g.cs", text); - - PropertyDeclarationSyntax shaderProfileProperty = LoadBytecode.GetShaderProfileSyntax(item.BytecodeInfo); - CompilationUnitSyntax shaderProfileCompilationUnit = GetCompilationUnitFromMember(item.Hierarchy, shaderProfileProperty, skipLocalsInit: false); - - context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.ShaderProfile.g.cs", shaderProfileCompilationUnit.GetText(Encoding.UTF8)); - - PropertyDeclarationSyntax compileOptionsProperty = LoadBytecode.GetCompileOptionsSyntax(item.BytecodeInfo); - CompilationUnitSyntax compileOptionsCompilationUnit = GetCompilationUnitFromMember(item.Hierarchy, compileOptionsProperty, skipLocalsInit: false); - - context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.CompileOptions.g.cs", compileOptionsCompilationUnit.GetText(Encoding.UTF8)); - }); - - // Get the output buffer info (hierarchy and output buffers) - IncrementalValuesProvider<(HierarchyInfo Hierarchy, OutputBufferInfo OutputBuffer)> outputBufferInfo = - shaderInfoWithErrors - .Select(static (item, _) => (item.Hierarchy, item.OutputBuffer)); - - // Generate the output buffer properties - context.RegisterSourceOutput(outputBufferInfo, static (context, item) => - { - PropertyDeclarationSyntax bufferPrecisionProperty = OutputBuffer.GetBufferPrecisionSyntax(item.OutputBuffer); - CompilationUnitSyntax bufferPrecisionCompilationUnit = GetCompilationUnitFromMember(item.Hierarchy, bufferPrecisionProperty, skipLocalsInit: false); - - context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.BufferPrecision.g.cs", bufferPrecisionCompilationUnit.GetText(Encoding.UTF8)); - - PropertyDeclarationSyntax channelDepthProperty = OutputBuffer.GetChannelDepthSyntax(item.OutputBuffer); - CompilationUnitSyntax channelDepthCompilationUnit = GetCompilationUnitFromMember(item.Hierarchy, channelDepthProperty, skipLocalsInit: false); - - context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.ChannelDepth.g.cs", channelDepthCompilationUnit.GetText(Encoding.UTF8)); - }); - - // Get the InputDescriptions info (hierarchy and input descriptions) - IncrementalValuesProvider<(HierarchyInfo Hierarchy, InputDescriptionsInfo InputDescriptions)> inputDescriptionsInfo = - shaderInfoWithErrors - .Select(static (item, _) => (item.Hierarchy, item.InputDescriptions)); - - // Generate the InputDescriptions properties - context.RegisterSourceOutput(inputDescriptionsInfo, static (context, item) => - { - PropertyDeclarationSyntax inputDescriptionsProperty = InputDescriptions.GetSyntax(item.InputDescriptions, out TypeDeclarationSyntax[] additionalTypes); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, inputDescriptionsProperty, skipLocalsInit: false, additionalMemberDeclarations: additionalTypes); - - context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(InputDescriptions)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); - }); - - // Get the PixelOptions info (hierarchy and pixel options) - IncrementalValuesProvider<(HierarchyInfo Hierarchy, D2D1PixelOptions PixelOptions)> pixelOptionsInfo = - shaderInfoWithErrors - .Select(static (item, _) => (item.Hierarchy, item.PixelOptions)); - - // Generate the PixelOptions properties - context.RegisterSourceOutput(pixelOptionsInfo, static (context, item) => - { + PropertyDeclarationSyntax effectAuthorProperty = EffectMetadata.GetEffectAuthorSyntax(item.EffectAuthor); + PropertyDeclarationSyntax inputCountProperty = InputCount.GetSyntax(item.InputTypes.Length); + PropertyDeclarationSyntax inputTypesProperty = InputTypes.GetSyntax(item.InputTypes, out TypeDeclarationSyntax[] inputTypesAdditionalTypes); + PropertyDeclarationSyntax inputDescriptionsProperty = InputDescriptions.GetSyntax(item.InputDescriptions, out MemberDeclarationSyntax[] inputDescriptionsAdditionalDataMembers); + PropertyDeclarationSyntax resourceTextureDescriptionsProperty = ResourceTextureDescriptions.GetSyntax(item.ResourceTextureDescriptions, out MemberDeclarationSyntax[] resourceTexturesAditionalDataMembers); + PropertyDeclarationSyntax hlslStringProperty = HlslSource.GetSyntax(item.HlslInfoKey.HlslSource, item.Hierarchy.Hierarchy.Length); + PropertyDeclarationSyntax hlslBytecodeProperty = LoadBytecode.GetHlslBytecodeSyntax(item.HlslInfo, out Func fixup, out TypeDeclarationSyntax[] hlslBytecodeAdditionalTypes); + PropertyDeclarationSyntax shaderProfileProperty = LoadBytecode.GetShaderProfileSyntax(item.HlslInfoKey.EffectiveShaderProfile); + PropertyDeclarationSyntax compileOptionsProperty = LoadBytecode.GetCompileOptionsSyntax(item.HlslInfoKey.EffectiveCompileOptions); + PropertyDeclarationSyntax bufferPrecisionProperty = OutputBuffer.GetBufferPrecisionSyntax(item.BufferPrecision); + PropertyDeclarationSyntax channelDepthProperty = OutputBuffer.GetChannelDepthSyntax(item.ChannelDepth); PropertyDeclarationSyntax pixelOptionsProperty = PixelOptions.GetSyntax(item.PixelOptions); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, pixelOptionsProperty, skipLocalsInit: false); - context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(PixelOptions)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); + MethodDeclarationSyntax initializeFromDispatchDataMethod = InitializeFromDispatchData.GetSyntax(item.Fields); + MethodDeclarationSyntax loadDispatchDataMethod = LoadDispatchData.GetSyntax(item.Hierarchy, item.Fields, item.ConstantBufferSizeInBytes, out TypeDeclarationSyntax[] loadDispatchDataAditionalTypes); + + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMembers( + hierarchyInfo: item.Hierarchy, + memberDeclarations: new (MemberDeclarationSyntax, bool)[] + { + (effectIdProperty, false), (effectDisplayNameProperty, false), (effectDescriptionProperty, false), (effectCategoryProperty, false), (effectAuthorProperty, false), + (inputCountProperty, false), (inputTypesProperty, false), (inputDescriptionsProperty, false), (resourceTextureDescriptionsProperty, false), (hlslStringProperty, false), + (hlslBytecodeProperty, false), (shaderProfileProperty, false), (compileOptionsProperty, false), (bufferPrecisionProperty, false), (channelDepthProperty, false), + (pixelOptionsProperty, false), (initializeFromDispatchDataMethod, true), (loadDispatchDataMethod, true) + }, + additionalMemberDeclarations: new TypeDeclarationSyntax[][] + { + loadDispatchDataAditionalTypes, + InputDescriptions.GetDataTypeDeclarations(new[] { inputDescriptionsAdditionalDataMembers, resourceTexturesAditionalDataMembers }.SelectMany(static members => members).ToArray()), + inputTypesAdditionalTypes, hlslBytecodeAdditionalTypes + } + .SelectMany(static types => types) + .Cast() + .ToArray()); + + SourceText sourceText = fixup(compilationUnit); + + context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.g.cs", sourceText); }); } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs index 5cd2c211..1540b7a0 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs @@ -7,31 +7,37 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models; /// A model representing all necessary info for a full generation pass for a D2D1 shader. /// /// The hierarchy info for the shader type. -/// The effect id info for the shader type. +/// The GUID bytes for the effect id. /// The effect display name for the shader type, if available. /// The effect description for the shader type, if available. /// The effect category for the shader type, if available. /// The effect author for the shader type, if available. -/// The gathered shader dispatch data. +/// The size of the shader constant buffer. /// The gathered input types for the shader. -/// The gathered resource texture descriptions for the shader. -/// The processed HLSL source for the shader. -/// The output buffer info for the shader. /// The gathered input descriptions for the shader. +/// The gathered resource texture descriptions for the shader. +/// The description on shader instance fields. +/// The buffer precision for the resulting output buffer. +/// The channel depth for the resulting output buffer. /// The pixel options used by the shader. +/// The key with processed info on the shader. +/// The value with processed info on the shader. /// The discovered diagnostics, if any. internal sealed record D2D1ShaderInfo( HierarchyInfo Hierarchy, - EffectIdInfo EffectId, + EquatableArray EffectId, string? EffectDisplayName, string? EffectDescription, string? EffectCategory, string? EffectAuthor, - DispatchDataInfo DispatchData, - InputTypesInfo InputTypes, - ResourceTextureDescriptionsInfo ResourceTextureDescriptions, - HlslShaderSourceInfo HlslShaderSource, - OutputBufferInfo OutputBuffer, - InputDescriptionsInfo InputDescriptions, + int ConstantBufferSizeInBytes, + EquatableArray InputTypes, + EquatableArray InputDescriptions, + EquatableArray ResourceTextureDescriptions, + EquatableArray Fields, + D2D1BufferPrecision BufferPrecision, + D2D1ChannelDepth ChannelDepth, D2D1PixelOptions PixelOptions, + HlslBytecodeInfoKey HlslInfoKey, + HlslBytecodeInfo HlslInfo, EquatableArray Diagnostcs); \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/DispatchDataInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/DispatchDataInfo.cs deleted file mode 100644 index f2bb9a0a..00000000 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/DispatchDataInfo.cs +++ /dev/null @@ -1,10 +0,0 @@ -using ComputeSharp.SourceGeneration.Helpers; - -namespace ComputeSharp.D2D1.SourceGenerators.Models; - -/// -/// A model representing gathered info on a shader dispatch data. -/// -/// The description on shader instance fields. -/// The size of the shader constant buffer. -internal sealed record DispatchDataInfo(EquatableArray FieldInfos, int ConstantBufferSizeInBytes); \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/EffectIdInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/EffectIdInfo.cs deleted file mode 100644 index 7b0a55de..00000000 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/EffectIdInfo.cs +++ /dev/null @@ -1,9 +0,0 @@ -using ComputeSharp.SourceGeneration.Helpers; - -namespace ComputeSharp.D2D1.SourceGenerators.Models; - -/// -/// A model representing info to use to generate an effect id for a shader. -/// -/// The bytes for the processed effect id. -internal sealed record EffectIdInfo(EquatableArray Bytes); \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeInfo.cs deleted file mode 100644 index d8dade33..00000000 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeInfo.cs +++ /dev/null @@ -1,12 +0,0 @@ -using ComputeSharp.SourceGeneration.Helpers; - -namespace ComputeSharp.D2D1.SourceGenerators.Models; - -/// -/// A model representing info on a shader that has requested to be precompiled at build time. -/// -/// The HLSL source for the shader. -/// The shader profile to use to compile the shader, or the default one. -/// The compile options to use to compile the shader, or the default one. -/// The compiled shader bytecode, if available. -internal sealed record EmbeddedBytecodeInfo(string HlslSource, D2D1ShaderProfile ShaderProfile, D2D1CompileOptions CompileOptions, EquatableArray Bytecode); \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslBytecodeInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslBytecodeInfo.cs new file mode 100644 index 00000000..fc547efe --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslBytecodeInfo.cs @@ -0,0 +1,39 @@ +using ComputeSharp.SourceGeneration.Helpers; + +namespace ComputeSharp.D2D1.SourceGenerators.Models; + +/// +/// A model representing info on compiled HLSL bytecode, if available. +/// +internal abstract record HlslBytecodeInfo +{ + /// + /// A successfully compiled HLSL shader. + /// + /// The resulting HLSL bytecode. + public sealed record Success(EquatableArray Bytecode) : HlslBytecodeInfo; + + /// + /// An HLSL shader that failed to compile due to a Win32 error. + /// + /// The HRESULT for the error. + /// The error message from compiling the shader. + public sealed record Win32Error(int HResult, string Message) : HlslBytecodeInfo; + + /// + /// An HLSL shader that failed to compile due to an FXC compiler error. + /// + /// The error message from compiling the shader. + public sealed record FxcError(string Message) : HlslBytecodeInfo; + + /// + /// No HLSL bytecode is available (ie. compilation was not requested or some other error was detected). + /// + public sealed record Missing : HlslBytecodeInfo + { + /// + /// Gets the shared instance. + /// + public static Missing Instance { get; } = new(); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslBytecodeInfoKey.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslBytecodeInfoKey.cs new file mode 100644 index 00000000..772e9aea --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslBytecodeInfoKey.cs @@ -0,0 +1,18 @@ +namespace ComputeSharp.D2D1.SourceGenerators.Models; + +/// +/// A model with info to be a unique key for instances. +/// +/// The input HLSL source code. +/// The requested shader profile, if available. +/// The requested compile options, if available. +/// The effective shader profile. +/// The effective compile options. +/// Whether any errors were produced when analyzing the shader. +internal sealed record HlslBytecodeInfoKey( + string HlslSource, + D2D1ShaderProfile? RequestedShaderProfile, + D2D1CompileOptions? RequestedCompileOptions, + D2D1ShaderProfile EffectiveShaderProfile, + D2D1CompileOptions EffectiveCompileOptions, + bool HasErrors); \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslShaderSourceInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslShaderSourceInfo.cs deleted file mode 100644 index d6dea5d5..00000000 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslShaderSourceInfo.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace ComputeSharp.D2D1.SourceGenerators.Models; - -/// -/// A model for extracted info on a processed HLSL shader. -/// -/// The HLSL source. -/// The shader profile to use to compile the shader, if requested. -/// The compile options to use to compile the shader. -/// Whether the shader supports linking. -/// Whether any errors have been detected, and therefore the shader compilation should be skipped. -internal sealed record HlslShaderSourceInfo( - string HlslSource, - D2D1ShaderProfile? ShaderProfile, - D2D1CompileOptions? CompileOptions, - bool IsLinkingSupported, - bool HasErrors); \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescriptionsInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescriptionsInfo.cs deleted file mode 100644 index 2ddb65f3..00000000 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescriptionsInfo.cs +++ /dev/null @@ -1,9 +0,0 @@ -using ComputeSharp.SourceGeneration.Helpers; - -namespace ComputeSharp.D2D1.SourceGenerators.Models; - -/// -/// A model representing gathered input descriptions for a shader. -/// -/// The input descriptions for a given shader. -internal sealed record InputDescriptionsInfo(EquatableArray InputDescriptions); \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/InputTypesInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/InputTypesInfo.cs deleted file mode 100644 index bdbb2116..00000000 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/InputTypesInfo.cs +++ /dev/null @@ -1,9 +0,0 @@ -using ComputeSharp.SourceGeneration.Helpers; - -namespace ComputeSharp.D2D1.SourceGenerators.Models; - -/// -/// A model representing gathered info on a shader input types. -/// -/// The input types for a given shader. -internal sealed record InputTypesInfo(EquatableArray InputTypes); \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/OutputBufferInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/OutputBufferInfo.cs deleted file mode 100644 index 98f3b85e..00000000 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/OutputBufferInfo.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ComputeSharp.D2D1.SourceGenerators.Models; - -/// -/// A model representing the output buffer info for a shader. -/// -/// The buffer precision for the resulting output buffer. -/// The channel depth for the resulting output buffer. -internal sealed record OutputBufferInfo(D2D1BufferPrecision BufferPrecision, D2D1ChannelDepth ChannelDepth); \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/ResourceTextureDescriptionsInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/ResourceTextureDescriptionsInfo.cs deleted file mode 100644 index 4661508c..00000000 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/ResourceTextureDescriptionsInfo.cs +++ /dev/null @@ -1,9 +0,0 @@ -using ComputeSharp.SourceGeneration.Helpers; - -namespace ComputeSharp.D2D1.SourceGenerators.Models; - -/// -/// A model representing gathered resource texture descriptions for a shader. -/// -/// The resource textures for the current shader. -internal sealed record ResourceTextureDescriptionsInfo(EquatableArray ResourceTextureDescriptions); \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Translation/D3DCompiler.cs b/src/ComputeSharp.D2D1/Shaders/Translation/D3DCompiler.cs index 3159873f..26f5fe00 100644 --- a/src/ComputeSharp.D2D1/Shaders/Translation/D3DCompiler.cs +++ b/src/ComputeSharp.D2D1/Shaders/Translation/D3DCompiler.cs @@ -175,16 +175,12 @@ internal static unsafe partial class D3DCompiler } /// - /// Throws an exception when a shader compilation fails. + /// Returns a "prettified" version of an FXC error message. /// - /// The input (faulting) operation. - /// This method always throws and never actually returs. - [DoesNotReturn] - [MethodImpl(MethodImplOptions.NoInlining)] - private static void ThrowHslsCompilationException(ID3DBlob* d3DOperationResult) + /// The input error message. + /// The "prettified" error message. + public static string PrettifyFxcErrorMessage(string message) { - string message = new((sbyte*)d3DOperationResult->GetBufferPointer()); - // The error message will be in a format like this: // "C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\Roslyn\Shader@0x0000019AD1B4BA70(22,32-35): error X3004: undeclared identifier 'this'" // This regex tries to match the unnecessary header and remove it, if present. This doesn't need to be bulletproof, and this regex should match all cases anyway. @@ -227,6 +223,21 @@ internal static unsafe partial class D3DCompiler updatedMessage += '.'; } + return updatedMessage; + } + + /// + /// Throws an exception when a shader compilation fails. + /// + /// The input (faulting) operation. + /// This method always throws and never actually returs. + [DoesNotReturn] + [MethodImpl(MethodImplOptions.NoInlining)] + private static void ThrowHslsCompilationException(ID3DBlob* d3DOperationResult) + { + string message = new((sbyte*)d3DOperationResult->GetBufferPointer()); + string updatedMessage = PrettifyFxcErrorMessage(message); + throw new FxcCompilationException(updatedMessage); }