From aec5615a5381d1f90b32bdbcb3c88a9a2ed70324 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 1 Jan 2024 23:33:08 +0100 Subject: [PATCH 1/3] Add InvalidD2DInputDescriptionAttributeUseAnalyzer --- ...D2DInputDescriptionAttributeUseAnalyzer.cs | 124 ++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DInputDescriptionAttributeUseAnalyzer.cs diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DInputDescriptionAttributeUseAnalyzer.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DInputDescriptionAttributeUseAnalyzer.cs new file mode 100644 index 00000000..23d7d45c --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2DInputDescriptionAttributeUseAnalyzer.cs @@ -0,0 +1,124 @@ +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 for all invalid uses of the [D2DInputDescription] attribute. +/// +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public sealed class InvalidD2DInputDescriptionAttributeUseAnalyzer : DiagnosticAnalyzer +{ + /// + public override ImmutableArray SupportedDiagnostics { get; } = ImmutableArray.Create( + OutOfRangeInputDescriptionIndex, + RepeatedD2DInputDescriptionIndices); + + /// + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); + context.EnableConcurrentExecution(); + + context.RegisterCompilationStartAction(static context => + { + // Get the [D2DInputDescription], [D2DInputCount] and ID2D1PixelShader symbols + if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DInputDescriptionAttribute") is not { } d2DInputDescriptionAttributeSymbol || + context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DInputCountAttribute") is not { } d2DInputCountAttributeSymbol || + 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; + } + + // Immediately bail if [D2DInputCount] is not present. If that's the case, there's no way to properly + // validate the indices of the input descriptions anyway. Another analyzer will catch these cases. + if (!typeSymbol.TryGetAttributeWithType(d2DInputCountAttributeSymbol, out AttributeData? inputCountData)) + { + return; + } + + int inputCount = (int)inputCountData.ConstructorArguments[0].Value!; + + // Just like in the resource texture analyzer, also bail if the input count is invalid (for the same reason) + if (inputCount is not (>= 0 and <= 8)) + { + return; + } + + using ImmutableArrayBuilder inputDescriptionIndices = new(); + + // Collect all indices of available input descriptions (there's no validation for the other properties) + foreach (AttributeData attributeData in typeSymbol.GetAttributes()) + { + if (SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, d2DInputDescriptionAttributeSymbol)) + { + inputDescriptionIndices.Add((int)attributeData.ConstructorArguments[0].Value!); + } + } + + // All simple indices must be in range + foreach (int index in inputDescriptionIndices.WrittenSpan) + { + if (index >= inputCount) + { + context.ReportDiagnostic(Diagnostic.Create( + OutOfRangeInputDescriptionIndex, + typeSymbol.Locations.First(), + typeSymbol)); + + break; + } + } + + Span selectedInputDescriptionIndices = stackalloc bool[8]; + + selectedInputDescriptionIndices.Clear(); + + // All input description indices must be unique + foreach (int index in inputDescriptionIndices.WrittenSpan) + { + // Skip this path for invalid indices (just like with resource textures again). + // This would just throw when accessing the span anyway (also it's unlikely). + if (index >= 8) + { + continue; + } + + ref bool isInputDescriptionIndexUsed = ref selectedInputDescriptionIndices[index]; + + if (isInputDescriptionIndexUsed) + { + context.ReportDiagnostic(Diagnostic.Create( + RepeatedD2DInputDescriptionIndices, + typeSymbol.Locations.First(), + typeSymbol)); + + break; + } + + isInputDescriptionIndexUsed = true; + } + }, SymbolKind.NamedType); + }); + } +} \ No newline at end of file From 3ae80f1698de90b0aaa49638e0800996509a709c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 1 Jan 2024 23:34:17 +0100 Subject: [PATCH 2/3] Remove diagnostics from D2D input descriptions generator --- ...erDescriptorGenerator.InputDescriptions.cs | 74 ++----------------- .../D2DPixelShaderDescriptorGenerator.cs | 1 - 2 files changed, 7 insertions(+), 68 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.InputDescriptions.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.InputDescriptions.cs index c03b4bf2..462591b2 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.InputDescriptions.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.InputDescriptions.cs @@ -1,11 +1,8 @@ -using System; using System.Collections.Immutable; using ComputeSharp.D2D1.SourceGenerators.Models; 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; @@ -20,85 +17,28 @@ partial class D2DPixelShaderDescriptorGenerator /// /// Extracts the input descriptions for the current shader. /// - /// The collection of produced instances. /// The input instance to process. /// The produced input descriptions for the shader. public static void GetInfo( - ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol, out ImmutableArray inputDescriptions) { - int inputCount = 0; - - using ImmutableArrayBuilder inputDescriptionsBuilder = new(); + using ImmutableArrayBuilder builder = new(); foreach (AttributeData attributeData in structDeclarationSymbol.GetAttributes()) { - using ImmutableArrayBuilder builder = new(); - - attributeData.AttributeClass?.AppendFullyQualifiedMetadataName(in builder); - - switch (builder.WrittenSpan) + if (attributeData.AttributeClass?.HasFullyQualifiedMetadataName("ComputeSharp.D2D1.D2DInputDescriptionAttribute") == true) { - case "ComputeSharp.D2D1.D2DInputCountAttribute": - inputCount = (int)attributeData.ConstructorArguments[0].Value!; - break; - case "ComputeSharp.D2D1.D2DInputDescriptionAttribute": - if (attributeData.ConstructorArguments.Length == 2) - { - int index = (int)attributeData.ConstructorArguments[0].Value!; - D2D1Filter filter = (D2D1Filter)attributeData.ConstructorArguments[1].Value!; + int index = (int)attributeData.ConstructorArguments[0].Value!; + D2D1Filter filter = (D2D1Filter)attributeData.ConstructorArguments[1].Value!; - _ = attributeData.TryGetNamedArgument("LevelOfDetailCount", out int levelOfDetailCount); + _ = attributeData.TryGetNamedArgument("LevelOfDetailCount", out int levelOfDetailCount); - inputDescriptionsBuilder.Add(new InputDescription(index, filter, levelOfDetailCount)); - } - - break; - default: - break; + builder.Add(new InputDescription(index, filter, levelOfDetailCount)); } } - inputDescriptions = ImmutableArray.Empty; - - // Validate the input count (ignore if invalid, this will be validated by GetInputType() generator) - if (inputCount is not (>= 0 and <= 8)) - { - return; - } - - // All simple indices must be in range - foreach (InputDescription inputDescription in inputDescriptionsBuilder.WrittenSpan) - { - if (inputDescription.Index >= inputCount) - { - diagnostics.Add(OutOfRangeInputDescriptionIndex, structDeclarationSymbol, structDeclarationSymbol); - - return; - } - } - - Span selectedInputDescriptionIndices = stackalloc bool[8]; - - selectedInputDescriptionIndices.Clear(); - - // All input description indices must be unique - foreach (InputDescription inputDescription in inputDescriptionsBuilder.WrittenSpan) - { - ref bool isInputDescriptionIndexUsed = ref selectedInputDescriptionIndices[inputDescription.Index]; - - if (isInputDescriptionIndexUsed) - { - diagnostics.Add(RepeatedD2DInputDescriptionIndices, structDeclarationSymbol, structDeclarationSymbol); - - return; - } - - isInputDescriptionIndexUsed = true; - } - - inputDescriptions = inputDescriptionsBuilder.ToImmutable(); + inputDescriptions = builder.ToImmutable(); } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs index 290a7733..85c6317f 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs @@ -132,7 +132,6 @@ public sealed partial class D2DPixelShaderDescriptorGenerator : IIncrementalGene // Get the info for InputDescriptions InputDescriptions.GetInfo( - diagnostics, typeSymbol, out ImmutableArray inputDescriptions); From 11deae1d7b18bafee12a62458ea6132277220aee Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 1 Jan 2024 23:42:35 +0100 Subject: [PATCH 3/3] Add InvalidD2DInputDescriptionAttributeUseAnalyzer tests --- .../Test_Analyzers.cs | 160 +++++++++++++++++- .../Test_D2DPixelShaderDescriptorGenerator.cs | 1 + 2 files changed, 160 insertions(+), 1 deletion(-) diff --git a/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_Analyzers.cs b/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_Analyzers.cs index 600e642c..fe3bb3f2 100644 --- a/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_Analyzers.cs +++ b/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_Analyzers.cs @@ -9,7 +9,7 @@ namespace ComputeSharp.D2D1.Tests.SourceGenerators; public class Test_Analyzers { [TestMethod] - public async Task MissingComputeShaderDescriptor_ComputeShader() + public async Task MissingD2DPixelShaderDescriptor_ComputeShader() { const string source = """ using ComputeSharp; @@ -735,4 +735,162 @@ public class Test_Analyzers await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); } + + [TestMethod] + public async Task OutOfRangeInputDescriptionIndex_Warns() + { + const string source = """ + using ComputeSharp.D2D1; + using float4 = ComputeSharp.Float4; + + [D2DInputCount(0)] + [D2DInputDescription(0, D2D1Filter.MinMagMipPoint)] + internal readonly partial struct {|CMPSD2D0042:MyType|} : ID2D1PixelShader + { + public float4 Execute() + { + return 0; + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + + [TestMethod] + public async Task OutOfRangeInputDescriptionIndex_WithMissingD2DInputCount_DoesNotWarn() + { + const string source = """ + using ComputeSharp.D2D1; + using float4 = ComputeSharp.Float4; + + [D2DInputDescription(0, D2D1Filter.MinMagMipPoint)] + internal readonly partial struct MyType : ID2D1PixelShader + { + public float4 Execute() + { + return 0; + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + + [TestMethod] + public async Task OutOfRangeInputDescriptionIndex_WithInvalidD2DInputCount_DoesNotWarn() + { + const string source = """ + using ComputeSharp.D2D1; + using float4 = ComputeSharp.Float4; + + [D2DInputCount(37)] + [D2DInputDescription(0, D2D1Filter.MinMagMipPoint)] + internal readonly partial struct MyType : ID2D1PixelShader + { + public float4 Execute() + { + return 0; + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + + [TestMethod] + public async Task RepeatedD2DInputDescriptionIndices_Warns() + { + const string source = """ + using ComputeSharp.D2D1; + using float4 = ComputeSharp.Float4; + + [D2DInputCount(4)] + [D2DInputDescription(0, D2D1Filter.MinMagMipPoint)] + [D2DInputDescription(2, D2D1Filter.MinMagMipPoint)] + [D2DInputDescription(0, D2D1Filter.MinMagMipPoint)] + internal readonly partial struct {|CMPSD2D0043:MyType|} : ID2D1PixelShader + { + public float4 Execute() + { + return 0; + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + + [TestMethod] + public async Task RepeatedD2DInputDescriptionIndices_WithMissingD2DInputCount_DoesNotWarn() + { + const string source = """ + using ComputeSharp.D2D1; + using float4 = ComputeSharp.Float4; + + [D2DInputDescription(0, D2D1Filter.MinMagMipPoint)] + [D2DInputDescription(2, D2D1Filter.MinMagMipPoint)] + [D2DInputDescription(0, D2D1Filter.MinMagMipPoint)] + internal readonly partial struct MyType : ID2D1PixelShader + { + public float4 Execute() + { + return 0; + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + + [TestMethod] + public async Task RepeatedD2DInputDescriptionIndices_WithInvalidD2DInputCount_DoesNotWarn() + { + const string source = """ + using ComputeSharp.D2D1; + using float4 = ComputeSharp.Float4; + + [D2DInputCount(37)] + [D2DInputDescription(0, D2D1Filter.MinMagMipPoint)] + [D2DInputDescription(2, D2D1Filter.MinMagMipPoint)] + [D2DInputDescription(0, D2D1Filter.MinMagMipPoint)] + internal readonly partial struct MyType : ID2D1PixelShader + { + public float4 Execute() + { + return 0; + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + + [TestMethod] + public async Task InvalidInputDescriptions_MultipleErrors_WarnsOncePerDiagnosticId() + { + const string source = """ + using ComputeSharp.D2D1; + using float4 = ComputeSharp.Float4; + + [D2DInputCount(2)] + [D2DInputDescription(0, D2D1Filter.MinMagMipPoint)] + [D2DInputDescription(2, D2D1Filter.MinMagMipPoint)] + [D2DInputDescription(0, D2D1Filter.MinMagMipPoint)] + [D2DInputDescription(1, D2D1Filter.MinMagMipPoint)] + [D2DInputDescription(1, D2D1Filter.MinMagMipPoint)] + [D2DInputDescription(33, D2D1Filter.MinMagMipPoint)] + [D2DInputDescription(34, D2D1Filter.MinMagMipPoint)] + [D2DInputDescription(-4, D2D1Filter.MinMagMipPoint)] + internal readonly partial struct {|CMPSD2D0042:{|CMPSD2D0043: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 50219cfa..e2da374e 100644 --- a/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator.cs +++ b/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_D2DPixelShaderDescriptorGenerator.cs @@ -1770,6 +1770,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);