diff --git a/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md index 8d27f716..f0709b41 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md +++ b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md @@ -63,3 +63,4 @@ CMPSD2D0053 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github CMPSD2D0054 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPSD2D0055 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPSD2D0056 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0057 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.Syntax.cs index 6dcdb293..93ef05c5 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.Syntax.cs @@ -24,31 +24,68 @@ partial class D2DPixelShaderSourceGenerator /// The resulting instance for the target method. public static MethodDeclarationSyntax GetSyntax(EmbeddedBytecodeMethodInfo bytecodeInfo, out Func fixup) { - // If there is no precompiled bytecode, just emit a span with a 0 value - string bytecodeLiterals = bytecodeInfo.Bytecode.IsDefaultOrEmpty - ? "0" - : ID2D1ShaderGenerator.LoadBytecode.BuildShaderBytecodeExpressionString(bytecodeInfo.Bytecode.AsSpan()); + // Get the TypeSyntax for the return type (either ReadOnlySpan, or an invalid one). + // This is done so that if the user picks an invalid type, the code is still generated, + // just returning default, so that proper diagnostic can be generated, without also + // having hard to understand compiler errors due to the mismatched return type here. + TypeSyntax returnType = bytecodeInfo.InvalidReturnType is string invalidReturnType + ? IdentifierName(invalidReturnType) + : GenericName(Identifier("global::System.ReadOnlySpan")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))); - // Prepare the fixup function - fixup = tree => SourceText.From(tree.ToFullString().Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals), Encoding.UTF8); + BlockSyntax methodBlock; + + if (bytecodeInfo.Bytecode.IsDefaultOrEmpty) + { + // This code generates the following block: + // + // { + // return default; + // } + methodBlock = + Block(ReturnStatement( + LiteralExpression( + SyntaxKind.DefaultLiteralExpression, + Token(SyntaxKind.DefaultKeyword)))); + + fixup = tree => tree.GetText(Encoding.UTF8); + } + else + { + // This code generates the following block: + // + // { + // return new byte[] { __EMBEDDED_SHADER_BYTECODE }; + // } + // + // As in the ID2D1Shader generator, the __EMBEDDED_SHADER_BYTECODE identifier will be replaced with the bytecode + // after the full string for the syntax tree has been generated, to avoid every literal going through a token. + methodBlock = + Block( + ReturnStatement( + ArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) + .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) + .WithInitializer( + InitializerExpression( + SyntaxKind.ArrayInitializerExpression, + SingletonSeparatedList(IdentifierName("__EMBEDDED_SHADER_BYTECODE")))))); + + string bytecodeLiterals = ID2D1ShaderGenerator.LoadBytecode.BuildShaderBytecodeExpressionString(bytecodeInfo.Bytecode.AsSpan()); + + // Prepare the fixup function + fixup = tree => SourceText.From(tree.ToFullString().Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals), Encoding.UTF8); + } // This code produces a branch as follows: // // /// // [global::System.CodeDom.Compiler.GeneratedCode("...", "...")] // [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] - // global::System.ReadOnlySpan () - // { - // return new byte[] { __EMBEDDED_SHADER_BYTECODE }; - // } - // - // As in the ID2D1Shader generator, the __EMBEDDED_SHADER_BYTECODE identifier will be replaced with the bytecode - // after the full string for the syntax tree has been generated, to avoid every literal going through a token. + // () + // return - MethodDeclaration( - GenericName(Identifier("global::System.ReadOnlySpan")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))), - Identifier(bytecodeInfo.MethodName)) + MethodDeclaration(returnType, Identifier(bytecodeInfo.MethodName)) .AddModifiers(bytecodeInfo.Modifiers.Select(Token).ToArray()) .AddAttributeLists( AttributeList(SingletonSeparatedList( @@ -61,15 +98,7 @@ partial class D2DPixelShaderSourceGenerator SyntaxKind.OpenBracketToken, TriviaList())), AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage"))))) - .WithBody(Block( - ReturnStatement( - ArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) - .WithInitializer( - InitializerExpression( - SyntaxKind.ArrayInitializerExpression, - SingletonSeparatedList(IdentifierName("__EMBEDDED_SHADER_BYTECODE"))))))); + .WithBody(methodBlock); } } } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs index a02ae0a9..72624b15 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs @@ -23,6 +23,35 @@ partial class D2DPixelShaderSourceGenerator /// private static partial class Execute { + /// + /// Validates that the return type of the annotated method is valid and returns the type name. + /// + /// The collection of produced instances. + /// The input instance to process. + /// The HLSL source to compile, if present. + public static string? GetInvalidReturnType(ImmutableArray.Builder diagnostics, IMethodSymbol methodSymbol) + { + if (!(methodSymbol.ReturnType is INamedTypeSymbol + { + Name: "ReadOnlySpan", + ContainingNamespace.Name: "System", + IsGenericType: true, + TypeParameters.Length: 1 + } returnType && returnType.TypeArguments[0].SpecialType == SpecialType.System_Byte)) + { + diagnostics.Add( + InvalidD2DPixelShaderSourceMethodReturnType, + methodSymbol, + methodSymbol.Name, + methodSymbol.ContainingType, + methodSymbol.ReturnType); + + return methodSymbol.ReturnType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + } + + return null; + } + /// /// Extracts the HLSL source from a method with the annotation. /// diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs index 6183d68c..88e02a33 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs @@ -41,6 +41,7 @@ public sealed partial class D2DPixelShaderSourceGenerator : IIncrementalGenerato // Get all necessary info for the current shader ImmutableArray modifiers = item.Syntax.Modifiers.Select(token => token.Kind()).ToImmutableArray(); string methodName = item.Symbol.Name; + string? invalidReturnType = Execute.GetInvalidReturnType(diagnostics, item.Symbol); string hlslSource = Execute.GetHlslSource(diagnostics, item.Symbol); D2D1ShaderProfile shaderProfile = Execute.GetShaderProfile(diagnostics, item.Symbol); D2D1CompileOptions compileOptions = Execute.GetCompileOptions(diagnostics, item.Symbol); @@ -48,6 +49,7 @@ public sealed partial class D2DPixelShaderSourceGenerator : IIncrementalGenerato HlslShaderMethodSourceInfo sourceInfo = new( modifiers, methodName, + invalidReturnType, hlslSource, shaderProfile, compileOptions, @@ -82,6 +84,7 @@ public sealed partial class D2DPixelShaderSourceGenerator : IIncrementalGenerato EmbeddedBytecodeMethodInfo bytecodeInfo = new( item.Source.Modifiers, item.Source.MethodName, + item.Source.InvalidReturnType, item.Source.HlslSource, bytecode); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 17e40f99..2701ce43 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -824,4 +824,20 @@ partial class DiagnosticDescriptors isEnabledByDefault: true, description: "Precompiled shaders using [D2DPixelShaderSource] must explicitly indicate the compile options.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for when a method with [D2DPixelShaderSource] has an invalid return type. + /// + /// Format: "The method \"{0}\" (in type {1}) is using [D2DPixelShaderSource] but has an invalid return type {2} (it must return a ReadOnlySpan<byte>)". + /// + /// + public static readonly DiagnosticDescriptor InvalidD2DPixelShaderSourceMethodReturnType = new DiagnosticDescriptor( + id: "CMPSD2D0057", + title: "Missing compile options for D2D pixel shader source", + messageFormat: "The method \"{0}\" (in type {1}) is using [D2DPixelShaderSource] but has an invalid return type {2} (it must return a ReadOnlySpan)", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "Methods using using [D2DPixelShaderSource] must use ReadOnlySpan as the return type.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeMethodInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeMethodInfo.cs index 4e74740c..5cb0a4b3 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeMethodInfo.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeMethodInfo.cs @@ -11,13 +11,15 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models; /// /// A model representing info on a shader method that has requested to be precompiled at build time. /// -///The modifiers for the annotated method. +/// The modifiers for the annotated method. /// The name of the annotated method. +/// The fully qualified name of the return type, if invalid. /// The HLSL source. /// The compiled shader bytecode, if available. internal sealed record EmbeddedBytecodeMethodInfo( ImmutableArray Modifiers, string MethodName, + string? InvalidReturnType, string HlslSource, ImmutableArray Bytecode) { @@ -31,6 +33,7 @@ internal sealed record EmbeddedBytecodeMethodInfo( { hashCode.AddRange(obj.Modifiers); hashCode.Add(obj.MethodName); + hashCode.Add(obj.InvalidReturnType); hashCode.Add(obj.HlslSource); hashCode.AddBytes(obj.Bytecode.AsSpan()); } @@ -41,6 +44,7 @@ internal sealed record EmbeddedBytecodeMethodInfo( return MemoryMarshal.Cast(x.Modifiers.AsSpan()).SequenceEqual(MemoryMarshal.Cast(y.Modifiers.AsSpan())) && x.MethodName == y.MethodName && + x.InvalidReturnType == y.InvalidReturnType && x.HlslSource == y.HlslSource && x.Bytecode.SequenceEqual(y.Bytecode); } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslShaderMethodSourceInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslShaderMethodSourceInfo.cs index 41563366..25b20451 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslShaderMethodSourceInfo.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslShaderMethodSourceInfo.cs @@ -12,6 +12,7 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models; /// /// The modifiers for the annotated method. /// The name of the annotated method. +/// The fully qualified name of the return type, if invalid. /// The HLSL source. /// The shader profile to use to compile the shader. /// The compile options to use to compile the shader. @@ -19,6 +20,7 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models; internal sealed record HlslShaderMethodSourceInfo( ImmutableArray Modifiers, string MethodName, + string? InvalidReturnType, string HlslSource, D2D1ShaderProfile ShaderProfile, D2D1CompileOptions CompileOptions, @@ -34,6 +36,7 @@ internal sealed record HlslShaderMethodSourceInfo( { hashCode.AddRange(obj.Modifiers); hashCode.Add(obj.MethodName); + hashCode.Add(obj.InvalidReturnType); hashCode.Add(obj.HlslSource); hashCode.Add(obj.ShaderProfile); hashCode.Add(obj.CompileOptions); @@ -46,6 +49,7 @@ internal sealed record HlslShaderMethodSourceInfo( return MemoryMarshal.Cast(x.Modifiers.AsSpan()).SequenceEqual(MemoryMarshal.Cast(y.Modifiers.AsSpan())) && x.MethodName == y.MethodName && + x.InvalidReturnType == y.InvalidReturnType && x.HlslSource == y.HlslSource && x.ShaderProfile == y.ShaderProfile && x.CompileOptions == y.CompileOptions &&