From 0200e867bb39577c17f1ede2dcd96c0db7fac816 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 18 Feb 2021 03:20:12 +0100 Subject: [PATCH] Added error for usage of dispatch types out of scope --- .../AnalyzerReleases.Unshipped.md | 7 +- .../Diagnostics/DiagnosticDescriptors.cs | 72 +++++++++++++++++-- .../IComputeShaderSourceGenerator.cs | 25 +++++-- .../ShaderMethodSourceGenerator.cs | 6 +- .../SyntaxRewriters/ShaderSourceRewriter.cs | 53 +++++++++++++- 5 files changed, 147 insertions(+), 16 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md index f42b3e64..fa8b86cd 100644 --- a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md +++ b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md @@ -8,4 +8,9 @@ Rule ID | Category | Severity | Notes CMPS0001 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0002 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0003 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0004 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) \ No newline at end of file +CMPS0004 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0005 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0006 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0007 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0008 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0009 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 48acd529..676b4f4c 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -58,13 +58,13 @@ namespace ComputeSharp.SourceGenerators.Diagnostics /// /// Gets a for an invalid group shared field declaration. /// - /// Format: "The compute shader of type {0} contains a group shared field \"{1}\" that is not static.". + /// Format: "The compute shader of type {0} contains a group shared field \"{1}\" that is not static". /// /// public static DiagnosticDescriptor InvalidGroupSharedFieldDeclaration { get; } = new( id: "CMPS0004", title: "Invalid group shared field declaration", - messageFormat: "The compute shader of type {0} contains a group shared field \"{1}\" that is not static.", + messageFormat: "The compute shader of type {0} contains a group shared field \"{1}\" that is not static", category: typeof(IComputeShader).FullName, defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, @@ -74,17 +74,81 @@ namespace ComputeSharp.SourceGenerators.Diagnostics /// /// Gets a for a shader with no resources. /// - /// Format: "The compute shader of type {0} contains no resources to work on.". + /// Format: "The compute shader of type {0} contains no resources to work on". /// /// public static DiagnosticDescriptor MissingShaderResources { get; } = new( id: "CMPS0005", title: "Missing shader resources", - messageFormat: "The compute shader of type {0} contains no resources to work on.", + messageFormat: "The compute shader of type {0} contains no resources to work on", category: typeof(IComputeShader).FullName, defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A compute shader must contain at least one resource.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an invalid usage. + /// + /// Format: "The ThreadIds type is used in method {0} of type {1}". + /// + /// + public static DiagnosticDescriptor InvalidThreadIdsUsage { get; } = new( + id: "CMPS0006", + title: "Invalid ThreadIds usage", + messageFormat: "The ThreadIds type can only be used within the main body of a compute shader", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "The ThreadIds type can only be used within the main body of a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an invalid usage. + /// + /// Format: "The GroupIds type is used in method {0} of type {1}". + /// + /// + public static DiagnosticDescriptor InvalidGroupIdsUsage { get; } = new( + id: "CMPS0007", + title: "Invalid GroupIds usage", + messageFormat: "The GroupIds type can only be used within the main body of a compute shader", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "The GroupIds type can only be used within the main body of a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an invalid usage. + /// + /// Format: "The GroupSize type is used in method {0} of type {1}". + /// + /// + public static DiagnosticDescriptor InvalidGroupSizeUsage { get; } = new( + id: "CMPS0008", + title: "Invalid GroupSize usage", + messageFormat: "The GroupSize type can only be used within the main body of a compute shader", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "The GroupSize type can only be used within the main body of a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an invalid usage. + /// + /// Format: "The WarpIds type is used in method {0} of type {1}". + /// + /// + public static DiagnosticDescriptor InvalidWarpIdsUsage { get; } = new( + id: "CMPS0009", + title: "Invalid WarpIds usage", + messageFormat: "The WarpIds type can only be used within the main body of a compute shader", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "The WarpIds type can only be used within the main body of a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } } diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index bf54077a..59eca030 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -52,7 +52,7 @@ namespace ComputeSharp.SourceGenerators // Explore the syntax tree and extract the processed info var processedMembers = GetProcessedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray(); var sharedBuffers = GetGroupSharedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray(); - var (entryPoint, localFunctions) = GetProcessedMethods(structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions); + var (entryPoint, localFunctions) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions); var processedTypes = GetProcessedTypes(discoveredTypes).ToArray(); var processedMethods = localFunctions.Concat(staticMethods.Values).Select(static method => method.NormalizeWhitespace().ToFullString()).ToArray(); var processedConstants = GetProcessedConstants(constantDefinitions); @@ -221,6 +221,7 @@ namespace ComputeSharp.SourceGenerators /// /// Gets a sequence of processed methods declared within a given type. /// + /// The current generator context in use. /// The type symbol for the shader type. /// The instance for the current type. /// The instance for the type to process. @@ -230,6 +231,7 @@ namespace ComputeSharp.SourceGenerators /// A sequence of processed methods in , and the entry point. [Pure] private static (string EntryPoint, IEnumerable Methods) GetProcessedMethods( + GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, SemanticModel semanticModel, @@ -249,16 +251,27 @@ namespace ComputeSharp.SourceGenerators foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) { IMethodSymbol methodDeclarationSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration)!; - ShaderSourceRewriter shaderSourceRewriter = new(structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions); + bool isShaderEntryPoint = + methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) && + methodDeclarationSymbol.ReturnsVoid && + methodDeclarationSymbol.TypeParameters.Length == 0 && + methodDeclarationSymbol.Parameters.Length == 0; + + // Create the source rewriter for the current method + ShaderSourceRewriter shaderSourceRewriter = new( + structDeclarationSymbol, + semanticModel, + discoveredTypes, + staticMethods, + constantDefinitions, + context, + isShaderEntryPoint); // Rewrite the method syntax tree MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia(); // If the method is the shader entry point, do additional processing - if (methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) && - methodDeclarationSymbol.ReturnsVoid && - methodDeclarationSymbol.TypeParameters.Length == 0 && - methodDeclarationSymbol.Parameters.Length == 0) + if (isShaderEntryPoint) { processedMethod = new ExecuteMethodRewriter(shaderSourceRewriter).Visit(processedMethod)!; diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index 6d817f4b..2bdf88e4 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -48,7 +48,7 @@ namespace ComputeSharp.SourceGenerators Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); // Explore the syntax tree and extract the processed info - var (invokeMethod, processedMethods) = GetProcessedMethods(methodDeclaration, semanticModel, discoveredTypes, staticMethods, constantDefinitions); + var (invokeMethod, processedMethods) = GetProcessedMethods(context, methodDeclaration, semanticModel, discoveredTypes, staticMethods, constantDefinitions); var processedTypes = IComputeShaderSourceGenerator.GetProcessedTypes(discoveredTypes).ToArray(); var processedConstants = IComputeShaderSourceGenerator.GetProcessedConstants(constantDefinitions); @@ -75,6 +75,7 @@ namespace ComputeSharp.SourceGenerators /// /// Gets a sequence of processed methods from a target method declaration. /// + /// The current generator context in use. /// The instance for the current method. /// The instance for the method to process. /// The collection of currently discovered types. @@ -83,13 +84,14 @@ namespace ComputeSharp.SourceGenerators /// A sequence of processed methods in . [Pure] private static (string InvokeMethod, IEnumerable Methods) GetProcessedMethods( + GeneratorExecutionContext context, MethodDeclarationSyntax methodDeclaration, SemanticModel semanticModel, ICollection discoveredTypes, IDictionary staticMethods, IDictionary constantDefinitions) { - ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, constantDefinitions); + ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, constantDefinitions, context); // Rewrite the method syntax tree var processedMethod = shaderSourceRewriter diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index c5d8de24..4e17c631 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; +using ComputeSharp.SourceGenerators.Diagnostics; using ComputeSharp.SourceGenerators.Extensions; using ComputeSharp.SourceGenerators.Mappings; using Microsoft.CodeAnalysis; @@ -52,11 +53,26 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// private readonly List implicitVariables; + /// + /// The current generator context in use. + /// + private readonly GeneratorExecutionContext context; + + /// + /// Whether or not the current instance is processing a shader entry point. + /// + private readonly bool isEntryPoint; + /// /// The current tree being visited. /// private MethodDeclarationSyntax? currentMethod; + /// + /// The current depth inside local declarations. + /// + private int localFunctionDepth; + /// /// Creates a new instance with the specified parameters. /// @@ -65,12 +81,16 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// The set of discovered custom types. /// The set of discovered and processed static methods. /// The collection of discovered constant definitions. + /// The current generator context in use. + /// Whether or not the current instance is processing a shader entry point. public ShaderSourceRewriter( INamedTypeSymbol shaderType, SemanticModel semanticModel, ICollection discoveredTypes, IDictionary staticMethods, - IDictionary constantDefinitions) + IDictionary constantDefinitions, + GeneratorExecutionContext context, + bool isEntryPoint) { this.shaderType = shaderType; this.semanticModel = semanticModel; @@ -79,6 +99,8 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters this.constantDefinitions = constantDefinitions; this.localFunctions = new(); this.implicitVariables = new(); + this.context = context; + this.isEntryPoint = isEntryPoint; } /// @@ -88,11 +110,13 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// The set of discovered custom types. /// The set of discovered and processed static methods. /// The collection of discovered constant definitions. + /// The current generator context in use. public ShaderSourceRewriter( SemanticModel semanticModel, ICollection discoveredTypes, IDictionary staticMethods, - IDictionary constantDefinitions) + IDictionary constantDefinitions, + GeneratorExecutionContext context) { this.semanticModel = semanticModel; this.discoveredTypes = discoveredTypes; @@ -100,6 +124,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters this.constantDefinitions = constantDefinitions; this.implicitVariables = new(); this.localFunctions = new(); + this.context = context; } /// @@ -285,12 +310,16 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// public override SyntaxNode? VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) { + this.localFunctionDepth++; + var updatedNode = ((LocalFunctionStatementSyntax)base.VisitLocalFunctionStatement(node)!) .WithBlockBody() .WithAttributeLists(List()) .WithIdentifier(Identifier($"__{this.currentMethod!.Identifier.Text}__{node.Identifier.Text}")); + this.localFunctionDepth--; + // HLSL doesn't support local functions, so we first process them as usual and then remove // them from the current syntax tree completely. These will be added to the shader source // as external static method with a special name to avoid conflicts with other methods. @@ -331,6 +360,24 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters if (mapping == $"__{nameof(GroupIds)}__get_Index") IsGroupIdsIndexUsed = true; else if (typeName == typeof(GroupIds).FullName) IsGroupIdsUsed = true; else if (typeName == typeof(WarpIds).FullName) IsWarpIdsUsed = true; + + // Check that the dispatch info types are only used from the main shader body + if (!this.isEntryPoint || this.localFunctionDepth > 0) + { + DiagnosticDescriptor? descriptor = typeName switch + { + _ when typeName == typeof(ThreadIds).FullName => DiagnosticDescriptors.InvalidThreadIdsUsage, + _ when typeName == typeof(GroupIds).FullName => DiagnosticDescriptors.InvalidGroupIdsUsage, + _ when typeName == typeof(GroupSize).FullName => DiagnosticDescriptors.InvalidGroupSizeUsage, + _ when typeName == typeof(WarpIds).FullName => DiagnosticDescriptors.InvalidWarpIdsUsage, + _ => null + }; + + if (descriptor is not null) + { + this.context.ReportDiagnostic(Diagnostic.Create(descriptor, node.GetLocation())); + } + } } // Static and instance members are handled differently, with static members being @@ -436,7 +483,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters if (!this.staticMethods.ContainsKey(method)) { - ShaderSourceRewriter shaderSourceRewriter = new(this.semanticModel, this.discoveredTypes, this.staticMethods, this.constantDefinitions); + ShaderSourceRewriter shaderSourceRewriter = new(this.semanticModel, this.discoveredTypes, this.staticMethods, this.constantDefinitions, this.context); MethodDeclarationSyntax methodNode = (MethodDeclarationSyntax)method.DeclaringSyntaxReferences[0].GetSyntax(), processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace().WithoutTrivia();