From 4b280bf2b6345ab79ecb44a9a0e41d8ddea42bff Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 17 Feb 2021 19:22:42 +0100 Subject: [PATCH 01/14] Added error for captured fields of invalid types --- .../AnalyzerReleases.Shipped.md | 2 ++ .../AnalyzerReleases.Unshipped.md | 8 +++++ .../ComputeSharp.SourceGenerators.csproj | 4 +-- .../Diagnostics/DiagnosticDescriptors.cs | 26 ++++++++++++++++ .../Extensions/ISymbolExtensions.cs | 6 ++-- .../IComputeShaderDataLoaderGenerator.cs | 6 ++-- .../IComputeShaderHashCodeGenerator.cs | 9 +++--- .../IComputeShaderSourceGenerator.cs | 30 ++++++++++++++++--- .../SyntaxRewriters/ShaderSourceRewriter.cs | 2 +- 9 files changed, 76 insertions(+), 17 deletions(-) create mode 100644 src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md create mode 100644 src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md create mode 100644 src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs diff --git a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md new file mode 100644 index 00000000..054a5960 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md @@ -0,0 +1,2 @@ +; Shipped analyzer releases +; https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md new file mode 100644 index 00000000..2b28783f --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md @@ -0,0 +1,8 @@ +; Unshipped analyzer release +; https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md + +### New Rules + +Rule ID | Category | Severity | Notes +--------|----------|----------|------- +CMPS0001 | 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 b044bc0e..94eb7ab6 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -47,8 +47,8 @@ - - + + diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs new file mode 100644 index 00000000..81a35cae --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -0,0 +1,26 @@ +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.SourceGenerators.Diagnostics +{ + /// + /// A container for all instances for errors reported by analyzers in this project. + /// + internal static class DiagnosticDescriptors + { + /// + /// Gets a for an invalid shader field. + /// + /// Format: "The compute shader of type {0} contains a field \"{1}\" of an invalid type {2}". + /// + /// + public static DiagnosticDescriptor InvalidShaderField { get; } = new( + id: "CMPS0001", + title: "Invalid shader field", + messageFormat: "The compute shader of type {0} contains a field \"{1}\" of an invalid type {2}", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A type representing a compute shader contains a field of a type that is not supported in HLSL.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + } +} diff --git a/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs index e08f19e8..e84e89ad 100644 --- a/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs +++ b/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs @@ -31,12 +31,12 @@ namespace ComputeSharp.SourceGenerators.Extensions .WithParameterOptions(SymbolDisplayParameterOptions.None); /// - /// Gets the full metadata name for a given instance. + /// Gets the full metadata name for a given instance. /// - /// The input instance. + /// The input instance. /// The full metadata name for . [Pure] - public static string GetFullMetadataName(this INamedTypeSymbol symbol) + public static string GetFullMetadataName(this ITypeSymbol symbol) { static StringBuilder BuildFrom(ISymbol? symbol, StringBuilder builder) { diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs index 028d7ed4..e7bc5c2d 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs @@ -141,9 +141,11 @@ namespace ComputeSharp.SourceGenerators foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { - if (fieldSymbol.IsStatic) continue; + if (fieldSymbol.Type is not INamedTypeSymbol { IsStatic: false } typeSymbol) + { + continue; + } - INamedTypeSymbol typeSymbol = (INamedTypeSymbol)fieldSymbol.Type; string typeName = typeSymbol.GetFullMetadataName(); if (HlslKnownTypes.IsTypedResourceType(typeName)) diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs index 127677c7..b5dad985 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs @@ -120,11 +120,10 @@ namespace ComputeSharp.SourceGenerators { foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { - if (fieldSymbol.IsStatic) continue; - - INamedTypeSymbol typeSymbol = (INamedTypeSymbol)fieldSymbol.Type; - - if (typeSymbol.TypeKind != TypeKind.Delegate) continue; + if (fieldSymbol.Type is not INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false } typeSymbol) + { + continue; + } // hash += hash << 5; yield return ExpressionStatement(ParseExpression($"hash += hash << 5")); diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index 05ec04c3..1a799b82 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -4,6 +4,7 @@ using System.Diagnostics.Contracts; using System.Linq; using System.Text; using ComputeSharp.__Internals; +using ComputeSharp.SourceGenerators.Diagnostics; using ComputeSharp.SourceGenerators.Extensions; using ComputeSharp.SourceGenerators.Mappings; using ComputeSharp.SourceGenerators.SyntaxRewriters; @@ -49,7 +50,7 @@ namespace ComputeSharp.SourceGenerators Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); // Explore the syntax tree and extract the processed info - var processedMembers = GetProcessedMembers(structDeclarationSymbol, discoveredTypes).ToArray(); + var processedMembers = GetProcessedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray(); var sharedBuffers = GetGroupSharedMembers(structDeclarationSymbol, discoveredTypes).ToArray(); var (entryPoint, localFunctions) = GetProcessedMethods(structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions); var processedTypes = GetProcessedTypes(discoveredTypes).ToArray(); @@ -82,17 +83,30 @@ namespace ComputeSharp.SourceGenerators /// /// Gets a sequence of captured members and their mapped names. /// + /// The current generator context in use. /// The input instance to process. /// The collection of currently discovered types. /// A sequence of captured members in . [Pure] - private static IEnumerable> GetProcessedMembers(INamedTypeSymbol structDeclarationSymbol, ICollection types) + private static IEnumerable> GetProcessedMembers( + GeneratorExecutionContext context, + INamedTypeSymbol structDeclarationSymbol, + ICollection types) { foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { - if (fieldSymbol.IsStatic) continue; + // Captured fields must be named type symbols + if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol) + { + context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.InvalidShaderField, + fieldSymbol.Locations.FirstOrDefault(), + structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type)); - INamedTypeSymbol typeSymbol = (INamedTypeSymbol)fieldSymbol.Type; + continue; + } + + if (fieldSymbol.IsStatic) continue; string typeName = HlslKnownTypes.GetMappedName(typeSymbol); @@ -107,6 +121,14 @@ namespace ComputeSharp.SourceGenerators { types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]); } + else if (!typeSymbol.IsUnmanagedType) + { + // Shaders can only capture valid HLSL resource types or unmanaged types + context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.InvalidShaderField, + fieldSymbol.Locations.FirstOrDefault(), + structDeclarationSymbol, fieldSymbol.Name, typeSymbol)); + } } } diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 5c40b29d..c5d8de24 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -478,7 +478,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters // Track and rewrite the discarded declaration if (this.semanticModel.GetOperation(node.Expression) is IDiscardOperation operation) { - TypeSyntax typeSyntax = operation.Type.TrackType(this.discoveredTypes); + TypeSyntax typeSyntax = operation.Type!.TrackType(this.discoveredTypes); string identifier = $"__implicit{this.implicitVariables.Count}"; // Add the variable to the list of implicit declarations From 4fe3c857be49a3d90dddd1f961564a0242a6f41e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 17 Feb 2021 20:19:58 +0100 Subject: [PATCH 02/14] Added errors for invalid group shared fields --- samples/ComputeSharp.Sample.Shared/Program.cs | 5 ++- .../AnalyzerReleases.Unshipped.md | 4 ++- .../Diagnostics/DiagnosticDescriptors.cs | 32 +++++++++++++++++ .../IComputeShaderSourceGenerator.cs | 34 ++++++++++++++++--- 4 files changed, 69 insertions(+), 6 deletions(-) diff --git a/samples/ComputeSharp.Sample.Shared/Program.cs b/samples/ComputeSharp.Sample.Shared/Program.cs index ee01f2a1..a4e38ca1 100644 --- a/samples/ComputeSharp.Sample.Shared/Program.cs +++ b/samples/ComputeSharp.Sample.Shared/Program.cs @@ -21,7 +21,7 @@ namespace ComputeSharp.Sample using ReadWriteBuffer gpuBuffer = Gpu.Default.AllocateReadWriteBuffer(array); // Run the shader - Gpu.Default.For(100, new MainKernel(gpuBuffer)); + Gpu.Default.For(100, new MainKernel()); // Print the initial matrix PrintMatrix(array, width, height, "BEFORE"); @@ -41,6 +41,9 @@ namespace ComputeSharp.Sample { public readonly ReadWriteBuffer buffer; + [GroupShared] + public static string[] Foo; + /// public void Execute() { diff --git a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md index 2b28783f..bb77ae76 100644 --- a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md +++ b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md @@ -5,4 +5,6 @@ Rule ID | Category | Severity | Notes --------|----------|----------|------- -CMPS0001 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) \ No newline at end of file +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) \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 81a35cae..e54e2496 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -22,5 +22,37 @@ namespace ComputeSharp.SourceGenerators.Diagnostics isEnabledByDefault: true, description: "A type representing a compute shader contains a field of a type that is not supported in HLSL.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an invalid group shared field type. + /// + /// Format: "The compute shader of type {0} contains a group shared field \"{1}\" of an invalid type {2}". + /// + /// + public static DiagnosticDescriptor InvalidGroupSharedFieldType { get; } = new( + id: "CMPS0002", + title: "Invalid group shared field type", + messageFormat: "The compute shader of type {0} contains a group shared field \"{1}\" of an invalid type {2} (it must be an array)", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A group shared field must be of an array type.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an invalid group shared field element type. + /// + /// Format: "The compute shader of type {0} contains a group shared field \"{1}\" of an invalid element type {2}". + /// + /// + public static DiagnosticDescriptor InvalidGroupSharedFieldElementType { get; } = new( + id: "CMPS0003", + title: "Invalid group shared field type", + messageFormat: "The compute shader of type {0} contains a group shared field \"{1}\" of an invalid type {2} (it must be a primitive or unmanaged type)", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A group shared field element must be of a primitive or unmanaged type.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } } diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index 1a799b82..aba966b1 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -51,7 +51,7 @@ namespace ComputeSharp.SourceGenerators // Explore the syntax tree and extract the processed info var processedMembers = GetProcessedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray(); - var sharedBuffers = GetGroupSharedMembers(structDeclarationSymbol, discoveredTypes).ToArray(); + var sharedBuffers = GetGroupSharedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray(); var (entryPoint, localFunctions) = GetProcessedMethods(structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions); var processedTypes = GetProcessedTypes(discoveredTypes).ToArray(); var processedMethods = localFunctions.Concat(staticMethods.Values).Select(static method => method.NormalizeWhitespace().ToFullString()).ToArray(); @@ -135,19 +135,45 @@ namespace ComputeSharp.SourceGenerators /// /// Gets a sequence of captured members and their mapped names. /// + /// The current generator context in use. /// The input instance to process. /// The collection of currently discovered types. /// A sequence of captured members in . [Pure] - private static IEnumerable<(string Name, string Type, int? Count)> GetGroupSharedMembers(INamedTypeSymbol structDeclarationSymbol, ICollection types) + private static IEnumerable<(string Name, string Type, int? Count)> GetGroupSharedMembers( + GeneratorExecutionContext context, + INamedTypeSymbol structDeclarationSymbol, + ICollection types) { foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { if (!fieldSymbol.IsStatic) continue; - AttributeData attribute = fieldSymbol.GetAttributes().First(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); + AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); + + if (attribute is null) continue; + + if (fieldSymbol.Type is not IArrayTypeSymbol typeSymbol) + { + context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.InvalidGroupSharedFieldType, + fieldSymbol.Locations.FirstOrDefault(), + structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type)); + + continue; + } + + if (typeSymbol.ElementType.IsUnmanagedType) + { + context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.InvalidGroupSharedFieldElementType, + fieldSymbol.Locations.FirstOrDefault(), + structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type)); + + continue; + } + int? bufferSize = (int?)attribute.ConstructorArguments.FirstOrDefault().Value; - IArrayTypeSymbol typeSymbol = (IArrayTypeSymbol)fieldSymbol.Type; string typeName = HlslKnownTypes.GetMappedElementName(typeSymbol); From e278ac8b36203c29aa36e8c9777fc92882b7d064 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 18 Feb 2021 00:11:58 +0100 Subject: [PATCH 03/14] Fixed a crash when handling incorrect group shared fields --- samples/ComputeSharp.Sample.Shared/Program.cs | 5 +---- .../IComputeShaderSourceGenerator.cs | 20 +++++++++---------- .../Mappings/HlslKnownTypes.cs | 2 +- 3 files changed, 12 insertions(+), 15 deletions(-) diff --git a/samples/ComputeSharp.Sample.Shared/Program.cs b/samples/ComputeSharp.Sample.Shared/Program.cs index a4e38ca1..ee01f2a1 100644 --- a/samples/ComputeSharp.Sample.Shared/Program.cs +++ b/samples/ComputeSharp.Sample.Shared/Program.cs @@ -21,7 +21,7 @@ namespace ComputeSharp.Sample using ReadWriteBuffer gpuBuffer = Gpu.Default.AllocateReadWriteBuffer(array); // Run the shader - Gpu.Default.For(100, new MainKernel()); + Gpu.Default.For(100, new MainKernel(gpuBuffer)); // Print the initial matrix PrintMatrix(array, width, height, "BEFORE"); @@ -41,9 +41,6 @@ namespace ComputeSharp.Sample { public readonly ReadWriteBuffer buffer; - [GroupShared] - public static string[] Foo; - /// public void Execute() { diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index aba966b1..db8e5ccd 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -95,6 +95,8 @@ namespace ComputeSharp.SourceGenerators { foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { + if (fieldSymbol.IsStatic) continue; + // Captured fields must be named type symbols if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol) { @@ -106,15 +108,6 @@ namespace ComputeSharp.SourceGenerators continue; } - if (fieldSymbol.IsStatic) continue; - - string typeName = HlslKnownTypes.GetMappedName(typeSymbol); - - _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); - - // Yield back the current mapping for the name (if the name used a reserved keyword) - yield return new[] { fieldSymbol.Name, mapping ?? fieldSymbol.Name, typeName }; - // Track the type of items in the current buffer if (HlslKnownTypes.IsTypedResourceType(typeSymbol.GetFullMetadataName()) && typeSymbol.TypeArguments.Length == 1) @@ -129,6 +122,13 @@ namespace ComputeSharp.SourceGenerators fieldSymbol.Locations.FirstOrDefault(), structDeclarationSymbol, fieldSymbol.Name, typeSymbol)); } + + string typeName = HlslKnownTypes.GetMappedName(typeSymbol); + + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); + + // Yield back the current mapping for the name (if the name used a reserved keyword) + yield return new[] { fieldSymbol.Name, mapping ?? fieldSymbol.Name, typeName }; } } @@ -163,7 +163,7 @@ namespace ComputeSharp.SourceGenerators continue; } - if (typeSymbol.ElementType.IsUnmanagedType) + if (!typeSymbol.ElementType.IsUnmanagedType) { context.ReportDiagnostic(Diagnostic.Create( DiagnosticDescriptors.InvalidGroupSharedFieldElementType, diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs index c6716afd..17e9e6bb 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -195,7 +195,7 @@ namespace ComputeSharp.SourceGenerators.Mappings { if (KnownTypes.ContainsKey(type.GetFullMetadataName())) return; - customTypes.Add(type); + if (!customTypes.Add(type)) return; foreach (var field in type.GetMembers().OfType()) { From 707f0be5c4f33615a9eea147d1c2a8465da7785a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 18 Feb 2021 00:18:27 +0100 Subject: [PATCH 04/14] Added error for non static group shared buffer --- .../AnalyzerReleases.Unshipped.md | 3 ++- .../Diagnostics/DiagnosticDescriptors.cs | 18 +++++++++++++++++- .../IComputeShaderSourceGenerator.cs | 15 +++++++++++++++ 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md index bb77ae76..f42b3e64 100644 --- a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md +++ b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md @@ -7,4 +7,5 @@ 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) \ No newline at end of file +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 diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index e54e2496..0468bcb3 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -47,12 +47,28 @@ namespace ComputeSharp.SourceGenerators.Diagnostics /// public static DiagnosticDescriptor InvalidGroupSharedFieldElementType { get; } = new( id: "CMPS0003", - title: "Invalid group shared field type", + title: "Invalid group shared field element type", messageFormat: "The compute shader of type {0} contains a group shared field \"{1}\" of an invalid type {2} (it must be a primitive or unmanaged type)", category: typeof(IComputeShader).FullName, defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A group shared field element must be of a primitive or unmanaged type.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// 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.". + /// + /// + 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.", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A group shared field must be static.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } } diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index db8e5ccd..fa64fbf7 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -97,6 +97,19 @@ namespace ComputeSharp.SourceGenerators { if (fieldSymbol.IsStatic) continue; + AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); + + // Group shared fields must be static + if (attribute is not null) + { + context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.InvalidGroupSharedFieldDeclaration, + fieldSymbol.Locations.FirstOrDefault(), + structDeclarationSymbol, fieldSymbol.Name)); + + continue; + } + // Captured fields must be named type symbols if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol) { @@ -121,6 +134,8 @@ namespace ComputeSharp.SourceGenerators DiagnosticDescriptors.InvalidShaderField, fieldSymbol.Locations.FirstOrDefault(), structDeclarationSymbol, fieldSymbol.Name, typeSymbol)); + + continue; } string typeName = HlslKnownTypes.GetMappedName(typeSymbol); From 103f3abbe13c5a230ee2ac037257f28a56e19ff1 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 18 Feb 2021 00:37:55 +0100 Subject: [PATCH 05/14] Fixed build errors in the unit test projects --- .../ComputeSharp.SourceGenerators.csproj | 2 +- .../IComputeShaderSourceGenerator.cs | 9 ++++++--- .../Mappings/HlslKnownTypes.cs | 17 +++++++++++++++++ ...harp.Tests.Internals.SourceGenerators.csproj | 2 +- 4 files changed, 25 insertions(+), 5 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index 94eb7ab6..31003ac9 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -48,7 +48,7 @@ - + diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index fa64fbf7..b690a243 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -121,13 +121,16 @@ namespace ComputeSharp.SourceGenerators continue; } + string metadataName = typeSymbol.GetFullMetadataName(); + // Track the type of items in the current buffer - if (HlslKnownTypes.IsTypedResourceType(typeSymbol.GetFullMetadataName()) && - typeSymbol.TypeArguments.Length == 1) + if (HlslKnownTypes.IsStructuredBufferType(metadataName)) { types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]); } - else if (!typeSymbol.IsUnmanagedType) + else if (!HlslKnownTypes.IsTypedResourceType(metadataName) && + !typeSymbol.IsUnmanagedType && + typeSymbol.TypeKind != TypeKind.Delegate) { // Shaders can only capture valid HLSL resource types or unmanaged types context.ReportDiagnostic(Diagnostic.Create( diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs index 17e9e6bb..79dc5bb3 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -66,6 +66,23 @@ namespace ComputeSharp.SourceGenerators.Mappings typeof(WarpIds) }; + /// + /// Checks whether or not a given type name matches a structured buffer type. + /// + /// The input type name to check. + /// Whether or not represents a structured buffer type. + public static bool IsStructuredBufferType(string typeName) + { + switch (typeName) + { + case "ComputeSharp.ConstantBuffer`1": + case "ComputeSharp.ReadOnlyBuffer`1": + case "ComputeSharp.ReadWriteBuffer`1": + return true; + default: return false; + }; + } + /// /// Checks whether or not a given type name matches a typed resource type. /// diff --git a/tests/ComputeSharp.Tests.Internals.SourceGenerators/ComputeSharp.Tests.Internals.SourceGenerators.csproj b/tests/ComputeSharp.Tests.Internals.SourceGenerators/ComputeSharp.Tests.Internals.SourceGenerators.csproj index b0e8280b..dafba86a 100644 --- a/tests/ComputeSharp.Tests.Internals.SourceGenerators/ComputeSharp.Tests.Internals.SourceGenerators.csproj +++ b/tests/ComputeSharp.Tests.Internals.SourceGenerators/ComputeSharp.Tests.Internals.SourceGenerators.csproj @@ -9,7 +9,7 @@ - + From 74f60ad5c2eafd297e80e4ec56ee136a4fad82ae Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 18 Feb 2021 00:48:41 +0100 Subject: [PATCH 06/14] Added error for shaders with no resources --- .../Diagnostics/DiagnosticDescriptors.cs | 16 ++++++++++++ .../IComputeShaderSourceGenerator.cs | 25 +++++++++++++++---- 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 0468bcb3..48acd529 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -70,5 +70,21 @@ namespace ComputeSharp.SourceGenerators.Diagnostics isEnabledByDefault: true, description: "A group shared field must be static.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a shader with no resources. + /// + /// 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.", + 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"); } } diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index b690a243..bf54077a 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -93,6 +93,8 @@ namespace ComputeSharp.SourceGenerators INamedTypeSymbol structDeclarationSymbol, ICollection types) { + bool hlslResourceFound = false; + foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { if (fieldSymbol.IsStatic) continue; @@ -123,13 +125,18 @@ namespace ComputeSharp.SourceGenerators string metadataName = typeSymbol.GetFullMetadataName(); - // Track the type of items in the current buffer - if (HlslKnownTypes.IsStructuredBufferType(metadataName)) + // Allowed fields must be either resources, unmanaged values or delegates + if (HlslKnownTypes.IsTypedResourceType(metadataName)) { - types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]); + hlslResourceFound = true; + + // Track the type of items in the current buffer + if (HlslKnownTypes.IsStructuredBufferType(metadataName)) + { + types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]); + } } - else if (!HlslKnownTypes.IsTypedResourceType(metadataName) && - !typeSymbol.IsUnmanagedType && + else if (!typeSymbol.IsUnmanagedType && typeSymbol.TypeKind != TypeKind.Delegate) { // Shaders can only capture valid HLSL resource types or unmanaged types @@ -148,6 +155,14 @@ namespace ComputeSharp.SourceGenerators // Yield back the current mapping for the name (if the name used a reserved keyword) yield return new[] { fieldSymbol.Name, mapping ?? fieldSymbol.Name, typeName }; } + + if (!hlslResourceFound) + { + context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.MissingShaderResources, + structDeclarationSymbol.Locations.FirstOrDefault(), + structDeclarationSymbol)); + } } /// From 2cb775e51addea3775eaae4386fbec8d7d93caaf Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 18 Feb 2021 01:44:06 +0100 Subject: [PATCH 07/14] Downgraded Roslyn package --- .../ComputeSharp.SourceGenerators.csproj | 2 +- .../ComputeSharp.Tests.Internals.SourceGenerators.csproj | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index 31003ac9..b968ac10 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -47,7 +47,7 @@ - + diff --git a/tests/ComputeSharp.Tests.Internals.SourceGenerators/ComputeSharp.Tests.Internals.SourceGenerators.csproj b/tests/ComputeSharp.Tests.Internals.SourceGenerators/ComputeSharp.Tests.Internals.SourceGenerators.csproj index dafba86a..a41e2484 100644 --- a/tests/ComputeSharp.Tests.Internals.SourceGenerators/ComputeSharp.Tests.Internals.SourceGenerators.csproj +++ b/tests/ComputeSharp.Tests.Internals.SourceGenerators/ComputeSharp.Tests.Internals.SourceGenerators.csproj @@ -1,4 +1,4 @@ - + net5.0 @@ -9,7 +9,7 @@ - + From 0200e867bb39577c17f1ede2dcd96c0db7fac816 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 18 Feb 2021 03:20:12 +0100 Subject: [PATCH 08/14] 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(); From 922b65668c41b188764f5c2cdbdc7cdf64a1ce7e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 18 Feb 2021 14:08:56 +0100 Subject: [PATCH 09/14] Added more diagnostic errors to source generators --- .../AnalyzerReleases.Unshipped.md | 23 +- .../Diagnostics/DiagnosticDescriptors.cs | 276 ++++++++++++++++++ .../SyntaxRewriters/ShaderSourceRewriter.cs | 242 +++++++++++++++ 3 files changed, 540 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md index fa8b86cd..f9fd1d07 100644 --- a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md +++ b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md @@ -13,4 +13,25 @@ CMPS0005 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, 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 +CMPS0009 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0010 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0011 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0012 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0013 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0014 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0015 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0016 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0017 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0018 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0019 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0020 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0021 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0022 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0023 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0024 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0025 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0026 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0027 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0028 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0029 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0030 | 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 676b4f4c..d5447612 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -150,5 +150,281 @@ namespace ComputeSharp.SourceGenerators.Diagnostics isEnabledByDefault: true, description: "The WarpIds type can only be used within the main body of a compute shader.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an invalid object creation expression. + /// + /// Format: "The type {0} cannot be created in a compute shader". + /// + /// + public static DiagnosticDescriptor InvalidObjectCreationExpression { get; } = new( + id: "CMPS0010", + title: "Invalid object creation expression", + messageFormat: "The type {0} cannot be created in a compute shader (only unmanaged types are supported)", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "Only unmanaged value type objects can be created in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an anonymous object creation expression. + /// + public static DiagnosticDescriptor AnonymousObjectCreationExpression { get; } = new( + id: "CMPS0011", + title: "Anonymous object creation expression", + messageFormat: "An anonymous object cannot be created in a compute shader", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "An anonymous object cannot be created in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an async modifier on a method or function. + /// + public static DiagnosticDescriptor AsyncModifierOnMethodOrFunction { get; } = new( + id: "CMPS0012", + title: "Async modifier on method or function", + messageFormat: "The async modifier cannot be used in methods or functions used in a compute shader", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "The async modifier cannot be used in methods or functions used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an await expression. + /// + public static DiagnosticDescriptor AwaitExpression { get; } = new( + id: "CMPS0013", + title: "Await expression", + messageFormat: "The await expression cannot be used in a compute shader", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "The await expression cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a checked expression. + /// + public static DiagnosticDescriptor CheckedExpression { get; } = new( + id: "CMPS0014", + title: "Checked expression", + messageFormat: "A checked expression cannot be used in a compute shader", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A checked expression cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a checked statement. + /// + public static DiagnosticDescriptor CheckedStatement { get; } = new( + id: "CMPS0015", + title: "Checked statement", + messageFormat: "A checked statement cannot be used in a compute shader", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A checked statement cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a fixed statement. + /// + public static DiagnosticDescriptor FixedStatement { get; } = new( + id: "CMPS0016", + title: "Fixed statement", + messageFormat: "A fixed statement cannot be used in a compute shader", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A fixed statement cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a foreach statement. + /// + public static DiagnosticDescriptor ForEachStatement { get; } = new( + id: "CMPS0017", + title: "Foreach statement", + messageFormat: "A foreach statement cannot be used in a compute shader", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A foreach statement cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a lock statement. + /// + public static DiagnosticDescriptor LockStatement { get; } = new( + id: "CMPS0018", + title: "Foreach statement", + messageFormat: "A lock statement cannot be used in a compute shader", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A lock statement cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a query statement. + /// + public static DiagnosticDescriptor QueryExpression { get; } = new( + id: "CMPS0019", + title: "Foreach statement", + messageFormat: "A LINQ query expression cannot be used in a compute shader", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A LINQ query expression cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a range expression. + /// + public static DiagnosticDescriptor RangeExpression { get; } = new( + id: "CMPS0020", + title: "Range expression", + messageFormat: "A range expression cannot be used in a compute shader", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A range expression cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a recursive pattern. + /// + public static DiagnosticDescriptor RecursivePattern { get; } = new( + id: "CMPS0021", + title: "Recursive pattern", + messageFormat: "A recursive pattern cannot be used in a compute shader", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A recursive pattern cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a ref type. + /// + public static DiagnosticDescriptor RefType { get; } = new( + id: "CMPS0022", + title: "Ref type", + messageFormat: "A compute shader cannot have a ref type declaration", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A compute shader cannot have a ref type declaration.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a relational pattern. + /// + public static DiagnosticDescriptor RelationalPattern { get; } = new( + id: "CMPS0023", + title: "Relational pattern", + messageFormat: "A relational pattern cannot be used in a compute shader", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A relational pattern cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a sizeof expression. + /// + public static DiagnosticDescriptor SizeOfExpression { get; } = new( + id: "CMPS0024", + title: "Sizeof expression", + messageFormat: "A sizeof expression cannot be used in a compute shader", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A sizeof expression cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a stackalloc expression. + /// + public static DiagnosticDescriptor StackAllocArrayCreationExpression { get; } = new( + id: "CMPS0025", + title: "Stackalloc expression", + messageFormat: "A stackalloc expression cannot be used in a compute shader", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A stackalloc expression cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a throw expression or statement. + /// + public static DiagnosticDescriptor ThrowExpressionOrStatement { get; } = new( + id: "CMPS0026", + title: "Throw expression or statement", + messageFormat: "Throw expressions and statements cannot be used in a compute shader", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "Throw expressions and statements cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a try statement. + /// + public static DiagnosticDescriptor TryStatement { get; } = new( + id: "CMPS0027", + title: "Try statement", + messageFormat: "A try statement cannot be used in a compute shader", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A try statement cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a tuple type. + /// + public static DiagnosticDescriptor TupleType { get; } = new( + id: "CMPS0028", + title: "Tuple type", + messageFormat: "A compute shader cannot have a tuple type declaration", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A compute shader cannot have a tuple type declaration.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a using statement or declaration. + /// + public static DiagnosticDescriptor UsingStatementOrDeclaration { get; } = new( + id: "CMPS0029", + title: "Using statement or declaration", + messageFormat: "Using statements and declarations cannot be used in a compute shader", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "Using statements and declarations cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a yield statement. + /// + public static DiagnosticDescriptor YieldStatement { get; } = new( + id: "CMPS0030", + title: "Yield statement", + messageFormat: "A yield statement cannot be used in a compute shader", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A yield statement cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } } diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 4e17c631..9a52a64a 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -154,6 +154,14 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters var updatedNode = (MethodDeclarationSyntax?)base.Visit(node); + + if (node!.Modifiers.Contains(Token(SyntaxKind.AsyncKeyword))) + { + this.context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.AsyncModifierOnMethodOrFunction, + node.GetLocation())); + } + if (updatedNode is not null) { var implicitBlock = Block(this.implicitVariables.Select(static v => LocalDeclarationStatement(v)).ToArray()); @@ -201,6 +209,13 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters { var updatedNode = ((LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node)!); + if (this.semanticModel.GetOperation(node) is IOperation { Kind: OperationKind.UsingDeclaration }) + { + this.context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.UsingStatementOrDeclaration, + node.GetLocation())); + } + return updatedNode.ReplaceAndTrackType(updatedNode.Declaration.Type, node.Declaration.Type, this.semanticModel, this.discoveredTypes); } @@ -209,6 +224,14 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters { var updatedNode = (ObjectCreationExpressionSyntax)base.VisitObjectCreationExpression(node)!; + if (this.semanticModel.GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type) + { + this.context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.InvalidObjectCreationExpression, + node.GetLocation(), + type)); + } + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node, this.semanticModel, this.discoveredTypes); // New objects use the default HLSL cast syntax, eg. (float4)0 @@ -220,6 +243,18 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters return InvocationExpression(updatedNode.Type, updatedNode.ArgumentList); } + /// + public override SyntaxNode? VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node) + { + var updatedNode = (AnonymousObjectCreationExpressionSyntax)base.VisitAnonymousObjectCreationExpression(node)!; + + this.context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.AnonymousObjectCreationExpression, + node.GetLocation())); + + return updatedNode; + } + /// public override SyntaxNode VisitImplicitObjectCreationExpression(ImplicitObjectCreationExpressionSyntax node) { @@ -318,6 +353,13 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters .WithAttributeLists(List()) .WithIdentifier(Identifier($"__{this.currentMethod!.Identifier.Text}__{node.Identifier.Text}")); + if (node.Modifiers.Contains(Token(SyntaxKind.AsyncKeyword))) + { + this.context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.AsyncModifierOnMethodOrFunction, + node.GetLocation())); + } + this.localFunctionDepth--; // HLSL doesn't support local functions, so we first process them as usual and then remove @@ -555,6 +597,206 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters return updatedNode; } + /// + public override SyntaxNode? VisitAwaitExpression(AwaitExpressionSyntax node) + { + this.context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.AwaitExpression, + node.GetLocation())); + + return base.VisitAwaitExpression(node); + } + + /// + public override SyntaxNode? VisitCheckedExpression(CheckedExpressionSyntax node) + { + this.context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.CheckedExpression, + node.GetLocation())); + + return base.VisitCheckedExpression(node); + } + + /// + public override SyntaxNode? VisitCheckedStatement(CheckedStatementSyntax node) + { + this.context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.CheckedStatement, + node.GetLocation())); + + return base.VisitCheckedStatement(node); + } + + /// + public override SyntaxNode? VisitFixedStatement(FixedStatementSyntax node) + { + this.context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.FixedStatement, + node.GetLocation())); + + return base.VisitFixedStatement(node); + } + + /// + public override SyntaxNode? VisitForEachStatement(ForEachStatementSyntax node) + { + this.context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.ForEachStatement, + node.GetLocation())); + + return base.VisitForEachStatement(node); + } + + /// + public override SyntaxNode? VisitForEachVariableStatement(ForEachVariableStatementSyntax node) + { + this.context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.ForEachStatement, + node.GetLocation())); + + return base.VisitForEachVariableStatement(node); + } + + /// + public override SyntaxNode? VisitLockStatement(LockStatementSyntax node) + { + this.context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.LockStatement, + node.GetLocation())); + + return base.VisitLockStatement(node); + } + + /// + public override SyntaxNode? VisitQueryExpression(QueryExpressionSyntax node) + { + this.context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.QueryExpression, + node.GetLocation())); + + return base.VisitQueryExpression(node); + } + + /// + public override SyntaxNode? VisitRangeExpression(RangeExpressionSyntax node) + { + this.context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.RangeExpression, + node.GetLocation())); + + return base.VisitRangeExpression(node); + } + + /// + public override SyntaxNode? VisitRecursivePattern(RecursivePatternSyntax node) + { + this.context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.RecursivePattern, + node.GetLocation())); + + return base.VisitRecursivePattern(node); + } + + /// + public override SyntaxNode? VisitRefType(RefTypeSyntax node) + { + this.context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.RefType, + node.GetLocation())); + + return base.VisitRefType(node); + } + + /// + public override SyntaxNode? VisitRelationalPattern(RelationalPatternSyntax node) + { + this.context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.RelationalPattern, + node.GetLocation())); + + return base.VisitRelationalPattern(node); + } + + /// + public override SyntaxNode? VisitSizeOfExpression(SizeOfExpressionSyntax node) + { + this.context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.SizeOfExpression, + node.GetLocation())); + + return base.VisitSizeOfExpression(node); + } + + /// + public override SyntaxNode? VisitStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node) + { + this.context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.StackAllocArrayCreationExpression, + node.GetLocation())); + + return base.VisitStackAllocArrayCreationExpression(node); + } + + /// + public override SyntaxNode? VisitThrowExpression(ThrowExpressionSyntax node) + { + this.context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.ThrowExpressionOrStatement, + node.GetLocation())); + + return base.VisitThrowExpression(node); + } + + /// + public override SyntaxNode? VisitThrowStatement(ThrowStatementSyntax node) + { + this.context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.ThrowExpressionOrStatement, + node.GetLocation())); + + return base.VisitThrowStatement(node); + } + + /// + public override SyntaxNode? VisitTryStatement(TryStatementSyntax node) + { + this.context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.TryStatement, + node.GetLocation())); + + return base.VisitTryStatement(node); + } + + /// + public override SyntaxNode? VisitTupleType(TupleTypeSyntax node) + { + this.context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.TupleType, + node.GetLocation())); + + return base.VisitTupleType(node); + } + + /// + public override SyntaxNode? VisitUsingStatement(UsingStatementSyntax node) + { + this.context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.UsingStatementOrDeclaration, + node.GetLocation())); + + return base.VisitUsingStatement(node); + } + + /// + public override SyntaxNode? VisitYieldStatement(YieldStatementSyntax node) + { + this.context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.YieldStatement, + node.GetLocation())); + + return base.VisitYieldStatement(node); + } + /// public override SyntaxToken VisitToken(SyntaxToken token) { From d55d5009c6cc2c81a8211f12dfa75f4fe463da1a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 18 Feb 2021 14:34:35 +0100 Subject: [PATCH 10/14] Added error for declarations of invalid type --- .../AnalyzerReleases.Unshipped.md | 3 ++- .../Diagnostics/DiagnosticDescriptors.cs | 16 ++++++++++++++++ .../SyntaxRewriters/ShaderSourceRewriter.cs | 18 ++++++++++++++++++ 3 files changed, 36 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md index f9fd1d07..a1d77353 100644 --- a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md +++ b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md @@ -34,4 +34,5 @@ CMPS0026 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, CMPS0027 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0028 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0029 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0030 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) \ No newline at end of file +CMPS0030 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0031 | 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 d5447612..1a60fbce 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -426,5 +426,21 @@ namespace ComputeSharp.SourceGenerators.Diagnostics isEnabledByDefault: true, description: "A yield statement cannot be used in a compute shader.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an invalid object declaration. + /// + /// Format: "A variable of type {0} cannot be declared in a compute shader". + /// + /// + public static DiagnosticDescriptor InvalidObjectDeclaration { get; } = new( + id: "CMPS0031", + title: "Invalid object declaration", + messageFormat: "A variable of type {0} cannot be declared in a compute shader (only unmanaged types are supported)", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "Only unmanaged value type objects can be declared in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } } diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 9a52a64a..06db18f5 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -787,6 +787,24 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters return base.VisitUsingStatement(node); } + /// + public override SyntaxNode? VisitVariableDeclarator(VariableDeclaratorSyntax node) + { + var updatedNode = (VariableDeclaratorSyntax)base.VisitVariableDeclarator(node)!; + + if (node.Initializer is null && + node.Parent is VariableDeclarationSyntax declaration && + this.semanticModel.GetTypeInfo(declaration.Type).Type is ITypeSymbol { IsUnmanagedType: false } type) + { + this.context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.InvalidObjectDeclaration, + node.GetLocation(), + type)); + } + + return updatedNode; + } + /// public override SyntaxNode? VisitYieldStatement(YieldStatementSyntax node) { From 5a2fcbf4180022a5a1d9a3fa3df2dca7e648b621 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 18 Feb 2021 15:27:12 +0100 Subject: [PATCH 11/14] Minor code refactoring --- .../Diagnostics/DiagnosticsExtensions.cs | 43 +++++++ .../IComputeShaderSourceGenerator.cs | 31 ++--- .../SyntaxRewriters/ShaderSourceRewriter.cs | 109 +++++------------- 3 files changed, 78 insertions(+), 105 deletions(-) create mode 100644 src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs new file mode 100644 index 00000000..e9509100 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs @@ -0,0 +1,43 @@ +using System.Linq; +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.SourceGenerators.Diagnostics +{ + /// + /// Extension methods for , specifically for reporting diagnostics. + /// + internal static class DiagnosticsExtensions + { + /// + /// Adds a new diagnostics to the current compilation. + /// + /// The instance currently in use. + /// The input for the diagnostics to create. + /// The source to attach the diagnostics to. + /// The optional arguments for the formatted message to include. + public static void ReportDiagnostic( + this GeneratorExecutionContext context, + DiagnosticDescriptor descriptor, + ISymbol symbol, + params object[] args) + { + context.ReportDiagnostic(Diagnostic.Create(descriptor, symbol.Locations.FirstOrDefault(), args)); + } + + /// + /// Adds a new diagnostics to the current compilation. + /// + /// The instance currently in use. + /// The input for the diagnostics to create. + /// The source to attach the diagnostics to. + /// The optional arguments for the formatted message to include. + public static void ReportDiagnostic( + this GeneratorExecutionContext context, + DiagnosticDescriptor descriptor, + SyntaxNode node, + params object[] args) + { + context.ReportDiagnostic(Diagnostic.Create(descriptor, node.GetLocation(), args)); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index 59eca030..4b5c1337 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -14,6 +14,7 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; using static ComputeSharp.SourceGenerators.Helpers.SyntaxFactoryHelper; +using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; #pragma warning disable CS0618 @@ -104,10 +105,7 @@ namespace ComputeSharp.SourceGenerators // Group shared fields must be static if (attribute is not null) { - context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.InvalidGroupSharedFieldDeclaration, - fieldSymbol.Locations.FirstOrDefault(), - structDeclarationSymbol, fieldSymbol.Name)); + context.ReportDiagnostic(InvalidGroupSharedFieldDeclaration, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name); continue; } @@ -115,10 +113,7 @@ namespace ComputeSharp.SourceGenerators // Captured fields must be named type symbols if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol) { - context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.InvalidShaderField, - fieldSymbol.Locations.FirstOrDefault(), - structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type)); + context.ReportDiagnostic(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); continue; } @@ -140,10 +135,7 @@ namespace ComputeSharp.SourceGenerators typeSymbol.TypeKind != TypeKind.Delegate) { // Shaders can only capture valid HLSL resource types or unmanaged types - context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.InvalidShaderField, - fieldSymbol.Locations.FirstOrDefault(), - structDeclarationSymbol, fieldSymbol.Name, typeSymbol)); + context.ReportDiagnostic(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, typeSymbol); continue; } @@ -158,10 +150,7 @@ namespace ComputeSharp.SourceGenerators if (!hlslResourceFound) { - context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.MissingShaderResources, - structDeclarationSymbol.Locations.FirstOrDefault(), - structDeclarationSymbol)); + context.ReportDiagnostic(MissingShaderResources, structDeclarationSymbol, structDeclarationSymbol); } } @@ -188,20 +177,14 @@ namespace ComputeSharp.SourceGenerators if (fieldSymbol.Type is not IArrayTypeSymbol typeSymbol) { - context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.InvalidGroupSharedFieldType, - fieldSymbol.Locations.FirstOrDefault(), - structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type)); + context.ReportDiagnostic(InvalidGroupSharedFieldType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); continue; } if (!typeSymbol.ElementType.IsUnmanagedType) { - context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.InvalidGroupSharedFieldElementType, - fieldSymbol.Locations.FirstOrDefault(), - structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type)); + context.ReportDiagnostic(InvalidGroupSharedFieldElementType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); continue; } diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 06db18f5..8815b3ac 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -10,6 +10,7 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Operations; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; +using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; namespace ComputeSharp.SourceGenerators.SyntaxRewriters { @@ -157,9 +158,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters if (node!.Modifiers.Contains(Token(SyntaxKind.AsyncKeyword))) { - this.context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.AsyncModifierOnMethodOrFunction, - node.GetLocation())); + this.context.ReportDiagnostic(AsyncModifierOnMethodOrFunction, node); } if (updatedNode is not null) @@ -211,9 +210,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters if (this.semanticModel.GetOperation(node) is IOperation { Kind: OperationKind.UsingDeclaration }) { - this.context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.UsingStatementOrDeclaration, - node.GetLocation())); + this.context.ReportDiagnostic(UsingStatementOrDeclaration, node); } return updatedNode.ReplaceAndTrackType(updatedNode.Declaration.Type, node.Declaration.Type, this.semanticModel, this.discoveredTypes); @@ -226,10 +223,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters if (this.semanticModel.GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type) { - this.context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.InvalidObjectCreationExpression, - node.GetLocation(), - type)); + this.context.ReportDiagnostic(InvalidObjectCreationExpression, node, type); } updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node, this.semanticModel, this.discoveredTypes); @@ -248,9 +242,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters { var updatedNode = (AnonymousObjectCreationExpressionSyntax)base.VisitAnonymousObjectCreationExpression(node)!; - this.context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.AnonymousObjectCreationExpression, - node.GetLocation())); + this.context.ReportDiagnostic(DiagnosticDescriptors.AnonymousObjectCreationExpression, node); return updatedNode; } @@ -355,9 +347,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters if (node.Modifiers.Contains(Token(SyntaxKind.AsyncKeyword))) { - this.context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.AsyncModifierOnMethodOrFunction, - node.GetLocation())); + this.context.ReportDiagnostic(AsyncModifierOnMethodOrFunction, node); } this.localFunctionDepth--; @@ -417,7 +407,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters if (descriptor is not null) { - this.context.ReportDiagnostic(Diagnostic.Create(descriptor, node.GetLocation())); + this.context.ReportDiagnostic(descriptor, node); } } } @@ -600,9 +590,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// public override SyntaxNode? VisitAwaitExpression(AwaitExpressionSyntax node) { - this.context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.AwaitExpression, - node.GetLocation())); + this.context.ReportDiagnostic(DiagnosticDescriptors.AwaitExpression, node); return base.VisitAwaitExpression(node); } @@ -610,9 +598,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// public override SyntaxNode? VisitCheckedExpression(CheckedExpressionSyntax node) { - this.context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.CheckedExpression, - node.GetLocation())); + this.context.ReportDiagnostic(DiagnosticDescriptors.CheckedExpression, node); return base.VisitCheckedExpression(node); } @@ -620,9 +606,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// public override SyntaxNode? VisitCheckedStatement(CheckedStatementSyntax node) { - this.context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.CheckedStatement, - node.GetLocation())); + this.context.ReportDiagnostic(DiagnosticDescriptors.CheckedStatement, node); return base.VisitCheckedStatement(node); } @@ -630,9 +614,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// public override SyntaxNode? VisitFixedStatement(FixedStatementSyntax node) { - this.context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.FixedStatement, - node.GetLocation())); + this.context.ReportDiagnostic(DiagnosticDescriptors.FixedStatement, node); return base.VisitFixedStatement(node); } @@ -640,9 +622,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// public override SyntaxNode? VisitForEachStatement(ForEachStatementSyntax node) { - this.context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.ForEachStatement, - node.GetLocation())); + this.context.ReportDiagnostic(DiagnosticDescriptors.ForEachStatement, node); return base.VisitForEachStatement(node); } @@ -650,9 +630,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// public override SyntaxNode? VisitForEachVariableStatement(ForEachVariableStatementSyntax node) { - this.context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.ForEachStatement, - node.GetLocation())); + this.context.ReportDiagnostic(DiagnosticDescriptors.ForEachStatement, node); return base.VisitForEachVariableStatement(node); } @@ -660,9 +638,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// public override SyntaxNode? VisitLockStatement(LockStatementSyntax node) { - this.context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.LockStatement, - node.GetLocation())); + this.context.ReportDiagnostic(DiagnosticDescriptors.LockStatement, node); return base.VisitLockStatement(node); } @@ -670,9 +646,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// public override SyntaxNode? VisitQueryExpression(QueryExpressionSyntax node) { - this.context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.QueryExpression, - node.GetLocation())); + this.context.ReportDiagnostic(DiagnosticDescriptors.QueryExpression, node); return base.VisitQueryExpression(node); } @@ -680,9 +654,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// public override SyntaxNode? VisitRangeExpression(RangeExpressionSyntax node) { - this.context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.RangeExpression, - node.GetLocation())); + this.context.ReportDiagnostic(DiagnosticDescriptors.RangeExpression, node); return base.VisitRangeExpression(node); } @@ -690,9 +662,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// public override SyntaxNode? VisitRecursivePattern(RecursivePatternSyntax node) { - this.context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.RecursivePattern, - node.GetLocation())); + this.context.ReportDiagnostic(DiagnosticDescriptors.RecursivePattern, node); return base.VisitRecursivePattern(node); } @@ -700,9 +670,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// public override SyntaxNode? VisitRefType(RefTypeSyntax node) { - this.context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.RefType, - node.GetLocation())); + this.context.ReportDiagnostic(DiagnosticDescriptors.RefType, node); return base.VisitRefType(node); } @@ -710,9 +678,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// public override SyntaxNode? VisitRelationalPattern(RelationalPatternSyntax node) { - this.context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.RelationalPattern, - node.GetLocation())); + this.context.ReportDiagnostic(DiagnosticDescriptors.RelationalPattern, node); return base.VisitRelationalPattern(node); } @@ -720,9 +686,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// public override SyntaxNode? VisitSizeOfExpression(SizeOfExpressionSyntax node) { - this.context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.SizeOfExpression, - node.GetLocation())); + this.context.ReportDiagnostic(DiagnosticDescriptors.SizeOfExpression, node); return base.VisitSizeOfExpression(node); } @@ -730,9 +694,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// public override SyntaxNode? VisitStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node) { - this.context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.StackAllocArrayCreationExpression, - node.GetLocation())); + this.context.ReportDiagnostic(DiagnosticDescriptors.StackAllocArrayCreationExpression, node); return base.VisitStackAllocArrayCreationExpression(node); } @@ -740,9 +702,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// public override SyntaxNode? VisitThrowExpression(ThrowExpressionSyntax node) { - this.context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.ThrowExpressionOrStatement, - node.GetLocation())); + this.context.ReportDiagnostic(DiagnosticDescriptors.ThrowExpressionOrStatement, node); return base.VisitThrowExpression(node); } @@ -750,9 +710,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// public override SyntaxNode? VisitThrowStatement(ThrowStatementSyntax node) { - this.context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.ThrowExpressionOrStatement, - node.GetLocation())); + this.context.ReportDiagnostic(DiagnosticDescriptors.ThrowExpressionOrStatement, node); return base.VisitThrowStatement(node); } @@ -760,9 +718,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// public override SyntaxNode? VisitTryStatement(TryStatementSyntax node) { - this.context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.TryStatement, - node.GetLocation())); + this.context.ReportDiagnostic(DiagnosticDescriptors.TryStatement, node); return base.VisitTryStatement(node); } @@ -770,9 +726,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// public override SyntaxNode? VisitTupleType(TupleTypeSyntax node) { - this.context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.TupleType, - node.GetLocation())); + this.context.ReportDiagnostic(DiagnosticDescriptors.TupleType, node); return base.VisitTupleType(node); } @@ -780,9 +734,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// public override SyntaxNode? VisitUsingStatement(UsingStatementSyntax node) { - this.context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.UsingStatementOrDeclaration, - node.GetLocation())); + this.context.ReportDiagnostic(DiagnosticDescriptors.UsingStatementOrDeclaration, node); return base.VisitUsingStatement(node); } @@ -796,10 +748,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters node.Parent is VariableDeclarationSyntax declaration && this.semanticModel.GetTypeInfo(declaration.Type).Type is ITypeSymbol { IsUnmanagedType: false } type) { - this.context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.InvalidObjectDeclaration, - node.GetLocation(), - type)); + this.context.ReportDiagnostic(InvalidObjectDeclaration, node, type); } return updatedNode; @@ -808,9 +757,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// public override SyntaxNode? VisitYieldStatement(YieldStatementSyntax node) { - this.context.ReportDiagnostic(Diagnostic.Create( - DiagnosticDescriptors.YieldStatement, - node.GetLocation())); + this.context.ReportDiagnostic(DiagnosticDescriptors.YieldStatement, node); return base.VisitYieldStatement(node); } From 944ea0e6a06e2ee217394a7499ab96e64012d12d Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 18 Feb 2021 20:03:48 +0100 Subject: [PATCH 12/14] Added some more errorsand unit test pass --- .../AnalyzerReleases.Unshipped.md | 6 +- .../Diagnostics/DiagnosticDescriptors.cs | 52 + .../Extensions/SyntaxNodeExtensions.cs | 15 +- .../IComputeShaderSourceGenerator.cs | 2 - .../SyntaxRewriters/ShaderSourceRewriter.cs | 44 +- ...ts.cs => AutoConstructorGeneratorTests.cs} | 6 +- .../DiagnosticsTests.cs | 1104 +++++++++++++++++ 7 files changed, 1219 insertions(+), 10 deletions(-) rename tests/ComputeSharp.Tests.Internals.SourceGenerators/{SourceGeneratorTests.cs => AutoConstructorGeneratorTests.cs} (96%) create mode 100644 tests/ComputeSharp.Tests.Internals.SourceGenerators/DiagnosticsTests.cs diff --git a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md index a1d77353..c5fc51d1 100644 --- a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md +++ b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md @@ -35,4 +35,8 @@ CMPS0027 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, CMPS0028 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0029 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0030 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0031 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) \ No newline at end of file +CMPS0031 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0032 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0033 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0034 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0035 | 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 1a60fbce..119f197f 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -442,5 +442,57 @@ namespace ComputeSharp.SourceGenerators.Diagnostics isEnabledByDefault: true, description: "Only unmanaged value type objects can be declared in a compute shader.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a pointer type. + /// + public static DiagnosticDescriptor PointerType { get; } = new( + id: "CMPS0032", + title: "Pointer type", + messageFormat: "A compute shader cannot have a pointer type declaration", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A compute shader cannot have a pointer type declaration.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a function pointer type. + /// + public static DiagnosticDescriptor FunctionPointer { get; } = new( + id: "CMPS0033", + title: "Function pointer type", + messageFormat: "A compute shader cannot have a function pointer type declaration", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A compute shader cannot have a function pointer type declaration.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an unsafe statement. + /// + public static DiagnosticDescriptor UnsafeStatement { get; } = new( + id: "CMPS0034", + title: "Unsafe statement", + messageFormat: "A compute shader cannot have an unsafe statement", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A compute shader cannot have an unsafe statement.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an unsafe modifier on a method or function. + /// + public static DiagnosticDescriptor UnsafeModifierOnMethodOrFunction { get; } = new( + id: "CMPS0035", + title: "Unsafe modifier on method or function", + messageFormat: "The unsafe modifier cannot be used in methods or functions used in a compute shader", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "The unsafe modifier cannot be used in methods or functions used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } } diff --git a/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs index 77831764..86418169 100644 --- a/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs +++ b/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs @@ -44,7 +44,20 @@ namespace ComputeSharp.SourceGenerators.Extensions public static TRoot ReplaceAndTrackType(this TRoot node, TypeSyntax targetType, SyntaxNode sourceType, SemanticModel semanticModel, ICollection discoveredTypes) where TRoot : SyntaxNode { - ITypeSymbol typeSymbol = semanticModel.GetTypeInfo(sourceType).Type!; + // Skip immediately for function pointers + if (sourceType is FunctionPointerTypeSyntax) + { + return node.ReplaceNode(targetType, ParseTypeName("void*")); + } + + // Handle the various possible type kinds + ITypeSymbol typeSymbol = sourceType switch + { + RefTypeSyntax refType => semanticModel.GetTypeInfo(refType.Type).Type!, + PointerTypeSyntax pointerType => semanticModel.GetTypeInfo(pointerType.ElementType).Type!, + _ => semanticModel.GetTypeInfo(sourceType).Type! + }; + string typeName = typeSymbol.ToDisplayString(ISymbolExtensions.FullyQualifiedWithoutGlobalFormat); discoveredTypes.Add((INamedTypeSymbol)typeSymbol); diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index 4b5c1337..c7e4f57f 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -106,8 +106,6 @@ namespace ComputeSharp.SourceGenerators if (attribute is not null) { context.ReportDiagnostic(InvalidGroupSharedFieldDeclaration, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name); - - continue; } // Captured fields must be named type symbols diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 8815b3ac..75870fd3 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -155,12 +155,16 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters var updatedNode = (MethodDeclarationSyntax?)base.Visit(node); - - if (node!.Modifiers.Contains(Token(SyntaxKind.AsyncKeyword))) + if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword))) { this.context.ReportDiagnostic(AsyncModifierOnMethodOrFunction, node); } + if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword))) + { + this.context.ReportDiagnostic(UnsafeModifierOnMethodOrFunction, node); + } + if (updatedNode is not null) { var implicitBlock = Block(this.implicitVariables.Select(static v => LocalDeclarationStatement(v)).ToArray()); @@ -252,6 +256,11 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters { var updatedNode = (ImplicitObjectCreationExpressionSyntax)base.VisitImplicitObjectCreationExpression(node)!; + if (this.semanticModel.GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type) + { + this.context.ReportDiagnostic(InvalidObjectCreationExpression, node, type); + } + TypeSyntax explicitType = IdentifierName("").ReplaceAndTrackType(node, this.semanticModel, this.discoveredTypes); // Mutate the syntax like with explicit object creation expressions @@ -345,11 +354,16 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters .WithAttributeLists(List()) .WithIdentifier(Identifier($"__{this.currentMethod!.Identifier.Text}__{node.Identifier.Text}")); - if (node.Modifiers.Contains(Token(SyntaxKind.AsyncKeyword))) + if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword))) { this.context.ReportDiagnostic(AsyncModifierOnMethodOrFunction, node); } + if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword))) + { + this.context.ReportDiagnostic(UnsafeModifierOnMethodOrFunction, node); + } + this.localFunctionDepth--; // HLSL doesn't support local functions, so we first process them as usual and then remove @@ -762,6 +776,30 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters return base.VisitYieldStatement(node); } + /// + public override SyntaxNode? VisitFunctionPointerType(FunctionPointerTypeSyntax node) + { + this.context.ReportDiagnostic(DiagnosticDescriptors.FunctionPointer, node); + + return base.VisitFunctionPointerType(node); + } + + /// + public override SyntaxNode? VisitPointerType(PointerTypeSyntax node) + { + this.context.ReportDiagnostic(DiagnosticDescriptors.PointerType, node); + + return base.VisitPointerType(node); + } + + /// + public override SyntaxNode? VisitUnsafeStatement(UnsafeStatementSyntax node) + { + this.context.ReportDiagnostic(DiagnosticDescriptors.UnsafeStatement, node); + + return base.VisitUnsafeStatement(node); + } + /// public override SyntaxToken VisitToken(SyntaxToken token) { diff --git a/tests/ComputeSharp.Tests.Internals.SourceGenerators/SourceGeneratorTests.cs b/tests/ComputeSharp.Tests.Internals.SourceGenerators/AutoConstructorGeneratorTests.cs similarity index 96% rename from tests/ComputeSharp.Tests.Internals.SourceGenerators/SourceGeneratorTests.cs rename to tests/ComputeSharp.Tests.Internals.SourceGenerators/AutoConstructorGeneratorTests.cs index 82a2a0a1..487b41c1 100644 --- a/tests/ComputeSharp.Tests.Internals.SourceGenerators/SourceGeneratorTests.cs +++ b/tests/ComputeSharp.Tests.Internals.SourceGenerators/AutoConstructorGeneratorTests.cs @@ -10,11 +10,11 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ComputeSharp.Tests.Internals { [TestClass] - [TestCategory("SourceGenerator")] - public class SourceGeneratorTests + [TestCategory("AutoConstructorGenerator")] + public class AutoConstructorGeneratorTests { [TestMethod] - public void SequentialEnum() + public void GenerateConstructor() { string source = @" using System.Numerics; diff --git a/tests/ComputeSharp.Tests.Internals.SourceGenerators/DiagnosticsTests.cs b/tests/ComputeSharp.Tests.Internals.SourceGenerators/DiagnosticsTests.cs new file mode 100644 index 00000000..0004739d --- /dev/null +++ b/tests/ComputeSharp.Tests.Internals.SourceGenerators/DiagnosticsTests.cs @@ -0,0 +1,1104 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using ComputeSharp.SourceGenerators; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.Tests.Internals +{ + [TestClass] + [TestCategory("Diagnostics")] + public class DiagnosticsTests + { + [TestMethod] + public void InvalidShaderField() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + public string text; + + public void Execute() { } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0001"); + } + + [TestMethod] + public void InvalidGroupSharedFieldType() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + public class GroupSharedAttribute : Attribute { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + [GroupShared] + public static string text; + + public void Execute() { } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0002"); + } + + [TestMethod] + public void InvalidGroupSharedFieldElementType() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + public class GroupSharedAttribute : Attribute { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + [GroupShared] + public static string[] text; + + public void Execute() { } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0003"); + } + + [TestMethod] + public void InvalidGroupSharedFieldDeclaration() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + public class GroupSharedAttribute : Attribute { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + [GroupShared] + public ReadWriteBuffer buffer; + + public void Execute() { } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0004"); + } + + [TestMethod] + public void MissingShaderResources() + { + string source = @" + using ComputeSharp; + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public void Execute() { } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0005"); + } + + [TestMethod] + [DataRow(nameof(ThreadIds), "CMPS0006")] + [DataRow(nameof(GroupIds), "CMPS0007")] + [DataRow(nameof(GroupSize), "CMPS0008")] + [DataRow(nameof(WarpIds), "CMPS0009")] + public void InvalidDispatchInfoUsage_LocalFunction(string typeName, string diagnosticsId) + { + string source = $@" + using ComputeSharp; + + namespace ComputeSharp + {{ + public class ReadWriteBuffer {{ }} + public static class {typeName} {{ public static int X => 0; }} + }} + + namespace MyFancyApp.Sample + {{ + public struct MyShader : IComputeShader + {{ + public ReadWriteBuffer buffer; + + public void Execute() + {{ + static int Fail() => {typeName}.X; + + Fail(); + }} + }} + }}"; + + VerifyGeneratedDiagnostics(source, diagnosticsId); + } + + [TestMethod] + [DataRow(nameof(ThreadIds), "CMPS0006")] + [DataRow(nameof(GroupIds), "CMPS0007")] + [DataRow(nameof(GroupSize), "CMPS0008")] + [DataRow(nameof(WarpIds), "CMPS0009")] + public void InvalidDispatchInfoUsage_StaticMethod(string typeName, string diagnosticsId) + { + string source = $@" + using ComputeSharp; + + namespace ComputeSharp + {{ + public class ReadWriteBuffer {{ }} + public static class {typeName} {{ public static int X => 0; }} + }} + + namespace MyFancyApp.Sample + {{ + public struct MyShader : IComputeShader + {{ + public ReadWriteBuffer buffer; + + public static int Fail() => {typeName}.X; + + public void Execute() => Fail(); + }} + }}"; + + VerifyGeneratedDiagnostics(source, diagnosticsId); + } + + [TestMethod] + public void InvalidObjectCreationExpression_Explicit() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public void Execute() + { + object o = new object(); + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0010"); + } + + [TestMethod] + public void InvalidObjectCreationExpression_Implicit() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public void Execute() + { + object o = new(); + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0010"); + } + + [TestMethod] + public void AnonymousObjectCreationExpression() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public void Execute() + { + var o = new { Age = 12 }; + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0011"); + } + + [TestMethod] + public void AsyncModifierOnMethodOrFunction_LocalFunction() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public void Execute() + { + static async void Fail() { } + + Fail(); + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0012"); + } + + [TestMethod] + public void AsyncModifierOnMethodOrFunction_StaticMethod() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public static async void Fail() { } + + public void Execute() => Fail(); + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0012"); + } + + [TestMethod] + public void AwaitExpression() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public async void Execute() + { + await null; + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0012", "CMPS0013"); + } + + [TestMethod] + [DataRow("checked")] + [DataRow("unchecked")] + public void CheckedExpression(string text) + { + string source = $@" + using ComputeSharp; + + namespace ComputeSharp + {{ + public class ReadWriteBuffer {{ }} + }} + + namespace MyFancyApp.Sample + {{ + public struct MyShader : IComputeShader + {{ + public ReadWriteBuffer buffer; + + public void Execute() + {{ + int a = {text}(1 + 1); + }} + }} + }}"; + + VerifyGeneratedDiagnostics(source, "CMPS0014"); + } + + [TestMethod] + [DataRow("checked")] + [DataRow("unchecked")] + public void CheckedStatement(string text) + { + string source = $@" + using ComputeSharp; + + namespace ComputeSharp + {{ + public class ReadWriteBuffer {{ }} + }} + + namespace MyFancyApp.Sample + {{ + public struct MyShader : IComputeShader + {{ + public ReadWriteBuffer buffer; + + public void Execute() + {{ + {text} + {{ + int a = 1 + 1; + }} + }} + }} + }}"; + + VerifyGeneratedDiagnostics(source, "CMPS0015"); + } + + [TestMethod] + public void FixedStatement() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer + { + public int[] Data; + } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public void Execute() + { + fixed (void* p = buffer.Data) + { + } + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0016", "CMPS0032"); + } + + [TestMethod] + public void ForEachStatement() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer + { + public int[] Data; + } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public void Execute() + { + foreach (int i in buffer.Data) + { + } + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0017"); + } + + [TestMethod] + public void LockStatement() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public void Execute() + { + lock (buffer) + { + } + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0018"); + } + + [TestMethod] + public void QueryExpression() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer + { + public int[] Data; + } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public void Execute() + { + _ = from x in buffer.Data select x; + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0019"); + } + + [TestMethod] + public void RangeExpression() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer + { + public int[] Data; + } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public void Execute() + { + _ = buffer.Data[1..]; + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0020"); + } + + [TestMethod] + public void RecursivePattern() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer + { + public object Data; + } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public void Execute() + { + if (buffer.Data is int[] { Length: 50 } foo) + { + } + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0021"); + } + + [TestMethod] + public void RefType() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer + { + public ref T this[int x] => throw null; + } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public void Execute() + { + ref float x = ref buffer[0]; + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0022"); + } + + [TestMethod] + public void RelationalPattern() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer + { + public int Data; + } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public void Execute() + { + if (buffer.Data is > 0 and < 10) + { + } + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0023"); + } + + [TestMethod] + public void SizeOfExpression() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public void Execute() + { + _ = sizeof(float); + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0024"); + } + + [TestMethod] + public void StackAllocArrayCreationExpression() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public void Execute() + { + int* p = stackalloc int[10]; + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0032", "CMPS0025"); + } + + [TestMethod] + public void ThrowExpressionOrStatement() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public void Execute() + { + throw null; + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0026"); + } + + [TestMethod] + public void TryStatement() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public void Execute() + { + try + { + } + catch + { + } + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0027"); + } + + [TestMethod] + public void TupleType() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public void Execute() + { + (int, float) foo; + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0028"); + } + + [TestMethod] + public void UsingDeclaration() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public void Execute() + { + using IDisposable foo = null + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0029"); + } + + [TestMethod] + public void UsingStatement() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public void Execute() + { + using (IDisposable foo = null) + { + } + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0029"); + } + + [TestMethod] + public void YieldStatement() + { + string source = @" + using System.Collections.Generic; + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public static IEnumerable Fail() + { + yield return 3.14f; + } + + public void Execute() + { + Fail(); + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0030"); + } + + [TestMethod] + public void InvalidObjectDeclaration() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public void Execute() + { + object bar; + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0031"); + } + + [TestMethod] + public void PointerType() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public void Execute() + { + int* p; + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0032"); + } + + [TestMethod] + public void FunctionPointer() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public void Execute() + { + delegate* f; + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0033"); + } + + [TestMethod] + public void UnsafeStatement() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public void Execute() + { + unsafe + { + } + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0034"); + } + + [TestMethod] + public void UnsafeModifier_LocalFunction() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public void Execute() + { + static unsafe void Fail() { } + + Fail(); + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0035"); + } + + [TestMethod] + public void UnsafeModifier_StaticMethod() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public static unsafe void Fail() { } + + public ReadWriteBuffer buffer; + + public void Execute() + { + Fail(); + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0035"); + } + + /// + /// Verifies the output of a source generator. + /// + /// The generator type to use. + /// The input source to process. + /// The target index to check in the resulting output. + /// The expected body to compare with the generated code. + private void VerifyGeneratedDiagnostics(string source, params string[] diagnosticsIds) + where TGenerator : class, ISourceGenerator, new() + { + SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source); + + IEnumerable references = + from assembly in AppDomain.CurrentDomain.GetAssemblies() + where !assembly.IsDynamic + let reference = MetadataReference.CreateFromFile(assembly.Location) + select reference; + + CSharpCompilation compilation = CSharpCompilation.Create("original", new SyntaxTree[] { syntaxTree }, references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + + ISourceGenerator generator = new TGenerator(); + + CSharpGeneratorDriver driver = CSharpGeneratorDriver.Create(generator); + + driver.RunGeneratorsAndUpdateCompilation(compilation, out Compilation outputCompilation, out ImmutableArray diagnostics); + + HashSet resultingIds = diagnostics.Select(diagnostic => diagnostic.Id).ToHashSet(); + + Assert.IsTrue(resultingIds.SetEquals(diagnosticsIds)); + } + } +} \ No newline at end of file From 01623476ff29f8cc7fcedf04b808b95292f3e8a5 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 18 Feb 2021 20:44:40 +0100 Subject: [PATCH 13/14] Fixed an issue with some static members --- src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs | 4 ++++ .../DiagnosticsTests.cs | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs index 79dc5bb3..f9e79082 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -216,6 +216,8 @@ namespace ComputeSharp.SourceGenerators.Mappings foreach (var field in type.GetMembers().OfType()) { + if (field.IsStatic) continue; + ExploreTypes((INamedTypeSymbol)field.Type, customTypes); } } @@ -255,6 +257,8 @@ namespace ComputeSharp.SourceGenerators.Mappings // Only add other custom types as dependencies, and ignore HLSL types foreach (var field in type.GetMembers().OfType()) { + if (field.IsStatic) continue; + INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type; if (!KnownTypes.ContainsKey(fieldType.GetFullMetadataName())) diff --git a/tests/ComputeSharp.Tests.Internals.SourceGenerators/DiagnosticsTests.cs b/tests/ComputeSharp.Tests.Internals.SourceGenerators/DiagnosticsTests.cs index 0004739d..1abacd1b 100644 --- a/tests/ComputeSharp.Tests.Internals.SourceGenerators/DiagnosticsTests.cs +++ b/tests/ComputeSharp.Tests.Internals.SourceGenerators/DiagnosticsTests.cs @@ -921,7 +921,7 @@ namespace ComputeSharp.Tests.Internals public void Execute() { - object bar; + string bar; } } }"; From 6653cba24f1c110dbbbea7a201224aeb9c30ad2e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 18 Feb 2021 20:48:32 +0100 Subject: [PATCH 14/14] Added error for string literal expressions --- .../AnalyzerReleases.Unshipped.md | 3 ++- .../Diagnostics/DiagnosticDescriptors.cs | 13 +++++++++ .../SyntaxRewriters/ShaderSourceRewriter.cs | 4 +++ .../DiagnosticsTests.cs | 27 +++++++++++++++++++ 4 files changed, 46 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md index c5fc51d1..6d879574 100644 --- a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md +++ b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Unshipped.md @@ -39,4 +39,5 @@ CMPS0031 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, CMPS0032 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0033 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0034 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0035 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) \ No newline at end of file +CMPS0035 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0036 | 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 119f197f..50676fd5 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -494,5 +494,18 @@ namespace ComputeSharp.SourceGenerators.Diagnostics isEnabledByDefault: true, description: "The unsafe modifier cannot be used in methods or functions used in a compute shader.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a string literal. + /// + public static DiagnosticDescriptor StringLiteralExpression { get; } = new( + id: "CMPS0036", + title: "String literal expression", + messageFormat: "String literal expressions cannot be used in a compute shader", + category: typeof(IComputeShader).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "String literal expressions cannot be used in a compute shader.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } } diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 75870fd3..38cf34f3 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -316,6 +316,10 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters return updatedNode.WithToken(Literal(updatedNode.Token.ValueText + "L", 0d)); } } + else if (updatedNode.IsKind(SyntaxKind.StringLiteralExpression)) + { + this.context.ReportDiagnostic(StringLiteralExpression, node); + } return updatedNode; } diff --git a/tests/ComputeSharp.Tests.Internals.SourceGenerators/DiagnosticsTests.cs b/tests/ComputeSharp.Tests.Internals.SourceGenerators/DiagnosticsTests.cs index 1abacd1b..81336d41 100644 --- a/tests/ComputeSharp.Tests.Internals.SourceGenerators/DiagnosticsTests.cs +++ b/tests/ComputeSharp.Tests.Internals.SourceGenerators/DiagnosticsTests.cs @@ -1070,6 +1070,33 @@ namespace ComputeSharp.Tests.Internals VerifyGeneratedDiagnostics(source, "CMPS0035"); } + [TestMethod] + public void StringLiteralExpression() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public class ReadWriteBuffer { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public void Execute() + { + _ = ""Hello world""; + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0036"); + } + /// /// Verifies the output of a source generator. ///