From 17a95cac990a39f928cc90f10724c77ff852c90e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 2 Jan 2024 19:36:18 +0100 Subject: [PATCH 1/5] Add InvalidShaderTypeInputsAnalyzer --- .../InvalidShaderTypeInputsAnalyzer.cs | 203 ++++++++++++++++++ .../Diagnostics/DiagnosticDescriptors.cs | 6 +- 2 files changed, 206 insertions(+), 3 deletions(-) create mode 100644 src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidShaderTypeInputsAnalyzer.cs diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidShaderTypeInputsAnalyzer.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidShaderTypeInputsAnalyzer.cs new file mode 100644 index 00000000..61c623fd --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidShaderTypeInputsAnalyzer.cs @@ -0,0 +1,203 @@ +using System; +using System.Collections.Immutable; +using System.Linq; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +/// A diagnostic analyzer that generates errors whenever a shader type is declaring invalid inputs. +/// +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public sealed class InvalidShaderTypeInputsAnalyzer : DiagnosticAnalyzer +{ + /// + public override ImmutableArray SupportedDiagnostics { get; } = ImmutableArray.Create( + MissingD2DInputCountAttribute, + InvalidD2DInputCount, + OutOfRangeInputIndex, + RepeatedD2DInputSimpleIndices, + RepeatedD2DInputComplexIndices, + InvalidSimpleAndComplexIndicesCombination); + + /// + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); + context.EnableConcurrentExecution(); + + context.RegisterCompilationStartAction(static context => + { + // Get the [D2DInputCount], [D2DInputSimple], [D2DInputComplex] and ID2D1PixelShader symbols + if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DInputCountAttribute") is not { } d2DInputCountAttributeSymbol || + context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DInputSimpleAttribute") is not { } d2DInputSimpleAttributeSymbol || + context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DInputComplexAttribute") is not { } d2DInputComplexAttributeSymbol || + context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.ID2D1PixelShader") is not { } d2D1PixelShaderSymbol) + { + return; + } + + context.RegisterSymbolAction(context => + { + // We're validating all struct types (since they're the possible shader types) + if (context.Symbol is not INamedTypeSymbol { TypeKind: TypeKind.Struct } typeSymbol) + { + return; + } + + // Only validate fields for shader types (same as for resource textures) + if (!typeSymbol.HasInterfaceWithType(d2D1PixelShaderSymbol)) + { + return; + } + + // If there is no [D2DInputCount], we must stop here, but also emit a diagnostic (as it's mandatory) + if (!typeSymbol.TryGetAttributeWithType(d2DInputCountAttributeSymbol, out AttributeData? inputCountData)) + { + context.ReportDiagnostic(Diagnostic.Create( + MissingD2DInputCountAttribute, + typeSymbol.Locations.First(), + typeSymbol)); + + return; + } + + int inputCount = (int)inputCountData.ConstructorArguments[0].Value!; + + // Validate the input count + if (inputCount is not (>= 0 and <= 8)) + { + context.ReportDiagnostic(Diagnostic.Create( + InvalidD2DInputCount, + typeSymbol.Locations.First(), + typeSymbol, + inputCount)); + } + + // If we input is not valid, we can just clamp it to ensure it's nor negative, and + // continue to validate the rest normally. This will avoid some false positives. + inputCount = Math.Max(inputCount, 0); + + using ImmutableArrayBuilder inputSimpleIndices = new(); + using ImmutableArrayBuilder inputComplexIndices = new(); + + // Gather the indices of all explicitly declared simple and complex inputs + foreach (AttributeData attributeData in typeSymbol.GetAttributes()) + { + if (SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, d2DInputSimpleAttributeSymbol)) + { + inputSimpleIndices.Add((int)attributeData.ConstructorArguments[0].Value!); + } + else if (SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, d2DInputComplexAttributeSymbol)) + { + inputComplexIndices.Add((int)attributeData.ConstructorArguments[0].Value!); + } + } + + // All simple indices must be in range + foreach (int index in inputSimpleIndices.WrittenSpan) + { + if ((uint)index >= inputCount) + { + context.ReportDiagnostic(Diagnostic.Create( + OutOfRangeInputIndex, + typeSymbol.Locations.First(), + typeSymbol)); + + goto AfterOutOfRangeInputValidation; + } + } + + // All complex indices must also be in range (of course) + foreach (int index in inputComplexIndices.WrittenSpan) + { + if ((uint)index >= inputCount) + { + context.ReportDiagnostic(Diagnostic.Create( + OutOfRangeInputIndex, + typeSymbol.Locations.First(), + typeSymbol)); + + goto AfterOutOfRangeInputValidation; + } + } + + AfterOutOfRangeInputValidation: + + Span selectedSimpleInputIndices = stackalloc bool[8]; + Span selectedComplexInputIndices = stackalloc bool[8]; + + selectedSimpleInputIndices.Clear(); + selectedComplexInputIndices.Clear(); + + // All simple indices must be unique + foreach (int index in inputSimpleIndices.WrittenSpan) + { + // Skip this path for invalid indices (just like with resource textures again). + // This same exact pattern is also used when validating input descriptions. + if ((uint)index >= 8) + { + continue; + } + + ref bool isInputIndexUsed = ref selectedSimpleInputIndices[index]; + + if (isInputIndexUsed) + { + context.ReportDiagnostic(Diagnostic.Create( + RepeatedD2DInputSimpleIndices, + typeSymbol.Locations.First(), + typeSymbol)); + + break; + } + + isInputIndexUsed = true; + } + + // All complex indices must be unique as well (again, of course) + foreach (int index in inputComplexIndices.WrittenSpan) + { + if ((uint)index >= 8) + { + continue; + } + + ref bool isInputIndexUsed = ref selectedComplexInputIndices[index]; + + if (isInputIndexUsed) + { + context.ReportDiagnostic(Diagnostic.Create( + RepeatedD2DInputComplexIndices, + typeSymbol.Locations.First(), + typeSymbol)); + + break; + } + + isInputIndexUsed = true; + } + + // Simple and complex indices can't have indices in common. We just validate + // the entire temporary spans, so that even if some values are out of range, + // we still also detect that some are conflicting. + for (int i = 0; i < 8; i++) + { + if (selectedSimpleInputIndices[i] && selectedComplexInputIndices[i]) + { + context.ReportDiagnostic(Diagnostic.Create( + InvalidSimpleAndComplexIndicesCombination, + typeSymbol.Locations.First(), + typeSymbol)); + + break; + } + } + }, 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 2aabd19c..2e615f6c 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -479,17 +479,17 @@ partial class DiagnosticDescriptors /// /// Gets a for a invalid D2D input count value. /// - /// Format: "The D2D1 shader of type {0} is using an incorrect value for [D2DInputCount] (the number of inputs must be in the [0, 8] range)". + /// Format: "The D2D1 shader of type {0} is using an incorrect value for [D2DInputCount] (the number of inputs must be in the [0, 8] range, but it was {1})". /// /// public static readonly DiagnosticDescriptor InvalidD2DInputCount = new( id: "CMPSD2D0035", title: "Invalid D2D1 shader input count", - messageFormat: "The D2D1 shader of type {0} is using an incorrect value for [D2DInputCount] (the number of inputs must be in the [0, 8] range)", + messageFormat: "The D2D1 shader of type {0} is using an incorrect value for [D2DInputCount] (the number of inputs must be in the [0, 8] range, but it was {1})", category: "ComputeSharp.D2D1.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, - description: "A D2D1 shader must have a number of inputs in the [1, 8] range.", + description: "A D2D1 shader must have a number of inputs in the [0, 8] range.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); /// From cbcde032633e5834a63973ca9514a78e3112c973 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 2 Jan 2024 19:49:26 +0100 Subject: [PATCH 2/5] Remove leftover diagnostics from InputTypes generator --- ...xelShaderDescriptorGenerator.InputTypes.cs | 125 +++--------------- .../D2DPixelShaderDescriptorGenerator.cs | 1 - 2 files changed, 20 insertions(+), 106 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.InputTypes.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.InputTypes.cs index 8cd7e576..6802773c 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.InputTypes.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.InputTypes.cs @@ -1,10 +1,9 @@ using System; using System.Collections.Immutable; +using System.Runtime.CompilerServices; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; -using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; -using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; namespace ComputeSharp.D2D1.SourceGenerators; @@ -19,26 +18,18 @@ partial class D2DPixelShaderDescriptorGenerator /// /// Extracts the input info for the current shader. /// - /// The collection of produced instances. /// The input instance to process. /// The number of shader inputs to declare. /// The indicess of the simple shader inputs. /// The indices of the complex shader inputs. /// The combined and serialized input types for each available input. public static void GetInfo( - ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol, out int inputCount, out ImmutableArray inputSimpleIndices, out ImmutableArray inputComplexIndices, out ImmutableArray combinedInputTypes) { - // We need a separate local here so we can keep the original value to apply - // diagnostics to, but without returning invalid values to the caller which - // might cause generator errors (eg. -1 would cause other code to just throw). - int rawInputCount = 0; - bool isInputCountPresent = false; - // Note: this logic is shared with InvalidD2DResourceTextureIndexAttributeUseAnalyzer. // If any changes are made here, they should be reflected in that analyzer as well. inputCount = 0; @@ -55,9 +46,11 @@ partial class D2DPixelShaderDescriptorGenerator switch (builder.WrittenSpan) { case "ComputeSharp.D2D1.D2DInputCountAttribute": - rawInputCount = (int)attributeData.ConstructorArguments[0].Value!; - inputCount = Math.Max(rawInputCount, 0); - isInputCountPresent = true; + + // We ignore negative values here to avoid the rest of the generator crashing due + // to out of bound exceptions or other issues. The analyzer will detect this and + // emit a diagnostic if that's the case, so it is safe to ignore that from here. + inputCount = Math.Max((int)attributeData.ConstructorArguments[0].Value!, 0); break; case "ComputeSharp.D2D1.D2DInputSimpleAttribute": inputSimpleIndicesBuilder.Add((int)attributeData.ConstructorArguments[0].Value!); @@ -72,107 +65,29 @@ partial class D2DPixelShaderDescriptorGenerator inputSimpleIndices = inputSimpleIndicesBuilder.ToImmutable(); inputComplexIndices = inputComplexIndicesBuilder.ToImmutable(); - combinedInputTypes = ImmutableArray.Empty; - // Ensure that the input count is present - if (!isInputCountPresent) - { - diagnostics.Add(MissingD2DInputCountAttribute, structDeclarationSymbol, structDeclarationSymbol); + uint[] inputTypes = new uint[inputCount]; - return; - } + // The D2D_INPUT_SIMPLE define is optional, and if omitted, the corresponding input + // will automatically be of complex type. For the same reason, D2D_INPUT_COMPLEX is + // also essentially redundant. So we can do the following to compute the input types: + // - Create an array with as many inputs as the declared number of inputs + // - Fill it with 1 (ie. D2D1PixelShaderInputType.Complex), as that's the default + // - Traverse the declared simple inputs once, and update their corresponding values + inputTypes.AsSpan().Fill(1); - // Validate the input count - if (rawInputCount is not (>= 0 and <= 8)) - { - diagnostics.Add(InvalidD2DInputCount, structDeclarationSymbol, structDeclarationSymbol); - - return; - } - - // All simple indices must be in range foreach (int index in inputSimpleIndicesBuilder.WrittenSpan) { - if ((uint)index >= rawInputCount) + // Simply ignore any out of range indices here, to avoid throwing an exception. + // The analyzer will detect all of these cases and correctly issue a diagnostic. + if ((uint)index < inputCount) { - diagnostics.Add(OutOfRangeInputIndex, structDeclarationSymbol, structDeclarationSymbol); - - return; + inputTypes[index] = 0; } } - // All complex indices must be in range as well - foreach (int index in inputComplexIndicesBuilder.WrittenSpan) - { - if ((uint)index >= rawInputCount) - { - diagnostics.Add(OutOfRangeInputIndex, structDeclarationSymbol, structDeclarationSymbol); - - return; - } - } - - Span selectedSimpleInputIndices = stackalloc bool[8]; - Span selectedComplexInputIndices = stackalloc bool[8]; - - selectedSimpleInputIndices.Clear(); - selectedComplexInputIndices.Clear(); - - // All simple indices must be unique - foreach (int index in inputSimpleIndicesBuilder.WrittenSpan) - { - ref bool isInputIndexUsed = ref selectedSimpleInputIndices[index]; - - if (isInputIndexUsed) - { - diagnostics.Add(RepeatedD2DInputSimpleIndices, structDeclarationSymbol, structDeclarationSymbol); - - return; - } - - isInputIndexUsed = true; - } - - // All complex indices must be unique as well - foreach (int index in inputComplexIndicesBuilder.WrittenSpan) - { - ref bool isInputIndexUsed = ref selectedComplexInputIndices[index]; - - if (isInputIndexUsed) - { - diagnostics.Add(RepeatedD2DInputComplexIndices, structDeclarationSymbol, structDeclarationSymbol); - - return; - } - - isInputIndexUsed = true; - } - - // Simple and complex indices can't have indices in common - for (int i = 0; i < rawInputCount; i++) - { - if (selectedSimpleInputIndices[i] && selectedComplexInputIndices[i]) - { - diagnostics.Add(InvalidSimpleAndComplexIndicesCombination, structDeclarationSymbol, structDeclarationSymbol); - - return; - } - } - - // Build the combined input types list now that inputs have been validated - using ImmutableArrayBuilder combinedBuilder = new(); - - for (int i = 0; i < inputCount; i++) - { - // The D2D_INPUT_SIMPLE define is optional, and if omitted, the corresponding input - // will automatically be of complex type. So we just need to check whether the i-th - // input is present in the set of explicitly simple inputs. These values will map to - // values from D2D1PixelShaderInputType, which has Simple and Complex as members. - // So, simple inputs map to 0, and complex inputs map to 1. - combinedBuilder.Add(selectedSimpleInputIndices[i] ? 0u : 1u); - } - - combinedInputTypes = combinedBuilder.ToImmutable(); + // We own the array, so we can just reinterpret it here + combinedInputTypes = Unsafe.As>(ref inputTypes); } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs index 85c6317f..0a42c86a 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs @@ -97,7 +97,6 @@ public sealed partial class D2DPixelShaderDescriptorGenerator : IIncrementalGene // Get the input info for InputTypes InputTypes.GetInfo( - diagnostics, typeSymbol, out int inputCount, out ImmutableArray inputSimpleIndices, From 20b92d8810bff63e6fbe1d30db16b52375cb3b12 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 2 Jan 2024 19:50:36 +0100 Subject: [PATCH 3/5] Reorder steps in D2DPixelShaderDescriptorGenerator --- .../D2DPixelShaderDescriptorGenerator.cs | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs index 0a42c86a..62251b17 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs @@ -84,8 +84,6 @@ public sealed partial class D2DPixelShaderDescriptorGenerator : IIncrementalGene token.ThrowIfCancellationRequested(); - using ImmutableArrayBuilder diagnostics = new(); - // Constant buffer info ConstantBuffer.GetInfo( context.SemanticModel.Compilation, @@ -112,18 +110,6 @@ public sealed partial class D2DPixelShaderDescriptorGenerator : IIncrementalGene token.ThrowIfCancellationRequested(); - // Get HLSL source for HlslSource - string hlslSource = HlslSource.GetHlslSource( - diagnostics, - context.SemanticModel.Compilation, - typeSymbol, - inputCount, - inputSimpleIndices, - inputComplexIndices, - token); - - token.ThrowIfCancellationRequested(); - // Get the info for the output buffer properties OutputBuffer.GetInfo(typeSymbol, out D2D1BufferPrecision bufferPrecision, out D2D1ChannelDepth channelDepth); @@ -150,6 +136,20 @@ public sealed partial class D2DPixelShaderDescriptorGenerator : IIncrementalGene token.ThrowIfCancellationRequested(); + using ImmutableArrayBuilder diagnostics = new(); + + // Get HLSL source for HlslSource + string hlslSource = HlslSource.GetHlslSource( + diagnostics, + context.SemanticModel.Compilation, + typeSymbol, + inputCount, + inputSimpleIndices, + inputComplexIndices, + token); + + token.ThrowIfCancellationRequested(); + // As the last steps in the pipeline, try to compile the shader if needed. // This is done last so that it can be skipped if any errors happened before. HlslBytecodeInfoKey hlslInfoKey = new( From eb34febdda1df85098c4a5b1e3c7970801e94bd5 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 2 Jan 2024 20:07:33 +0100 Subject: [PATCH 4/5] Add InvalidShaderTypeInputsAnalyzer tests --- .../Test_Analyzers.cs | 225 ++++++++++++++++++ .../Test_D2DPixelShaderDescriptorGenerator.cs | 1 + 2 files changed, 226 insertions(+) diff --git a/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_Analyzers.cs b/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_Analyzers.cs index fe3bb3f2..548bf50f 100644 --- a/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_Analyzers.cs +++ b/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_Analyzers.cs @@ -893,4 +893,229 @@ public class Test_Analyzers await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); } + + [TestMethod] + public async Task MissingD2DInputCountAttribute_Warns() + { + const string source = """ + using ComputeSharp.D2D1; + using float4 = ComputeSharp.Float4; + + internal readonly partial struct {|CMPSD2D0058:MyType|} : ID2D1PixelShader + { + public float4 Execute() + { + return 0; + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + + [TestMethod] + [DataRow(-1)] + [DataRow(9)] + [DataRow(int.MaxValue)] + public async Task InvalidD2DInputCount_Warns(int inputCount) + { + string source = $$""" + using ComputeSharp.D2D1; + using float4 = ComputeSharp.Float4; + + [D2DInputCount({{inputCount}})] + internal readonly partial struct {|CMPSD2D0035:MyType|} : ID2D1PixelShader + { + public float4 Execute() + { + return 0; + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + + [TestMethod] + [DataRow("Simple")] + [DataRow("Complex")] + public async Task OutOfRangeInputIndex_NoInputs_Warns(string inputType) + { + string source = $$""" + using ComputeSharp.D2D1; + using float4 = ComputeSharp.Float4; + + [D2DInputCount(0)] + [D2DInput{{inputType}}(0)] + internal readonly partial struct {|CMPSD2D0039:MyType|} : ID2D1PixelShader + { + public float4 Execute() + { + return 0; + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + + [TestMethod] + [DataRow(-1)] + [DataRow(6)] + [DataRow(int.MaxValue)] + public async Task OutOfRangeInputIndex_OutOfRange_Warns(int inputIndex) + { + string source = $$""" + using ComputeSharp.D2D1; + using float4 = ComputeSharp.Float4; + + [D2DInputCount(6)] + [D2DInputSimple({{inputIndex}})] + internal readonly partial struct {|CMPSD2D0039:MyType|} : ID2D1PixelShader + { + public float4 Execute() + { + return 0; + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + + [TestMethod] + [DataRow(-1)] + [DataRow(6)] + [DataRow(int.MaxValue)] + public async Task OutOfRangeInputIndex_OutOfRange_BothInputTypes_WarnsOnce(int inputIndex) + { + const string source = """ + using ComputeSharp.D2D1; + using float4 = ComputeSharp.Float4; + + [D2DInputCount(6)] + [D2DInputSimple(0)] + [D2DInputSimple(1)] + [D2DInputSimple(6)] + [D2DInputSimple(8)] + [D2DInputComplex(-2)] + [D2DInputComplex(4)] + [D2DInputComplex(9)] + internal readonly partial struct {|CMPSD2D0039:MyType|} : ID2D1PixelShader + { + public float4 Execute() + { + return 0; + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + + [TestMethod] + public async Task RepeatedD2DInputSimpleIndices_Warns() + { + const string source = """ + using ComputeSharp.D2D1; + using float4 = ComputeSharp.Float4; + + [D2DInputCount(4)] + [D2DInputSimple(0)] + [D2DInputSimple(1)] + [D2DInputSimple(1)] + [D2DInputSimple(3)] + internal readonly partial struct {|CMPSD2D0036:MyType|} : ID2D1PixelShader + { + public float4 Execute() + { + return 0; + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + + [TestMethod] + public async Task RepeatedD2DInputComplexIndices_Warns() + { + const string source = """ + using ComputeSharp.D2D1; + using float4 = ComputeSharp.Float4; + + [D2DInputCount(4)] + [D2DInputComplex(0)] + [D2DInputComplex(1)] + [D2DInputComplex(1)] + [D2DInputComplex(3)] + internal readonly partial struct {|CMPSD2D0037:MyType|} : ID2D1PixelShader + { + public float4 Execute() + { + return 0; + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + + [TestMethod] + public async Task InvalidSimpleAndComplexIndicesCombination_Warns() + { + const string source = """ + using ComputeSharp.D2D1; + using float4 = ComputeSharp.Float4; + + [D2DInputCount(6)] + [D2DInputSimple(0)] + [D2DInputSimple(2)] + [D2DInputSimple(3)] + [D2DInputComplex(1)] + [D2DInputComplex(2)] + [D2DInputComplex(5)] + internal readonly partial struct {|CMPSD2D0038:MyType|} : ID2D1PixelShader + { + public float4 Execute() + { + return 0; + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + + [TestMethod] + public async Task InvalidInputTypes_MultipleErrors_WarnsOncePerDiagnosticId() + { + const string source = """ + using ComputeSharp.D2D1; + using float4 = ComputeSharp.Float4; + + [D2DInputCount(17)] + [D2DInputSimple(0)] + [D2DInputSimple(1)] + [D2DInputSimple(3)] + [D2DInputSimple(3)] + [D2DInputSimple(-1)] + [D2DInputSimple(32)] + [D2DInputComplex(4)] + [D2DInputComplex(5)] + [D2DInputComplex(5)] + [D2DInputComplex(-100)] + [D2DInputComplex(99)] + [D2DInputComplex(1)] + internal readonly partial struct {|CMPSD2D0035:{|CMPSD2D0039:{|CMPSD2D0036:{|CMPSD2D0037:{|CMPSD2D0038:MyType|}|}|}|}|} : ID2D1PixelShader + { + public float4 Execute() + { + return 0; + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } } \ No newline at end of file diff --git a/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator.cs b/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator.cs index e2da374e..43ef4515 100644 --- a/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator.cs +++ b/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator.cs @@ -1777,6 +1777,7 @@ public class Test_D2DPixelShaderDescriptorGenerator await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); From bebc74941ec043222d7d068bfe8e10bf242dd660 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 4 Jan 2024 15:21:55 +0100 Subject: [PATCH 5/5] Detect invalid input combinations in more cases --- .../Analyzers/InvalidShaderTypeInputsAnalyzer.cs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidShaderTypeInputsAnalyzer.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidShaderTypeInputsAnalyzer.cs index 61c623fd..95192608 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidShaderTypeInputsAnalyzer.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidShaderTypeInputsAnalyzer.cs @@ -134,6 +134,9 @@ public sealed class InvalidShaderTypeInputsAnalyzer : DiagnosticAnalyzer selectedSimpleInputIndices.Clear(); selectedComplexInputIndices.Clear(); + bool hasReportedRepeatedD2DinputSimpleIndex = false; + bool hasReportedRepeatedD2DinputComplexIndex = false; + // All simple indices must be unique foreach (int index in inputSimpleIndices.WrittenSpan) { @@ -146,14 +149,18 @@ public sealed class InvalidShaderTypeInputsAnalyzer : DiagnosticAnalyzer ref bool isInputIndexUsed = ref selectedSimpleInputIndices[index]; - if (isInputIndexUsed) + // If we detect a repeated index, we emit the diagnostic (only at most once), but + // then we also continue processing all remaining items. This is done to make sure + // that all used indices are correctly marked, so that the detection of invalid + // combinations at the end of the analyzer doesn't risk having false negatives. + if (isInputIndexUsed && !hasReportedRepeatedD2DinputSimpleIndex) { context.ReportDiagnostic(Diagnostic.Create( RepeatedD2DInputSimpleIndices, typeSymbol.Locations.First(), typeSymbol)); - break; + hasReportedRepeatedD2DinputSimpleIndex = true; } isInputIndexUsed = true; @@ -169,14 +176,14 @@ public sealed class InvalidShaderTypeInputsAnalyzer : DiagnosticAnalyzer ref bool isInputIndexUsed = ref selectedComplexInputIndices[index]; - if (isInputIndexUsed) + if (isInputIndexUsed && !hasReportedRepeatedD2DinputComplexIndex) { context.ReportDiagnostic(Diagnostic.Create( RepeatedD2DInputComplexIndices, typeSymbol.Locations.First(), typeSymbol)); - break; + hasReportedRepeatedD2DinputComplexIndex = true; } isInputIndexUsed = true;