From e930c969cb6b97472cd188e4b9cc0be5ce72300d Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 2 Mar 2021 16:14:12 +0100 Subject: [PATCH] Added diagnostics for non constant matrix swizzling indices --- .../AnalyzerReleases.Unshipped.md | 3 +- .../ComputeSharp.SourceGenerators.csproj | 6 ++ .../Diagnostics/DiagnosticDescriptors.cs | 13 ++++ .../Extensions/ISymbolExtensions.cs | 11 +++ .../Mappings/HlslKnownMembers.cs | 72 +++++++++++++++++-- .../SyntaxRewriters/ShaderSourceRewriter.cs | 28 ++++++-- 6 files changed, 123 insertions(+), 10 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md index 64faf974..dad27523 100644 --- a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md +++ b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md @@ -45,4 +45,5 @@ CMPS0037 | ComputeSharp.SourceGenerators.AutoConstructorGenerator | Warning | Au CMPS0038 | ComputeSharp.SourceGenerators.IComputeShaderDataLoaderGenerator | Warning | IComputeShaderDataLoaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0039 | ComputeSharp.SourceGenerators.IComputeShaderHashCodeGenerator | Warning | IComputeShaderHashCodeGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0040 | ComputeSharp.SourceGenerators.IComputeShaderSourceGenerator | Warning | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0041 | ComputeSharp.SourceGenerators.ShaderMethodSourceGenerator | Warning | ShaderMethodSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) \ No newline at end of file +CMPS0041 | ComputeSharp.SourceGenerators.ShaderMethodSourceGenerator | Warning | ShaderMethodSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0042 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index 15c7d1ee..3c4ea32d 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -35,30 +35,36 @@ + + + + + + diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 25dbe67e..e7e12598 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -587,5 +587,18 @@ namespace ComputeSharp.SourceGenerators.Diagnostics isEnabledByDefault: true, description: $"The {nameof(ShaderMethodSourceGenerator)} generator encountered an error while processing a method, and using it in a shader might result in a runtime crash. Please report this issue at https://github.com/Sergio0694/ComputeSharp/issues.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an incorrect matrix swizzling property argument. + /// + public static readonly DiagnosticDescriptor NonConstantMatrixSwizzledIndex = new( + id: "CMPS0042", + title: "Non constant matrix swizzled property argument", + messageFormat: "The arguments in a swizzled indexer for a matrix type must be compile-time constants", + category: typeof(ShaderMethodSourceGenerator).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "The arguments in a swizzled indexer for a matrix type must be compile-time constants.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } } diff --git a/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs index e84e89ad..f89b5aa1 100644 --- a/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs +++ b/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs @@ -94,6 +94,17 @@ namespace ComputeSharp.SourceGenerators.Extensions return $"{declaringTypeName}.{symbol.Name}"; } + /// + /// Gets the full metadata name for a given instance. + /// + /// The input instance. + /// The full metadata name for . + [Pure] + public static string GetFullMetadataName(this IFieldSymbol symbol) + { + return $"{symbol.ContainingType.GetFullMetadataName()}.{symbol.Name}"; + } + /// /// Gets a valid filename for a target symbol and generator type. /// diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs index 707abb64..a4f545f1 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs @@ -1,9 +1,11 @@ using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.Diagnostics.Contracts; using System.Linq; using System.Numerics; using System.Reflection; +using System.Text.RegularExpressions; namespace ComputeSharp.SourceGenerators.Mappings { @@ -13,9 +15,9 @@ namespace ComputeSharp.SourceGenerators.Mappings internal static class HlslKnownMembers { /// - /// The mapping of supported known indexers to HLSL vector type names. + /// The mapping of supported known indexers to HLSL resource type names. /// - private static readonly IReadOnlyDictionary KnownIndexers = new Dictionary + private static readonly IReadOnlyDictionary KnownResourceIndexers = new Dictionary { [$"ComputeSharp.ReadOnlyTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", [$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", @@ -236,6 +238,66 @@ namespace ComputeSharp.SourceGenerators.Mappings return knownMembers; } + /// + /// The mapping of supported known members to HLSL names. + /// + private static readonly IReadOnlyCollection KnownMatrixIndexers = BuildKnownMatrixIndexers(); + + /// + /// Builds the mapping of swizzled matrix indexer properties. + /// + [Pure] + private static IReadOnlyCollection BuildKnownMatrixIndexers() + { + return ( + 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() + let indices = property.GetIndexParameters() + 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(); + } + + /// + /// The mapping of supported known members to HLSL names. + /// + private static readonly IReadOnlyCollection KnownMatrixIndices = BuildKnownMatrixIndices(); + + /// + /// Builds the mapping of swizzled matrix indices. + /// + [Pure] + private static IReadOnlyCollection BuildKnownMatrixIndices() + { + return ( + from name in Enum.GetNames(typeof(MatrixIndex)) + select $"{typeof(MatrixIndex).FullName}.{name}").ToImmutableHashSet(); + } + + /// + /// Checks whether or not a given property fullname matches a matrix swizzled indexer. + /// + /// The input fully qualified member name. + /// Whether or not is a matrix swizzled indexer. + [Pure] + public static bool IsKnownMatrixIndexer(string name) + { + return KnownMatrixIndexers.Contains(name); + } + + /// + /// Checks whether or not a given property fullname matches a matrix swizzled index. + /// + /// The input fully qualified member name. + /// Whether or not is a matrix swizzled index. + [Pure] + public static bool IsKnownMatrixIndex(string name) + { + return KnownMatrixIndices.Contains(name); + } + /// /// Tries to get the mapped HLSL-compatible member name for the input member name. /// @@ -249,15 +311,15 @@ namespace ComputeSharp.SourceGenerators.Mappings } /// - /// Tries to get the mapped HLSL-compatible indexer vector type name for the input indexer name. + /// Tries to get the mapped HLSL-compatible indexer resource type name for the input indexer name. /// /// The input fully qualified indexer name. /// The mapped type name, if one is found. /// The HLSL-compatible type name that can be used in an HLSL shader for the given indexer. [Pure] - public static bool TryGetMappedIndexerTypeName(string name, out string? mapped) + public static bool TryGetMappedResourceIndexerTypeName(string name, out string? mapped) { - return KnownIndexers.TryGetValue(name, out mapped); + return KnownResourceIndexers.TryGetValue(name, out mapped); } /// diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 637d6c36..af938698 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -557,12 +557,32 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters { var updatedNode = (ElementAccessExpressionSyntax)base.VisitElementAccessExpression(node)!; - if (this.semanticModel.GetOperation(node) is IPropertyReferenceOperation operation && - HlslKnownMembers.TryGetMappedIndexerTypeName(operation.Property.GetFullMetadataName(), out string? mapping)) + if (this.semanticModel.GetOperation(node) is IPropertyReferenceOperation operation) { - var index = InvocationExpression(IdentifierName(mapping!), ArgumentList(updatedNode.ArgumentList.Arguments)); + string propertyName = operation.Property.GetFullMetadataName(); - return updatedNode.WithArgumentList(BracketedArgumentList(SingletonSeparatedList(Argument(index)))); + // Rewrite texture resource indices taking vectors into individual indices as per HLSL spec. + // For instance: texture[ThreadIds.XY] will be rewritten as texture[ThreadIds.X, ThreadIds.Y]. + if (HlslKnownMembers.TryGetMappedResourceIndexerTypeName(propertyName, out string? mapping)) + { + var index = InvocationExpression(IdentifierName(mapping!), ArgumentList(updatedNode.ArgumentList.Arguments)); + + return updatedNode.WithArgumentList(BracketedArgumentList(SingletonSeparatedList(Argument(index)))); + } + + // If the current property is a swizzled matrix indexer, ensure all the arguments are constants, and rewrite + // the property access to the corresponding HLSL syntax. For instance, m[M11, M12] will become m._m00_m01. + if (HlslKnownMembers.IsKnownMatrixIndexer(propertyName)) + { + foreach (ArgumentSyntax argument in node.ArgumentList.Arguments) + { + if (this.semanticModel.GetOperation(argument.Expression) is not IFieldReferenceOperation fieldReference || + !HlslKnownMembers.IsKnownMatrixIndex(fieldReference.Field.GetFullMetadataName())) + { + this.context.ReportDiagnostic(NonConstantMatrixSwizzledIndex, argument); + } + } + } } return updatedNode;