diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs index febbcfbe..e02941d4 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs @@ -137,14 +137,6 @@ partial class ComputeShaderDescriptorGenerator continue; } - AttributeData? groupSharedAttribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass?.ToDisplayString() == "ComputeSharp.GroupSharedAttribute"); - - // Group shared fields must be static - if (groupSharedAttribute is not null) - { - diagnostics.Add(InvalidGroupSharedFieldDeclaration, fieldSymbol, structDeclarationSymbol, fieldName); - } - // Captured fields must be named type symbols if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol) { @@ -239,9 +231,7 @@ partial class ComputeShaderDescriptorGenerator continue; } - AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass?.ToDisplayString() == "ComputeSharp.GroupSharedAttribute"); - - if (attribute is not null) + if (fieldSymbol.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.GroupSharedAttribute", out _)) { continue; } @@ -292,34 +282,19 @@ partial class ComputeShaderDescriptorGenerator { using ImmutableArrayBuilder<(string, string, int?)> builder = new(); - foreach (IFieldSymbol fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) + foreach (ISymbol memberSymbol in structDeclarationSymbol.GetMembers()) { - if (!fieldSymbol.IsStatic) + // We're only looking for static fields of a valid type for group shared buffers + if (memberSymbol is not IFieldSymbol { IsStatic: true, Type: IArrayTypeSymbol { ElementType.IsUnmanagedType: true } typeSymbol } fieldSymbol) { continue; } - AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass?.ToDisplayString() == "ComputeSharp.GroupSharedAttribute"); - - if (attribute is null) + if (!fieldSymbol.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.GroupSharedAttribute", out AttributeData? attribute)) { continue; } - if (fieldSymbol.Type is not IArrayTypeSymbol typeSymbol) - { - diagnostics.Add(InvalidGroupSharedFieldType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); - - continue; - } - - if (!typeSymbol.ElementType.IsUnmanagedType) - { - diagnostics.Add(InvalidGroupSharedFieldElementType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); - - continue; - } - int? bufferSize = (int?)attribute.ConstructorArguments.FirstOrDefault().Value; string typeName = HlslKnownTypes.GetMappedElementName(typeSymbol); diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/Analyzers/InvalidGloballyCoherentFieldDeclarationAnalyzer.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/Analyzers/InvalidGloballyCoherentFieldDeclarationAnalyzer.cs index f3b00ae8..aa084b5e 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/Analyzers/InvalidGloballyCoherentFieldDeclarationAnalyzer.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/Analyzers/InvalidGloballyCoherentFieldDeclarationAnalyzer.cs @@ -39,7 +39,7 @@ public sealed class InvalidGloballyCoherentFieldDeclarationAnalyzer : Diagnostic return; } - // If the current type does not have [GloballyCoherent], there is nothing to do + // If the current type does not have the [GloballyCoherent] attribute, there is nothing to do if (!fieldSymbol.TryGetAttributeWithType(globallyCoherentAttributeSymbol, out AttributeData? attribute)) { return; diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/Analyzers/InvalidGroupSharedFieldDeclarationAnalyzer.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/Analyzers/InvalidGroupSharedFieldDeclarationAnalyzer.cs new file mode 100644 index 00000000..571ea8d3 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/Analyzers/InvalidGroupSharedFieldDeclarationAnalyzer.cs @@ -0,0 +1,61 @@ +using System.Collections.Immutable; +using ComputeSharp.SourceGeneration.Extensions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; + +namespace ComputeSharp.SourceGenerators; + +/// +/// A diagnostic analyzer that generates an error whenever the [GroupShared] attribute is used on an invalid target field. +/// +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public sealed class InvalidGroupSharedFieldDeclarationAnalyzer : DiagnosticAnalyzer +{ + /// + public override ImmutableArray SupportedDiagnostics { get; } = ImmutableArray.Create(InvalidGroupSharedFieldDeclaration); + + /// + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); + context.EnableConcurrentExecution(); + + context.RegisterCompilationStartAction(static context => + { + // Get the IComputeShader, IComputeShader, ReadWriteBuffer and [GloballyCoherent] symbols + if (context.Compilation.GetTypeByMetadataName("ComputeSharp.IComputeShader") is not { } computeShaderSymbol || + context.Compilation.GetTypeByMetadataName("ComputeSharp.IComputeShader`1") is not { } pixelShaderSymbol || + context.Compilation.GetTypeByMetadataName("ComputeSharp.ReadWriteBuffer`1") is not { } readWriteBufferSymbol || + context.Compilation.GetTypeByMetadataName("ComputeSharp.GroupSharedAttribute") is not { } groupSharedAttribute) + { + return; + } + + context.RegisterSymbolAction(context => + { + if (context.Symbol is not IFieldSymbol { ContainingType: { } typeSymbol } fieldSymbol) + { + return; + } + + // If the current type does not have the [GroupShared] attribute, there is nothing to do + if (!fieldSymbol.TryGetAttributeWithType(groupSharedAttribute, out AttributeData? attribute)) + { + return; + } + + // Emit a diagnostic if the field is not valid (either static, not of ReadWriteBuffer type, or not within a compute shader type) + if (!fieldSymbol.IsStatic || + fieldSymbol.Type is not IArrayTypeSymbol { ElementType.IsUnmanagedType: true } || + !MissingComputeShaderDescriptorOnComputeShaderAnalyzer.IsComputeShaderType(typeSymbol, computeShaderSymbol, pixelShaderSymbol)) + { + context.ReportDiagnostic(Diagnostic.Create( + InvalidGroupSharedFieldDeclaration, + attribute.GetLocation(), + fieldSymbol)); + } + }, SymbolKind.Field); + }); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index a879aabb..87340a59 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -61,17 +61,17 @@ partial class DiagnosticDescriptors /// /// Gets a for an invalid group shared field declaration. /// - /// Format: "The compute shader of type {0} contains a group shared field "{1}" that is not static". + /// Format: "The field "{0}" is annotated with [GroupShared], but is not a valid target for it (only static fields of array type in compute shader types, with an unmanaged element type can be annotated with [GroupShared])". /// /// public static readonly DiagnosticDescriptor InvalidGroupSharedFieldDeclaration = new( id: "CMPS0004", - title: "Invalid group shared field declaration", - messageFormat: """The compute shader of type {0} contains a group shared field "{1}" that is not static""", + title: "Invalid [GroupShared] field declaration", + messageFormat: """The field "{0}" is annotated with [GroupShared], but is not a valid target for it (only static fields of array type in compute shader types, with an unmanaged element type can be annotated with [GroupShared])""", category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, - description: "A group shared field must be static.", + description: "The [GroupShared] attribute is only valid on static fields of array type in compute shader types, with an unmanaged element type.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); /// diff --git a/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs b/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs index 0ec5579e..65b1e28a 100644 --- a/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs +++ b/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs @@ -58,73 +58,6 @@ public class DiagnosticsTests VerifyGeneratedDiagnostics(source, "CMPS0001", "CMPS0047"); } - [TestMethod] - public void InvalidGroupSharedFieldType() - { - const string source = """ - using ComputeSharp; - - namespace MyFancyApp.Sample; - - [GeneratedComputeShaderDescriptor] - public partial struct MyShader : IComputeShader - { - public ReadWriteBuffer buffer; - - [GroupShared] - public static string text; - - public void Execute() { } - } - """; - - VerifyGeneratedDiagnostics(source, "CMPS0002", "CMPS0047"); - } - - [TestMethod] - public void InvalidGroupSharedFieldElementType() - { - const string source = """ - using ComputeSharp; - - namespace MyFancyApp.Sample; - - [GeneratedComputeShaderDescriptor] - public partial struct MyShader : IComputeShader - { - public ReadWriteBuffer buffer; - - [GroupShared] - public static string[] text; - - public void Execute() { } - } - """; - - VerifyGeneratedDiagnostics(source, "CMPS0003", "CMPS0047"); - } - - [TestMethod] - public void InvalidGroupSharedFieldDeclaration() - { - const string source = """ - using ComputeSharp; - - namespace MyFancyApp.Sample; - - [GeneratedComputeShaderDescriptor] - public partial struct MyShader : IComputeShader - { - [GroupShared] - public ReadWriteBuffer buffer; - - public void Execute() { } - } - """; - - VerifyGeneratedDiagnostics(source, "CMPS0004", "CMPS0047"); - } - [TestMethod] public void MissingShaderResources() { diff --git a/tests/ComputeSharp.Tests.SourceGenerators/Test_Analyzers.cs b/tests/ComputeSharp.Tests.SourceGenerators/Test_Analyzers.cs index a489605f..c5c42200 100644 --- a/tests/ComputeSharp.Tests.SourceGenerators/Test_Analyzers.cs +++ b/tests/ComputeSharp.Tests.SourceGenerators/Test_Analyzers.cs @@ -169,4 +169,88 @@ public class Test_Analyzers await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); } + + [TestMethod] + public async Task GroupSharedAttribute_NotWithinShaderType() + { + const string source = """ + using ComputeSharp; + + namespace MyFancyApp.Sample; + + internal partial struct MyType + { + [{|CMPS0004:GroupShared|}] + public static int[] numbers; + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + + [TestMethod] + public async Task GroupSharedAttribute_IncorrectType() + { + const string source = """ + using ComputeSharp; + + namespace MyFancyApp.Sample; + + internal partial struct MyType : IComputeShader + { + [{|CMPS0004:GroupShared|}] + public static ReadWriteBuffer numbers; + + public void Execute() + { + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + + [TestMethod] + public async Task GroupSharedAttribute_InstanceField() + { + const string source = """ + using ComputeSharp; + + namespace MyFancyApp.Sample; + + internal partial struct MyType : IComputeShader + { + [{|CMPS0004:GroupShared|}] + public int[] numbers; + + public void Execute() + { + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + + [TestMethod] + public async Task GroupSharedAttribute_ValidField_DoesNotWarn() + { + const string source = """ + using ComputeSharp; + + namespace MyFancyApp.Sample; + + internal partial struct MyType : IComputeShader + { + [GroupShared] + public static int[] numbers; + + public void Execute() + { + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } } \ No newline at end of file diff --git a/tests/ComputeSharp.Tests.SourceGenerators/Test_D2DPixelShaderSourceGenerator.cs b/tests/ComputeSharp.Tests.SourceGenerators/Test_D2DPixelShaderSourceGenerator.cs index d62829e7..5e4d6743 100644 --- a/tests/ComputeSharp.Tests.SourceGenerators/Test_D2DPixelShaderSourceGenerator.cs +++ b/tests/ComputeSharp.Tests.SourceGenerators/Test_D2DPixelShaderSourceGenerator.cs @@ -896,6 +896,7 @@ public class Test_D2DPixelShaderSourceGenerator 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);