From 7cfaf16ef8d8c871c25d00495e0259aded2032b8 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 3 Dec 2023 12:33:52 +0100 Subject: [PATCH] Improve primary constructors error state, add test --- .../SyntaxRewriters/ShaderSourceRewriter.cs | 7 ++++- .../DiagnosticsTests.cs | 29 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs index 10baf557..b5afaf6f 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs @@ -655,11 +655,16 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter if (!this.constructors.ContainsKey(constructor)) { + // If we can't find the constructor declaration for the syntax reference of the constructor, it means that either the + // type is from another assembly (hence we have no syntax references at all), or the constructor is compiler generated + // (even if IsImplicitlyDeclared is false) and a primary constructor. This is deliberately not supported, as there + // are very subtle ways in which captures can interact with fields and methods, and we cannot guarantee to track and + // rewrite all of them correctly to exactly preserve the same semantics. So we just block such cases entirely as well. if (constructor.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() is not ConstructorDeclarationSyntax constructorNode) { Diagnostics.Add(InvalidMethodOrConstructorCall, node, constructor); - return updatedNode; + return base.VisitUserDefinedObjectCreationExpression(node, updatedNode, targetType); } // Chaining constructors is not supported, so emit a diagnostic to inform the user. diff --git a/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs b/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs index 33a36fb3..7f040069 100644 --- a/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs +++ b/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs @@ -1452,6 +1452,35 @@ public class DiagnosticsTests VerifyGeneratedDiagnostics(source, "CMPS0047", "CMPS0061"); } + [TestMethod] + public void InvalidMethodOrConstructorCall_PrimaryConstructor() + { + const string source = """ + using ComputeSharp; + + public struct MyStruct(int x) + { + public int PlusOne() + { + return x + 1; + } + } + + [GeneratedComputeShaderDescriptor] + public partial struct MyShader : IComputeShader + { + public ReadWriteBuffer buffer; + + public void Execute() + { + buffer[ThreadIds.X] = new MyStruct(ThreadIds.X).PlusOne(); + } + } + """; + + VerifyGeneratedDiagnostics(source, "CMPS0047", "CMPS0049"); + } + /// /// Verifies the output of a source generator. ///