Merge pull request #753 from Sergio0694/dev/d2d-input-description-analyzer

Move D2D input descriptions diagnostics to analyzer
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2024-01-01 23:34:56 +00:00
コミット 464027722e
5ファイル変更
+291 -69

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

@@ -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
/// <summary>
/// Extracts the input descriptions for the current shader.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="inputDescriptions">The produced input descriptions for the shader.</param>
public static void GetInfo(
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
INamedTypeSymbol structDeclarationSymbol,
out ImmutableArray<InputDescription> inputDescriptions)
{
int inputCount = 0;
using ImmutableArrayBuilder<InputDescription> inputDescriptionsBuilder = new();
using ImmutableArrayBuilder<InputDescription> builder = new();
foreach (AttributeData attributeData in structDeclarationSymbol.GetAttributes())
{
using ImmutableArrayBuilder<char> 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<InputDescription>.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<bool> 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();
}
}
}
-1
ファイルの表示
@@ -132,7 +132,6 @@ public sealed partial class D2DPixelShaderDescriptorGenerator : IIncrementalGene
// Get the info for InputDescriptions
InputDescriptions.GetInfo(
diagnostics,
typeSymbol,
out ImmutableArray<InputDescription> inputDescriptions);
@@ -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;
/// <summary>
/// A diagnostic analyzer that generates errors for all invalid uses of the [D2DInputDescription] attribute.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class InvalidD2DInputDescriptionAttributeUseAnalyzer : DiagnosticAnalyzer
{
/// <inheritdoc/>
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(
OutOfRangeInputDescriptionIndex,
RepeatedD2DInputDescriptionIndices);
/// <inheritdoc/>
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<int> 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<bool> 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);
});
}
}
+159 -1
ファイルの表示
@@ -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<ExceededPixelShaderDispatchDataSizeAnalyzer>.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<InvalidD2DInputDescriptionAttributeUseAnalyzer>.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<InvalidD2DInputDescriptionAttributeUseAnalyzer>.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<InvalidD2DInputDescriptionAttributeUseAnalyzer>.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<InvalidD2DInputDescriptionAttributeUseAnalyzer>.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<InvalidD2DInputDescriptionAttributeUseAnalyzer>.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<InvalidD2DInputDescriptionAttributeUseAnalyzer>.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<InvalidD2DInputDescriptionAttributeUseAnalyzer>.VerifyAnalyzerAsync(source);
}
}
@@ -1770,6 +1770,7 @@ public class Test_D2DPixelShaderDescriptorGenerator
await CSharpAnalyzerWithLanguageVersionTest<InvalidAssemblyLevelCompileOptionsAnalyzer>.VerifyAnalyzerAsync(source);
await CSharpAnalyzerWithLanguageVersionTest<InvalidD2D1CompileOptionsEnableLinkingOnShaderTypeAnalyzer>.VerifyAnalyzerAsync(source);
await CSharpAnalyzerWithLanguageVersionTest<InvalidD2DGeneratedPixelShaderDescriptorAttributeTargetAnalyzer>.VerifyAnalyzerAsync(source);
await CSharpAnalyzerWithLanguageVersionTest<InvalidD2DInputDescriptionAttributeUseAnalyzer>.VerifyAnalyzerAsync(source);
await CSharpAnalyzerWithLanguageVersionTest<InvalidD2DRequiresDoublePrecisionSupportAnalyzer>.VerifyAnalyzerAsync(source);
await CSharpAnalyzerWithLanguageVersionTest<InvalidD2DResourceTextureIndexAttributeLocationAnalyzer>.VerifyAnalyzerAsync(source);
await CSharpAnalyzerWithLanguageVersionTest<InvalidD2DResourceTextureIndexAttributeUseAnalyzer>.VerifyAnalyzerAsync(source);