From 6aec5893b25bc32c467675ea8086c29f133106b5 Mon Sep 17 00:00:00 2001 From: matt-edmondson <19528727+matt-edmondson@users.noreply.github.com> Date: Sun, 8 Nov 2026 03:30:20 +0000 Subject: [PATCH 1/2] Write virtual only where C++ and C# accept it [patch] C++ wrote `virtual` on static members, constructors and functions outside a class, and C# on constructors and finalizers. Each now drops it with a note saying what was dropped. A C++ destructor keeps it, and a static or free abstract function in C++ is declared without `= 0`. Fixes ktsu-dev/Coder#467 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017vfJW2mFigVQkgzUYqEcdJ --- Coder.Test/Ast/FunctionShapeTests.cs | 8 +- .../VirtualModifierPlacementTests.cs | 208 ++++++++++++++++++ Coder/Languages/CSharpGenerator.cs | 32 ++- Coder/Languages/CppGenerator.cs | 47 +++- 4 files changed, 288 insertions(+), 7 deletions(-) create mode 100644 Coder.Test/Languages/VirtualModifierPlacementTests.cs diff --git a/Coder.Test/Ast/FunctionShapeTests.cs b/Coder.Test/Ast/FunctionShapeTests.cs index d30538f3..e62872d1 100644 --- a/Coder.Test/Ast/FunctionShapeTests.cs +++ b/Coder.Test/Ast/FunctionShapeTests.cs @@ -96,10 +96,10 @@ public void Cpp_SpellsEachKindOfDefinition() Assert.Contains("Handle() = default;", code, StringComparison.Ordinal); Assert.Contains("Handle(Handle other) = delete;", code, StringComparison.Ordinal); - Assert.Contains( - "virtual void step() = 0;", - new CppGenerator().Generate(new FunctionDeclaration("step") { ReturnType = "void", IsAbstract = true }), - StringComparison.Ordinal); + // Only a member function can be pure virtual; outside a class C++ has no virtual to write (#467). + ClassDeclaration stepper = new("Stepper"); + stepper.Members.Add(new FunctionDeclaration("step") { ReturnType = "void", IsAbstract = true }); + Assert.Contains("virtual void step() = 0;", new CppGenerator().Generate(stepper), StringComparison.Ordinal); } /// diff --git a/Coder.Test/Languages/VirtualModifierPlacementTests.cs b/Coder.Test/Languages/VirtualModifierPlacementTests.cs new file mode 100644 index 00000000..fe7baf63 --- /dev/null +++ b/Coder.Test/Languages/VirtualModifierPlacementTests.cs @@ -0,0 +1,208 @@ +// Copyright (c) 2023-2026 ktsu-dev contributors + +namespace ktsu.Coder.Test.Languages; + +using ktsu.Coder.Ast; +using ktsu.Coder.Languages; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +/// +/// Tests that virtual and abstract are written only where C++ and C# accept them (#467). +/// +/// +/// C++ refuses virtual on a static member, a constructor and a function outside a class, and +/// C# refuses it on a constructor and a finalizer (CS0106). A virtual destructor is the ordinary C++ +/// base-class shape, so an AST written C++-first carries one, and C++ keeps it. +/// +[TestClass] +public class VirtualModifierPlacementTests +{ + /// + /// The C++ compilers to look for, in the order a C++ project would. + /// + private static readonly string[] CppCompilers = ["c++", "g++", "clang++"]; + + /// + /// The project the generated C# is built in. + /// + private const string Project = """ + + + net10.0 + disable + disable + + + """; + + /// + /// The consumer of the generated C#, which calls everything that is still declared. + /// + private const string CSharpDriver = """ + public static class Driver + { + public static int Use() => new Shape().area() + Shape.make() + Globals.helper(); + } + """; + + /// + /// The consumer of the generated C++ header, which calls everything that is still defined. + /// + private const string CppDriver = """ + #include "shape.h" + + int main() + { + Shape s; + return (s.area() + Shape::make() + helper()) * 0; + } + + """; + + /// + /// Builds the file the issue reproduces with: a class holding a virtual and an abstract static + /// function, a virtual constructor, a virtual destructor and an ordinary virtual method, beside a + /// virtual free function. + /// + /// The file. + private static SourceFile ShapeFile() + { + ClassDeclaration shape = new("Shape"); + shape.Members.Add(new FunctionDeclaration("Shape") { Kind = FunctionKind.Constructor, IsVirtual = true }); + shape.Members.Add(new FunctionDeclaration("Shape") { Kind = FunctionKind.Destructor, IsVirtual = true }); + shape.Members.Add(new FunctionDeclaration("make") + { + ReturnType = "int", + IsStatic = true, + IsVirtual = true, + Body = { new ReturnStatement(new LiteralExpression(1)) }, + }); + shape.Members.Add(new FunctionDeclaration("build") { ReturnType = "int", IsStatic = true, IsAbstract = true }); + shape.Members.Add(new FunctionDeclaration("area") + { + ReturnType = "int", + IsVirtual = true, + Body = { new ReturnStatement(new LiteralExpression(2)) }, + }); + + SourceFile file = new("shape"); + file.Members.Add(shape); + file.Members.Add(new FunctionDeclaration("helper") + { + ReturnType = "int", + IsVirtual = true, + Body = { new ReturnStatement(new LiteralExpression(3)) }, + }); + return file; + } + + /// + /// Tests that C++ writes virtual on the destructor and the instance method only, and says + /// what it dropped from the rest. + /// + [TestMethod] + public void Cpp_WritesVirtualOnlyOnNonStaticMembersThatAreNotConstructors() + { + string header = new CppGenerator().Generate(ShapeFile()); + + Assert.Contains("virtual ~Shape()", header, StringComparison.Ordinal, header); + Assert.Contains("virtual int area()", header, StringComparison.Ordinal, header); + Assert.DoesNotContain("static virtual", header, StringComparison.Ordinal, header); + Assert.DoesNotContain("virtual Shape()", header, StringComparison.Ordinal, header); + Assert.DoesNotContain("virtual int helper()", header, StringComparison.Ordinal, header); + Assert.Contains("static int build();", header, StringComparison.Ordinal, header); + Assert.DoesNotContain("= 0", header, StringComparison.Ordinal, header); + Assert.Contains("// virtual: make is static, which C++ cannot declare virtual", header, StringComparison.Ordinal, header); + Assert.Contains("// abstract: build is static, which C++ cannot declare virtual", header, StringComparison.Ordinal, header); + Assert.Contains("// virtual: Shape is a constructor, which C++ cannot declare virtual", header, StringComparison.Ordinal, header); + Assert.Contains("// virtual: helper is not a member of a class, which C++ cannot declare virtual", header, StringComparison.Ordinal, header); + } + + /// + /// Tests that C# writes virtual on neither the constructor nor the finalizer, and says so. + /// + [TestMethod] + public void CSharp_WritesVirtualOnNeitherConstructorNorFinalizer() + { + string source = new CSharpGenerator().Generate(ShapeFile()); + + Assert.DoesNotContain("virtual Shape(", source, StringComparison.Ordinal, source); + Assert.DoesNotContain("virtual ~Shape(", source, StringComparison.Ordinal, source); + Assert.Contains("public virtual int area()", source, StringComparison.Ordinal, source); + Assert.Contains("// virtual: Shape is a constructor, which C# never overrides", source, StringComparison.Ordinal, source); + Assert.Contains("// virtual: ~Shape is a finalizer", source, StringComparison.Ordinal, source); + } + + /// + /// Tests that an abstract constructor or destructor is written down rather than declared in C#, + /// since without the modifier it has no body. + /// + [TestMethod] + public void CSharp_AbstractConstructorAndDestructor_AreWrittenDown() + { + ClassDeclaration shape = new("Shape"); + shape.Members.Add(new FunctionDeclaration("Shape") { Kind = FunctionKind.Constructor, IsAbstract = true }); + shape.Members.Add(new FunctionDeclaration("Shape") { Kind = FunctionKind.Destructor, IsAbstract = true }); + + string source = new CSharpGenerator().Generate(shape); + + Assert.DoesNotContain("Shape();", source, StringComparison.Ordinal, source); + Assert.DoesNotContain("abstract", source.Replace("an abstract", string.Empty, StringComparison.Ordinal), StringComparison.Ordinal, source); + Assert.Contains("// Shape is an abstract constructor", source, StringComparison.Ordinal, source); + Assert.Contains("// ~Shape is an abstract destructor", source, StringComparison.Ordinal, source); + } + + /// + /// Tests that the C++ the issue's file generates compiles. + /// + [TestMethod] + public void Cpp_Compiles() + { + string? compiler = ToolchainHarness.FindOnPath("--version", CppCompilers); + if (compiler is null) + { + Assert.Inconclusive("No C++ compiler on the path, so nothing was compiled."); + return; + } + + string header = new CppGenerator().Generate(ShapeFile()); + + ToolchainHarness.InTemporaryDirectory(directory => + { + File.WriteAllText(Path.Combine(directory, "shape.h"), header); + File.WriteAllText(Path.Combine(directory, "driver.cpp"), CppDriver); + + (int exitCode, string output) = ToolchainHarness.Run( + compiler, + "-std=c++20 -Wall -Wextra -pedantic -Werror -c driver.cpp -o driver.o", + directory); + + Assert.AreEqual(0, exitCode, $"{compiler} rejected the generated header:{Environment.NewLine}{output}{Environment.NewLine}{header}"); + }); + } + + /// + /// Tests that the C# the issue's file generates compiles. + /// + [TestMethod] + public void CSharp_Compiles() + { + if (ToolchainHarness.FindOnPath("--version", "dotnet") is null) + { + Assert.Inconclusive("No dotnet on the path, so nothing was compiled."); + return; + } + + string source = new CSharpGenerator().Generate(ShapeFile()); + + ToolchainHarness.InTemporaryDirectory(directory => + { + File.WriteAllText(Path.Combine(directory, "Generated.csproj"), Project); + File.WriteAllText(Path.Combine(directory, "Driver.cs"), CSharpDriver); + File.WriteAllText(Path.Combine(directory, "Generated.cs"), source); + + (int exitCode, string output) = ToolchainHarness.Run("dotnet", "build -nologo", directory); + Assert.AreEqual(0, exitCode, $"C# rejected the generated source:{Environment.NewLine}{output}{Environment.NewLine}{source}"); + }); + } +} diff --git a/Coder/Languages/CSharpGenerator.cs b/Coder/Languages/CSharpGenerator.cs index acd5cf49..27624aaf 100644 --- a/Coder/Languages/CSharpGenerator.cs +++ b/Coder/Languages/CSharpGenerator.cs @@ -1761,9 +1761,21 @@ private bool WriteOverrideNote(FunctionDeclaration function, string name, Overri case OverrideObstacleKind.Struct when function.IsAbstract: WriteInexpressible(code, $"{name} is abstract, which a C# struct cannot declare: nothing can derive from it to supply a body."); return false; + case OverrideObstacleKind.Constructor when function.IsAbstract: + WriteInexpressible(code, $"{name} is an abstract constructor, which C# cannot declare: a constructor is never overridden, so it has no body to declare."); + return false; + case OverrideObstacleKind.Destructor when function.IsAbstract: + WriteInexpressible(code, $"{name} is an abstract destructor, which C# cannot declare: a finalizer is never overridden, so it has no body to declare."); + return false; case OverrideObstacleKind.Static: WriteInexpressible(code, $"{modifier}: {name} is static, which C# cannot override outside an interface"); return true; + case OverrideObstacleKind.Constructor: + WriteInexpressible(code, $"{modifier}: {name} is a constructor, which C# never overrides"); + return true; + case OverrideObstacleKind.Destructor: + WriteInexpressible(code, $"{modifier}: {name} is a finalizer, which C# chains to its base without being overridden"); + return true; case OverrideObstacleKind.Struct: WriteInexpressible(code, $"{modifier}: {name} belongs to a struct, which C# cannot derive from"); return true; @@ -1786,6 +1798,12 @@ private enum OverrideObstacleKind /// The member is private, which nothing outside the type can override (CS0621). Private, + + /// The member is a constructor, which C# never overrides (CS0106). + Constructor, + + /// The member is a destructor, a finalizer C# chains to its base itself (CS0106). + Destructor, } /// @@ -1809,6 +1827,18 @@ private enum OverrideObstacleKind return null; } + // A C++ base class's destructor is virtual by convention, and a constructor may be marked so by + // mistake; C# accepts the modifier on neither (CS0106). + if (function.Kind == FunctionKind.Constructor) + { + return OverrideObstacleKind.Constructor; + } + + if (function.Kind == FunctionKind.Destructor) + { + return OverrideObstacleKind.Destructor; + } + if (function.IsStatic || ReferenceEquals(function, heldMember)) { return OverrideObstacleKind.Static; @@ -1908,7 +1938,7 @@ private void WriteFunctionModifiers(FunctionDeclaration function, CodeBlocker co } // An operator outside an interface can be neither virtual nor abstract (CS0106), and neither - // can a static or struct member (CS0112, CS0106); the note written above the declaration says + // can a static or struct member, a constructor or a destructor (CS0112, CS0106); the note written above the declaration says // what was dropped. A private one is written protected instead, so it keeps its modifier. bool canOverride = (!IsOperator(function) || enclosingType?.Kind == TypeDeclarationKind.Interface) && OverrideObstacle(function, enclosingType) is null or OverrideObstacleKind.Private; diff --git a/Coder/Languages/CppGenerator.cs b/Coder/Languages/CppGenerator.cs index cd68dd58..34dbfaf3 100644 --- a/Coder/Languages/CppGenerator.cs +++ b/Coder/Languages/CppGenerator.cs @@ -250,6 +250,46 @@ protected override void WriteFloatingRemainder(Expression dividend, Expression d code.Write(")"); } + /// + /// Decides whether a declaration's virtual or abstract can be written as + /// virtual, and writes a note saying what was dropped where it cannot. + /// + /// The declaration being emitted. + /// The writer to emit into. + /// The name of the type it belongs to, when it belongs to one. + /// True when the declaration is written virtual. + /// + /// C++ allows virtual only on a non-static member function that is not a constructor: + /// a static member cannot be both (it has no object to dispatch on), a constructor runs before + /// there is a dynamic type to dispatch to, and a function outside a class has nothing to be + /// overridden by. A destructor keeps it, since a virtual destructor is how a base class is + /// deleted through a pointer to it. + /// + private bool WriteVirtualNote(FunctionDeclaration funcDecl, CodeBlocker code, string? enclosingType) + { + if (!(funcDecl.IsVirtual || funcDecl.IsAbstract)) + { + return false; + } + + string? obstacle = enclosingType is null + ? "is not a member of a class" + : funcDecl.Kind == FunctionKind.Constructor + ? "is a constructor" + : funcDecl.IsStatic + ? "is static" + : null; + + if (obstacle is null) + { + return true; + } + + string modifier = funcDecl.IsAbstract ? "abstract" : "virtual"; + WriteInexpressible(code, $"{modifier}: {funcDecl.Name} {obstacle}, which C++ cannot declare virtual"); + return false; + } + /// /// /// A constructor and a destructor are named after the type rather than after themselves, so the @@ -269,6 +309,7 @@ protected override void GenerateFunction(FunctionDeclaration funcDecl, CodeBlock Ensure.NotNull(code); WritePreamble(funcDecl, code, enclosingType is null ? PreambleSite.Function : PreambleSite.Method); + bool isVirtual = WriteVirtualNote(funcDecl, code, enclosingType); WriteUnaskedConstraints(funcDecl.TypeParameters, code); WriteTemplateHead(funcDecl.TypeParameters, code); @@ -300,7 +341,7 @@ protected override void GenerateFunction(FunctionDeclaration funcDecl, CodeBlock // An abstract declaration is virtual whether or not it was asked to be: there is nothing else // `= 0` could mean. - if (funcDecl.IsVirtual || funcDecl.IsAbstract) + if (isVirtual) { code.Write("virtual "); } @@ -334,9 +375,11 @@ protected override void GenerateFunction(FunctionDeclaration funcDecl, CodeBlock code.Write(" noexcept"); } + // Where virtual cannot be written, `= 0` has nothing to mean either, so an abstract declaration + // is declared and left for something else to define. if (funcDecl.IsAbstract) { - code.WriteLine(" = 0;"); + code.WriteLine(isVirtual ? " = 0;" : ";"); return; } From e69b0e9fd003f18cea9a884efab2de09d0802ca8 Mon Sep 17 00:00:00 2001 From: matt-edmondson <19528727+matt-edmondson@users.noreply.github.com> Date: Sun, 8 Nov 2026 03:43:17 +0000 Subject: [PATCH 2/2] Spell the C++ virtual obstacle as an if chain, not nested ternaries Addresses SonarQube S3358 on the new WriteVirtualNote. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017vfJW2mFigVQkgzUYqEcdJ --- Coder/Languages/CppGenerator.cs | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/Coder/Languages/CppGenerator.cs b/Coder/Languages/CppGenerator.cs index 34dbfaf3..5d1da54c 100644 --- a/Coder/Languages/CppGenerator.cs +++ b/Coder/Languages/CppGenerator.cs @@ -272,15 +272,20 @@ private bool WriteVirtualNote(FunctionDeclaration funcDecl, CodeBlocker code, st return false; } - string? obstacle = enclosingType is null - ? "is not a member of a class" - : funcDecl.Kind == FunctionKind.Constructor - ? "is a constructor" - : funcDecl.IsStatic - ? "is static" - : null; - - if (obstacle is null) + string obstacle; + if (enclosingType is null) + { + obstacle = "is not a member of a class"; + } + else if (funcDecl.Kind == FunctionKind.Constructor) + { + obstacle = "is a constructor"; + } + else if (funcDecl.IsStatic) + { + obstacle = "is static"; + } + else { return true; }