Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions Coder.Test/Ast/FunctionShapeTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

/// <summary>
Expand Down
208 changes: 208 additions & 0 deletions Coder.Test/Languages/VirtualModifierPlacementTests.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// Tests that <c>virtual</c> and <c>abstract</c> are written only where C++ and C# accept them (#467).
/// </summary>
/// <remarks>
/// C++ refuses <c>virtual</c> 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.
/// </remarks>
[TestClass]
public class VirtualModifierPlacementTests
{
/// <summary>
/// The C++ compilers to look for, in the order a C++ project would.
/// </summary>
private static readonly string[] CppCompilers = ["c++", "g++", "clang++"];

/// <summary>
/// The project the generated C# is built in.
/// </summary>
private const string Project = """
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>disable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
</PropertyGroup>
</Project>
""";

/// <summary>
/// The consumer of the generated C#, which calls everything that is still declared.
/// </summary>
private const string CSharpDriver = """
public static class Driver
{
public static int Use() => new Shape().area() + Shape.make() + Globals.helper();
}
""";

/// <summary>
/// The consumer of the generated C++ header, which calls everything that is still defined.
/// </summary>
private const string CppDriver = """
#include "shape.h"

int main()
{
Shape s;
return (s.area() + Shape::make() + helper()) * 0;
}

""";

/// <summary>
/// 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.
/// </summary>
/// <returns>The file.</returns>
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<int>(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<int>(2)) },
});

SourceFile file = new("shape");
file.Members.Add(shape);
file.Members.Add(new FunctionDeclaration("helper")
{
ReturnType = "int",
IsVirtual = true,
Body = { new ReturnStatement(new LiteralExpression<int>(3)) },
});
return file;
}

/// <summary>
/// Tests that C++ writes <c>virtual</c> on the destructor and the instance method only, and says
/// what it dropped from the rest.
/// </summary>
[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);
}

/// <summary>
/// Tests that C# writes <c>virtual</c> on neither the constructor nor the finalizer, and says so.
/// </summary>
[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);
}

/// <summary>
/// Tests that an abstract constructor or destructor is written down rather than declared in C#,
/// since without the modifier it has no body.
/// </summary>
[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);
}

/// <summary>
/// Tests that the C++ the issue's file generates compiles.
/// </summary>
[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}");
});
}

/// <summary>
/// Tests that the C# the issue's file generates compiles.
/// </summary>
[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}");
});
}
}
32 changes: 31 additions & 1 deletion Coder/Languages/CSharpGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -219,12 +219,12 @@
/// </remarks>
protected override IReadOnlySet<string> ReservedWords { get; } = new HashSet<string>(StringComparer.Ordinal)
{
"abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const",

Check warning on line 222 in Coder/Languages/CSharpGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Define a constant instead of using this literal 'abstract' 4 times.
"continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit",

Check warning on line 223 in Coder/Languages/CSharpGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Define a constant instead of using this literal 'double' 5 times.
"extern", "false", "finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int",

Check warning on line 224 in Coder/Languages/CSharpGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Define a constant instead of using this literal 'float' 5 times.
"interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out",

Check warning on line 225 in Coder/Languages/CSharpGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Define a constant instead of using this literal 'object' 4 times.
"override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed",
"short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try",

Check warning on line 227 in Coder/Languages/CSharpGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Define a constant instead of using this literal 'string' 5 times.
"typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void", "volatile", "while",
};

Expand Down Expand Up @@ -553,7 +553,7 @@
_ => null,
});

foreach (string? name in shadowed)

Check warning on line 556 in Coder/Languages/CSharpGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Loops should be simplified using the "Where" LINQ method
{
if (name is not null)
{
Expand Down Expand Up @@ -1761,9 +1761,21 @@
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;
Expand All @@ -1786,6 +1798,12 @@

/// <summary>The member is private, which nothing outside the type can override (CS0621).</summary>
Private,

/// <summary>The member is a constructor, which C# never overrides (CS0106).</summary>
Constructor,

/// <summary>The member is a destructor, a finalizer C# chains to its base itself (CS0106).</summary>
Destructor,
}

/// <summary>
Expand All @@ -1809,6 +1827,18 @@
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;
Expand Down Expand Up @@ -1908,7 +1938,7 @@
}

// 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;
Expand Down
52 changes: 50 additions & 2 deletions Coder/Languages/CppGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@
/// </remarks>
protected override string SpellNonFiniteDouble(double value) =>
double.IsNaN(value) ? "std::numeric_limits<double>::quiet_NaN()"
: value > 0 ? "std::numeric_limits<double>::infinity()"

Check warning on line 172 in Coder/Languages/CppGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Extract this nested ternary operation into an independent statement.
: "-std::numeric_limits<double>::infinity()";

/// <inheritdoc/>
Expand All @@ -179,7 +179,7 @@
/// </remarks>
protected override string SpellNonFiniteSingle(float value) =>
float.IsNaN(value) ? "std::numeric_limits<float>::quiet_NaN()"
: value > 0 ? "std::numeric_limits<float>::infinity()"

Check warning on line 182 in Coder/Languages/CppGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Extract this nested ternary operation into an independent statement.
: "-std::numeric_limits<float>::infinity()";

/// <inheritdoc/>
Expand Down Expand Up @@ -250,6 +250,51 @@
code.Write(")");
}

/// <summary>
/// Decides whether a declaration's <c>virtual</c> or <c>abstract</c> can be written as
/// <c>virtual</c>, and writes a note saying what was dropped where it cannot.
/// </summary>
/// <param name="funcDecl">The declaration being emitted.</param>
/// <param name="code">The writer to emit into.</param>
/// <param name="enclosingType">The name of the type it belongs to, when it belongs to one.</param>
/// <returns>True when the declaration is written <c>virtual</c>.</returns>
/// <remarks>
/// C++ allows <c>virtual</c> 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.
/// </remarks>
private bool WriteVirtualNote(FunctionDeclaration funcDecl, CodeBlocker code, string? enclosingType)
{
if (!(funcDecl.IsVirtual || funcDecl.IsAbstract))
{
return false;
}

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;
}

string modifier = funcDecl.IsAbstract ? "abstract" : "virtual";
WriteInexpressible(code, $"{modifier}: {funcDecl.Name} {obstacle}, which C++ cannot declare virtual");
return false;
}

/// <inheritdoc/>
/// <remarks>
/// A constructor and a destructor are named after the type rather than after themselves, so the
Expand All @@ -263,12 +308,13 @@
/// elided or duplicated, which is a stronger promise than the AST is in a position to make.
/// </para>
/// </remarks>
protected override void GenerateFunction(FunctionDeclaration funcDecl, CodeBlocker code, string? enclosingType)

Check warning on line 311 in Coder/Languages/CppGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Refactor this method to reduce its Cognitive Complexity from 19 to the 15 allowed.
{
Ensure.NotNull(funcDecl);
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);

Expand Down Expand Up @@ -300,7 +346,7 @@

// 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 ");
}
Expand Down Expand Up @@ -334,9 +380,11 @@
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;
}

Expand Down Expand Up @@ -478,7 +526,7 @@
/// describing a scope.
/// </para>
/// </remarks>
protected override void GenerateClassDeclaration(ClassDeclaration classDecl, CodeBlocker code)

Check warning on line 529 in Coder/Languages/CppGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Refactor this method to reduce its Cognitive Complexity from 17 to the 15 allowed.
{
Ensure.NotNull(classDecl);
Ensure.NotNull(code);
Expand Down
Loading