From f95079ea51ff1f3cb5f825492547b2c4ece449cc Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 9 Apr 2022 14:56:39 +0200 Subject: [PATCH] Add and implement ID2D1Shader.BuildHlslSource method --- .../Extensions/ISymbolExtensions.cs | 38 +++++++++++++++ ...ator.CreateBuildHlslSourceMethod.Syntax.cs | 42 +++++++++++++++++ ...rGenerator.CreateBuildHlslSourceMethod.cs} | 23 +++------ ...aderGenerator.CreateLoadBytecodeMethod.cs} | 17 +++++++ .../ID2D1ShaderGenerator.cs | 47 ++++++++++++------- .../Interfaces/__Internals/ID2D1Shader.cs | 18 ++++++- 6 files changed, 151 insertions(+), 34 deletions(-) create mode 100644 src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs rename src/ComputeSharp.D2D1Interop.SourceGenerators/{ID2D1ShaderGenerator.CreateLoadBytecodeMethod.HlslSource.cs => ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs} (96%) rename src/ComputeSharp.D2D1Interop.SourceGenerators/{ID2D1ShaderGenerator.CreateLoadBytecodeMethod.D3DCompile.cs => ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs} (78%) diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/ISymbolExtensions.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/ISymbolExtensions.cs index 035b3abe..9481f70e 100644 --- a/src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/ISymbolExtensions.cs +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/Extensions/ISymbolExtensions.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Collections.Immutable; using System.Linq; using System.Text; using ComputeSharp.D2D1Interop.SourceGenerators.Mappings; @@ -29,6 +30,17 @@ internal static class ISymbolExtensions .WithMemberOptions(SymbolDisplayMemberOptions.IncludeContainingType) .WithParameterOptions(SymbolDisplayParameterOptions.None); + /// + /// Checks whether or not a given type symbol has a specified full name. + /// + /// The input instance to check. + /// The full name to check. + /// Whether has a full name equals to . + public static bool HasFullyQualifiedName(this ISymbol symbol, string name) + { + return symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) == name; + } + /// /// Gets the full metadata name for a given instance. /// @@ -131,4 +143,30 @@ internal static class ISymbolExtensions return ParseTypeName(typeName.ToHlslIdentifierName()); } + + /// + /// Tries to get an attribute with the specified full name. + /// + /// The input instance to check. + /// The attribute name to look for. + /// The resulting attribute data, if found. + /// Whether or not has an attribute with the specified name. + public static bool TryGetAttributeWithFullyQualifiedName(this ISymbol symbol, string name, out AttributeData? attributeData) + { + ImmutableArray attributes = symbol.GetAttributes(); + + foreach (AttributeData attribute in attributes) + { + if (attribute.AttributeClass?.HasFullyQualifiedName(name) == true) + { + attributeData = attribute; + + return true; + } + } + + attributeData = null; + + return false; + } } diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs new file mode 100644 index 00000000..e1a06c0e --- /dev/null +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs @@ -0,0 +1,42 @@ +using ComputeSharp.D2D1Interop.__Internals; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618 + +namespace ComputeSharp.D2D1Interop.SourceGenerators; + +/// +partial class ID2D1ShaderGenerator +{ + /// + partial class BuildHlslSource + { + /// + /// Creates a instance for the BuildHlslSource method. + /// + /// The input HLSL source. + /// The resulting instance for the BuildHlslSource method. + public static MethodDeclarationSyntax GetSyntax(string hlslSource) + { + // This code produces a method declaration as follows: + // + // readonly void global::ComputeSharp.D2D1Interop.__Internals.ID2D1Shader.BuildHlslSource(out string hlslSource) + // { + // hlslSource = ; + // } + return + MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier("BuildHlslSource")) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1Interop.__Internals.{nameof(ID2D1Shader)}"))) + .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) + .AddParameterListParameters( + Parameter(Identifier("hlslSource")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(PredefinedType(Token(SyntaxKind.StringKeyword)))) + .WithBody(Block(ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + IdentifierName("hlslSource"), + LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(hlslSource)))))); + } + } +} diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.HlslSource.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs similarity index 96% rename from src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.HlslSource.cs rename to src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs index 534108e9..90fc7840 100644 --- a/src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.HlslSource.cs +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs @@ -22,9 +22,9 @@ namespace ComputeSharp.D2D1Interop.SourceGenerators; partial class ID2D1ShaderGenerator { /// - /// A helper with all logic to generate the LoadBytecode method. + /// A helper with all logic to generate the BuildHlslSource method. /// - internal static partial class LoadBytecode + internal static partial class BuildHlslSource { /// /// Gathers all necessary information on a transpiled HLSL source for a given shader type. @@ -33,8 +33,8 @@ partial class ID2D1ShaderGenerator /// The node to process. /// The for . /// The resulting diagnostics from the processing operation. - /// The resulting info on the processed shader. - public static (string HlslSource, D2D1ShaderProfile? ShaderProfile) GetHlslSource( + /// The HLSL source for the shader. + public static string GetHlslSource( Compilation compilation, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, @@ -64,13 +64,12 @@ partial class ID2D1ShaderGenerator out int inputCount, out ImmutableArray inputSimpleIndices, out ImmutableArray inputComplexIndices, - out bool requiresScenePosition, - out D2D1ShaderProfile? shaderProfile); + out bool requiresScenePosition); diagnostics = builder.ToImmutable(); // Get the HLSL source - string hlslSource = GetHlslSource( + return GetHlslSource( definedConstants, declaredTypes, valueFields, @@ -81,8 +80,6 @@ partial class ID2D1ShaderGenerator inputSimpleIndices, inputComplexIndices, requiresScenePosition); - - return (hlslSource, shaderProfile); } /// @@ -373,18 +370,15 @@ partial class ID2D1ShaderGenerator /// The indicess of the simple shader inputs. /// The indicess of the complex shader inputs. /// Whether the shader requires the scene position. - /// The shader profile to use to precompile the shader, if requested. private static void GatherD2D1AttributeInfo( INamedTypeSymbol structDeclarationSymbol, out int inputCount, out ImmutableArray inputSimpleIndices, out ImmutableArray inputComplexIndices, - out bool requiresScenePosition, - out D2D1ShaderProfile? shaderProfile) + out bool requiresScenePosition) { inputCount = 0; requiresScenePosition = false; - shaderProfile = null; ImmutableArray.Builder inputSimpleIndicesBuilder = ImmutableArray.CreateBuilder(); ImmutableArray.Builder inputComplexIndicesBuilder = ImmutableArray.CreateBuilder(); @@ -405,9 +399,6 @@ partial class ID2D1ShaderGenerator case "ComputeSharp.D2D1Interop.D2DRequiresScenePositionAttribute": requiresScenePosition = true; break; - case "ComputeSharp.D2D1Interop.D2DEmbeddedBytecodeAttribute": - shaderProfile = (D2D1ShaderProfile)attributeData.ConstructorArguments[0].Value!; - break; default: break; } diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.D3DCompile.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs similarity index 78% rename from src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.D3DCompile.cs rename to src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs index 358a4a73..243947c7 100644 --- a/src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.D3DCompile.cs +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs @@ -5,7 +5,9 @@ using System.Runtime.CompilerServices; using System.Threading; using ComputeSharp.D2D1Interop.Exceptions; using ComputeSharp.D2D1Interop.Shaders.Translation; +using ComputeSharp.D2D1Interop.SourceGenerators.Extensions; using ComputeSharp.D2D1Interop.SourceGenerators.Models; +using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; @@ -19,6 +21,21 @@ partial class ID2D1ShaderGenerator /// internal static partial class LoadBytecode { + /// + /// Extracts the 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) + { + if (structDeclarationSymbol.TryGetAttributeWithFullyQualifiedName("ComputeSharp.D2D1Interop.D2DEmbeddedBytecodeAttribute", out AttributeData? attributeData)) + { + return (D2D1ShaderProfile)attributeData!.ConstructorArguments[0].Value!; + } + + return null; + } + /// /// Gets a instance with the logic to try to get a compiled shader bytecode. /// diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.cs index 4879ca3e..87ccc6f8 100644 --- a/src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using ComputeSharp.D2D1Interop.SourceGenerators.Diagnostics; @@ -50,7 +51,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator // Get the dispatch data, HLSL source and embedded bytecode info. This info is computed on the // same step as parts are shared in following sub-branches in the incremental generator pipeline. - IncrementalValuesProvider<(Result Dispatch, Result SourceInfo)> shaderInfoWithErrors = + IncrementalValuesProvider<(Result Dispatch, Result SourceInfo, Result ProfileInfo)> shaderInfoWithErrors = shaderDeclarations .Combine(context.CompilationProvider) .Select(static (item, token) => @@ -70,8 +71,8 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator token.ThrowIfCancellationRequested(); - // Get HLSL source for LoadBytecode() - (string hlslSource, D2D1ShaderProfile? shaderProfile) = LoadBytecode.GetHlslSource( + // Get HLSL source for BuildHlslSource() + string hlslSource = BuildHlslSource.GetHlslSource( item.Right, item.Left.Syntax, item.Left.Symbol, @@ -79,14 +80,13 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator token.ThrowIfCancellationRequested(); - HlslShaderSourceInfo sourceInfo = new( - item.Left.Hierarchy, - hlslSource, - shaderProfile); + // Get the shader profile + D2D1ShaderProfile? shaderProfile = LoadBytecode.GetShaderProfile(item.Left.Symbol); return ( new Result(dispatchDataInfo, dispatchDataDiagnostics), - new Result(sourceInfo, hlslSourceDiagnostics)); + new Result(hlslSource, hlslSourceDiagnostics), + new Result(shaderProfile, ImmutableArray.Empty)); }); // Output the diagnostics @@ -94,10 +94,10 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, token) => item.SourceInfo.Errors)); // Filter all items to enable caching at a coarse level, and remove diagnostics - IncrementalValuesProvider<(DispatchDataInfo Dispatch, HlslShaderSourceInfo SourceInfo)> shaderInfo = + IncrementalValuesProvider<(DispatchDataInfo Dispatch, string HlslSource, D2D1ShaderProfile? ShaderProfile)> shaderInfo = shaderInfoWithErrors - .Select(static (item, token) => (item.Dispatch.Value, item.SourceInfo.Value)) - .WithComparers(DispatchDataInfo.Comparer.Default, HlslShaderSourceInfo.Comparer.Default); + .Select(static (item, token) => (item.Dispatch.Value, item.SourceInfo.Value, item.ProfileInfo.Value)) + .WithComparers(DispatchDataInfo.Comparer.Default, EqualityComparer.Default, EqualityComparer.Default); // Get a filtered sequence to enable caching IncrementalValuesProvider dispatchDataInfo = @@ -114,15 +114,30 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(LoadDispatchData)}", compilationUnit.ToFullString()); }); - // Get a filtered sequence to enable caching - IncrementalValuesProvider hlslSourceInfo = + // Get the filtered sequence to enable caching + IncrementalValuesProvider<(HierarchyInfo Hierarchy, string HlslSource)> hlslSourceInfo = shaderInfo - .Select(static (item, token) => item.SourceInfo) - .WithComparer(HlslShaderSourceInfo.Comparer.Default); + .Select(static (item, token) => (item.Dispatch.Hierarchy, item.HlslSource)) + .WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer.Default); + + // Generate the BuildHlslSource() methods + context.RegisterSourceOutput(hlslSourceInfo, static (context, item) => + { + MethodDeclarationSyntax buildHlslStringMethod = BuildHlslSource.GetSyntax(item.HlslSource); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, buildHlslStringMethod, canUseSkipLocalsInit: false); + + context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(BuildHlslSource)}", compilationUnit.ToFullString()); + }); + + // Get a filtered sequence to enable caching + IncrementalValuesProvider<(HierarchyInfo Hierarchy, string HlslSource, D2D1ShaderProfile? ShaderProfile)> shaderBytecodeInfo = + shaderInfo + .Select(static (item, token) => (item.Dispatch.Hierarchy, item.HlslSource, item.ShaderProfile)) + .WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer.Default, EqualityComparer.Default); // Compile the requested shader bytecodes IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo, DiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors = - hlslSourceInfo + shaderBytecodeInfo .Select(static (item, token) => { ImmutableArray bytecode = LoadBytecode.GetBytecode(item.HlslSource, item.ShaderProfile, token, out DiagnosticInfo? diagnostic); diff --git a/src/ComputeSharp.D2D1Interop/Interfaces/__Internals/ID2D1Shader.cs b/src/ComputeSharp.D2D1Interop/Interfaces/__Internals/ID2D1Shader.cs index ee6b1402..1f9666c2 100644 --- a/src/ComputeSharp.D2D1Interop/Interfaces/__Internals/ID2D1Shader.cs +++ b/src/ComputeSharp.D2D1Interop/Interfaces/__Internals/ID2D1Shader.cs @@ -28,17 +28,31 @@ public interface ID2D1Shader ; #endif + /// + /// Builds the HLSL source code for the current shader instance. + /// + /// The resulting HLSL source. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be called directly by user code")] + void BuildHlslSource(out string hlslSource) +#if NET6_0_OR_GREATER + { + throw new NotImplementedException(); + } +#else + ; +#endif + /// /// Loads the bytecode for the current shader. /// /// The type of bytecode loader being used. /// The instance to use to load the bytecode. /// The shader profile to use to get the shader bytecode (if , the precompiled shader will be used). - /// The HLSL source that was compiled. /// Thrown if a precompiled bytecode was requested ( is ), but it wasn't availablle. [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This method is not intended to be used directly by user code")] - void LoadBytecode(ref TLoader loader, D2D1ShaderProfile? shaderProfile, out string hlslSource) + void LoadBytecode(ref TLoader loader, D2D1ShaderProfile? shaderProfile) where TLoader : struct, ID2D1BytecodeLoader #if NET6_0_OR_GREATER {