Merge pull request #633 from Sergio0694/dev/not-accessible-field-type-analyzer

Add analyzers for shader fields of types being less accessible than internal
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2023-10-19 14:57:27 +02:00
コミット 240cffcb16
15ファイル変更
+234 -6

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

+1
ファイルの表示
@@ -74,3 +74,4 @@ CMPSD2D0064 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github
CMPSD2D0065 | ComputeSharp.D2D1.Shaders | Warning | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPSD2D0066 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPSD2D0067 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPSD2D0068 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
@@ -25,16 +25,19 @@ partial class D2DPixelShaderDescriptorGenerator
/// Explores a given type hierarchy and generates statements to load fields.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
/// <param name="structDeclarationSymbol">The current shader type being explored.</param>
/// <param name="constantBufferSizeInBytes">The size of the shader constant buffer.</param>
/// <returns>The sequence of <see cref="FieldInfo"/> instances for all captured resources and values.</returns>
public static ImmutableArray<FieldInfo> GetInfo(
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
Compilation compilation,
ITypeSymbol structDeclarationSymbol,
out int constantBufferSizeInBytes)
{
// Helper method that uses boxes instead of ref-s (illegal in enumerators)
static IEnumerable<FieldInfo> GetCapturedFieldInfos(
Compilation compilation,
ITypeSymbol currentTypeSymbol,
ImmutableArray<string> fieldPath,
StrongBox<int> rawDataOffset)
@@ -47,6 +50,12 @@ partial class D2DPixelShaderDescriptorGenerator
where fieldSymbol is { Type: INamedTypeSymbol { IsStatic: false }, IsConst: false, IsStatic: false, IsFixedSizeBuffer: false, IsImplicitlyDeclared: false }
select fieldSymbol)
{
// Skip fields of not accessible types (the analyzer will handle this)
if (!fieldSymbol.Type.IsAccessibleFromCompilationAssembly(compilation))
{
continue;
}
string fieldName = fieldSymbol.Name;
string typeName = fieldSymbol.Type.GetFullyQualifiedMetadataName();
@@ -65,7 +74,7 @@ partial class D2DPixelShaderDescriptorGenerator
else if (fieldSymbol.Type.IsUnmanagedType)
{
// Custom struct type defined by the user
foreach (FieldInfo fieldInfo in GetCapturedFieldInfos(fieldSymbol.Type, fieldPath.Add(fieldName), rawDataOffset))
foreach (FieldInfo fieldInfo in GetCapturedFieldInfos(compilation, fieldSymbol.Type, fieldPath.Add(fieldName), rawDataOffset))
{
yield return fieldInfo;
}
@@ -78,6 +87,7 @@ partial class D2DPixelShaderDescriptorGenerator
// Traverse all shader fields and gather info, and update the tracking offsets
ImmutableArray<FieldInfo> fieldInfos = GetCapturedFieldInfos(
compilation,
structDeclarationSymbol,
ImmutableArray<string>.Empty,
rawDataOffsetAsBox).ToImmutableArray();
+1
ファイルの表示
@@ -85,6 +85,7 @@ public sealed partial class D2DPixelShaderDescriptorGenerator : IIncrementalGene
// LoadDispatchData() info
ImmutableArray<FieldInfo> fieldInfos = LoadConstantBuffer.GetInfo(
diagnostics,
context.SemanticModel.Compilation,
typeSymbol,
out int constantBufferSizeInBytes);
@@ -7,12 +7,12 @@ namespace ComputeSharp.D2D1.SourceGenerators;
/// <inheritdoc/>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class NotAccessibleGeneratedComputeShaderDescriptorAttributeTargetAnalyzer : NotAccessibleGeneratedShaderDescriptorAttributeTargetAnalyzerBase
public sealed class NotAccessibleD2DGeneratedPixelShaderDescriptorAttributeTargetAnalyzer : NotAccessibleGeneratedShaderDescriptorAttributeTargetAnalyzerBase
{
/// <summary>
/// Creates a new <see cref="NotAccessibleGeneratedComputeShaderDescriptorAttributeTargetAnalyzer"/> instance.
/// Creates a new <see cref="NotAccessibleD2DGeneratedPixelShaderDescriptorAttributeTargetAnalyzer"/> instance.
/// </summary>
public NotAccessibleGeneratedComputeShaderDescriptorAttributeTargetAnalyzer()
public NotAccessibleD2DGeneratedPixelShaderDescriptorAttributeTargetAnalyzer()
: base(NotAccessibleTargetTypeForD2DGeneratedPixelShaderDescriptorAttribute, "ComputeSharp.D2D1.D2DGeneratedPixelShaderDescriptorAttribute")
{
}
@@ -0,0 +1,19 @@
using ComputeSharp.SourceGeneration.Diagnostics;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
namespace ComputeSharp.D2D1.SourceGenerators;
/// <inheritdoc/>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class NotAccessibleFieldTypeInD2DGeneratedShaderDescriptorAttributeTargetAnalyzer : NotAccessibleFieldTypeInGeneratedShaderDescriptorAttributeTargetAnalyzerBase
{
/// <summary>
/// Creates a new <see cref="NotAccessibleFieldTypeInD2DGeneratedShaderDescriptorAttributeTargetAnalyzer"/> instance.
/// </summary>
public NotAccessibleFieldTypeInD2DGeneratedShaderDescriptorAttributeTargetAnalyzer()
: base(NotAccessibleFieldTypeInTargetTypeForD2DGeneratedPixelShaderDescriptorAttribute, "ComputeSharp.D2D1.D2DGeneratedPixelShaderDescriptorAttribute")
{
}
}
+16
ファイルの表示
@@ -1008,4 +1008,20 @@ partial class DiagnosticDescriptors
isEnabledByDefault: true,
description: "The [D2DGeneratedPixelShaderDescriptor] attribute requires target types to be accessible from their containing assembly.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for when a field in a type using the <c>[D2DGeneratedPixelShaderDescriptor]</c> attribute has a type that is not accessible from its containing assembly.
/// <para>
/// Format: <c>"The [D2DGeneratedPixelShaderDescriptor] attribute requires the type of all fields of target types to be accessible from their containing assembly (type {0} has a field "{1}" of type {2} that has less effective accessibility than internal)"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor NotAccessibleFieldTypeInTargetTypeForD2DGeneratedPixelShaderDescriptorAttribute = new DiagnosticDescriptor(
id: "CMPSD2D0068",
title: "Invalid [D2DGeneratedPixelShaderDescriptor] attribute target",
messageFormat: """The [D2DGeneratedPixelShaderDescriptor] attribute requires the type of all fields of target types to be accessible from their containing assembly (type {0} has a field "{1}" of type {2} that has less effective accessibility than internal)""",
category: "ComputeSharp.D2D1.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The [D2DGeneratedPixelShaderDescriptor] attribute requires the type of all fields of target types to be accessible from their containing assembly.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
}
@@ -9,6 +9,7 @@
<Import_RootNamespace>ComputeSharp.SourceGeneration.Hlsl</Import_RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\Analyzers\NotAccessibleFieldTypeInGeneratedShaderDescriptorAttributeTargetAnalyzerBase.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\Analyzers\NotAccessibleGeneratedShaderDescriptorAttributeTargetAnalyzerBase.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\Analyzers\MissingAllowUnsafeBlocksCompilationOptionAnalyzerBase.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Diagnostics\DiagnosticDescriptors.cs" />
@@ -0,0 +1,91 @@
using System.Collections.Immutable;
using ComputeSharp.SourceGeneration.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
namespace ComputeSharp.SourceGeneration.Diagnostics;
/// <summary>
/// A diagnostic analyzer that generates an error if a field in a target shader type is of a type that is not accessible from its containing assembly.
/// </summary>
public abstract class NotAccessibleFieldTypeInGeneratedShaderDescriptorAttributeTargetAnalyzerBase : DiagnosticAnalyzer
{
/// <summary>
/// The <see cref="DiagnosticDescriptor"/> instance to use.
/// </summary>
private readonly DiagnosticDescriptor diagnosticDescriptor;
/// <summary>
/// The fully qualified type name of the target attribute.
/// </summary>
private readonly string generatedShaderDescriptorFullyQualifiedTypeName;
/// <summary>
/// Creates a new <see cref="NotAccessibleFieldTypeInGeneratedShaderDescriptorAttributeTargetAnalyzerBase"/> instance with the specified arguments.
/// </summary>
/// <param name="diagnosticDescriptor">The <see cref="DiagnosticDescriptor"/> instance to use.</param>
/// <param name="generatedShaderDescriptorFullyQualifiedTypeName">The fully qualified type name of the target attribute.</param>
private protected NotAccessibleFieldTypeInGeneratedShaderDescriptorAttributeTargetAnalyzerBase(
DiagnosticDescriptor diagnosticDescriptor,
string generatedShaderDescriptorFullyQualifiedTypeName)
{
this.diagnosticDescriptor = diagnosticDescriptor;
this.generatedShaderDescriptorFullyQualifiedTypeName = generatedShaderDescriptorFullyQualifiedTypeName;
SupportedDiagnostics = ImmutableArray.Create(diagnosticDescriptor);
}
/// <inheritdoc/>
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }
/// <inheritdoc/>
public sealed override void Initialize(AnalysisContext context)
{
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
context.EnableConcurrentExecution();
context.RegisterCompilationStartAction(context =>
{
// Get the symbol for the target attribute type
if (context.Compilation.GetTypeByMetadataName(this.generatedShaderDescriptorFullyQualifiedTypeName) is not { } generatedShaderDescriptorAttributeSymbol)
{
return;
}
context.RegisterSymbolAction(context =>
{
// Only struct types are possible targets
if (context.Symbol is not INamedTypeSymbol { TypeKind: TypeKind.Struct } typeSymbol)
{
return;
}
// If the target type is not using the attribute, there's nothing left to do
if (!typeSymbol.TryGetAttributeWithType(generatedShaderDescriptorAttributeSymbol, out AttributeData? attribute))
{
return;
}
foreach (ISymbol memberSymbol in typeSymbol.GetMembers())
{
// Only select allowed fields (ie. skip constants, static fields, etc.)
if (memberSymbol is not IFieldSymbol { Type: INamedTypeSymbol fieldTypeSymbol, IsConst: false, IsStatic: false, IsFixedSizeBuffer: false, IsImplicitlyDeclared: false })
{
continue;
}
// Emit a diagnostic if the field type is not accessible
if (!fieldTypeSymbol.IsAccessibleFromCompilationAssembly(context.Compilation))
{
context.ReportDiagnostic(Diagnostic.Create(
this.diagnosticDescriptor,
attribute.GetLocation(),
typeSymbol,
memberSymbol.Name,
fieldTypeSymbol));
}
}
}, SymbolKind.NamedType);
});
}
}
+11
ファイルの表示
@@ -34,6 +34,17 @@ internal static class ISymbolExtensions
return compilation.IsSymbolAccessibleWithin(symbol, assemblySymbol);
}
/// <summary>
/// Checks whether a given symbol is accessible from the assembly of a given compilation (including eg. through nested types).
/// </summary>
/// <param name="symbol">The input <see cref="ISymbol"/> instance.</param>
/// <param name="compilation">The <see cref="Compilation"/> instance currently in use.</param>
/// <returns>Whether <paramref name="symbol"/> is accessible from the assembly for <paramref name="compilation"/>.</returns>
public static bool IsAccessibleFromCompilationAssembly(this ISymbol symbol, Compilation compilation)
{
return compilation.IsSymbolAccessibleWithin(symbol, compilation.Assembly);
}
/// <summary>
/// Gets the fully qualified name for a given symbol.
/// </summary>
+1
ファイルの表示
@@ -61,3 +61,4 @@ CMPS0052 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Ser
CMPS0053 | ComputeSharp.Shaders | Warning | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0054 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0055 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0056 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
@@ -23,6 +23,7 @@ partial class ComputeShaderDescriptorGenerator
/// Explores a given type hierarchy and generates statements to load fields.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
/// <param name="structDeclarationSymbol">The current shader type being explored.</param>
/// <param name="isPixelShaderLike">Whether the compute shader is "pixel shader like", ie. outputting a pixel into a target texture.</param>
/// <param name="constantBufferSizeInBytes">The size of the shader constant buffer.</param>
@@ -31,6 +32,7 @@ partial class ComputeShaderDescriptorGenerator
/// <param name="resources">The sequence of <see cref="ResourceInfo"/> instances for all captured resources.</param>
public static void GetInfo(
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
Compilation compilation,
ITypeSymbol structDeclarationSymbol,
bool isPixelShaderLike,
out int constantBufferSizeInBytes,
@@ -39,6 +41,7 @@ partial class ComputeShaderDescriptorGenerator
out ImmutableArray<ResourceInfo> resources)
{
static void GetInfo(
Compilation compilation,
ITypeSymbol currentTypeSymbol,
ImmutableArray<string> fieldPath,
ref int resourceOffset,
@@ -56,6 +59,12 @@ partial class ComputeShaderDescriptorGenerator
continue;
}
// Skip fields of not accessible types (the analyzer will handle this)
if (!fieldSymbol.Type.IsAccessibleFromCompilationAssembly(compilation))
{
continue;
}
string fieldName = fieldSymbol.Name;
string typeName = fieldSymbol.Type.GetFullyQualifiedMetadataName();
@@ -78,7 +87,7 @@ partial class ComputeShaderDescriptorGenerator
else if (fieldSymbol.Type.IsUnmanagedType)
{
// Custom struct type defined by the user
GetInfo(fieldSymbol.Type, fieldPath.Add(fieldName), ref resourceOffset, ref rawDataOffset, fields, resources);
GetInfo(compilation, fieldSymbol.Type, fieldPath.Add(fieldName), ref resourceOffset, ref rawDataOffset, fields, resources);
}
}
}
@@ -93,6 +102,7 @@ partial class ComputeShaderDescriptorGenerator
{
// Traverse all shader fields and gather info, and update the tracking offsets
GetInfo(
compilation,
structDeclarationSymbol,
ImmutableArray<string>.Empty,
ref resourceOffset,
+1
ファイルの表示
@@ -60,6 +60,7 @@ public sealed partial class ComputeShaderDescriptorGenerator : IIncrementalGener
// Get the fields info
DispatchDataLoading.GetInfo(
diagnostics,
context.SemanticModel.Compilation,
typeSymbol,
isPixelShaderLike,
out int constantBufferSizeInBytes,
@@ -0,0 +1,19 @@
using ComputeSharp.SourceGeneration.Diagnostics;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class NotAccessibleFieldTypeInGeneratedShaderDescriptorAttributeTargetAnalyzer : NotAccessibleFieldTypeInGeneratedShaderDescriptorAttributeTargetAnalyzerBase
{
/// <summary>
/// Creates a new <see cref="NotAccessibleFieldTypeInGeneratedShaderDescriptorAttributeTargetAnalyzer"/> instance.
/// </summary>
public NotAccessibleFieldTypeInGeneratedShaderDescriptorAttributeTargetAnalyzer()
: base(NotAccessibleFieldTypeInTargetTypeForGeneratedComputeShaderDescriptorAttribute, "ComputeSharp.GeneratedComputeShaderDescriptorAttribute")
{
}
}
+16
ファイルの表示
@@ -784,4 +784,20 @@ partial class DiagnosticDescriptors
isEnabledByDefault: true,
description: "The [GeneratedComputeShaderDescriptor] attribute requires target types to be accessible from their containing assembly.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for when a field in a type using the <c>[GeneratedComputeShaderDescriptor]</c> attribute has a type that is not accessible from its containing assembly.
/// <para>
/// Format: <c>"The [GeneratedComputeShaderDescriptor] attribute requires the type of all fields of target types to be accessible from their containing assembly (type {0} has a field "{1}" of type {2} that has less effective accessibility than internal)"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor NotAccessibleFieldTypeInTargetTypeForGeneratedComputeShaderDescriptorAttribute = new DiagnosticDescriptor(
id: "CMPS0056",
title: "Invalid [GeneratedComputeShaderDescriptor] attribute target",
messageFormat: """The [GeneratedComputeShaderDescriptor] attribute requires the type of all fields of target types to be accessible from their containing assembly (type {0} has a field "{1}" of type {2} that has less effective accessibility than internal)""",
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The [GeneratedComputeShaderDescriptor] attribute requires the type of all fields of target types to be accessible from their containing assembly.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
}
+32 -1
ファイルの表示
@@ -10,7 +10,7 @@ namespace ComputeSharp.Tests.SourceGenerators;
public class AnalyzerTests
{
[TestMethod]
public async Task InvalidShaderField()
public async Task NotAccessibleNestedShaderType()
{
const string source = """
using ComputeSharp;
@@ -33,4 +33,35 @@ public class AnalyzerTests
await CSharpAnalyzerWithLanguageVersionTest<NotAccessibleGeneratedComputeShaderDescriptorAttributeTargetAnalyzer>.VerifyAnalyzerAsync(source);
}
[TestMethod]
public async Task NotAccessibleShaderFieldType()
{
const string source = """
using ComputeSharp;
namespace MyFancyApp.Sample;
public partial class Foo
{
[{|CMPS0056:GeneratedComputeShaderDescriptor|}]
private partial struct MyShader : IComputeShader
{
public ReadWriteBuffer<float> buffer;
public Bar bar;
public void Execute()
{
}
}
private struct Bar
{
public int X;
}
}
""";
await CSharpAnalyzerWithLanguageVersionTest<NotAccessibleFieldTypeInGeneratedShaderDescriptorAttributeTargetAnalyzer>.VerifyAnalyzerAsync(source);
}
}