From 97a2df23d50d19b4cc26b12be34f0550eabd2cc8 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 14 Sep 2023 14:45:43 +0200 Subject: [PATCH 01/17] Add ID2D1Shader.EffectDisplayName property --- ....CreateEffectDisplayNameProperty.Syntax.cs | 35 +++++++++++++++++++ .../ID2D1ShaderGenerator.Helpers.cs | 10 +++--- .../ID2D1ShaderGenerator.cs | 34 ++++++++++++------ .../Interfaces/__Internals/ID2D1Shader.cs | 8 +++++ 4 files changed, 72 insertions(+), 15 deletions(-) create mode 100644 src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectDisplayNameProperty.Syntax.cs diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectDisplayNameProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectDisplayNameProperty.Syntax.cs new file mode 100644 index 00000000..dde40d98 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectDisplayNameProperty.Syntax.cs @@ -0,0 +1,35 @@ +using ComputeSharp.D2D1.__Internals; +using ComputeSharp.SourceGeneration.Models; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618 + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +partial class ID2D1ShaderGenerator +{ + /// + partial class EffectDisplayName + { + /// + /// Creates a instance for the EffectDisplayName property. + /// + /// The input instance. + /// The resulting instance for the EffectDisplayName property. + public static PropertyDeclarationSyntax GetSyntax(HierarchyInfo info) + { + // This code produces a method declaration as follows: + // + // readonly string global::ComputeSharp.D2D1.__Internals.ID2D1Shader.EffectDisplayName => ""; + return + PropertyDeclaration(PredefinedType(Token(SyntaxKind.StringKeyword)), Identifier(nameof(EffectDisplayName))) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) + .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) + .WithExpressionBody(ArrowExpressionClause(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(info.FullyQualifiedMetadataName)))) + .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.Helpers.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.Helpers.cs index e0a8ca76..58baed10 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.Helpers.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.Helpers.cs @@ -38,12 +38,12 @@ partial class ID2D1ShaderGenerator /// Creates a instance wrapping the given method. /// /// The instance for the current type. - /// The item to insert. + /// The item to insert. /// Whether [SkipLocalsInit] can be used. - /// A object wrapping . - private static CompilationUnitSyntax GetCompilationUnitFromMethod( + /// A object wrapping . + private static CompilationUnitSyntax GetCompilationUnitFromMember( HierarchyInfo hierarchyInfo, - MethodDeclarationSyntax methodDeclaration, + MemberDeclarationSyntax memberDeclarationSyntax, bool canUseSkipLocalsInit) { // Method attributes @@ -71,6 +71,6 @@ partial class ID2D1ShaderGenerator attributes.Add(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Runtime.CompilerServices.SkipLocalsInit"))))); } - return hierarchyInfo.GetSyntax(methodDeclaration.AddAttributeLists(attributes.ToArray())); + return hierarchyInfo.GetSyntax(memberDeclarationSyntax.AddAttributeLists(attributes.ToArray())); } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs index bf135864..4bec8a17 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -136,6 +136,20 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator shaderInfoWithErrors .Select(static (item, _) => item.Diagnostcs)); + // Get the EffectDisplayName info (hierarchy) + IncrementalValuesProvider hierarchyInfo = + shaderInfoWithErrors + .Select(static (item, _) => item.Hierarchy); + + // Generate the EffectDisplayName properties + context.RegisterSourceOutput(hierarchyInfo, static (context, item) => + { + PropertyDeclarationSyntax effectDisplayNameProperty = EffectDisplayName.GetSyntax(item); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item, effectDisplayNameProperty, canUseSkipLocalsInit: false); + + context.AddSource($"{item.FullyQualifiedMetadataName}.{nameof(EffectDisplayName)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); + }); + // Get the GetInputCount() info (hierarchy and input count) IncrementalValuesProvider<(HierarchyInfo Hierarchy, int InputCount)> inputCountInfo = shaderInfoWithErrors @@ -145,7 +159,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.RegisterSourceOutput(inputCountInfo, static (context, item) => { MethodDeclarationSyntax getInputCountMethod = GetInputCount.GetSyntax(item.InputCount); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, getInputCountMethod, canUseSkipLocalsInit: false); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, getInputCountMethod, canUseSkipLocalsInit: false); context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(GetInputCount)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); @@ -159,7 +173,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.RegisterSourceOutput(inputTypesInfo, static (context, item) => { MethodDeclarationSyntax getInputTypeMethod = GetInputType.GetSyntax(item.InputTypes.InputTypes); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, getInputTypeMethod, canUseSkipLocalsInit: false); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, getInputTypeMethod, canUseSkipLocalsInit: false); context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(GetInputType)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); @@ -173,7 +187,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.RegisterSourceOutput(resourceTextureDescriptionsInfo, static (context, item) => { MethodDeclarationSyntax getInputTypeMethod = LoadResourceTextureDescriptions.GetSyntax(item.ResourceTextureDescriptions); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, getInputTypeMethod, canUseSkipLocalsInit: false); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, getInputTypeMethod, canUseSkipLocalsInit: false); context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadResourceTextureDescriptions)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); @@ -187,7 +201,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.RegisterSourceOutput(initializeFromDispatchDataInfo, static (context, item) => { MethodDeclarationSyntax loadDispatchDataMethod = InitializeFromDispatchData.GetSyntax(item.Dispatch); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, loadDispatchDataMethod, canUseSkipLocalsInit: false); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, loadDispatchDataMethod, canUseSkipLocalsInit: false); context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(InitializeFromDispatchData)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); @@ -201,7 +215,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.RegisterSourceOutput(dispatchDataInfo, static (context, item) => { MethodDeclarationSyntax loadDispatchDataMethod = LoadDispatchData.GetSyntax(item.Info.Dispatch); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Info.Hierarchy, loadDispatchDataMethod, item.CanUseSkipLocalsInit); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Info.Hierarchy, loadDispatchDataMethod, item.CanUseSkipLocalsInit); context.AddSource($"{item.Info.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadDispatchData)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); @@ -221,7 +235,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.RegisterSourceOutput(hlslSourceInfo, static (context, item) => { MethodDeclarationSyntax buildHlslStringMethod = BuildHlslSource.GetSyntax(item.Info.HlslSource, item.Info.Hierarchy.Hierarchy.Length, item.CanUseRawMultilineStringLiterals); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Info.Hierarchy, buildHlslStringMethod, canUseSkipLocalsInit: false); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Info.Hierarchy, buildHlslStringMethod, canUseSkipLocalsInit: false); context.AddSource($"{item.Info.Hierarchy.FullyQualifiedMetadataName}.{nameof(BuildHlslSource)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); @@ -279,7 +293,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.RegisterSourceOutput(embeddedBytecode, static (context, item) => { MethodDeclarationSyntax loadBytecodeMethod = LoadBytecode.GetSyntax(item.BytecodeInfo, out Func fixup); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, loadBytecodeMethod, canUseSkipLocalsInit: false); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, loadBytecodeMethod, canUseSkipLocalsInit: false); SourceText text = fixup(compilationUnit); context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadBytecode)}.g.cs", text); @@ -294,7 +308,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.RegisterSourceOutput(outputBufferInfo, static (context, item) => { MethodDeclarationSyntax getOutputBufferMethod = GetOutputBuffer.GetSyntax(item.OutputBuffer); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, getOutputBufferMethod, canUseSkipLocalsInit: false); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, getOutputBufferMethod, canUseSkipLocalsInit: false); context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(GetOutputBuffer)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); @@ -309,7 +323,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.RegisterSourceOutput(inputDescriptionsInfo, static (context, item) => { MethodDeclarationSyntax loadInputDescriptionsMethod = LoadInputDescriptions.GetSyntax(item.Info.InputDescriptions); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Info.Hierarchy, loadInputDescriptionsMethod, item.CanUseSkipLocalsInit); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Info.Hierarchy, loadInputDescriptionsMethod, item.CanUseSkipLocalsInit); context.AddSource($"{item.Info.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadInputDescriptions)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); @@ -323,7 +337,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.RegisterSourceOutput(pixelOptionsInfo, static (context, item) => { MethodDeclarationSyntax getPixelOptionsMethod = GetPixelOptions.GetSyntax(item.PixelOptions); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, getPixelOptionsMethod, canUseSkipLocalsInit: false); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, getPixelOptionsMethod, canUseSkipLocalsInit: false); context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(GetPixelOptions)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); diff --git a/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs index e4c9ae28..89a2a96f 100644 --- a/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs +++ b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs @@ -11,6 +11,14 @@ namespace ComputeSharp.D2D1.__Internals; [Obsolete("This interface is not intended to be used directly by user code")] public interface ID2D1Shader { + /// + /// Gets the display name of the D2D effect using this shader. + /// + /// + /// This only applies to effects created from . + /// + string EffectDisplayName { get; } + /// /// Initializes the current shader from a buffer with the serialized dispatch data. /// From c31572f68f72e813323c64f2ded3f16de7855ff6 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 14 Sep 2023 18:26:53 +0200 Subject: [PATCH 02/17] Add ID2D1Shader.EffectId property --- ...Generator.CreateEffectIdProperty.Syntax.cs | 113 ++++++++++++++++++ .../ID2D1ShaderGenerator.cs | 12 +- .../Interfaces/__Internals/ID2D1Shader.cs | 8 ++ 3 files changed, 132 insertions(+), 1 deletion(-) create mode 100644 src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs new file mode 100644 index 00000000..94057b71 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs @@ -0,0 +1,113 @@ +using System; +using System.Text; +using ComputeSharp.D2D1.__Internals; +using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Models; +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 + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +partial class ID2D1ShaderGenerator +{ + /// + partial class EffectId + { + /// + /// Creates a instance for the EffectId property. + /// + /// The input instance. + /// An opaque instance to transform the final tree into text. + /// The resulting instance for the EffectId property. + public static PropertyDeclarationSyntax GetSyntax(HierarchyInfo info, out Func fixup) + { + // Create the local declaration: + // + // global::System.ReadOnlySpan bytes = new byte[] { __EMBEDDED_EFFECT_ID_BYTES }; + LocalDeclarationStatementSyntax guidBytesDeclaration = + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("global::System.ReadOnlySpan")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))) + .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(new byte[] { 1, 2, 3, 4 }.AsSpan()); + + // Set the fixup function + fixup = tree => SourceText.From(tree.ToFullString().Replace("__EMBEDDED_EFFECT_ID_BYTES", effectIdLiterals), Encoding.UTF8); + + // Prepare the return statement: + // + // return + // ref global::System.Runtime.CompilerServices.Unsafe.As( + // ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(bytes)); + ReturnStatementSyntax returnStatement = + ReturnStatement( + RefExpression( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("global::System.Runtime.CompilerServices.Unsafe"), + GenericName(Identifier("As")) + .AddTypeArgumentListArguments( + PredefinedType(Token(SyntaxKind.ByteKeyword)), + IdentifierName("global::System.Guid")))) + .AddArgumentListArguments( + Argument( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("global::System.Runtime.InteropServices.MemoryMarshal"), + IdentifierName("GetReference"))) + .AddArgumentListArguments(Argument(IdentifierName("bytes")))) + .WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword))))); + + // This code produces a method declaration as follows: + // + // readonly ref readonly global::System.Guid global::ComputeSharp.D2D1.__Internals.ID2D1Shader.EffectId + // { + // [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + // get + // { + // + // + // } + // } + return + PropertyDeclaration( + RefType(IdentifierName("global::System.Guid")).WithReadOnlyKeyword(Token(SyntaxKind.ReadOnlyKeyword)), + Identifier(nameof(EffectId))) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) + .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) + .AddAccessorListAccessors( + AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) + .AddAttributeLists( + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("global::System.Runtime.CompilerServices.MethodImpl")) + .AddArgumentListArguments( + AttributeArgument( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("global::System.Runtime.CompilerServices.MethodImplOptions"), + IdentifierName("AggressiveInlining"))))))) + .AddBodyStatements(guidBytesDeclaration, returnStatement)); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs index 4bec8a17..703bda66 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -136,7 +136,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator shaderInfoWithErrors .Select(static (item, _) => item.Diagnostcs)); - // Get the EffectDisplayName info (hierarchy) + // Get the EffectDisplayName and EffectId info (hierarchy) IncrementalValuesProvider hierarchyInfo = shaderInfoWithErrors .Select(static (item, _) => item.Hierarchy); @@ -150,6 +150,16 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.AddSource($"{item.FullyQualifiedMetadataName}.{nameof(EffectDisplayName)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); + // Generate the EffectId properties + context.RegisterSourceOutput(hierarchyInfo, static (context, item) => + { + PropertyDeclarationSyntax effectDisplayNameProperty = EffectId.GetSyntax(item, out Func fixup); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item, effectDisplayNameProperty, canUseSkipLocalsInit: false); + SourceText text = fixup(compilationUnit); + + context.AddSource($"{item.FullyQualifiedMetadataName}.{nameof(EffectId)}.g.cs", text); + }); + // Get the GetInputCount() info (hierarchy and input count) IncrementalValuesProvider<(HierarchyInfo Hierarchy, int InputCount)> inputCountInfo = shaderInfoWithErrors diff --git a/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs index 89a2a96f..3a6b4ce0 100644 --- a/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs +++ b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs @@ -11,6 +11,14 @@ namespace ComputeSharp.D2D1.__Internals; [Obsolete("This interface is not intended to be used directly by user code")] public interface ID2D1Shader { + /// + /// Gets the effect id of the D2D effect using this shader. + /// + /// + /// This only applies to effects created from . + /// + ref readonly Guid EffectId { get; } + /// /// Gets the display name of the D2D effect using this shader. /// From 3303c0f2f3d36410ff7de2c7c4d18604dfa3ea1e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 14 Sep 2023 21:55:01 +0200 Subject: [PATCH 03/17] Generate EffectId from derived type identifiers --- ...Generator.CreateEffectIdProperty.Syntax.cs | 8 +- ...1ShaderGenerator.CreateEffectIdProperty.cs | 77 +++++++++++++++++++ .../ID2D1ShaderGenerator.cs | 25 ++++-- .../Models/D2D1ShaderInfo.cs | 2 + .../Models/EffectIdInfo.cs | 9 +++ .../Helpers/ImmutableArrayBuilder{T}.cs | 59 ++++++++++++-- 6 files changed, 163 insertions(+), 17 deletions(-) create mode 100644 src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.cs create mode 100644 src/ComputeSharp.D2D1.SourceGenerators/Models/EffectIdInfo.cs diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs index 94057b71..04e1e4bc 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.Syntax.cs @@ -1,8 +1,8 @@ using System; using System.Text; using ComputeSharp.D2D1.__Internals; +using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Helpers; -using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -22,10 +22,10 @@ partial class ID2D1ShaderGenerator /// /// Creates a instance for the EffectId property. /// - /// The input instance. + /// The input instance. /// An opaque instance to transform the final tree into text. /// The resulting instance for the EffectId property. - public static PropertyDeclarationSyntax GetSyntax(HierarchyInfo info, out Func fixup) + public static PropertyDeclarationSyntax GetSyntax(EffectIdInfo info, out Func fixup) { // Create the local declaration: // @@ -48,7 +48,7 @@ partial class ID2D1ShaderGenerator SingletonSeparatedList(IdentifierName("__EMBEDDED_EFFECT_ID_BYTES")))))))); // Prepare the initialization text - string effectIdLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(new byte[] { 1, 2, 3, 4 }.AsSpan()); + 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); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.cs new file mode 100644 index 00000000..831069bc --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Immutable; +using System.Runtime.CompilerServices; +using System.Security.Cryptography; +using System.Text; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Models; +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +partial class ID2D1ShaderGenerator +{ + /// + /// A helper with all logic to generate the EffectId property. + /// + private static partial class EffectId + { + /// + /// The instance currently in use for the running thread, if any. + /// + [ThreadStatic] + private static IncrementalHash? incrementalHash; + + /// + /// Extracts the effect id info for the current shader. + /// + /// The collection of produced instances. + /// The for the shader type in use. + /// The resulting effect id. + public static ImmutableArray GetInfo(ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol) + { + // Initialize an instance using the MD5 algorithm. We use this for several reasons: + // - We don't really need security, this is just to uniquely identify types + // - The hash size is 128 bits, which is exactly the size of a GUID. + IncrementalHash incrementalHash = EffectId.incrementalHash ??= IncrementalHash.CreateHash(HashAlgorithmName.MD5); + + string assemblyName = structDeclarationSymbol.ContainingAssembly?.Name ?? string.Empty; + + using ImmutableArrayBuilder byteBuffer = ImmutableArrayBuilder.Rent(); + using ImmutableArrayBuilder charBuffer = ImmutableArrayBuilder.Rent(); + + // Format the fully qualified name into a pooled builder to avoid the string allocation + structDeclarationSymbol.AppendFullyQualifiedMetadataName(in charBuffer); + + int maxTypeNameCharsLength = Encoding.UTF8.GetMaxByteCount(charBuffer.Count); + int maxAssemblyNameCharsLength = Encoding.UTF8.GetMaxByteCount(assemblyName.Length); + int maxEncodedCharsLength = Math.Max(maxTypeNameCharsLength, maxAssemblyNameCharsLength); + + byteBuffer.EnsureCapacity(maxEncodedCharsLength); + + // UTF8 encode the fully qualified name first + int typeNameCharsLength = Encoding.UTF8.GetBytes(charBuffer.WrittenSpan, byteBuffer.DangerousGetArray().AsSpan()); + + byteBuffer.Advance(typeNameCharsLength); + + // Append the UTF8 fully qualified name to the MD5 hash + incrementalHash.AppendData(byteBuffer.DangerousGetArray(), 0, byteBuffer.Count); + + // UTF8 encode the assembly name as well + int assemblyNameCharsLength = Encoding.UTF8.GetBytes(assemblyName.AsSpan(), byteBuffer.DangerousGetArray().AsSpan()); + + byteBuffer.Advance(assemblyNameCharsLength); + + // Append the UTF8 assembly name to the MD5 hash + incrementalHash.AppendData(byteBuffer.DangerousGetArray(), 0, byteBuffer.Count); + + // Get the resulting MD5 hash (128 bits) + byte[] hash = incrementalHash.GetHashAndReset(); + + // We own this buffer, so we can just reinterpret to an immutable array + return Unsafe.As>(ref hash); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs index 703bda66..61e2fead 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -52,6 +52,11 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator using ImmutableArrayBuilder diagnostics = ImmutableArrayBuilder.Rent(); + // EffectId info + ImmutableArray effectId = EffectId.GetInfo(diagnostics, typeSymbol); + + token.ThrowIfCancellationRequested(); + // LoadDispatchData() info ImmutableArray fieldInfos = LoadDispatchData.GetInfo( diagnostics, @@ -115,6 +120,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator return new D2D1ShaderInfo( Hierarchy: HierarchyInfo.From(typeSymbol), + EffectId: new EffectIdInfo(effectId), DispatchData: new DispatchDataInfo(fieldInfos, constantBufferSizeInBytes), InputTypes: new InputTypesInfo(inputTypes), ResourceTextureDescriptions: new ResourceTextureDescriptionsInfo(resourceTextureDescriptions), @@ -136,10 +142,8 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator shaderInfoWithErrors .Select(static (item, _) => item.Diagnostcs)); - // Get the EffectDisplayName and EffectId info (hierarchy) - IncrementalValuesProvider hierarchyInfo = - shaderInfoWithErrors - .Select(static (item, _) => item.Hierarchy); + // Get the EffectDisplayName info (hierarchy) + IncrementalValuesProvider hierarchyInfo = shaderInfoWithErrors.Select(static (item, _) => item.Hierarchy); // Generate the EffectDisplayName properties context.RegisterSourceOutput(hierarchyInfo, static (context, item) => @@ -150,14 +154,19 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.AddSource($"{item.FullyQualifiedMetadataName}.{nameof(EffectDisplayName)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); + // 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(hierarchyInfo, static (context, item) => + context.RegisterSourceOutput(effectIdInfo, static (context, item) => { - PropertyDeclarationSyntax effectDisplayNameProperty = EffectId.GetSyntax(item, out Func fixup); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item, effectDisplayNameProperty, canUseSkipLocalsInit: false); + PropertyDeclarationSyntax effectDisplayNameProperty = EffectId.GetSyntax(item.EffectId, out Func fixup); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, effectDisplayNameProperty, canUseSkipLocalsInit: false); SourceText text = fixup(compilationUnit); - context.AddSource($"{item.FullyQualifiedMetadataName}.{nameof(EffectId)}.g.cs", text); + context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(EffectId)}.g.cs", text); }); // Get the GetInputCount() info (hierarchy and input count) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs index 5674a782..df8c8c7d 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs @@ -7,6 +7,7 @@ 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 gathered shader dispatch data. /// The gathered input types for the shader. /// The gathered resource texture descriptions for the shader. @@ -17,6 +18,7 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models; /// The discovered diagnostics, if any. internal sealed record D2D1ShaderInfo( HierarchyInfo Hierarchy, + EffectIdInfo EffectId, DispatchDataInfo DispatchData, InputTypesInfo InputTypes, ResourceTextureDescriptionsInfo ResourceTextureDescriptions, diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/EffectIdInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/EffectIdInfo.cs new file mode 100644 index 00000000..7b0a55de --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/EffectIdInfo.cs @@ -0,0 +1,9 @@ +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.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs index 3aa5b62b..fca0f6f0 100644 --- a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs +++ b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs @@ -75,6 +75,33 @@ internal struct ImmutableArrayBuilder : IDisposable this.writer!.AddRange(items); } + /// + /// Advances the current writer by the specified amount. + /// + /// The amoutn to advance by. + public readonly void Advance(int count) + { + this.writer!.Advance(count); + } + + /// + /// Gets the array currently in use (rented from the pool). + /// + /// The array currently in use. + public readonly T[] DangerousGetArray() + { + return this.writer!.DangerousGetArray(); + } + + /// + /// Ensures that the current instance has enough free space to contain a given number of new items. + /// + /// The minimum number of items to ensure space for. + public readonly void EnsureCapacity(int requestedSize) + { + this.writer!.EnsureCapacity(requestedSize); + } + /// /// Inserts an item to the builder at the specified index. /// @@ -177,6 +204,23 @@ internal struct ImmutableArrayBuilder : IDisposable this.index += items.Length; } + /// + public void Advance(int count) + { + if (count > this.array.Length - this.index) + { + ImmutableArrayBuilder.ThrowArgumentOutOfRangeExceptionForCount(); + } + + this.index += count; + } + + /// + public T[] DangerousGetArray() + { + return this.array; + } + /// public void Insert(int index, T item) { @@ -209,12 +253,9 @@ internal struct ImmutableArrayBuilder : IDisposable this.index = 0; } - /// - /// Ensures that has enough free space to contain a given number of new items. - /// - /// The minimum number of items to ensure space for in . + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void EnsureCapacity(int requestedSize) + public void EnsureCapacity(int requestedSize) { if (requestedSize > this.array.Length - this.index) { @@ -253,4 +294,12 @@ file static class ImmutableArrayBuilder { throw new ArgumentOutOfRangeException("index"); } + + /// + /// Throws an for "count". + /// + public static void ThrowArgumentOutOfRangeExceptionForCount() + { + throw new ArgumentOutOfRangeException("count"); + } } \ No newline at end of file From 2dea566d18b9b1997f50a86f4c6074bb28be2d48 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 14 Sep 2023 22:56:31 +0200 Subject: [PATCH 04/17] Add D2DEffectIdAttribute type --- .../Attributes/D2DEffectIdAttribute.cs | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/ComputeSharp.D2D1/Attributes/D2DEffectIdAttribute.cs diff --git a/src/ComputeSharp.D2D1/Attributes/D2DEffectIdAttribute.cs b/src/ComputeSharp.D2D1/Attributes/D2DEffectIdAttribute.cs new file mode 100644 index 00000000..07f3556d --- /dev/null +++ b/src/ComputeSharp.D2D1/Attributes/D2DEffectIdAttribute.cs @@ -0,0 +1,27 @@ +using System; + +namespace ComputeSharp.D2D1; + +/// +/// An attribute for a D2D1 shader indicating the id of the shader effect to create. +/// +/// +/// This only applies to effects created from . +/// +[AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)] +public sealed class D2DEffectIdAttribute : Attribute +{ + /// + /// Creates a new instance of the type with the specified arguments. + /// + /// The value for the effect id. + public D2DEffectIdAttribute(string value) + { + Value = Guid.Parse(value); + } + + /// + /// Gets the number of texture inputs for the shader. + /// + public Guid Value { get; } +} \ No newline at end of file From e37395e871b96b20791fa1183c0db326c903a111 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 14 Sep 2023 22:56:49 +0200 Subject: [PATCH 05/17] Support [D2DEffectId] in source generator --- ...1ShaderGenerator.CreateEffectIdProperty.cs | 56 ++++++++++++++++++- .../ID2D1ShaderGenerator.cs | 2 +- 2 files changed, 54 insertions(+), 4 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.cs index 831069bc..f1e0d2e8 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.cs @@ -28,22 +28,72 @@ partial class ID2D1ShaderGenerator /// Extracts the effect id info for the current shader. /// /// The collection of produced instances. + /// The input object currently in use. /// The for the shader type in use. /// The resulting effect id. - public static ImmutableArray GetInfo(ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol) + public static ImmutableArray GetInfo( + ImmutableArrayBuilder diagnostics, + Compilation compilation, + INamedTypeSymbol structDeclarationSymbol) + { + if (TryGetDefinedEffectId(compilation, structDeclarationSymbol, out ImmutableArray effectId)) + { + return effectId; + } + + return CreateDefaultEffectId(structDeclarationSymbol); + } + + /// + /// Tries to get the defined effect id for a given shader type. + /// + /// The input object currently in use. + /// The input instance. + /// The resulting defined effect id, if found. + /// Whether or not a defined effect id could be found. + private static bool TryGetDefinedEffectId(Compilation compilation, INamedTypeSymbol typeSymbol, out ImmutableArray effectId) + { + INamedTypeSymbol effectIdAttributeSymbol = compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DEffectIdAttribute")!; + + foreach (AttributeData attributeData in typeSymbol.GetAttributes()) + { + // Check that the attribute is [D2DEffectId] and with a valid parameter + if (SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, effectIdAttributeSymbol) && + attributeData.ConstructorArguments is [{ Value: string value }] && + Guid.TryParse(value, out Guid guid)) + { + byte[] bytes = guid.ToByteArray(); + + effectId = Unsafe.As>(ref bytes); + + return true; + } + } + + effectId = default; + + return false; + } + + /// + /// Creates the default effect id for a given type symbol. + /// + /// The input instance. + /// The resulting effect id. + private static ImmutableArray CreateDefaultEffectId(INamedTypeSymbol typeSymbol) { // Initialize an instance using the MD5 algorithm. We use this for several reasons: // - We don't really need security, this is just to uniquely identify types // - The hash size is 128 bits, which is exactly the size of a GUID. IncrementalHash incrementalHash = EffectId.incrementalHash ??= IncrementalHash.CreateHash(HashAlgorithmName.MD5); - string assemblyName = structDeclarationSymbol.ContainingAssembly?.Name ?? string.Empty; + string assemblyName = typeSymbol.ContainingAssembly?.Name ?? string.Empty; using ImmutableArrayBuilder byteBuffer = ImmutableArrayBuilder.Rent(); using ImmutableArrayBuilder charBuffer = ImmutableArrayBuilder.Rent(); // Format the fully qualified name into a pooled builder to avoid the string allocation - structDeclarationSymbol.AppendFullyQualifiedMetadataName(in charBuffer); + typeSymbol.AppendFullyQualifiedMetadataName(in charBuffer); int maxTypeNameCharsLength = Encoding.UTF8.GetMaxByteCount(charBuffer.Count); int maxAssemblyNameCharsLength = Encoding.UTF8.GetMaxByteCount(assemblyName.Length); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs index 61e2fead..c7811456 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -53,7 +53,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator using ImmutableArrayBuilder diagnostics = ImmutableArrayBuilder.Rent(); // EffectId info - ImmutableArray effectId = EffectId.GetInfo(diagnostics, typeSymbol); + ImmutableArray effectId = EffectId.GetInfo(diagnostics, context.SemanticModel.Compilation, typeSymbol); token.ThrowIfCancellationRequested(); From 8c7f464876842d546216ef5894dbde2399e626f3 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 14 Sep 2023 22:58:32 +0200 Subject: [PATCH 06/17] Add D2DEffectDisplayNameAttribute type --- .../D2DEffectDisplayNameAttribute.cs | 27 +++++++++++++++++++ .../Attributes/D2DEffectIdAttribute.cs | 2 +- 2 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 src/ComputeSharp.D2D1/Attributes/D2DEffectDisplayNameAttribute.cs diff --git a/src/ComputeSharp.D2D1/Attributes/D2DEffectDisplayNameAttribute.cs b/src/ComputeSharp.D2D1/Attributes/D2DEffectDisplayNameAttribute.cs new file mode 100644 index 00000000..5b68b638 --- /dev/null +++ b/src/ComputeSharp.D2D1/Attributes/D2DEffectDisplayNameAttribute.cs @@ -0,0 +1,27 @@ +using System; + +namespace ComputeSharp.D2D1; + +/// +/// An attribute for a D2D1 shader indicating the display name of the shader effect to create. +/// +/// +/// This only applies to effects created from . +/// +[AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)] +public sealed class D2DEffectDisplayNameAttribute : Attribute +{ + /// + /// Creates a new instance of the type with the specified arguments. + /// + /// The value for the display name. + public D2DEffectDisplayNameAttribute(string value) + { + Value = value; + } + + /// + /// Gets the display name value. + /// + public string Value { get; } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Attributes/D2DEffectIdAttribute.cs b/src/ComputeSharp.D2D1/Attributes/D2DEffectIdAttribute.cs index 07f3556d..c64e8bb8 100644 --- a/src/ComputeSharp.D2D1/Attributes/D2DEffectIdAttribute.cs +++ b/src/ComputeSharp.D2D1/Attributes/D2DEffectIdAttribute.cs @@ -21,7 +21,7 @@ public sealed class D2DEffectIdAttribute : Attribute } /// - /// Gets the number of texture inputs for the shader. + /// Gets the effect id value. /// public Guid Value { get; } } \ No newline at end of file From 321430b6da16763fccd4b92cf9d8e06affabb73b Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 15 Sep 2023 14:26:48 +0200 Subject: [PATCH 07/17] Support [EffectDisplayName] in source generator --- ....CreateEffectDisplayNameProperty.Syntax.cs | 9 +-- ...nerator.CreateEffectDisplayNameProperty.cs | 74 +++++++++++++++++++ .../ID2D1ShaderGenerator.cs | 20 +++-- .../Models/D2D1ShaderInfo.cs | 2 + 4 files changed, 94 insertions(+), 11 deletions(-) create mode 100644 src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectDisplayNameProperty.cs diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectDisplayNameProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectDisplayNameProperty.Syntax.cs index dde40d98..51b9de28 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectDisplayNameProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectDisplayNameProperty.Syntax.cs @@ -1,5 +1,4 @@ using ComputeSharp.D2D1.__Internals; -using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; @@ -17,18 +16,18 @@ partial class ID2D1ShaderGenerator /// /// Creates a instance for the EffectDisplayName property. /// - /// The input instance. + /// The input effect display name value. /// The resulting instance for the EffectDisplayName property. - public static PropertyDeclarationSyntax GetSyntax(HierarchyInfo info) + public static PropertyDeclarationSyntax GetSyntax(string effectDisplayName) { // This code produces a method declaration as follows: // - // readonly string global::ComputeSharp.D2D1.__Internals.ID2D1Shader.EffectDisplayName => ""; + // readonly string global::ComputeSharp.D2D1.__Internals.ID2D1Shader.EffectDisplayName => ""; return PropertyDeclaration(PredefinedType(Token(SyntaxKind.StringKeyword)), Identifier(nameof(EffectDisplayName))) .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithExpressionBody(ArrowExpressionClause(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(info.FullyQualifiedMetadataName)))) + .WithExpressionBody(ArrowExpressionClause(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(effectDisplayName)))) .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); } } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectDisplayNameProperty.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectDisplayNameProperty.cs new file mode 100644 index 00000000..fb216133 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectDisplayNameProperty.cs @@ -0,0 +1,74 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.Security; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Models; +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +partial class ID2D1ShaderGenerator +{ + /// + /// A helper with all logic to generate the EffectDisplayName property. + /// + private static partial class EffectDisplayName + { + /// + /// Extracts the effect display name info for the current shader. + /// + /// The collection of produced instances. + /// The input object currently in use. + /// The for the shader type in use. + /// The resulting effect display name. + public static string GetInfo( + ImmutableArrayBuilder diagnostics, + Compilation compilation, + INamedTypeSymbol structDeclarationSymbol) + { + if (TryGetDefinedEffectDisplayName(compilation, structDeclarationSymbol, out string? effectDisplayName)) + { + return effectDisplayName; + } + + return structDeclarationSymbol.GetFullyQualifiedMetadataName(); + } + + /// + /// Tries to get the defined effect display name for a given shader type. + /// + /// The input object currently in use. + /// The input instance. + /// The resulting defined effect display name, if found. + /// Whether or not a defined effect display name could be found. + private static bool TryGetDefinedEffectDisplayName(Compilation compilation, INamedTypeSymbol typeSymbol, [NotNullWhen(true)] out string? effectDisplayName) + { + INamedTypeSymbol effectIdAttributeSymbol = compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DEffectDisplayNameAttribute")!; + + foreach (AttributeData attributeData in typeSymbol.GetAttributes()) + { + // Check that the attribute is [D2DEffectDisplayName] and with a valid parameter + if (SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, effectIdAttributeSymbol) && + attributeData.ConstructorArguments is [{ Value: string { Length: > 0 } value }]) + { + // Make sure to escape any invalid XML characters + string escapedValue = SecurityElement.Escape(value); + + // Trim the display name as well + if (escapedValue.AsSpan().Trim() is { Length: > 0 } trimmedValue) + { + effectDisplayName = trimmedValue.ToString(); + + return true; + } + } + } + + effectDisplayName = default; + + return false; + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs index c7811456..1e7f8568 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -57,6 +57,11 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator token.ThrowIfCancellationRequested(); + // EffectDisplayName info + string effectDisplayName = EffectDisplayName.GetInfo(diagnostics, context.SemanticModel.Compilation, typeSymbol); + + token.ThrowIfCancellationRequested(); + // LoadDispatchData() info ImmutableArray fieldInfos = LoadDispatchData.GetInfo( diagnostics, @@ -121,6 +126,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator return new D2D1ShaderInfo( Hierarchy: HierarchyInfo.From(typeSymbol), EffectId: new EffectIdInfo(effectId), + EffectDisplayName: effectDisplayName, DispatchData: new DispatchDataInfo(fieldInfos, constantBufferSizeInBytes), InputTypes: new InputTypesInfo(inputTypes), ResourceTextureDescriptions: new ResourceTextureDescriptionsInfo(resourceTextureDescriptions), @@ -142,16 +148,18 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator shaderInfoWithErrors .Select(static (item, _) => item.Diagnostcs)); - // Get the EffectDisplayName info (hierarchy) - IncrementalValuesProvider hierarchyInfo = shaderInfoWithErrors.Select(static (item, _) => item.Hierarchy); + // 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(hierarchyInfo, static (context, item) => + context.RegisterSourceOutput(effectDisplayNameInfo, static (context, item) => { - PropertyDeclarationSyntax effectDisplayNameProperty = EffectDisplayName.GetSyntax(item); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item, effectDisplayNameProperty, canUseSkipLocalsInit: false); + PropertyDeclarationSyntax effectDisplayNameProperty = EffectDisplayName.GetSyntax(item.EffectDisplayName); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, effectDisplayNameProperty, canUseSkipLocalsInit: false); - context.AddSource($"{item.FullyQualifiedMetadataName}.{nameof(EffectDisplayName)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); + context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(EffectDisplayName)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); // Get the EffectId info (hierarchy and effect id info) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs index df8c8c7d..568ca2ef 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs @@ -8,6 +8,7 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models; /// /// The hierarchy info for the shader type. /// The effect id info for the shader type. +/// The effect display name for the shader type. /// The gathered shader dispatch data. /// The gathered input types for the shader. /// The gathered resource texture descriptions for the shader. @@ -19,6 +20,7 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models; internal sealed record D2D1ShaderInfo( HierarchyInfo Hierarchy, EffectIdInfo EffectId, + string EffectDisplayName, DispatchDataInfo DispatchData, InputTypesInfo InputTypes, ResourceTextureDescriptionsInfo ResourceTextureDescriptions, From 4066899e44eb34d72b2b44b401bfe06df79ea45f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 15 Sep 2023 15:31:58 +0200 Subject: [PATCH 08/17] Add D2D1PixelShaderEffect.GetEffectId() API --- .../Shaders/Interop/D2D1PixelShaderEffect.cs | 23 +++++++++++++++---- .../Effects/PixelShaderEffect.For{T}.cs | 2 +- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs index d9adec9c..0555ba2a 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs @@ -18,6 +18,19 @@ namespace ComputeSharp.D2D1.Interop; /// public static unsafe class D2D1PixelShaderEffect { + /// + /// Gets the effect id of the D2D effect using this shader. + /// + /// The type of D2D1 pixel shader to get the effect id for. + /// The effect id of the D2D effect using shaders. + public static ref readonly Guid GetEffectId() + where T : unmanaged, ID2D1PixelShader + { + Unsafe.SkipInit(out T shader); + + return ref shader.EffectId; + } + /// /// Registers an effect from an input D2D1 pixel shader, by calling ID2D1Factory1::RegisterEffectFromString. /// @@ -26,7 +39,10 @@ public static unsafe class D2D1PixelShaderEffect /// The of the registered effect, which can be used to call ID2D1DeviceContext::CreateEffect. /// Thrown if is . /// Thrown if an effect is registered multiple times with different properties. - /// For more info, see . + /// + /// The returned value is the same as that returned by . + /// For more info, see . + /// public static void RegisterForD2D1Factory1(void* d2D1Factory1, out Guid effectId) where T : unmanaged, ID2D1PixelShader { @@ -261,9 +277,8 @@ public static unsafe class D2D1PixelShaderEffect /// To make the deserialization easier, the type can be used to read and validate the returned blob. /// The leading blob id will determine what subtype should be used to deserialize the blob (eg. ). /// - /// - /// For more info, see . - /// + /// The returned value is the same as that returned by . + /// For more info, see . /// public static ReadOnlyMemory GetRegistrationBlob(out Guid effectId) where T : unmanaged, ID2D1PixelShader diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.For{T}.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.For{T}.cs index 37204600..52eb31d9 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.For{T}.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.For{T}.cs @@ -165,7 +165,7 @@ internal unsafe partial struct PixelShaderEffect private static For CreateInstance() { // Load all shader properties - Guid shaderId = typeof(T).GUID; + Guid shaderId = D2D1PixelShaderEffect.GetEffectId(); int constantBufferSize = D2D1PixelShader.GetConstantBufferSize(); D2D1BufferPrecision bufferPrecision = D2D1PixelShader.GetOutputBufferPrecision(); D2D1ChannelDepth channelDepth = D2D1PixelShader.GetOutputBufferChannelDepth(); From 8acb8b0b1ab8be72a00225646e616c0bba1293c2 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 15 Sep 2023 15:32:13 +0200 Subject: [PATCH 09/17] Add unit tests for D2D1PixelShaderEffect.GetEffectId() --- .../D2D1PixelShaderEffectTests.cs | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderEffectTests.cs b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderEffectTests.cs index ac7a715f..7142c7b0 100644 --- a/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderEffectTests.cs +++ b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderEffectTests.cs @@ -165,4 +165,58 @@ public partial class D2D1PixelShaderEffectTests return this.a + this.b + this.c.X + this.d + this.e; } } + + [TestMethod] + public unsafe void DefaultEffectId_MatchesValue() + { + using ComPtr d2D1Factory2 = D2D1Helper.CreateD2D1Factory2(); + using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); + using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); + + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out Guid effectId); + + Assert.AreEqual(D2D1PixelShaderEffect.GetEffectId(), effectId); + Assert.AreNotEqual(D2D1PixelShaderEffect.GetEffectId(), effectId); + } + + [D2DInputCount(0)] + private partial struct ShaderWithDefaultEffectId : ID2D1PixelShader + { + public float4 Execute() + { + return 0; + } + } + + [D2DInputCount(0)] + private partial struct ShaderWithDefaultEffectId2 : ID2D1PixelShader + { + public float4 Execute() + { + return 0; + } + } + + [TestMethod] + public unsafe void ExplicitEffectId_MatchesValue() + { + using ComPtr d2D1Factory2 = D2D1Helper.CreateD2D1Factory2(); + using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); + using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); + + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out Guid effectId); + + Assert.AreEqual(Guid.Parse("8E1F7F49-EF0D-4242-8912-08ADA36AB4EC"), effectId); + Assert.AreEqual(D2D1PixelShaderEffect.GetEffectId(), effectId); + } + + [D2DInputCount(0)] + [D2DEffectId("8E1F7F49-EF0D-4242-8912-08ADA36AB4EC")] + private partial struct ShaderWithExplicitEffectId : ID2D1PixelShader + { + public float4 Execute() + { + return 0; + } + } } \ No newline at end of file From 7fc302312dda667e5c8bc2e8f574570a84b0bce7 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 15 Sep 2023 16:21:54 +0200 Subject: [PATCH 10/17] Filter newlines from effect display names --- ...ShaderGenerator.CreateEffectDisplayNameProperty.cs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectDisplayNameProperty.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectDisplayNameProperty.cs index fb216133..953abbd6 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectDisplayNameProperty.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectDisplayNameProperty.cs @@ -1,6 +1,7 @@ using System; using System.Diagnostics.CodeAnalysis; using System.Security; +using System.Text.RegularExpressions; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; @@ -16,6 +17,11 @@ partial class ID2D1ShaderGenerator /// private static partial class EffectDisplayName { + /// + /// A instance to find all newlines. + /// + private static readonly Regex NewLinesRegex = new("[\r\n\v]", RegexOptions.Compiled); + /// /// Extracts the effect display name info for the current shader. /// @@ -53,8 +59,11 @@ partial class ID2D1ShaderGenerator if (SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, effectIdAttributeSymbol) && attributeData.ConstructorArguments is [{ Value: string { Length: > 0 } value }]) { + // Remove new lines (the values cannot span multiple lines in XML) + string singleLineValue = NewLinesRegex.Replace(value, string.Empty); + // Make sure to escape any invalid XML characters - string escapedValue = SecurityElement.Escape(value); + string escapedValue = SecurityElement.Escape(singleLineValue); // Trim the display name as well if (escapedValue.AsSpan().Trim() is { Length: > 0 } trimmedValue) From 23cd90d4810437b7ee7e91be417308908ffc815e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 15 Sep 2023 16:31:47 +0200 Subject: [PATCH 11/17] Add D2D1PixelShaderEffect.GetEffectDisplayName() API --- .../Shaders/Interop/D2D1PixelShaderEffect.cs | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs index 0555ba2a..c6e2bd09 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs @@ -31,6 +31,19 @@ public static unsafe class D2D1PixelShaderEffect return ref shader.EffectId; } + /// + /// Gets the effect display name of the D2D effect using this shader. + /// + /// The type of D2D1 pixel shader to get the effect id for. + /// The effect display name of the D2D effect using shaders. + public static string GetEffectDisplayName() + where T : unmanaged, ID2D1PixelShader + { + Unsafe.SkipInit(out T shader); + + return shader.EffectDisplayName; + } + /// /// Registers an effect from an input D2D1 pixel shader, by calling ID2D1Factory1::RegisterEffectFromString. /// @@ -58,7 +71,7 @@ public static unsafe class D2D1PixelShaderEffect @@ -298,7 +311,7 @@ public static unsafe class D2D1PixelShaderEffect From 37fee87489f3586e06529d5358fdab99772e26e8 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 15 Sep 2023 16:36:14 +0200 Subject: [PATCH 12/17] Add unit tests for D2D1PixelShaderEffect.GetEffectDisplayName() --- .../D2D1PixelShaderEffectTests.cs | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderEffectTests.cs b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderEffectTests.cs index 7142c7b0..153179b0 100644 --- a/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderEffectTests.cs +++ b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderEffectTests.cs @@ -219,4 +219,57 @@ public partial class D2D1PixelShaderEffectTests return 0; } } + + [TestMethod] + public unsafe void DefaultEffectDisplayName_MatchesValue() + { + Assert.AreEqual(D2D1PixelShaderEffect.GetEffectDisplayName(), typeof(ShaderWithDefaultEffectDisplayName).FullName); + } + + [D2DInputCount(0)] + private partial struct ShaderWithDefaultEffectDisplayName : ID2D1PixelShader + { + public float4 Execute() + { + return 0; + } + } + + [TestMethod] + public unsafe void ExplicitEffectDisplayName_MatchesValue() + { + Assert.AreEqual(D2D1PixelShaderEffect.GetEffectDisplayName(), "Fancy blur"); + Assert.AreEqual(D2D1PixelShaderEffect.GetEffectDisplayName(), "Fancy"<"); + Assert.AreEqual(D2D1PixelShaderEffect.GetEffectDisplayName(), "FancyBlurEffect"); + } + + [D2DInputCount(0)] + [D2DEffectDisplayName("Fancy blur")] + private partial struct ShaderWithExplicitEffectDisplayName : ID2D1PixelShader + { + public float4 Execute() + { + return 0; + } + } + + [D2DInputCount(0)] + [D2DEffectDisplayName("Fancy\"<")] + private partial struct ShaderWithExplicitEffectDisplayName2 : ID2D1PixelShader + { + public float4 Execute() + { + return 0; + } + } + + [D2DInputCount(0)] + [D2DEffectDisplayName("Fancy\r\nBlur\nEffect")] + private partial struct ShaderWithExplicitEffectDisplayName3 : ID2D1PixelShader + { + public float4 Execute() + { + return 0; + } + } } \ No newline at end of file From 8cbb3c958eb304c242e915675ee36531b209856a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 16 Sep 2023 22:55:49 +0200 Subject: [PATCH 13/17] Add InvalidEffectIdValueAnalyzer --- .../AnalyzerReleases.Shipped.md | 3 +- .../Analyzers/InvalidEffectIdValueAnalyzer.cs | 63 +++++++++++++++++++ .../Diagnostics/DiagnosticDescriptors.cs | 16 +++++ .../Extensions/AttributeDataExtensions.cs | 15 +++++ 4 files changed, 96 insertions(+), 1 deletion(-) create mode 100644 src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidEffectIdValueAnalyzer.cs diff --git a/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md index 227c5323..57915d4d 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md +++ b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md @@ -1,4 +1,4 @@ -; Shipped analyzer releases +; Shipped analyzer releases ; https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md ## Release 1.0 @@ -65,3 +65,4 @@ CMPSD2D0055 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github CMPSD2D0056 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPSD2D0057 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPSD2D0058 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0059 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidEffectIdValueAnalyzer.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidEffectIdValueAnalyzer.cs new file mode 100644 index 00000000..e7b07246 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidEffectIdValueAnalyzer.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Immutable; +using ComputeSharp.SourceGeneration.Extensions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +/// A diagnostic analyzer that generates an error whenever [D2DEffectId] is used with an invalid value. +/// +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public sealed class InvalidEffectIdValueAnalyzer : DiagnosticAnalyzer +{ + /// + public override ImmutableArray SupportedDiagnostics { get; } = ImmutableArray.Create(InvalidD2DEffectIdAttributeValue); + + /// + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); + context.EnableConcurrentExecution(); + + context.RegisterCompilationStartAction(static context => + { + // Get the [D2DEffectId] symbol + if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DEffectIdAttribute") is not { } d2DEffectIdAttributeSymbol) + { + return; + } + + context.RegisterSymbolAction(context => + { + // Only struct types are possible targets + if (context.Symbol is not INamedTypeSymbol { TypeKind: TypeKind.Struct } typeSymbol) + { + return; + } + + foreach (AttributeData attributeDate in typeSymbol.GetAttributes()) + { + // Look for the [D2DEffectId] use + if (!SymbolEqualityComparer.Default.Equals(attributeDate.AttributeClass, d2DEffectIdAttributeSymbol)) + { + continue; + } + + // Validate the GUID text and emit a diagnostic if needed + if (attributeDate.ConstructorArguments is not [{ Value: string value }] || + !Guid.TryParse(value, out _)) + { + context.ReportDiagnostic(Diagnostic.Create( + InvalidD2DEffectIdAttributeValue, + attributeDate.GetLocation())); + } + + return; + } + }, SymbolKind.NamedType); + }); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 49a26ccf..8b673569 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -857,4 +857,20 @@ partial class DiagnosticDescriptors isEnabledByDefault: true, description: "A D2D1 shader must be annotated with the [D2DInputCount] attribute.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for when the [D2DEffectId] attribute is being used with an invalid value. + /// + /// Format: "The [D2DEffectId] attribute is being used with an invalid value (the input text must be a valid GUID)". + /// + /// + public static readonly DiagnosticDescriptor InvalidD2DEffectIdAttributeValue = new DiagnosticDescriptor( + id: "CMPSD2D0059", + title: "Invalid [D2DEffectId] attribute value", + messageFormat: "The [D2DEffectId] attribute is being used with an invalid value (the input text must be a valid GUID)", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "The [D2DEffectId] attribute must use a valid GUID expression as value.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration/Extensions/AttributeDataExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/AttributeDataExtensions.cs index 96b3872d..6450f6bf 100644 --- a/src/ComputeSharp.SourceGeneration/Extensions/AttributeDataExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/AttributeDataExtensions.cs @@ -8,6 +8,21 @@ namespace ComputeSharp.SourceGeneration.Extensions; /// internal static class AttributeDataExtensions { + /// + /// Tries to get the location of the input instance. + /// + /// The input instance to get the location for. + /// The resulting location for , if a syntax reference is available. + public static Location? GetLocation(this AttributeData attributeData) + { + if (attributeData.ApplicationSyntaxReference is { } syntaxReference) + { + return syntaxReference.SyntaxTree.GetLocation(syntaxReference.Span); + } + + return null; + } + /// /// Tries to get a constructor argument at a given index from the input instance. /// From 9d5e412f7d04da9c53a06fa117f53809a74965bf Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 16 Sep 2023 23:10:19 +0200 Subject: [PATCH 14/17] Add InvalidEffectDisplayNameValueAnalyzer --- .../AnalyzerReleases.Shipped.md | 1 + .../InvalidEffectDisplayNameValueAnalyzer.cs | 62 +++++++++++++++++ .../Analyzers/InvalidEffectIdValueAnalyzer.cs | 8 +-- .../Diagnostics/DiagnosticDescriptors.cs | 16 +++++ .../Helpers/D2D1EffectMetadataParser.cs | 68 +++++++++++++++++++ ...nerator.CreateEffectDisplayNameProperty.cs | 28 ++------ 6 files changed, 155 insertions(+), 28 deletions(-) create mode 100644 src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidEffectDisplayNameValueAnalyzer.cs create mode 100644 src/ComputeSharp.D2D1.SourceGenerators/Helpers/D2D1EffectMetadataParser.cs diff --git a/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md index 57915d4d..b3e8a176 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md +++ b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md @@ -66,3 +66,4 @@ CMPSD2D0056 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github CMPSD2D0057 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPSD2D0058 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPSD2D0059 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0060 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidEffectDisplayNameValueAnalyzer.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidEffectDisplayNameValueAnalyzer.cs new file mode 100644 index 00000000..ec1cbabb --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidEffectDisplayNameValueAnalyzer.cs @@ -0,0 +1,62 @@ +using System.Collections.Immutable; +using ComputeSharp.D2D1.SourceGenerators.Helpers; +using ComputeSharp.SourceGeneration.Extensions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +/// A diagnostic analyzer that generates an error whenever [D2DEffectName] is used with an invalid value. +/// +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public sealed class InvalidEffectDisplayNameValueAnalyzer : DiagnosticAnalyzer +{ + /// + public override ImmutableArray SupportedDiagnostics { get; } = ImmutableArray.Create(InvalidD2DEffectDisplayNameAttributeValue); + + /// + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); + context.EnableConcurrentExecution(); + + context.RegisterCompilationStartAction(static context => + { + // Get the [D2DEffectDisplayName] symbol + if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DEffectDisplayNameAttribute") is not { } d2DEffectIdAttributeSymbol) + { + return; + } + + context.RegisterSymbolAction(context => + { + // Only struct types are possible targets + if (context.Symbol is not INamedTypeSymbol { TypeKind: TypeKind.Struct } typeSymbol) + { + return; + } + + foreach (AttributeData attributeData in typeSymbol.GetAttributes()) + { + // Look for the [D2DEffectDisplayName] use + if (!SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, d2DEffectIdAttributeSymbol)) + { + continue; + } + + // Validate the effect display name + if (!D2D1EffectMetadataParser.IsValidEffectDisplayName(attributeData)) + { + context.ReportDiagnostic(Diagnostic.Create( + InvalidD2DEffectDisplayNameAttributeValue, + attributeData.GetLocation())); + } + + return; + } + }, SymbolKind.NamedType); + }); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidEffectIdValueAnalyzer.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidEffectIdValueAnalyzer.cs index e7b07246..f2f0e57f 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidEffectIdValueAnalyzer.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidEffectIdValueAnalyzer.cs @@ -38,21 +38,21 @@ public sealed class InvalidEffectIdValueAnalyzer : DiagnosticAnalyzer return; } - foreach (AttributeData attributeDate in typeSymbol.GetAttributes()) + foreach (AttributeData attributeData in typeSymbol.GetAttributes()) { // Look for the [D2DEffectId] use - if (!SymbolEqualityComparer.Default.Equals(attributeDate.AttributeClass, d2DEffectIdAttributeSymbol)) + if (!SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, d2DEffectIdAttributeSymbol)) { continue; } // Validate the GUID text and emit a diagnostic if needed - if (attributeDate.ConstructorArguments is not [{ Value: string value }] || + if (attributeData.ConstructorArguments is not [{ Value: string value }] || !Guid.TryParse(value, out _)) { context.ReportDiagnostic(Diagnostic.Create( InvalidD2DEffectIdAttributeValue, - attributeDate.GetLocation())); + attributeData.GetLocation())); } return; diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 8b673569..3f1debd2 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -873,4 +873,20 @@ partial class DiagnosticDescriptors isEnabledByDefault: true, description: "The [D2DEffectId] attribute must use a valid GUID expression as value.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for when the [D2DEffectDisplayName] attribute is being used with an invalid value. + /// + /// Format: "The [D2DEffectDisplayName] attribute is being used with an invalid value (the input text must be a valid GUID)". + /// + /// + public static readonly DiagnosticDescriptor InvalidD2DEffectDisplayNameAttributeValue = new DiagnosticDescriptor( + id: "CMPSD2D0060", + title: "Invalid [D2DEffectDisplayName] attribute value", + messageFormat: "The [D2DEffectDisplayName] attribute is being used with an invalid value", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "The [D2DEffectDisplayName] attribute must contain valid text.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Helpers/D2D1EffectMetadataParser.cs b/src/ComputeSharp.D2D1.SourceGenerators/Helpers/D2D1EffectMetadataParser.cs new file mode 100644 index 00000000..79148ef2 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Helpers/D2D1EffectMetadataParser.cs @@ -0,0 +1,68 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.Security; +using System.Text.RegularExpressions; +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.D2D1.SourceGenerators.Helpers; + +/// +/// A helper class to parse D2D metadata values. +/// +internal static class D2D1EffectMetadataParser +{ + /// + /// A instance to find all newlines. + /// + private static readonly Regex NewLinesRegex = new("[\r\n\v]", RegexOptions.Compiled); + + /// + /// Checks whether a given value contains a valid effect display name. + /// + /// The input object to inspect. + /// Whether contains a valid effect display name. + public static bool IsValidEffectDisplayName(AttributeData attributeData) + { + if (attributeData.ConstructorArguments is [{ Value: string { Length: > 0 } value }]) + { + // Remove new lines (the values cannot span multiple lines in XML) + string singleLineValue = NewLinesRegex.Replace(value, string.Empty); + + // Trim directly and check that (no need to escape, as that wouldn't change things) + return singleLineValue.AsSpan().Trim().Length > 0; + } + + return false; + } + + /// + /// Tries to get the defined effect display name for a given attribute. + /// + /// The input object to inspect. + /// The resulting defined effect display name, if found. + /// Whether or not a defined effect display name could be found. + public static bool TryGetEffectDisplayName(AttributeData attributeData, [NotNullWhen(true)] out string? effectDisplayName) + { + // Check that the attribute is [D2DEffectDisplayName] and with a valid parameter + if (attributeData.ConstructorArguments is [{ Value: string { Length: > 0 } value }]) + { + // Remove new lines (the values cannot span multiple lines in XML) + string singleLineValue = NewLinesRegex.Replace(value, string.Empty); + + // Make sure to escape any invalid XML characters + string escapedValue = SecurityElement.Escape(singleLineValue); + + // Trim the display name as well + if (escapedValue.AsSpan().Trim() is { Length: > 0 } trimmedValue) + { + effectDisplayName = trimmedValue.ToString(); + + return true; + } + } + + effectDisplayName = default; + + return false; + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectDisplayNameProperty.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectDisplayNameProperty.cs index 953abbd6..6fa0b3ad 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectDisplayNameProperty.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectDisplayNameProperty.cs @@ -1,7 +1,5 @@ -using System; using System.Diagnostics.CodeAnalysis; -using System.Security; -using System.Text.RegularExpressions; +using ComputeSharp.D2D1.SourceGenerators.Helpers; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; @@ -17,11 +15,6 @@ partial class ID2D1ShaderGenerator /// private static partial class EffectDisplayName { - /// - /// A instance to find all newlines. - /// - private static readonly Regex NewLinesRegex = new("[\r\n\v]", RegexOptions.Compiled); - /// /// Extracts the effect display name info for the current shader. /// @@ -55,23 +48,10 @@ partial class ID2D1ShaderGenerator foreach (AttributeData attributeData in typeSymbol.GetAttributes()) { - // Check that the attribute is [D2DEffectDisplayName] and with a valid parameter - if (SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, effectIdAttributeSymbol) && - attributeData.ConstructorArguments is [{ Value: string { Length: > 0 } value }]) + // Check that the attribute is [D2DEffectDisplayName] + if (SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, effectIdAttributeSymbol)) { - // Remove new lines (the values cannot span multiple lines in XML) - string singleLineValue = NewLinesRegex.Replace(value, string.Empty); - - // Make sure to escape any invalid XML characters - string escapedValue = SecurityElement.Escape(singleLineValue); - - // Trim the display name as well - if (escapedValue.AsSpan().Trim() is { Length: > 0 } trimmedValue) - { - effectDisplayName = trimmedValue.ToString(); - - return true; - } + return D2D1EffectMetadataParser.TryGetEffectDisplayName(attributeData, out effectDisplayName); } } From 2c1ab945b2bbce42a3116124fc28a828d1808e36 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 16 Sep 2023 23:11:48 +0200 Subject: [PATCH 15/17] Remove unnecessary diagnostic parameters --- ...D2D1ShaderGenerator.CreateEffectDisplayNameProperty.cs | 8 +------- .../ID2D1ShaderGenerator.CreateEffectIdProperty.cs | 7 +------ .../ID2D1ShaderGenerator.cs | 4 ++-- 3 files changed, 4 insertions(+), 15 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectDisplayNameProperty.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectDisplayNameProperty.cs index 6fa0b3ad..0879e724 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectDisplayNameProperty.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectDisplayNameProperty.cs @@ -1,8 +1,6 @@ using System.Diagnostics.CodeAnalysis; using ComputeSharp.D2D1.SourceGenerators.Helpers; using ComputeSharp.SourceGeneration.Extensions; -using ComputeSharp.SourceGeneration.Helpers; -using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; namespace ComputeSharp.D2D1.SourceGenerators; @@ -18,14 +16,10 @@ partial class ID2D1ShaderGenerator /// /// Extracts the effect display name info for the current shader. /// - /// The collection of produced instances. /// The input object currently in use. /// The for the shader type in use. /// The resulting effect display name. - public static string GetInfo( - ImmutableArrayBuilder diagnostics, - Compilation compilation, - INamedTypeSymbol structDeclarationSymbol) + public static string GetInfo(Compilation compilation, INamedTypeSymbol structDeclarationSymbol) { if (TryGetDefinedEffectDisplayName(compilation, structDeclarationSymbol, out string? effectDisplayName)) { diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.cs index f1e0d2e8..23b9e15c 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.cs @@ -5,7 +5,6 @@ using System.Security.Cryptography; using System.Text; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; -using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; namespace ComputeSharp.D2D1.SourceGenerators; @@ -27,14 +26,10 @@ partial class ID2D1ShaderGenerator /// /// Extracts the effect id info for the current shader. /// - /// The collection of produced instances. /// The input object currently in use. /// The for the shader type in use. /// The resulting effect id. - public static ImmutableArray GetInfo( - ImmutableArrayBuilder diagnostics, - Compilation compilation, - INamedTypeSymbol structDeclarationSymbol) + public static ImmutableArray GetInfo(Compilation compilation, INamedTypeSymbol structDeclarationSymbol) { if (TryGetDefinedEffectId(compilation, structDeclarationSymbol, out ImmutableArray effectId)) { diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs index 1e7f8568..31767b11 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -53,12 +53,12 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator using ImmutableArrayBuilder diagnostics = ImmutableArrayBuilder.Rent(); // EffectId info - ImmutableArray effectId = EffectId.GetInfo(diagnostics, context.SemanticModel.Compilation, typeSymbol); + ImmutableArray effectId = EffectId.GetInfo(context.SemanticModel.Compilation, typeSymbol); token.ThrowIfCancellationRequested(); // EffectDisplayName info - string effectDisplayName = EffectDisplayName.GetInfo(diagnostics, context.SemanticModel.Compilation, typeSymbol); + string effectDisplayName = EffectDisplayName.GetInfo(context.SemanticModel.Compilation, typeSymbol); token.ThrowIfCancellationRequested(); From fd62b28d8297e5641edd61508db578bc1e03c894 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 18 Sep 2023 20:42:29 +0200 Subject: [PATCH 16/17] Fix and simplify EffectId hashing logic --- ...1ShaderGenerator.CreateEffectIdProperty.cs | 64 +++++++++++-------- .../Helpers/ImmutableArrayBuilder{T}.cs | 59 ++--------------- 2 files changed, 42 insertions(+), 81 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.cs index 23b9e15c..a38c5f47 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.cs @@ -1,4 +1,5 @@ using System; +using System.Buffers; using System.Collections.Immutable; using System.Runtime.CompilerServices; using System.Security.Cryptography; @@ -77,46 +78,55 @@ partial class ID2D1ShaderGenerator /// The resulting effect id. private static ImmutableArray CreateDefaultEffectId(INamedTypeSymbol typeSymbol) { - // Initialize an instance using the MD5 algorithm. We use this for several reasons: - // - We don't really need security, this is just to uniquely identify types - // - The hash size is 128 bits, which is exactly the size of a GUID. - IncrementalHash incrementalHash = EffectId.incrementalHash ??= IncrementalHash.CreateHash(HashAlgorithmName.MD5); + try + { + // Initialize an instance using the MD5 algorithm. We use this for several reasons: + // - We don't really need security, this is just to uniquely identify types + // - The hash size is 128 bits, which is exactly the size of a GUID. + IncrementalHash incrementalHash = EffectId.incrementalHash ??= IncrementalHash.CreateHash(HashAlgorithmName.MD5); - string assemblyName = typeSymbol.ContainingAssembly?.Name ?? string.Empty; + string assemblyName = typeSymbol.ContainingAssembly?.Name ?? string.Empty; - using ImmutableArrayBuilder byteBuffer = ImmutableArrayBuilder.Rent(); - using ImmutableArrayBuilder charBuffer = ImmutableArrayBuilder.Rent(); + using ImmutableArrayBuilder charBuffer = ImmutableArrayBuilder.Rent(); - // Format the fully qualified name into a pooled builder to avoid the string allocation - typeSymbol.AppendFullyQualifiedMetadataName(in charBuffer); + // Format the fully qualified name into a pooled builder to avoid the string allocation + typeSymbol.AppendFullyQualifiedMetadataName(in charBuffer); - int maxTypeNameCharsLength = Encoding.UTF8.GetMaxByteCount(charBuffer.Count); - int maxAssemblyNameCharsLength = Encoding.UTF8.GetMaxByteCount(assemblyName.Length); - int maxEncodedCharsLength = Math.Max(maxTypeNameCharsLength, maxAssemblyNameCharsLength); + int maxTypeNameByteCount = Encoding.UTF8.GetMaxByteCount(charBuffer.Count); + int maxAssemblyNameByteCount = Encoding.UTF8.GetMaxByteCount(assemblyName.Length); + int maxEncodedByteCount = Math.Max(maxTypeNameByteCount, maxAssemblyNameByteCount); - byteBuffer.EnsureCapacity(maxEncodedCharsLength); + byte[] bufferUtf8 = ArrayPool.Shared.Rent(maxEncodedByteCount); - // UTF8 encode the fully qualified name first - int typeNameCharsLength = Encoding.UTF8.GetBytes(charBuffer.WrittenSpan, byteBuffer.DangerousGetArray().AsSpan()); + // UTF8 encode the fully qualified name first + int typeNameBytesWritten = Encoding.UTF8.GetBytes(charBuffer.WrittenSpan, bufferUtf8.AsSpan()); - byteBuffer.Advance(typeNameCharsLength); + // Append the UTF8 fully qualified name to the MD5 hash + incrementalHash.AppendData(bufferUtf8, 0, typeNameBytesWritten); - // Append the UTF8 fully qualified name to the MD5 hash - incrementalHash.AppendData(byteBuffer.DangerousGetArray(), 0, byteBuffer.Count); + // UTF8 encode the assembly name as well + int assemblyNameBytesWritten = Encoding.UTF8.GetBytes(assemblyName.AsSpan(), bufferUtf8.AsSpan()); - // UTF8 encode the assembly name as well - int assemblyNameCharsLength = Encoding.UTF8.GetBytes(assemblyName.AsSpan(), byteBuffer.DangerousGetArray().AsSpan()); + // Append the UTF8 assembly name to the MD5 hash + incrementalHash.AppendData(bufferUtf8, 0, assemblyNameBytesWritten); - byteBuffer.Advance(assemblyNameCharsLength); + // The state is not fully in the incremental hash, we can return the array + ArrayPool.Shared.Return(bufferUtf8); - // Append the UTF8 assembly name to the MD5 hash - incrementalHash.AppendData(byteBuffer.DangerousGetArray(), 0, byteBuffer.Count); + // Get the resulting MD5 hash (128 bits) + byte[] hash = incrementalHash.GetHashAndReset(); - // Get the resulting MD5 hash (128 bits) - byte[] hash = incrementalHash.GetHashAndReset(); + // We own this buffer, so we can just reinterpret to an immutable array + return Unsafe.As>(ref hash); + } + catch + { + // Something went wrong, throw away the current incremental hash. + // Realistically speaking, this should just never happen. + incrementalHash = null; - // We own this buffer, so we can just reinterpret to an immutable array - return Unsafe.As>(ref hash); + throw; + } } } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs index fca0f6f0..3aa5b62b 100644 --- a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs +++ b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs @@ -75,33 +75,6 @@ internal struct ImmutableArrayBuilder : IDisposable this.writer!.AddRange(items); } - /// - /// Advances the current writer by the specified amount. - /// - /// The amoutn to advance by. - public readonly void Advance(int count) - { - this.writer!.Advance(count); - } - - /// - /// Gets the array currently in use (rented from the pool). - /// - /// The array currently in use. - public readonly T[] DangerousGetArray() - { - return this.writer!.DangerousGetArray(); - } - - /// - /// Ensures that the current instance has enough free space to contain a given number of new items. - /// - /// The minimum number of items to ensure space for. - public readonly void EnsureCapacity(int requestedSize) - { - this.writer!.EnsureCapacity(requestedSize); - } - /// /// Inserts an item to the builder at the specified index. /// @@ -204,23 +177,6 @@ internal struct ImmutableArrayBuilder : IDisposable this.index += items.Length; } - /// - public void Advance(int count) - { - if (count > this.array.Length - this.index) - { - ImmutableArrayBuilder.ThrowArgumentOutOfRangeExceptionForCount(); - } - - this.index += count; - } - - /// - public T[] DangerousGetArray() - { - return this.array; - } - /// public void Insert(int index, T item) { @@ -253,9 +209,12 @@ internal struct ImmutableArrayBuilder : IDisposable this.index = 0; } - /// + /// + /// Ensures that has enough free space to contain a given number of new items. + /// + /// The minimum number of items to ensure space for in . [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void EnsureCapacity(int requestedSize) + private void EnsureCapacity(int requestedSize) { if (requestedSize > this.array.Length - this.index) { @@ -294,12 +253,4 @@ file static class ImmutableArrayBuilder { throw new ArgumentOutOfRangeException("index"); } - - /// - /// Throws an for "count". - /// - public static void ThrowArgumentOutOfRangeExceptionForCount() - { - throw new ArgumentOutOfRangeException("count"); - } } \ No newline at end of file From c2386ebcbd76a0ffac7b306e651fb850e3712e95 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 18 Sep 2023 20:42:38 +0200 Subject: [PATCH 17/17] Add tests to ensure default EffectId-s are stable --- .../ComputeSharp.D2D1.Tests/D2D1PixelShaderEffectTests.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderEffectTests.cs b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderEffectTests.cs index 153179b0..2e62f459 100644 --- a/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderEffectTests.cs +++ b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderEffectTests.cs @@ -174,9 +174,14 @@ public partial class D2D1PixelShaderEffectTests using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out Guid effectId); + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out Guid effectId2); + + // Ensure that the dynamically generated GUIDs are deterministic and stable + Assert.AreEqual(Guid.Parse("F5287184-0EC7-0BC6-3942-8BFB70E77C4B"), effectId); + Assert.AreEqual(Guid.Parse("96310279-E716-D336-5097-BE516792CBF0"), effectId2); Assert.AreEqual(D2D1PixelShaderEffect.GetEffectId(), effectId); - Assert.AreNotEqual(D2D1PixelShaderEffect.GetEffectId(), effectId); + Assert.AreEqual(D2D1PixelShaderEffect.GetEffectId(), effectId2); } [D2DInputCount(0)]