Add InvalidGroupSharedFieldDeclarationAnalyzer

Also move the diagnostics there from the source generator
このコミットが含まれているのは:
Sergio Pedri committed 2023-11-24 11:51:17 +01:00
1 親 73f30af5eb
コミット a6c4b05e43
7ファイル変更
+156 -102

検索条件に一致するファイルはありません

+5 -30
ファイルの表示
@@ -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<IFieldSymbol>())
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);
@@ -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;
@@ -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;
/// <summary>
/// A diagnostic analyzer that generates an error whenever the [GroupShared] attribute is used on an invalid target field.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class InvalidGroupSharedFieldDeclarationAnalyzer : DiagnosticAnalyzer
{
/// <inheritdoc/>
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(InvalidGroupSharedFieldDeclaration);
/// <inheritdoc/>
public override void Initialize(AnalysisContext context)
{
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
context.EnableConcurrentExecution();
context.RegisterCompilationStartAction(static context =>
{
// Get the IComputeShader, IComputeShader<TPixel>, ReadWriteBuffer<T> 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<T> 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);
});
}
}
+4 -4
ファイルの表示
@@ -61,17 +61,17 @@ partial class DiagnosticDescriptors
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid group shared field declaration.
/// <para>
/// Format: <c>"The compute shader of type {0} contains a group shared field "{1}" that is not static"</c>.
/// Format: <c>"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])"</c>.
/// </para>
/// </summary>
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");
/// <summary>
-67
ファイルの表示
@@ -58,73 +58,6 @@ public class DiagnosticsTests
VerifyGeneratedDiagnostics<ComputeShaderDescriptorGenerator>(source, "CMPS0001", "CMPS0047");
}
[TestMethod]
public void InvalidGroupSharedFieldType()
{
const string source = """
using ComputeSharp;
namespace MyFancyApp.Sample;
[GeneratedComputeShaderDescriptor]
public partial struct MyShader : IComputeShader
{
public ReadWriteBuffer<float> buffer;
[GroupShared]
public static string text;
public void Execute() { }
}
""";
VerifyGeneratedDiagnostics<ComputeShaderDescriptorGenerator>(source, "CMPS0002", "CMPS0047");
}
[TestMethod]
public void InvalidGroupSharedFieldElementType()
{
const string source = """
using ComputeSharp;
namespace MyFancyApp.Sample;
[GeneratedComputeShaderDescriptor]
public partial struct MyShader : IComputeShader
{
public ReadWriteBuffer<float> buffer;
[GroupShared]
public static string[] text;
public void Execute() { }
}
""";
VerifyGeneratedDiagnostics<ComputeShaderDescriptorGenerator>(source, "CMPS0003", "CMPS0047");
}
[TestMethod]
public void InvalidGroupSharedFieldDeclaration()
{
const string source = """
using ComputeSharp;
namespace MyFancyApp.Sample;
[GeneratedComputeShaderDescriptor]
public partial struct MyShader : IComputeShader
{
[GroupShared]
public ReadWriteBuffer<float> buffer;
public void Execute() { }
}
""";
VerifyGeneratedDiagnostics<ComputeShaderDescriptorGenerator>(source, "CMPS0004", "CMPS0047");
}
[TestMethod]
public void MissingShaderResources()
{
+84
ファイルの表示
@@ -169,4 +169,88 @@ public class Test_Analyzers
await CSharpAnalyzerWithLanguageVersionTest<InvalidGloballyCoherentFieldDeclarationAnalyzer>.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<InvalidGroupSharedFieldDeclarationAnalyzer>.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<int> numbers;
public void Execute()
{
}
}
""";
await CSharpAnalyzerWithLanguageVersionTest<InvalidGroupSharedFieldDeclarationAnalyzer>.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<InvalidGroupSharedFieldDeclarationAnalyzer>.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<InvalidGroupSharedFieldDeclarationAnalyzer>.VerifyAnalyzerAsync(source);
}
}
+1
ファイルの表示
@@ -896,6 +896,7 @@ public class Test_D2DPixelShaderSourceGenerator
await CSharpAnalyzerWithLanguageVersionTest<InvalidComputeContextCopyAnalyzer>.VerifyAnalyzerAsync(source);
await CSharpAnalyzerWithLanguageVersionTest<InvalidGeneratedComputeShaderDescriptorAttributeTargetAnalyzer>.VerifyAnalyzerAsync(source);
await CSharpAnalyzerWithLanguageVersionTest<InvalidGloballyCoherentFieldDeclarationAnalyzer>.VerifyAnalyzerAsync(source);
await CSharpAnalyzerWithLanguageVersionTest<InvalidGroupSharedFieldDeclarationAnalyzer>.VerifyAnalyzerAsync(source);
await CSharpAnalyzerWithLanguageVersionTest<MissingAllowUnsafeBlocksCompilationOptionAnalyzer>.VerifyAnalyzerAsync(source);
await CSharpAnalyzerWithLanguageVersionTest<MissingComputeShaderDescriptorOnComputeShaderAnalyzer>.VerifyAnalyzerAsync(source);
await CSharpAnalyzerWithLanguageVersionTest<NotAccessibleFieldTypeInGeneratedShaderDescriptorAttributeTargetAnalyzer>.VerifyAnalyzerAsync(source);