Add InvalidShaderTypeInputsAnalyzer

このコミットが含まれているのは:
Sergio Pedri committed 2024-01-04 12:14:55 +00:00
1 親 9fb5c85c92
コミット 17a95cac99
2ファイル変更
+206 -3

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

@@ -0,0 +1,203 @@
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 whenever a shader type is declaring invalid inputs.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class InvalidShaderTypeInputsAnalyzer : DiagnosticAnalyzer
{
/// <inheritdoc/>
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(
MissingD2DInputCountAttribute,
InvalidD2DInputCount,
OutOfRangeInputIndex,
RepeatedD2DInputSimpleIndices,
RepeatedD2DInputComplexIndices,
InvalidSimpleAndComplexIndicesCombination);
/// <inheritdoc/>
public override void Initialize(AnalysisContext context)
{
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
context.EnableConcurrentExecution();
context.RegisterCompilationStartAction(static context =>
{
// Get the [D2DInputCount], [D2DInputSimple], [D2DInputComplex] and ID2D1PixelShader symbols
if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DInputCountAttribute") is not { } d2DInputCountAttributeSymbol ||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DInputSimpleAttribute") is not { } d2DInputSimpleAttributeSymbol ||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DInputComplexAttribute") is not { } d2DInputComplexAttributeSymbol ||
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;
}
// If there is no [D2DInputCount], we must stop here, but also emit a diagnostic (as it's mandatory)
if (!typeSymbol.TryGetAttributeWithType(d2DInputCountAttributeSymbol, out AttributeData? inputCountData))
{
context.ReportDiagnostic(Diagnostic.Create(
MissingD2DInputCountAttribute,
typeSymbol.Locations.First(),
typeSymbol));
return;
}
int inputCount = (int)inputCountData.ConstructorArguments[0].Value!;
// Validate the input count
if (inputCount is not (>= 0 and <= 8))
{
context.ReportDiagnostic(Diagnostic.Create(
InvalidD2DInputCount,
typeSymbol.Locations.First(),
typeSymbol,
inputCount));
}
// If we input is not valid, we can just clamp it to ensure it's nor negative, and
// continue to validate the rest normally. This will avoid some false positives.
inputCount = Math.Max(inputCount, 0);
using ImmutableArrayBuilder<int> inputSimpleIndices = new();
using ImmutableArrayBuilder<int> inputComplexIndices = new();
// Gather the indices of all explicitly declared simple and complex inputs
foreach (AttributeData attributeData in typeSymbol.GetAttributes())
{
if (SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, d2DInputSimpleAttributeSymbol))
{
inputSimpleIndices.Add((int)attributeData.ConstructorArguments[0].Value!);
}
else if (SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, d2DInputComplexAttributeSymbol))
{
inputComplexIndices.Add((int)attributeData.ConstructorArguments[0].Value!);
}
}
// All simple indices must be in range
foreach (int index in inputSimpleIndices.WrittenSpan)
{
if ((uint)index >= inputCount)
{
context.ReportDiagnostic(Diagnostic.Create(
OutOfRangeInputIndex,
typeSymbol.Locations.First(),
typeSymbol));
goto AfterOutOfRangeInputValidation;
}
}
// All complex indices must also be in range (of course)
foreach (int index in inputComplexIndices.WrittenSpan)
{
if ((uint)index >= inputCount)
{
context.ReportDiagnostic(Diagnostic.Create(
OutOfRangeInputIndex,
typeSymbol.Locations.First(),
typeSymbol));
goto AfterOutOfRangeInputValidation;
}
}
AfterOutOfRangeInputValidation:
Span<bool> selectedSimpleInputIndices = stackalloc bool[8];
Span<bool> selectedComplexInputIndices = stackalloc bool[8];
selectedSimpleInputIndices.Clear();
selectedComplexInputIndices.Clear();
// All simple indices must be unique
foreach (int index in inputSimpleIndices.WrittenSpan)
{
// Skip this path for invalid indices (just like with resource textures again).
// This same exact pattern is also used when validating input descriptions.
if ((uint)index >= 8)
{
continue;
}
ref bool isInputIndexUsed = ref selectedSimpleInputIndices[index];
if (isInputIndexUsed)
{
context.ReportDiagnostic(Diagnostic.Create(
RepeatedD2DInputSimpleIndices,
typeSymbol.Locations.First(),
typeSymbol));
break;
}
isInputIndexUsed = true;
}
// All complex indices must be unique as well (again, of course)
foreach (int index in inputComplexIndices.WrittenSpan)
{
if ((uint)index >= 8)
{
continue;
}
ref bool isInputIndexUsed = ref selectedComplexInputIndices[index];
if (isInputIndexUsed)
{
context.ReportDiagnostic(Diagnostic.Create(
RepeatedD2DInputComplexIndices,
typeSymbol.Locations.First(),
typeSymbol));
break;
}
isInputIndexUsed = true;
}
// Simple and complex indices can't have indices in common. We just validate
// the entire temporary spans, so that even if some values are out of range,
// we still also detect that some are conflicting.
for (int i = 0; i < 8; i++)
{
if (selectedSimpleInputIndices[i] && selectedComplexInputIndices[i])
{
context.ReportDiagnostic(Diagnostic.Create(
InvalidSimpleAndComplexIndicesCombination,
typeSymbol.Locations.First(),
typeSymbol));
break;
}
}
}, SymbolKind.NamedType);
});
}
}
+3 -3
ファイルの表示
@@ -479,17 +479,17 @@ partial class DiagnosticDescriptors
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a invalid D2D input count value.
/// <para>
/// Format: <c>"The D2D1 shader of type {0} is using an incorrect value for [D2DInputCount] (the number of inputs must be in the [0, 8] range)"</c>.
/// Format: <c>"The D2D1 shader of type {0} is using an incorrect value for [D2DInputCount] (the number of inputs must be in the [0, 8] range, but it was {1})"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor InvalidD2DInputCount = new(
id: "CMPSD2D0035",
title: "Invalid D2D1 shader input count",
messageFormat: "The D2D1 shader of type {0} is using an incorrect value for [D2DInputCount] (the number of inputs must be in the [0, 8] range)",
messageFormat: "The D2D1 shader of type {0} is using an incorrect value for [D2DInputCount] (the number of inputs must be in the [0, 8] range, but it was {1})",
category: "ComputeSharp.D2D1.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A D2D1 shader must have a number of inputs in the [1, 8] range.",
description: "A D2D1 shader must have a number of inputs in the [0, 8] range.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>