From 6e4351030141ff0c7ee50fb8e389f250fd9941c5 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 20 Nov 2024 23:51:43 -0800 Subject: [PATCH 1/6] Add 'NonConstantD2DInputArgumentAnalyzer' --- .../AnalyzerReleases.Shipped.md | 1 + .../InvalidD2DInputArgumentAnalyzer.cs | 20 +-- .../NonConstantD2DInputArgumentAnalyzer.cs | 133 ++++++++++++++++++ .../Diagnostics/DiagnosticDescriptors.cs | 16 +++ 4 files changed, 160 insertions(+), 10 deletions(-) create mode 100644 src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/NonConstantD2DInputArgumentAnalyzer.cs diff --git a/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md index 6dd956e8..2576182d 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md +++ b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md @@ -91,3 +91,4 @@ CMPSD2D0081 | ComputeSharp.D2D1.Shaders | Warning | [Documentation](https://gith CMPSD2D0082 | ComputeSharp.D2D1.Shaders | Warning | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPSD2D0083 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPSD2D0084 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0085 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DInputArgumentAnalyzer.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DInputArgumentAnalyzer.cs index 18359efb..254f6a83 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DInputArgumentAnalyzer.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DInputArgumentAnalyzer.cs @@ -130,23 +130,23 @@ public sealed class InvalidD2DInputArgumentAnalyzer : DiagnosticAnalyzer return false; } - // Get the symbols for all relevant 'D2D' methods - IMethodSymbol?[] d2DMethodSymbols = + // These are all the 'D2D' intrinsic methods that take a target shader input index + string[] d2DMethodNames = [ - d2DSymbol.GetMethod(nameof(D2D.GetInput)), - d2DSymbol.GetMethod(nameof(D2D.GetInputCoordinate)), - d2DSymbol.GetMethod(nameof(D2D.SampleInput)), - d2DSymbol.GetMethod(nameof(D2D.SampleInputAtOffset)), - d2DSymbol.GetMethod(nameof(D2D.SampleInputAtPosition)) + nameof(D2D.GetInput), + nameof(D2D.GetInputCoordinate), + nameof(D2D.SampleInput), + nameof(D2D.SampleInputAtOffset), + nameof(D2D.SampleInputAtPosition) ]; ImmutableDictionary.Builder inputTypeMethodMap = ImmutableDictionary.CreateBuilder(SymbolEqualityComparer.Default); // Validate all methods and build the map - foreach (IMethodSymbol? d2DMethodSymbol in d2DMethodSymbols) + foreach (string d2DMethodName in d2DMethodNames) { - // We failed to find a symbol (shouldn't really ever happen), just stop here - if (d2DMethodSymbol is null) + // If we can't resolve a symbol (shouldn't really ever happen), just stop here + if (d2DSymbol.GetMethod(d2DMethodName) is not { } d2DMethodSymbol) { methodSymbols = null; diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/NonConstantD2DInputArgumentAnalyzer.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/NonConstantD2DInputArgumentAnalyzer.cs new file mode 100644 index 00000000..fbc4c86f --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/NonConstantD2DInputArgumentAnalyzer.cs @@ -0,0 +1,133 @@ +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using ComputeSharp.SourceGeneration.Extensions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Operations; +using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +/// A diagnostic analyzer that generates an error whenever an invocation to a D2D intrinsic is using an argument that is not constant for the source shader input. +/// +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public sealed class NonConstantD2DInputArgumentAnalyzer : DiagnosticAnalyzer +{ + /// + public override ImmutableArray SupportedDiagnostics { get; } = [NonConstantSourceInputIndexForD2DIntrinsic]; + + /// + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + context.EnableConcurrentExecution(); + + context.RegisterCompilationStartAction(static context => + { + // Ensure we can get all methods, or stop immediately + if (!TryBuildMethodSymbolSet(context.Compilation, out ImmutableHashSet? methodSymbols)) + { + return; + } + + context.CancellationToken.ThrowIfCancellationRequested(); + + // Register a callback for each argument we want to validate + context.RegisterOperationAction(context => + { + IArgumentOperation operation = (IArgumentOperation)context.Operation; + + // Ensure the argument is for an invocation, and get its first argument + if (operation.Parent is not IInvocationOperation { Arguments: [{ } firstArgument, ..] } invocationOperation) + { + return; + } + + // We also want to verify that the argument is the first one (that's the only one that should be constant) + if (operation != firstArgument) + { + return; + } + + // Ensure the argument is for a 'D2D' method (ignore all other arguments, ie. almost all of them) + if (invocationOperation is not { TargetMethod: { IsStatic: true, ContainingType.Name: "D2D" } targetMethodSymbol }) + { + return; + } + + // We only want to kick in when the target parameter is an 'int' + if (operation is not { Parameter: { Type.SpecialType: SpecialType.System_Int32 } parameterSymbol }) + { + return; + } + + // This analyzer should only kick in when the target parameter is an 'int', and the argument is not constant + if (operation.Value is ILiteralOperation { ConstantValue.HasValue: true } or IUnaryOperation { ConstantValue.HasValue: true, Operand: ILiteralOperation }) + { + return; + } + + // Now we can actually verify that the target method is indeed one we care about (this should always match) + if (!methodSymbols.Contains(targetMethodSymbol)) + { + return; + } + + // Finally, we can emit the diagnostic + context.ReportDiagnostic(Diagnostic.Create( + NonConstantSourceInputIndexForD2DIntrinsic, + operation.Syntax.GetLocation(), + parameterSymbol.Name, + targetMethodSymbol.Name)); + }, OperationKind.Argument); + }); + } + + /// + /// Tries to build a set of instances for all D2D intrinsics targeting a specific shader input. + /// + /// The to consider for analysis. + /// The resulting set of resolved instances. + /// Whether all requested instances could be resolved. + private static bool TryBuildMethodSymbolSet(Compilation compilation, [NotNullWhen(true)] out ImmutableHashSet? methodSymbols) + { + // Get the 'D2D' symbol, to get methods from it + if (compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2D") is not { } d2DSymbol) + { + methodSymbols = null; + + return false; + } + + // All 'D2D' intrinsics targeting an input (see 'InvalidD2DInputArgumentAnalyzer') + string[] d2DMethodNames = + [ + nameof(D2D.GetInput), + nameof(D2D.GetInputCoordinate), + nameof(D2D.SampleInput), + nameof(D2D.SampleInputAtOffset), + nameof(D2D.SampleInputAtPosition) + ]; + + ImmutableHashSet.Builder inputTypeMethodSet = ImmutableHashSet.CreateBuilder(SymbolEqualityComparer.Default); + + // Validate all methods and build the map + foreach (string d2DMethodName in d2DMethodNames) + { + // Ensure we can find the target method symbol (again just like in 'InvalidD2DInputArgumentAnalyzer') + if (d2DSymbol.GetMethod(d2DMethodName) is not { } d2DMethodSymbol) + { + methodSymbols = null; + + return false; + } + + _ = inputTypeMethodSet.Add(d2DMethodSymbol); + } + + methodSymbols = inputTypeMethodSet.ToImmutable(); + + return true; + } +} \ 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 148bedf5..43409107 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -1269,4 +1269,20 @@ partial class DiagnosticDescriptors isEnabledByDefault: true, description: "D2D intrinsics must be used with compatible input types (the input type of each shader input can be configured using [D2DInputSimple] and [D2DInputComplex] on the shader type).", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a D2D intrinsic call with a source input index that is not a constant. + /// + /// Format: "The argument for parameter '{0}' in the call to the D2D intrinsic '{1}' must be a constant value with a literal expression (for instance, 'D2D.GetInput(0)' is valid, whereas 'D2D.GetInput(x)' or 'D2D.GetInput(ConstantIndex)' are not)". + /// + /// + public static readonly DiagnosticDescriptor NonConstantSourceInputIndexForD2DIntrinsic = new( + id: "CMPSD2D0085", + title: "Non constant input index for D2D intrinsic", + messageFormat: "The argument for parameter '{0}' in the call to the D2D intrinsic '{1}' must be a constant value with a literal expression (for instance, 'D2D.GetInput(0)' is valid, whereas 'D2D.GetInput(x)' or 'D2D.GetInput(ConstantIndex)' are not)", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "Arguments for parameters indicating the source shader input index in calls to D2D intrinsics must be constant values with a literal expression (for instance, 'D2D.GetInput(0)' is valid, whereas 'D2D.GetInput(x)' or 'D2D.GetInput(ConstantIndex)' are not).", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } \ No newline at end of file From 40b0c639095b2629259ca02f5bd191a24752f600 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 20 Nov 2024 23:51:53 -0800 Subject: [PATCH 2/6] Add unit tests for new analyzer --- ...ixelShaderDescriptorGenerator_Analyzers.cs | 102 ++++++++++++++++++ 1 file changed, 102 insertions(+) diff --git a/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator_Analyzers.cs b/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator_Analyzers.cs index 658f71f9..153b1f81 100644 --- a/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator_Analyzers.cs +++ b/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator_Analyzers.cs @@ -1394,4 +1394,106 @@ public class Test_D2DPixelShaderDescriptorGenerator_Analyzers await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); } + + [TestMethod] + public async Task NonConstantSourceInputIndexForD2DIntrinsic_LiteralExpression_DoesNotWarn() + { + const string source = """ + using ComputeSharp.D2D1; + using float4 = ComputeSharp.Float4; + + [D2DInputCount(1)] + [D2DInputSimple(0)] + internal readonly partial struct MyType : ID2D1PixelShader + { + public float4 Execute() + { + return D2D.GetInput(0); + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + + [TestMethod] + public async Task NonConstantSourceInputIndexForD2DIntrinsic_LiteralExpression_WithOtherMethodsTakingNonConstants_DoesNotWarn() + { + const string source = """ + using ComputeSharp.D2D1; + using float4 = ComputeSharp.Float4; + + [D2DInputCount(1)] + [D2DInputSimple(0)] + internal readonly partial struct MyType(int x) : ID2D1PixelShader + { + public float4 Execute() + { + return D2D.GetInput(0) + M1(x) + M2(x, 1) + M3(x) + M4(x, 1); + } + + public int M1(int index) => 1; + public int M2(int index, int x) => 2; + + public static int M3(int index) => 1; + public static int M4(int index, int x) => 1; + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + + [TestMethod] + public async Task NonConstantSourceInputIndexForD2DIntrinsic_NonConstantExpression_Warns() + { + const string source = """ + using ComputeSharp.D2D1; + using float4 = ComputeSharp.Float4; + + [D2DInputCount(1)] + internal readonly partial struct MyType(int x) : ID2D1PixelShader + { + public float4 Execute() + { + D2D.GetInput({|CMPSD2D0085:x|}); + D2D.GetInputCoordinate({|CMPSD2D0085:x|}); + D2D.SampleInput({|CMPSD2D0085:x|}, 0); + D2D.SampleInputAtOffset({|CMPSD2D0085:x|}, 0); + D2D.SampleInputAtPosition({|CMPSD2D0085:x|}, 0); + + return 0; + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + + [TestMethod] + public async Task NonConstantSourceInputIndexForD2DIntrinsic_NonLiteralConstant_Warns() + { + const string source = """ + using ComputeSharp.D2D1; + using float4 = ComputeSharp.Float4; + + [D2DInputCount(1)] + internal readonly partial struct MyType(int x) : ID2D1PixelShader + { + public const int SourceIndex = 0; + + public float4 Execute() + { + D2D.GetInput({|CMPSD2D0085:SourceIndex|}); + D2D.GetInputCoordinate({|CMPSD2D0085:SourceIndex|}); + D2D.SampleInput({|CMPSD2D0085:SourceIndex|}, 0); + D2D.SampleInputAtOffset({|CMPSD2D0085:SourceIndex|}, 0); + D2D.SampleInputAtPosition({|CMPSD2D0085:SourceIndex|}, 0); + + return 0; + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } } \ No newline at end of file From 2834eb67dde17ce22e2df8c952cf48b5c75b11cf Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 21 Nov 2024 09:18:47 -0800 Subject: [PATCH 3/6] Allow shader input indices from defined constants --- .../NonConstantD2DInputArgumentAnalyzer.cs | 4 +- .../Diagnostics/DiagnosticDescriptors.cs | 6 +- ...ixelShaderDescriptorGenerator_Analyzers.cs | 56 +++++++++---------- 3 files changed, 33 insertions(+), 33 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/NonConstantD2DInputArgumentAnalyzer.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/NonConstantD2DInputArgumentAnalyzer.cs index fbc4c86f..6e16e46e 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/NonConstantD2DInputArgumentAnalyzer.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/NonConstantD2DInputArgumentAnalyzer.cs @@ -62,8 +62,8 @@ public sealed class NonConstantD2DInputArgumentAnalyzer : DiagnosticAnalyzer return; } - // This analyzer should only kick in when the target parameter is an 'int', and the argument is not constant - if (operation.Value is ILiteralOperation { ConstantValue.HasValue: true } or IUnaryOperation { ConstantValue.HasValue: true, Operand: ILiteralOperation }) + // This analyzer should also only kick in when the argument is not constant + if (operation.Value.ConstantValue.HasValue) { return; } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 43409107..72b8a204 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -1273,16 +1273,16 @@ partial class DiagnosticDescriptors /// /// Gets a for a D2D intrinsic call with a source input index that is not a constant. /// - /// Format: "The argument for parameter '{0}' in the call to the D2D intrinsic '{1}' must be a constant value with a literal expression (for instance, 'D2D.GetInput(0)' is valid, whereas 'D2D.GetInput(x)' or 'D2D.GetInput(ConstantIndex)' are not)". + /// Format: "The argument for parameter '{0}' in the call to the D2D intrinsic '{1}' must be a constant value (for instance, 'D2D.GetInput(0)' is valid, whereas 'D2D.GetInput(x)' is not)". /// /// public static readonly DiagnosticDescriptor NonConstantSourceInputIndexForD2DIntrinsic = new( id: "CMPSD2D0085", title: "Non constant input index for D2D intrinsic", - messageFormat: "The argument for parameter '{0}' in the call to the D2D intrinsic '{1}' must be a constant value with a literal expression (for instance, 'D2D.GetInput(0)' is valid, whereas 'D2D.GetInput(x)' or 'D2D.GetInput(ConstantIndex)' are not)", + messageFormat: "The argument for parameter '{0}' in the call to the D2D intrinsic '{1}' must be a constant value (for instance, 'D2D.GetInput(0)' is valid, whereas 'D2D.GetInput(x)' is not)", category: "ComputeSharp.D2D1.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, - description: "Arguments for parameters indicating the source shader input index in calls to D2D intrinsics must be constant values with a literal expression (for instance, 'D2D.GetInput(0)' is valid, whereas 'D2D.GetInput(x)' or 'D2D.GetInput(ConstantIndex)' are not).", + description: "Arguments for parameters indicating the source shader input index in calls to D2D intrinsics must be constant values (for instance, 'D2D.GetInput(0)' is valid, whereas 'D2D.GetInput(x)' is not).", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } \ No newline at end of file diff --git a/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator_Analyzers.cs b/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator_Analyzers.cs index 153b1f81..778129b9 100644 --- a/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator_Analyzers.cs +++ b/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator_Analyzers.cs @@ -1443,6 +1443,34 @@ public class Test_D2DPixelShaderDescriptorGenerator_Analyzers await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); } + [TestMethod] + public async Task NonConstantSourceInputIndexForD2DIntrinsic_NonLiteralConstant_DoesNotWarn() + { + const string source = """ + using ComputeSharp.D2D1; + using float4 = ComputeSharp.Float4; + + [D2DInputCount(1)] + internal readonly partial struct MyType(int x) : ID2D1PixelShader + { + public const int SourceIndex = 0; + + public float4 Execute() + { + D2D.GetInput(SourceIndex); + D2D.GetInputCoordinate(SourceIndex); + D2D.SampleInput(SourceIndex, 0); + D2D.SampleInputAtOffset(SourceIndex, 0); + D2D.SampleInputAtPosition(SourceIndex, 0); + + return 0; + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + [TestMethod] public async Task NonConstantSourceInputIndexForD2DIntrinsic_NonConstantExpression_Warns() { @@ -1468,32 +1496,4 @@ public class Test_D2DPixelShaderDescriptorGenerator_Analyzers await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); } - - [TestMethod] - public async Task NonConstantSourceInputIndexForD2DIntrinsic_NonLiteralConstant_Warns() - { - const string source = """ - using ComputeSharp.D2D1; - using float4 = ComputeSharp.Float4; - - [D2DInputCount(1)] - internal readonly partial struct MyType(int x) : ID2D1PixelShader - { - public const int SourceIndex = 0; - - public float4 Execute() - { - D2D.GetInput({|CMPSD2D0085:SourceIndex|}); - D2D.GetInputCoordinate({|CMPSD2D0085:SourceIndex|}); - D2D.SampleInput({|CMPSD2D0085:SourceIndex|}, 0); - D2D.SampleInputAtOffset({|CMPSD2D0085:SourceIndex|}, 0); - D2D.SampleInputAtPosition({|CMPSD2D0085:SourceIndex|}, 0); - - return 0; - } - } - """; - - await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); - } } \ No newline at end of file From 7a3dd640b16d4d2490f8bdc0c7616a0faec1d419 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 25 Nov 2024 20:24:15 -0800 Subject: [PATCH 4/6] Always emit diagnostics directly on arguments --- .../Analyzers/InvalidD2DInputArgumentAnalyzer.cs | 6 +++--- ...st_D2DPixelShaderDescriptorGenerator_Analyzers.cs | 12 ++++++------ 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DInputArgumentAnalyzer.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DInputArgumentAnalyzer.cs index 254f6a83..078c9360 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DInputArgumentAnalyzer.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DInputArgumentAnalyzer.cs @@ -59,7 +59,7 @@ public sealed class InvalidD2DInputArgumentAnalyzer : DiagnosticAnalyzer // Second cheap inital filter: we only care about invocations with a constant 'int' argument in first position. // While we're validating this, let's also get the 'index' parameter, since we need to validate it anyway. - if (operation.Arguments is not [{ Value.ConstantValue: { HasValue: true, Value: int index } }, ..]) + if (operation.Arguments is not [{ Value.ConstantValue: { HasValue: true, Value: int index } } firstArgument, ..]) { return; } @@ -95,7 +95,7 @@ public sealed class InvalidD2DInputArgumentAnalyzer : DiagnosticAnalyzer { context.ReportDiagnostic(Diagnostic.Create( IndexOutOfRangeForD2DIntrinsic, - operation.Syntax.GetLocation(), + firstArgument.Syntax.GetLocation(), targetMethodSymbol.Name, index, typeSymbol, @@ -106,7 +106,7 @@ public sealed class InvalidD2DInputArgumentAnalyzer : DiagnosticAnalyzer // Second validation: the input type must match context.ReportDiagnostic(Diagnostic.Create( InvalidInputTypeForD2DIntrinsic, - operation.Syntax.GetLocation(), + firstArgument.Syntax.GetLocation(), targetMethodSymbol.Name, index)); } diff --git a/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator_Analyzers.cs b/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator_Analyzers.cs index 778129b9..988c05b4 100644 --- a/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator_Analyzers.cs +++ b/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator_Analyzers.cs @@ -1307,7 +1307,7 @@ public class Test_D2DPixelShaderDescriptorGenerator_Analyzers { public float4 Execute() { - return {|CMPSD2D0083:D2D.GetInput({{index}})|}; + return D2D.GetInput({|CMPSD2D0083:{{index}}|}); } } """; @@ -1331,7 +1331,7 @@ public class Test_D2DPixelShaderDescriptorGenerator_Analyzers { public float4 Execute() { - return {|CMPSD2D0083:D2D.GetInput({{index}})|}; + return D2D.GetInput({|CMPSD2D0083:{{index}}|}); } } """; @@ -1382,10 +1382,10 @@ public class Test_D2DPixelShaderDescriptorGenerator_Analyzers { public float4 Execute() { - {|CMPSD2D0084:D2D.GetInputCoordinate(0)|}; - {|CMPSD2D0084:D2D.SampleInput(0, 0)|}; - {|CMPSD2D0084:D2D.SampleInputAtOffset(0, 0)|}; - {|CMPSD2D0084:D2D.SampleInputAtPosition(0, 0)|}; + D2D.GetInputCoordinate({|CMPSD2D0084:0|}); + D2D.SampleInput({|CMPSD2D0084:0|}, 0); + D2D.SampleInputAtOffset({|CMPSD2D0084:0|}, 0); + D2D.SampleInputAtPosition({|CMPSD2D0084:0|}, 0); return 0; } From 1facaba03a9de0ab8b5bb6b852b98825568b2bb1 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 25 Nov 2024 21:29:42 -0800 Subject: [PATCH 5/6] Add 'InvalidIndexSyntaxForD2DIntrinsic' diagnostic --- .../AnalyzerReleases.Shipped.md | 1 + .../InvalidD2DInputArgumentAnalyzer.cs | 31 ++++++++++++++++++- .../Diagnostics/DiagnosticDescriptors.cs | 16 ++++++++++ 3 files changed, 47 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md index 2576182d..e9637e0e 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md +++ b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md @@ -92,3 +92,4 @@ CMPSD2D0082 | ComputeSharp.D2D1.Shaders | Warning | [Documentation](https://gith CMPSD2D0083 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPSD2D0084 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPSD2D0085 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0086 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DInputArgumentAnalyzer.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DInputArgumentAnalyzer.cs index 078c9360..24631108 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DInputArgumentAnalyzer.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DInputArgumentAnalyzer.cs @@ -5,6 +5,7 @@ using ComputeSharp.D2D1.Interop; using ComputeSharp.D2D1.Intrinsics; using ComputeSharp.SourceGeneration.Extensions; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; @@ -21,7 +22,8 @@ public sealed class InvalidD2DInputArgumentAnalyzer : DiagnosticAnalyzer public override ImmutableArray SupportedDiagnostics { get; } = [ IndexOutOfRangeForD2DIntrinsic, - InvalidInputTypeForD2DIntrinsic + InvalidInputTypeForD2DIntrinsic, + InvalidIndexSyntaxForD2DIntrinsic ]; /// @@ -64,12 +66,39 @@ public sealed class InvalidD2DInputArgumentAnalyzer : DiagnosticAnalyzer return; } + // We only want to kick in when the target parameter is an 'int' (same as in 'NonConstantD2DInputArgumentAnalyzer') + if (firstArgument.Parameter is not { Type.SpecialType: SpecialType.System_Int32 } parameterSymbol) + { + return; + } + // Validate that the target method is one of the ones we care about, and get the target input type if (!methodSymbols.TryGetValue(targetMethodSymbol, out D2D1PixelShaderInputType? targetInputType)) { return; } + // Also check that the actual syntax for the index argument is valid (only literals and direct constant field references + // are valid). For parenthesized expressions, we need to check the parent syntax node (the operation just ignores it). + if (firstArgument.Value is not (ILiteralOperation or IFieldReferenceOperation)) + { + context.ReportDiagnostic(Diagnostic.Create( + InvalidIndexSyntaxForD2DIntrinsic, + firstArgument.Syntax.GetLocation(), + parameterSymbol.Name, + targetMethodSymbol.Name)); + } + else if (firstArgument.Syntax.Parent.IsKind(SyntaxKind.ParenthesizedExpression)) + { + // In this case, we pass the parent syntax node for the location, so that we can + // include the parentheses as well. Otherwise we'd just underline the inner value. + context.ReportDiagnostic(Diagnostic.Create( + InvalidIndexSyntaxForD2DIntrinsic, + firstArgument.Syntax.Parent.GetLocation(), + parameterSymbol.Name, + targetMethodSymbol.Name)); + } + // We have matched a target symbol, so let's try to get the parent shader if (context.ContainingSymbol.FirstAncestorOrSelf() is not { TypeKind: TypeKind.Struct } typeSymbol) { diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 72b8a204..80df85c4 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -1285,4 +1285,20 @@ partial class DiagnosticDescriptors isEnabledByDefault: true, description: "Arguments for parameters indicating the source shader input index in calls to D2D intrinsics must be constant values (for instance, 'D2D.GetInput(0)' is valid, whereas 'D2D.GetInput(x)' is not).", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a D2D intrinsic call with a source input index using invalid syntax. + /// + /// Format: "The argument for parameter '{0}' in the call to the D2D intrinsic '{1}' must be a literal or a constant field reference (for instance, 'D2D.GetInput(0)' and 'D2D.GetInput(TextureIndex)' are valid, whereas 'D2D.GetInput(BaseIndex + 1)' and 'D2D.GetInput(1 + 2)' are not)". + /// + /// + public static readonly DiagnosticDescriptor InvalidIndexSyntaxForD2DIntrinsic = new( + id: "CMPSD2D0086", + title: "Invalid input index syntax for D2D intrinsic", + messageFormat: "The argument for parameter '{0}' in the call to the D2D intrinsic '{1}' must be a literal or a constant field reference (for instance, 'D2D.GetInput(0)' and 'D2D.GetInput(TextureIndex)' are valid, whereas 'D2D.GetInput(BaseIndex + 1)' and 'D2D.GetInput(1 + 2)' are not)", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "Arguments for parameters indicating the source shader input index in calls to D2D intrinsics must be a literal or constant field references (for instance, 'D2D.GetInput(0)' and 'D2D.GetInput(TextureIndex)' are valid, whereas 'D2D.GetInput(BaseIndex + 1)' and 'D2D.GetInput(1 + 2)' are not).", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } \ No newline at end of file From 82ab453aebe1178e011a277fdb6760a1bc5475ad Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 25 Nov 2024 21:29:54 -0800 Subject: [PATCH 6/6] Update unit tests for new diagnostic --- ...ixelShaderDescriptorGenerator_Analyzers.cs | 74 ++++++++++++++++++- 1 file changed, 71 insertions(+), 3 deletions(-) diff --git a/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator_Analyzers.cs b/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator_Analyzers.cs index 988c05b4..fa1d3ccc 100644 --- a/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator_Analyzers.cs +++ b/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator_Analyzers.cs @@ -1292,7 +1292,6 @@ public class Test_D2DPixelShaderDescriptorGenerator_Analyzers } [TestMethod] - [DataRow(-1)] [DataRow(0)] [DataRow(1)] [DataRow(16)] @@ -1316,11 +1315,30 @@ public class Test_D2DPixelShaderDescriptorGenerator_Analyzers } [TestMethod] - [DataRow(-1)] + public async Task IndexOutOfRangeForD2DIntrinsic_InvalidArgument2_Warns() + { + const string source = """ + using ComputeSharp.D2D1; + using float4 = ComputeSharp.Float4; + + [D2DInputCount(0)] + internal readonly partial struct MyType : ID2D1PixelShader + { + public float4 Execute() + { + return D2D.GetInput({|CMPSD2D0086:{|CMPSD2D0083:-1|}|}); + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + + [TestMethod] [DataRow(5)] [DataRow(6)] [DataRow(16)] - public async Task IndexOutOfRangeForD2DIntrinsic_InvalidArgument2_Warns(int index) + public async Task IndexOutOfRangeForD2DIntrinsic_InvalidArgument3_Warns(int index) { string source = $$""" using ComputeSharp.D2D1; @@ -1339,6 +1357,26 @@ public class Test_D2DPixelShaderDescriptorGenerator_Analyzers await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); } + [TestMethod] + public async Task IndexOutOfRangeForD2DIntrinsic_InvalidArgument4_Warns() + { + const string source = """ + using ComputeSharp.D2D1; + using float4 = ComputeSharp.Float4; + + [D2DInputCount(5)] + internal readonly partial struct MyType : ID2D1PixelShader + { + public float4 Execute() + { + return D2D.GetInput({|CMPSD2D0086:{|CMPSD2D0083:-1|}|}); + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + [TestMethod] public async Task InvalidInputTypeForD2DIntrinsic_ValidArguments_DoesNotWarn() { @@ -1395,6 +1433,36 @@ public class Test_D2DPixelShaderDescriptorGenerator_Analyzers await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); } + [TestMethod] + public async Task InvalidInputTypeForD2DIntrinsic_InvalidSyntax_Warns() + { + const string source = """ + using ComputeSharp.D2D1; + using float4 = ComputeSharp.Float4; + + [D2DInputCount(2)] + [D2DInputSimple(0)] + [D2DInputComplex(1)] + internal readonly partial struct MyType : ID2D1PixelShader + { + const int BaseIndex = 0; + + public float4 Execute() + { + D2D.GetInput({|CMPSD2D0086:+1|}); + D2D.GetInput({|CMPSD2D0086:-0|}); + D2D.GetInput({|CMPSD2D0086:(1)|}); + D2D.GetInput({|CMPSD2D0086:BaseIndex + 1|}); + D2D.GetInput({|CMPSD2D0086:0 + 1|}); + + return 0; + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + [TestMethod] public async Task NonConstantSourceInputIndexForD2DIntrinsic_LiteralExpression_DoesNotWarn() {