diff --git a/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md index 227c5323..b3e8a176 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,5 @@ 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) +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 new file mode 100644 index 00000000..f2f0e57f --- /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 attributeData in typeSymbol.GetAttributes()) + { + // Look for the [D2DEffectId] use + if (!SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, d2DEffectIdAttributeSymbol)) + { + continue; + } + + // Validate the GUID text and emit a diagnostic if needed + if (attributeData.ConstructorArguments is not [{ Value: string value }] || + !Guid.TryParse(value, out _)) + { + context.ReportDiagnostic(Diagnostic.Create( + InvalidD2DEffectIdAttributeValue, + attributeData.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..3f1debd2 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -857,4 +857,36 @@ 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"); + + /// + /// 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.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectDisplayNameProperty.Syntax.cs new file mode 100644 index 00000000..51b9de28 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectDisplayNameProperty.Syntax.cs @@ -0,0 +1,34 @@ +using ComputeSharp.D2D1.__Internals; +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 effect display name value. + /// The resulting instance for the EffectDisplayName property. + public static PropertyDeclarationSyntax GetSyntax(string effectDisplayName) + { + // 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(effectDisplayName)))) + .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectDisplayNameProperty.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectDisplayNameProperty.cs new file mode 100644 index 00000000..0879e724 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectDisplayNameProperty.cs @@ -0,0 +1,57 @@ +using System.Diagnostics.CodeAnalysis; +using ComputeSharp.D2D1.SourceGenerators.Helpers; +using ComputeSharp.SourceGeneration.Extensions; +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 input object currently in use. + /// The for the shader type in use. + /// The resulting effect display name. + public static string GetInfo(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] + if (SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, effectIdAttributeSymbol)) + { + return D2D1EffectMetadataParser.TryGetEffectDisplayName(attributeData, out effectDisplayName); + } + } + + effectDisplayName = default; + + return false; + } + } +} \ No newline at end of file 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..04e1e4bc --- /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.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Helpers; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618 + +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(EffectIdInfo 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(info.Bytes.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.CreateEffectIdProperty.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.cs new file mode 100644 index 00000000..a38c5f47 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateEffectIdProperty.cs @@ -0,0 +1,132 @@ +using System; +using System.Buffers; +using System.Collections.Immutable; +using System.Runtime.CompilerServices; +using System.Security.Cryptography; +using System.Text; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +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 input object currently in use. + /// The for the shader type in use. + /// The resulting effect id. + public static ImmutableArray GetInfo(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) + { + 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; + + using ImmutableArrayBuilder charBuffer = ImmutableArrayBuilder.Rent(); + + // Format the fully qualified name into a pooled builder to avoid the string allocation + typeSymbol.AppendFullyQualifiedMetadataName(in charBuffer); + + int maxTypeNameByteCount = Encoding.UTF8.GetMaxByteCount(charBuffer.Count); + int maxAssemblyNameByteCount = Encoding.UTF8.GetMaxByteCount(assemblyName.Length); + int maxEncodedByteCount = Math.Max(maxTypeNameByteCount, maxAssemblyNameByteCount); + + byte[] bufferUtf8 = ArrayPool.Shared.Rent(maxEncodedByteCount); + + // UTF8 encode the fully qualified name first + int typeNameBytesWritten = Encoding.UTF8.GetBytes(charBuffer.WrittenSpan, bufferUtf8.AsSpan()); + + // Append the UTF8 fully qualified name to the MD5 hash + incrementalHash.AppendData(bufferUtf8, 0, typeNameBytesWritten); + + // UTF8 encode the assembly name as well + int assemblyNameBytesWritten = Encoding.UTF8.GetBytes(assemblyName.AsSpan(), bufferUtf8.AsSpan()); + + // Append the UTF8 assembly name to the MD5 hash + incrementalHash.AppendData(bufferUtf8, 0, assemblyNameBytesWritten); + + // The state is not fully in the incremental hash, we can return the array + ArrayPool.Shared.Return(bufferUtf8); + + // 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; + + throw; + } + } + } +} \ 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..31767b11 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -52,6 +52,16 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator using ImmutableArrayBuilder diagnostics = ImmutableArrayBuilder.Rent(); + // EffectId info + ImmutableArray effectId = EffectId.GetInfo(context.SemanticModel.Compilation, typeSymbol); + + token.ThrowIfCancellationRequested(); + + // EffectDisplayName info + string effectDisplayName = EffectDisplayName.GetInfo(context.SemanticModel.Compilation, typeSymbol); + + token.ThrowIfCancellationRequested(); + // LoadDispatchData() info ImmutableArray fieldInfos = LoadDispatchData.GetInfo( diagnostics, @@ -115,6 +125,8 @@ 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), @@ -136,6 +148,35 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator shaderInfoWithErrors .Select(static (item, _) => item.Diagnostcs)); + // Get the EffectDisplayName info (hierarchy and effect display name) + IncrementalValuesProvider<(HierarchyInfo Hierarchy, string EffectDisplayName)> effectDisplayNameInfo = + shaderInfoWithErrors + .Select(static (item, _) => (item.Hierarchy, item.EffectDisplayName)); + + // Generate the EffectDisplayName properties + context.RegisterSourceOutput(effectDisplayNameInfo, static (context, item) => + { + PropertyDeclarationSyntax effectDisplayNameProperty = EffectDisplayName.GetSyntax(item.EffectDisplayName); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, effectDisplayNameProperty, canUseSkipLocalsInit: false); + + context.AddSource($"{item.Hierarchy.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(effectIdInfo, static (context, item) => + { + PropertyDeclarationSyntax effectDisplayNameProperty = EffectId.GetSyntax(item.EffectId, out Func fixup); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, effectDisplayNameProperty, canUseSkipLocalsInit: false); + SourceText text = fixup(compilationUnit); + + context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(EffectId)}.g.cs", text); + }); + // Get the GetInputCount() info (hierarchy and input count) IncrementalValuesProvider<(HierarchyInfo Hierarchy, int InputCount)> inputCountInfo = shaderInfoWithErrors @@ -145,7 +186,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 +200,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 +214,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 +228,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 +242,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 +262,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 +320,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 +335,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 +350,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 +364,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.SourceGenerators/Models/D2D1ShaderInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs index 5674a782..568ca2ef 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs @@ -7,6 +7,8 @@ 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 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. @@ -17,6 +19,8 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models; /// The discovered diagnostics, if any. internal sealed record D2D1ShaderInfo( HierarchyInfo Hierarchy, + EffectIdInfo EffectId, + string EffectDisplayName, 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.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 new file mode 100644 index 00000000..c64e8bb8 --- /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 effect id value. + /// + public Guid Value { get; } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs index e4c9ae28..3a6b4ce0 100644 --- a/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs +++ b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs @@ -11,6 +11,22 @@ 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. + /// + /// + /// This only applies to effects created from . + /// + string EffectDisplayName { get; } + /// /// Initializes the current shader from a buffer with the serialized dispatch data. /// diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs index d9adec9c..c6e2bd09 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs @@ -18,6 +18,32 @@ 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; + } + + /// + /// 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. /// @@ -26,7 +52,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 { @@ -42,7 +71,7 @@ public static unsafe class D2D1PixelShaderEffect @@ -261,9 +290,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 @@ -283,7 +311,7 @@ public static unsafe class D2D1PixelShaderEffect 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(); 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. /// diff --git a/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderEffectTests.cs b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderEffectTests.cs index ac7a715f..2e62f459 100644 --- a/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderEffectTests.cs +++ b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderEffectTests.cs @@ -165,4 +165,116 @@ 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); + 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.AreEqual(D2D1PixelShaderEffect.GetEffectId(), effectId2); + } + + [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; + } + } + + [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