Merge pull request #748 from Sergio0694/dev/resource-texture-analyzers

Refactor and optimize D2D resource texture diagnostics
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2023-12-31 13:53:32 +00:00
コミット cef8f69812
20ファイル変更
+548 -216

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

@@ -39,6 +39,8 @@ partial class D2DPixelShaderDescriptorGenerator
int rawInputCount = 0;
bool isInputCountPresent = false;
// Note: this logic is shared with InvalidD2DResourceTextureIndexAttributeUseAnalyzer.
// If any changes are made here, they should be reflected in that analyzer as well.
inputCount = 0;
using ImmutableArrayBuilder<int> inputSimpleIndicesBuilder = new();
@@ -1,13 +1,9 @@
using System;
using System.Collections.Immutable;
using System.Globalization;
using ComputeSharp.D2D1.SourceGenerators.Models;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGeneration.Mappings;
using ComputeSharp.SourceGeneration.Models;
using Microsoft.CodeAnalysis;
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
namespace ComputeSharp.D2D1.SourceGenerators;
@@ -22,23 +18,19 @@ partial class D2DPixelShaderDescriptorGenerator
/// <summary>
/// Extracts the resource texture 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="inputCount">The number of inputs for the shader.</param>
/// <param name="resourceTextureDescriptions">The produced resource texture descriptions for the shader.</param>
public static void GetInfo(
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
INamedTypeSymbol structDeclarationSymbol,
int inputCount,
out ImmutableArray<ResourceTextureDescription> resourceTextureDescriptions)
{
using ImmutableArrayBuilder<(int? Index, int Rank)> resourceTextureInfos = new();
using ImmutableArrayBuilder<ResourceTextureDescription> builder = new();
foreach (IFieldSymbol fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>())
foreach (ISymbol memberSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>())
{
// Only look for fields of a named type symbol (diagnostics is emitted by the HLSL rewriter if it's not the case).
// We're only looking for instance fields of unmanaged types in this case (as resource textures are structs).
if (fieldSymbol is not { IsStatic: false, Type: INamedTypeSymbol { IsUnmanagedType: true } typeSymbol })
if (memberSymbol is not IFieldSymbol { IsStatic: false, Type: INamedTypeSymbol { IsUnmanagedType: true, IsGenericType: true } typeSymbol } fieldSymbol)
{
continue;
}
@@ -48,8 +40,10 @@ partial class D2DPixelShaderDescriptorGenerator
// Check that the field is a resource texture type (if not, it will be processed by the HLSL rewriter too)
if (HlslKnownTypes.IsResourceTextureType(metadataName))
{
// The type name will be ComputeSharp.D2D1.D2D1ResourceTexture1D`1 or the 2D/3D versions
int rank = int.Parse(metadataName.Substring(metadataName.Length - 4, 1), CultureInfo.InvariantCulture);
// The type name will be ComputeSharp.D2D1.D2D1ResourceTexture1D`1 or the 2D/3D versions.
// To avoid the intermediate string and the parsing, we can rely on the fact the metadata
// has already been validated here, so we can get the rank by offsetting the characters.
int rank = metadataName[^4] - '0';
int? index = null;
// Get the index from the [D2DResourceTextureIndex] attribute over the field
@@ -62,76 +56,12 @@ partial class D2DPixelShaderDescriptorGenerator
index = resourceIndex;
}
}
else
{
// If the attribute is missing, emit a diagnostic
diagnostics.Add(MissingD2DResourceTextureIndexAttribute, fieldSymbol, fieldSymbol.Name, structDeclarationSymbol);
}
resourceTextureInfos.Add((index, rank));
builder.Add(new ResourceTextureDescription(index ?? 0, rank));
}
}
// Extract the resource texture descriptions for the rest of the pipeline
using (ImmutableArrayBuilder<ResourceTextureDescription> resourceTextureDescriptionsBuilder = new())
{
foreach ((int? index, int rank) in resourceTextureInfos.WrittenSpan)
{
resourceTextureDescriptionsBuilder.Add(new ResourceTextureDescription(index ?? 0, rank));
}
resourceTextureDescriptions = resourceTextureDescriptionsBuilder.ToImmutable();
}
// If the input count is invalid, do nothing and avoid emitting potentially incorrect
// diagnostics based on the resource texture indices with respect to the input count.
// The GetInputType() generator has already emitted diagnostic for this error, so this
// generator can just wait for users to go back and fix that issue before proceeding.
if (inputCount is not (>= 0 and <= 8))
{
return;
}
// Validate that the resource texture indices don't overlap with the shader inputs
foreach ((int? index, _) in resourceTextureInfos.WrittenSpan)
{
if (index < inputCount)
{
diagnostics.Add(ResourceTextureIndexOverlappingWithInputIndex, structDeclarationSymbol, structDeclarationSymbol);
return;
}
}
// Validate that no resource texture has an index greater than or equal to 16
foreach ((int? index, _) in resourceTextureInfos.WrittenSpan)
{
if (index >= 16)
{
diagnostics.Add(OutOfRangeResourceTextureIndex, structDeclarationSymbol, structDeclarationSymbol);
return;
}
}
Span<bool> selectedResourceTextureIndices = stackalloc bool[16];
selectedResourceTextureIndices.Clear();
// All input description indices must be unique (also take this path for invalid indices)
foreach ((int? index, _) in resourceTextureInfos.WrittenSpan)
{
ref bool isResourceTextureIndexUsed = ref selectedResourceTextureIndices[index ?? 0];
if (isResourceTextureIndexUsed)
{
diagnostics.Add(RepeatedD2DResourceTextureIndices, structDeclarationSymbol, structDeclarationSymbol);
return;
}
isResourceTextureIndexUsed = true;
}
resourceTextureDescriptions = builder.ToImmutable();
}
}
}
-2
ファイルの表示
@@ -109,9 +109,7 @@ public sealed partial class D2DPixelShaderDescriptorGenerator : IIncrementalGene
// Get the resource texture info for ResourceTextureDescriptions
ResourceTextureDescriptions.GetInfo(
diagnostics,
typeSymbol,
inputCount,
out ImmutableArray<ResourceTextureDescription> resourceTextureDescriptions);
token.ThrowIfCancellationRequested();
@@ -0,0 +1,64 @@
using System.Collections.Immutable;
using System.Linq;
using ComputeSharp.SourceGeneration.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
namespace ComputeSharp.D2D1.SourceGenerators;
/// <summary>
/// A diagnostic analyzer that generates an error whenever [D2DResourceTextureIndex] is used incorrectly to annotate a field.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class InvalidD2DResourceTextureIndexAttributeLocationAnalyzer : DiagnosticAnalyzer
{
/// <inheritdoc/>
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(InvalidD2DResourceTextureIndexAttributeLocation);
/// <inheritdoc/>
public override void Initialize(AnalysisContext context)
{
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
context.EnableConcurrentExecution();
context.RegisterCompilationStartAction(static context =>
{
// Get the [D2DResourceTextureIndex] symbol, and the ones for the D2D resource texture types
if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DResourceTextureIndexAttribute") is not { } d2DResourceTextureIndexAttributeSymbol ||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2D1ResourceTexture1D`1") is not { } d2D1ResourceTexture1DSymbol ||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2D1ResourceTexture2D`1") is not { } d2D1ResourceTexture2DSymbol ||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2D1ResourceTexture3D`1") is not { } d2D1ResourceTexture3DSymbol)
{
return;
}
// Inspect all fields to make sure they're not using the attribute incorrectly
context.RegisterSymbolAction(context =>
{
IFieldSymbol fieldSymbol = (IFieldSymbol)context.Symbol;
if (fieldSymbol.HasAttributeWithType(d2DResourceTextureIndexAttributeSymbol))
{
// If the field is using [D2DResourceTextureIndex], it must be a D2D resource texture. We can first
// just check that the field type is a generic named type (since that's the case if it's indeed of
// a D2D resource texture type). Past that, we just check that it's one of the three possible types.
if (fieldSymbol.Type is not INamedTypeSymbol { IsGenericType: true } typeSymbol ||
!(SymbolEqualityComparer.Default.Equals(typeSymbol.ConstructedFrom, d2D1ResourceTexture1DSymbol) ||
SymbolEqualityComparer.Default.Equals(typeSymbol.ConstructedFrom, d2D1ResourceTexture2DSymbol) ||
SymbolEqualityComparer.Default.Equals(typeSymbol.ConstructedFrom, d2D1ResourceTexture3DSymbol)))
{
Diagnostic diagnostic = Diagnostic.Create(
InvalidD2DResourceTextureIndexAttributeLocation,
fieldSymbol.Locations.First(),
fieldSymbol.Name,
fieldSymbol.ContainingType,
fieldSymbol.Type);
context.ReportDiagnostic(diagnostic);
}
}
}, SymbolKind.Field);
});
}
}
@@ -0,0 +1,191 @@
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 [D2DResourceTextureIndex] attribute.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class InvalidD2DResourceTextureIndexAttributeUseAnalyzer : DiagnosticAnalyzer
{
/// <inheritdoc/>
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(
MissingD2DResourceTextureIndexAttribute,
ResourceTextureIndexOverlappingWithInputIndex,
OutOfRangeResourceTextureIndex,
RepeatedD2DResourceTextureIndices);
/// <inheritdoc/>
public override void Initialize(AnalysisContext context)
{
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
context.EnableConcurrentExecution();
context.RegisterCompilationStartAction(static context =>
{
// Get all necessary symbols (we need a whole bunch of them here)
if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DResourceTextureIndexAttribute") is not { } d2DResourceTextureIndexAttributeSymbol ||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2D1ResourceTexture1D`1") is not { } d2D1ResourceTexture1DSymbol ||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2D1ResourceTexture2D`1") is not { } d2D1ResourceTexture2DSymbol ||
context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2D1ResourceTexture3D`1") is not { } d2D1ResourceTexture3DSymbol ||
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 (even without a generated descriptor)
if (!typeSymbol.HasInterfaceWithType(d2D1PixelShaderSymbol))
{
return;
}
using ImmutableArrayBuilder<(int? Index, int Rank)> resourceTextureInfos = new();
foreach (ISymbol memberSymbol in typeSymbol.GetMembers())
{
// Only look for valid candidate fields (same logic as in D2DPixelShaderDescriptorGenerator.InputTypes)
if (memberSymbol is not IFieldSymbol { IsStatic: false, Type: INamedTypeSymbol { IsUnmanagedType: true } } fieldSymbol)
{
continue;
}
// Specifically check that the type is generic and grab the source one
if (fieldSymbol.Type is not INamedTypeSymbol { ConstructedFrom: { } nonGenericFieldTypeSymbol })
{
continue;
}
// Check that the field is a D2D resource texture and get the rank
int rank = nonGenericFieldTypeSymbol switch
{
_ when SymbolEqualityComparer.Default.Equals(d2D1ResourceTexture1DSymbol, nonGenericFieldTypeSymbol) => 1,
_ when SymbolEqualityComparer.Default.Equals(d2D1ResourceTexture2DSymbol, nonGenericFieldTypeSymbol) => 2,
_ when SymbolEqualityComparer.Default.Equals(d2D1ResourceTexture3DSymbol, nonGenericFieldTypeSymbol) => 3,
_ => 0
};
// The field is not a D2D resource texture, just skip it
if (rank == 0)
{
continue;
}
int? index = null;
// Try to get the annotated index for the D2D texture, and track it. This
// logic is also in sync with D2DPixelShaderDescriptorGenerator.InputTypes.
if (fieldSymbol.TryGetAttributeWithType(d2DResourceTextureIndexAttributeSymbol, out AttributeData? textureIndexData))
{
if (textureIndexData.TryGetConstructorArgument(0, out int resourceIndex))
{
index = resourceIndex;
}
}
else
{
// If the attribute is missing, emit a diagnostic
context.ReportDiagnostic(Diagnostic.Create(
MissingD2DResourceTextureIndexAttribute,
fieldSymbol.Locations.First(),
fieldSymbol.Name,
typeSymbol));
}
resourceTextureInfos.Add((index, rank));
}
int inputCount = 0;
// Same logic as in D2DPixelShaderDescriptorGenerator.InputTypes (see there for reference).
// Keeping this in sync to ensure a consistent behavior (this should be updated if that changes).
if (typeSymbol.TryGetAttributeWithType(d2DInputCountAttributeSymbol, out AttributeData? inputCountData))
{
inputCount = Math.Max((int)inputCountData.ConstructorArguments[0].Value!, 0);
}
// If the input count is invalid, do nothing and avoid emitting potentially incorrect diagnostics
// based on the resource texture indices with respect to the input count. The generator for the
// InputType property has already emitted diagnostic for this error, so this analyzer can just
// wait for users to go back and fix that issue before proceeding.
if (inputCount is not (>= 0 and <= 8))
{
return;
}
// Validate that the resource texture indices don't overlap with the shader inputs
foreach ((int? index, _) in resourceTextureInfos.WrittenSpan)
{
if (index < inputCount)
{
context.ReportDiagnostic(Diagnostic.Create(
ResourceTextureIndexOverlappingWithInputIndex,
typeSymbol.Locations.First(),
typeSymbol));
break;
}
}
// Validate that no resource texture has an index greater than or equal to 16
foreach ((int? index, _) in resourceTextureInfos.WrittenSpan)
{
if (index >= 16)
{
context.ReportDiagnostic(Diagnostic.Create(
OutOfRangeResourceTextureIndex,
typeSymbol.Locations.First(),
typeSymbol));
break;
}
}
Span<bool> selectedResourceTextureIndices = stackalloc bool[16];
selectedResourceTextureIndices.Clear();
// All input description indices must be unique
foreach ((int? index, _) in resourceTextureInfos.WrittenSpan)
{
// Skip this path for invalid indices, as those will receive other diagnostics.
// We have to do this to avoid generating false positives for the default value.
// Because indices could be out of range, we also have to skip any of those.
if (index is null or >= 16)
{
continue;
}
ref bool isResourceTextureIndexUsed = ref selectedResourceTextureIndices[index ?? 0];
if (isResourceTextureIndexUsed)
{
context.ReportDiagnostic(Diagnostic.Create(
RepeatedD2DResourceTextureIndices,
typeSymbol.Locations.First(),
typeSymbol));
break;
}
isResourceTextureIndexUsed = true;
}
}, SymbolKind.NamedType);
});
}
}
@@ -1,48 +0,0 @@
using System.Collections.Immutable;
using System.Linq;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Mappings;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
namespace ComputeSharp.D2D1.SourceGenerators;
/// <summary>
/// A diagnostic analyzer that generates an error whenever [D2DResourceTextureIndex] is used incorrectly to annotate an invalid field.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class InvalidD2DResourceTextureIndexUseAnalyzer : DiagnosticAnalyzer
{
/// <inheritdoc/>
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(InvalidD2DResourceTextureIndexAttributeUse);
/// <inheritdoc/>
public override void Initialize(AnalysisContext context)
{
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
context.EnableConcurrentExecution();
context.RegisterSymbolAction(static context =>
{
IFieldSymbol fieldSymbol = (IFieldSymbol)context.Symbol;
if (fieldSymbol.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.D2D1.D2DResourceTextureIndexAttribute", out _))
{
string metadataName = fieldSymbol.Type.GetFullyQualifiedMetadataName();
if (!HlslKnownTypes.IsResourceTextureType(metadataName))
{
Diagnostic diagnostic = Diagnostic.Create(
InvalidD2DResourceTextureIndexAttributeUse,
fieldSymbol.Locations.First(),
fieldSymbol.Name,
fieldSymbol.ContainingType,
fieldSymbol.Type);
context.ReportDiagnostic(diagnostic);
}
}
}, SymbolKind.Field);
}
}
+6 -6
ファイルの表示
@@ -654,9 +654,9 @@ partial class DiagnosticDescriptors
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a shader with an out of range resource texture index (or more).
/// Gets a <see cref="DiagnosticDescriptor"/> for a shader with an overlapping resource texture index (or more).
/// <para>
/// Format: <c>"The D2D1 shader of type {0} is using some out of range resource texture indices"</c>.
/// Format: <c>"The D2D1 shader of type {0} is using some resource texture indices that overlap with the shader input indices"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor ResourceTextureIndexOverlappingWithInputIndex = new(
@@ -702,14 +702,14 @@ partial class DiagnosticDescriptors
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid use of <c>[D2DResourceTextureIndex]</c>.
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid location of <c>[D2DResourceTextureIndex]</c>.
/// <para>
/// Format: <c>"The field "{0}" (in type {1}) is using [D2DResourceTextureIndex] incorrectly (the attribute can only be used on D2D1 resource texture types, but the field is of type {2})"</c>.
/// Format: <c>"The field "{0}" (in type {1}) is using [D2DResourceTextureIndex] on an invalid location (the attribute can only be used on D2D1 resource texture types, but the field is of type {2})"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor InvalidD2DResourceTextureIndexAttributeUse = new(
public static readonly DiagnosticDescriptor InvalidD2DResourceTextureIndexAttributeLocation = new(
id: "CMPSD2D0049",
title: "Invalid [D2DResourceTextureIndex] use",
title: "Invalid [D2DResourceTextureIndex] location",
messageFormat: """The field "{0}" (in type {1}) is using [D2DResourceTextureIndex] incorrectly (the attribute can only be used on D2D1 resource texture types, but the field is of type {2})""",
category: "ComputeSharp.D2D1.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
+13 -13
ファイルの表示
@@ -21,6 +21,19 @@ partial class HlslKnownMethods
return name is "ComputeSharp.D2D1.D2D.GetScenePosition" or "ComputeSharp.D2D1.D2D.SampleInputAtPosition";
}
/// <inheritdoc/>
private static partial Dictionary<string, string?> BuildKnownResourceSamplers()
{
return new()
{
[$"ComputeSharp.D2D1.D2D1ResourceTexture1D`1.Sample({typeof(float).FullName})"] = null,
[$"ComputeSharp.D2D1.D2D1ResourceTexture2D`1.Sample({typeof(float).FullName}, {typeof(float).FullName})"] = "float2",
[$"ComputeSharp.D2D1.D2D1ResourceTexture2D`1.Sample({typeof(Float2).FullName})"] = null,
[$"ComputeSharp.D2D1.D2D1ResourceTexture3D`1.Sample({typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName})"] = "float3",
[$"ComputeSharp.D2D1.D2D1ResourceTexture3D`1.Sample({typeof(Float3).FullName})"] = null
};
}
/// <inheritdoc/>
static partial void AddKnownMethods(IDictionary<string, string> knownMethods)
@@ -37,17 +50,4 @@ partial class HlslKnownMethods
knownMethods.Add($"{typeof(D2D).FullName}{Type.Delimiter}{method.Name}", hlslName);
}
}
/// <inheritdoc/>
private static partial IReadOnlyDictionary<string, string?> BuildKnownResourceSamplers()
{
return new Dictionary<string, string?>
{
[$"ComputeSharp.D2D1.D2D1ResourceTexture1D`1.Sample({typeof(float).FullName})"] = null,
[$"ComputeSharp.D2D1.D2D1ResourceTexture2D`1.Sample({typeof(float).FullName}, {typeof(float).FullName})"] = "float2",
[$"ComputeSharp.D2D1.D2D1ResourceTexture2D`1.Sample({typeof(Float2).FullName})"] = null,
[$"ComputeSharp.D2D1.D2D1ResourceTexture3D`1.Sample({typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName})"] = "float3",
[$"ComputeSharp.D2D1.D2D1ResourceTexture3D`1.Sample({typeof(Float3).FullName})"] = null
};
}
}
+4 -4
ファイルの表示
@@ -6,9 +6,9 @@ namespace ComputeSharp.SourceGeneration.Mappings;
partial class HlslKnownProperties
{
/// <inheritdoc/>
private static partial IReadOnlyDictionary<string, string> BuildKnownResourceIndexers()
private static partial Dictionary<string, string> BuildKnownResourceIndexers()
{
return new Dictionary<string, string>
return new()
{
[$"ComputeSharp.D2D1.D2D1ResourceTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.D2D1.D2D1ResourceTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3"
@@ -16,9 +16,9 @@ partial class HlslKnownProperties
}
/// <inheritdoc/>
private static partial IReadOnlyDictionary<string, (int Rank, int Axis)> BuildKnownSizeAccessors()
private static partial Dictionary<string, (int Rank, int Axis)> BuildKnownSizeAccessors()
{
return new Dictionary<string, (int, int)>
return new()
{
["ComputeSharp.D2D1.D2D1ResourceTexture1D`1.Width"] = (1, 0),
["ComputeSharp.D2D1.D2D1ResourceTexture2D`1.Width"] = (2, 0),
+1 -1
ファイルの表示
@@ -10,7 +10,7 @@ internal static partial class HlslKnownFields
/// <summary>
/// The mapping of supported known fields to HLSL names.
/// </summary>
private static readonly IReadOnlyDictionary<string, string> KnownFields = BuildKnownFieldsMap();
private static readonly Dictionary<string, string> KnownFields = BuildKnownFieldsMap();
/// <summary>
/// Builds the mapping of supported known fields to HLSL names.
+1 -1
ファイルの表示
@@ -16,7 +16,7 @@ internal static partial class HlslKnownKeywords
/// <summary>
/// The mapping of known HLSL keywords.
/// </summary>
private static readonly IReadOnlyCollection<string> KnownKeywords = BuildKnownKeywordsMap();
private static readonly HashSet<string> KnownKeywords = BuildKnownKeywordsMap();
/// <summary>
/// Builds the mapping of all known HLSL keywords.
+13 -13
ファイルの表示
@@ -14,12 +14,17 @@ internal static partial class HlslKnownMethods
/// <summary>
/// The mapping of supported known methods to HLSL names.
/// </summary>
private static readonly IReadOnlyDictionary<string, string> KnownMethods = BuildKnownMethodsMap();
private static readonly Dictionary<string, string> KnownMethods = BuildKnownMethodsMap();
/// <summary>
/// The mapping of supported known methods that require parameters mapping to HLSL names.
/// </summary>
private static readonly IReadOnlyDictionary<string, string> KnownMethodsParametersMapping = BuildKnownMethodsParametersMappingMap();
private static readonly Dictionary<string, string> KnownMethodsParametersMapping = BuildKnownMethodsParametersMappingMap();
/// <summary>
/// The mapping of supported known samplers to HLSL resource type names.
/// </summary>
private static readonly Dictionary<string, string?> KnownResourceSamplers = BuildKnownResourceSamplers();
/// <summary>
/// Builds the mapping of supported known methods to HLSL names.
@@ -94,23 +99,18 @@ internal static partial class HlslKnownMethods
return knownMethods;
}
/// <summary>
/// Builds the mapping of supported known samplers to HLSL resource type names.
/// </summary>
/// <returns>The mapping of supported known samplers to HLSL resource type names.</returns>
private static partial Dictionary<string, string?> BuildKnownResourceSamplers();
/// <summary>
/// Adds more known methods to the mapping to use.
/// </summary>
/// <param name="knownMethods">The mapping of known methods being built.</param>
static partial void AddKnownMethods(IDictionary<string, string> knownMethods);
/// <summary>
/// The mapping of supported known samplers to HLSL resource type names.
/// </summary>
private static readonly IReadOnlyDictionary<string, string?> KnownResourceSamplers = BuildKnownResourceSamplers();
/// <summary>
/// Builds the mapping of supported known samplers to HLSL resource type names.
/// </summary>
/// <returns>The mapping of supported known samplers to HLSL resource type names.</returns>
private static partial IReadOnlyDictionary<string, string?> BuildKnownResourceSamplers();
/// <summary>
/// Tries to get the mapped HLSL-compatible sampler resource type name for the input indexer name.
/// </summary>
+1 -1
ファイルの表示
@@ -14,7 +14,7 @@ internal static partial class HlslKnownOperators
/// <summary>
/// The mapping of supported known operators to HLSL names.
/// </summary>
private static readonly IReadOnlyDictionary<string, string> KnownOperators = BuildKnownOperatorsMap();
private static readonly Dictionary<string, string> KnownOperators = BuildKnownOperatorsMap();
/// <summary>
/// Builds the mapping of supported known operators to HLSL names.
+35 -36
ファイルの表示
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
@@ -15,7 +14,27 @@ internal static partial class HlslKnownProperties
/// <summary>
/// The mapping of supported known properties to HLSL names.
/// </summary>
private static readonly IReadOnlyDictionary<string, string> KnownProperties = BuildKnownPropertiesMap();
private static readonly Dictionary<string, string> KnownProperties = BuildKnownPropertiesMap();
/// <summary>
/// The mapping of supported known properties to HLSL names.
/// </summary>
private static readonly HashSet<string> KnownMatrixIndexers = BuildKnownMatrixIndexers();
/// <summary>
/// The mapping of supported known members to HLSL names.
/// </summary>
private static readonly HashSet<string> KnownMatrixIndices = BuildKnownMatrixIndices();
/// <summary>
/// The mapping of supported known indexers to HLSL resource type names.
/// </summary>
private static readonly Dictionary<string, string> KnownResourceIndexers = BuildKnownResourceIndexers();
/// <summary>
/// The mapping of supported known size accessors for HLSL resource types.
/// </summary>
private static readonly Dictionary<string, (int Rank, int Axis)> KnownSizeAccessors = BuildKnownSizeAccessors();
/// <summary>
/// Builds the mapping of supported known properties to HLSL names.
@@ -143,23 +162,12 @@ internal static partial class HlslKnownProperties
return knownProperties;
}
/// <summary>
/// Adds more known members to the mapping to use.
/// </summary>
/// <param name="knownProperties">The mapping of known properties being built.</param>
static partial void AddKnownProperties(IDictionary<string, string> knownProperties);
/// <summary>
/// The mapping of supported known properties to HLSL names.
/// </summary>
private static readonly IReadOnlyCollection<string> KnownMatrixIndexers = BuildKnownMatrixIndexers();
/// <summary>
/// Builds the mapping of swizzled matrix indexer properties.
/// </summary>
private static IReadOnlyCollection<string> BuildKnownMatrixIndexers()
private static HashSet<string> BuildKnownMatrixIndexers()
{
return (
return new(
from type in Assembly.GetExecutingAssembly().ExportedTypes
where Regex.IsMatch(type.FullName, @"ComputeSharp\.(Bool|Double|Float|Int|UInt)[1-4]x[1-4]")
from property in type.GetProperties()
@@ -167,45 +175,36 @@ internal static partial class HlslKnownProperties
where indices.Length > 0 &&
indices.All(static index => index.ParameterType == typeof(MatrixIndex))
let metadataName = $"{type.FullName}.this[{string.Join(", ", indices.Select(index => index.ParameterType))}]"
select metadataName).ToImmutableHashSet();
select metadataName);
}
/// <summary>
/// The mapping of supported known members to HLSL names.
/// </summary>
private static readonly IReadOnlyCollection<string> KnownMatrixIndices = BuildKnownMatrixIndices();
/// <summary>
/// Builds the mapping of swizzled matrix indices.
/// </summary>
private static IReadOnlyCollection<string> BuildKnownMatrixIndices()
private static HashSet<string> BuildKnownMatrixIndices()
{
return (
return new(
from name in Enum.GetNames(typeof(MatrixIndex))
select $"{typeof(MatrixIndex).FullName}.{name}").ToImmutableHashSet();
select $"{typeof(MatrixIndex).FullName}.{name}");
}
/// <summary>
/// The mapping of supported known indexers to HLSL resource type names.
/// </summary>
private static readonly IReadOnlyDictionary<string, string> KnownResourceIndexers = BuildKnownResourceIndexers();
/// <summary>
/// Builds the mapping of supported known indexers to HLSL resource type names.
/// </summary>
/// <returns>The mapping of supported known indexers to HLSL resource type names.</returns>
private static partial IReadOnlyDictionary<string, string> BuildKnownResourceIndexers();
/// <summary>
/// The mapping of supported known size accessors for HLSL resource types.
/// </summary>
private static readonly IReadOnlyDictionary<string, (int Rank, int Axis)> KnownSizeAccessors = BuildKnownSizeAccessors();
private static partial Dictionary<string, string> BuildKnownResourceIndexers();
/// <summary>
/// Builds the mapping of supported known size accessors for HLSL resource types.
/// </summary>
/// <returns>The mapping of supported known size accessors for HLSL resource types.</returns>
private static partial IReadOnlyDictionary<string, (int Rank, int Axis)> BuildKnownSizeAccessors();
private static partial Dictionary<string, (int Rank, int Axis)> BuildKnownSizeAccessors();
/// <summary>
/// Adds more known members to the mapping to use.
/// </summary>
/// <param name="knownProperties">The mapping of known properties being built.</param>
static partial void AddKnownProperties(IDictionary<string, string> knownProperties);
/// <summary>
/// Checks whether or not a given property fullname matches a matrix swizzled indexer.
+1 -1
ファイルの表示
@@ -14,7 +14,7 @@ internal static class HlslKnownSizes
/// <summary>
/// The mapping of supported known sizes to HLSL type names.
/// </summary>
private static readonly IReadOnlyDictionary<string, (int, int)> KnownSizes = BuildKnownSizesMap();
private static readonly Dictionary<string, (int, int)> KnownSizes = BuildKnownSizesMap();
/// <summary>
/// Builds the mapping of known type sizes and alignments.
+4 -4
ファイルの表示
@@ -57,22 +57,22 @@ internal static partial class HlslKnownTypes
/// <summary>
/// The mapping of supported known vector types to HLSL types.
/// </summary>
private static readonly IReadOnlyDictionary<string, string> KnownVectorTypeMetadataNames = BuildKnownVectorTypeMetadataNames();
private static readonly Dictionary<string, string> KnownVectorTypeMetadataNames = BuildKnownVectorTypeMetadataNames();
/// <summary>
/// The mapping of supported known matrix types to HLSL types.
/// </summary>
private static readonly IReadOnlyDictionary<string, string> KnownMatrixTypesMetadataNames = BuildKnownMatrixTypeMetadataNames();
private static readonly Dictionary<string, string> KnownMatrixTypesMetadataNames = BuildKnownMatrixTypeMetadataNames();
/// <summary>
/// The mapping of supported known types to HLSL types.
/// </summary>
private static readonly IReadOnlyDictionary<string, string> KnownHlslTypeMetadataNames = BuildKnownHlslTypeMetadataNames();
private static readonly Dictionary<string, string> KnownHlslTypeMetadataNames = BuildKnownHlslTypeMetadataNames();
/// <summary>
/// The mapping of type info for all supported known matrix types to HLSL types.
/// </summary>
private static readonly IReadOnlyDictionary<string, NonLinearMatrixTypeInfo> KnownNonLinearMatrixTypeInfo = BuildKnownNonLinearMatrixTypeInfo();
private static readonly Dictionary<string, NonLinearMatrixTypeInfo> KnownNonLinearMatrixTypeInfo = BuildKnownNonLinearMatrixTypeInfo();
/// <summary>
/// Builds the mapping of known HLSL vector types.
+2 -2
ファイルの表示
@@ -6,9 +6,9 @@ namespace ComputeSharp.SourceGeneration.Mappings;
partial class HlslKnownMethods
{
/// <inheritdoc/>
private static partial IReadOnlyDictionary<string, string?> BuildKnownResourceSamplers()
private static partial Dictionary<string, string?> BuildKnownResourceSamplers()
{
return new Dictionary<string, string?>
return new()
{
[$"ComputeSharp.ReadOnlyTexture1D`2.Sample({typeof(float).FullName})"] = null,
[$"ComputeSharp.IReadOnlyTexture1D`1.Sample({typeof(float).FullName})"] = null,
+4 -4
ファイルの表示
@@ -9,9 +9,9 @@ namespace ComputeSharp.SourceGeneration.Mappings;
partial class HlslKnownProperties
{
/// <inheritdoc/>
private static partial IReadOnlyDictionary<string, string> BuildKnownResourceIndexers()
private static partial Dictionary<string, string> BuildKnownResourceIndexers()
{
return new Dictionary<string, string>
return new()
{
[$"ComputeSharp.ReadOnlyTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
@@ -33,9 +33,9 @@ partial class HlslKnownProperties
}
/// <inheritdoc/>
private static partial IReadOnlyDictionary<string, (int Rank, int Axis)> BuildKnownSizeAccessors()
private static partial Dictionary<string, (int Rank, int Axis)> BuildKnownSizeAccessors()
{
return new Dictionary<string, (int, int)>
return new()
{
["ComputeSharp.Resources.Buffer`1.Length"] = (2, 0),
["ComputeSharp.Resources.Texture1D`1.Width"] = (1, 0),
+195
ファイルの表示
@@ -415,4 +415,199 @@ public class Test_Analyzers
await CSharpAnalyzerWithLanguageVersionTest<InvalidD2DRequiresDoublePrecisionSupportAnalyzer>.VerifyAnalyzerAsync(source);
}
[TestMethod]
public async Task MissingD2DResourceTextureIndexAttribute_WarnsOnlyIfMissing()
{
const string source = """
using ComputeSharp;
using ComputeSharp.D2D1;
[D2DInputCount(0)]
internal partial struct MyType : ID2D1PixelShader
{
public D2D1ResourceTexture1D<float> {|CMPSD2D0050:texture1D|};
public D2D1ResourceTexture2D<float> {|CMPSD2D0050:texture2D|};
public D2D1ResourceTexture3D<float> {|CMPSD2D0050:texture3D|};
[D2DResourceTextureIndex(0)]
public D2D1ResourceTexture1D<float> texture1D_2;
[D2DResourceTextureIndex(1)]
public D2D1ResourceTexture2D<float> texture2D_2;
[D2DResourceTextureIndex(2)]
public D2D1ResourceTexture3D<float> texture3D_2;
public Float4 Execute()
{
return 0;
}
}
""";
await CSharpAnalyzerWithLanguageVersionTest<InvalidD2DResourceTextureIndexAttributeUseAnalyzer>.VerifyAnalyzerAsync(source);
}
[TestMethod]
public async Task ResourceTextureIndexOverlappingWithInputIndex_Warns()
{
const string source = """
using ComputeSharp;
using ComputeSharp.D2D1;
[D2DInputCount(2)]
internal partial struct {|CMPSD2D0046:MyType|} : ID2D1PixelShader
{
[D2DResourceTextureIndex(1)]
public D2D1ResourceTexture1D<float> texture;
public Float4 Execute()
{
return 0;
}
}
""";
await CSharpAnalyzerWithLanguageVersionTest<InvalidD2DResourceTextureIndexAttributeUseAnalyzer>.VerifyAnalyzerAsync(source);
}
[TestMethod]
public async Task ResourceTextureIndexOverlappingWithInputIndex_WarnsOnlyOnce()
{
const string source = """
using ComputeSharp;
using ComputeSharp.D2D1;
[D2DInputCount(2)]
internal partial struct {|CMPSD2D0046:MyType|} : ID2D1PixelShader
{
[D2DResourceTextureIndex(0)]
public D2D1ResourceTexture1D<float> texture1D;
[D2DResourceTextureIndex(1)]
public D2D1ResourceTexture2D<float> texture2D;
public Float4 Execute()
{
return 0;
}
}
""";
await CSharpAnalyzerWithLanguageVersionTest<InvalidD2DResourceTextureIndexAttributeUseAnalyzer>.VerifyAnalyzerAsync(source);
}
[TestMethod]
public async Task OutOfRangeResourceTextureIndex_Warns()
{
const string source = """
using ComputeSharp;
using ComputeSharp.D2D1;
[D2DInputCount(0)]
internal partial struct {|CMPSD2D0047:MyType|} : ID2D1PixelShader
{
[D2DResourceTextureIndex(16)]
public D2D1ResourceTexture1D<float> texture;
public Float4 Execute()
{
return 0;
}
}
""";
await CSharpAnalyzerWithLanguageVersionTest<InvalidD2DResourceTextureIndexAttributeUseAnalyzer>.VerifyAnalyzerAsync(source);
}
[TestMethod]
public async Task OutOfRangeResourceTextureIndex_WarnsOnlyOnce()
{
const string source = """
using ComputeSharp;
using ComputeSharp.D2D1;
[D2DInputCount(0)]
internal partial struct {|CMPSD2D0047:MyType|} : ID2D1PixelShader
{
[D2DResourceTextureIndex(16)]
public D2D1ResourceTexture1D<float> texture1D;
[D2DResourceTextureIndex(17)]
public D2D1ResourceTexture2D<float> texture2D;
public Float4 Execute()
{
return 0;
}
}
""";
await CSharpAnalyzerWithLanguageVersionTest<InvalidD2DResourceTextureIndexAttributeUseAnalyzer>.VerifyAnalyzerAsync(source);
}
[TestMethod]
public async Task RepeatedD2DResourceTextureIndices_Warns()
{
const string source = """
using ComputeSharp;
using ComputeSharp.D2D1;
[D2DInputCount(0)]
internal partial struct {|CMPSD2D0048:MyType|} : ID2D1PixelShader
{
[D2DResourceTextureIndex(0)]
public D2D1ResourceTexture1D<float> texture1;
[D2DResourceTextureIndex(0)]
public D2D1ResourceTexture1D<float> texture2;
public Float4 Execute()
{
return 0;
}
}
""";
await CSharpAnalyzerWithLanguageVersionTest<InvalidD2DResourceTextureIndexAttributeUseAnalyzer>.VerifyAnalyzerAsync(source);
}
[TestMethod]
public async Task InvalidD2DResourceTextureIndices_MultipleErrors_WarnsOncePerDiagnosticId()
{
const string source = """
using ComputeSharp;
using ComputeSharp.D2D1;
[D2DInputCount(3)]
internal partial struct {|CMPSD2D0046:{|CMPSD2D0047:{|CMPSD2D0048:MyType|}|}|} : ID2D1PixelShader
{
[D2DResourceTextureIndex(0)]
public D2D1ResourceTexture1D<float> texture1;
[D2DResourceTextureIndex(1)]
public D2D1ResourceTexture1D<float> texture2;
[D2DResourceTextureIndex(16)]
public D2D1ResourceTexture1D<float> texture3;
[D2DResourceTextureIndex(17)]
public D2D1ResourceTexture2D<float> texture4;
[D2DResourceTextureIndex(2)]
public D2D1ResourceTexture1D<float> texture5;
[D2DResourceTextureIndex(2)]
public D2D1ResourceTexture1D<float> texture6;
public Float4 Execute()
{
return 0;
}
}
""";
await CSharpAnalyzerWithLanguageVersionTest<InvalidD2DResourceTextureIndexAttributeUseAnalyzer>.VerifyAnalyzerAsync(source);
}
}
@@ -1770,7 +1770,8 @@ public class Test_D2DPixelShaderDescriptorGenerator
await CSharpAnalyzerWithLanguageVersionTest<InvalidD2D1CompileOptionsEnableLinkingOnShaderTypeAnalyzer>.VerifyAnalyzerAsync(source);
await CSharpAnalyzerWithLanguageVersionTest<InvalidD2DGeneratedPixelShaderDescriptorAttributeTargetAnalyzer>.VerifyAnalyzerAsync(source);
await CSharpAnalyzerWithLanguageVersionTest<InvalidD2DRequiresDoublePrecisionSupportAnalyzer>.VerifyAnalyzerAsync(source);
await CSharpAnalyzerWithLanguageVersionTest<InvalidD2DResourceTextureIndexUseAnalyzer>.VerifyAnalyzerAsync(source);
await CSharpAnalyzerWithLanguageVersionTest<InvalidD2DResourceTextureIndexAttributeLocationAnalyzer>.VerifyAnalyzerAsync(source);
await CSharpAnalyzerWithLanguageVersionTest<InvalidD2DResourceTextureIndexAttributeUseAnalyzer>.VerifyAnalyzerAsync(source);
await CSharpAnalyzerWithLanguageVersionTest<InvalidEffectIdValueAnalyzer>.VerifyAnalyzerAsync(source);
await CSharpAnalyzerWithLanguageVersionTest<InvalidEffectMetadataValueAnalyzer>.VerifyAnalyzerAsync(source);
await CSharpAnalyzerWithLanguageVersionTest<MissingAllowUnsafeBlocksCompilationOptionAnalyzer>.VerifyAnalyzerAsync(source);