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
44 changes: 44 additions & 0 deletions Coder.Test/Languages/CSharpGeneratedSourceCompilesTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -141,4 +141,48 @@ public void Operators_Compile()
Assert.AreEqual(0, exitCode, $"C# rejected the generated source:{Environment.NewLine}{output}{Environment.NewLine}{source}");
});
}

/// <summary>
/// Tests that operators declared private, protected or virtual, which C++ allows, still compile
/// as the public static operators C# requires, with what was dropped written down (#260).
/// </summary>
[TestMethod]
public void OperatorsDeclaredPrivateOrVirtual_Compile()
{
if (ToolchainHarness.FindOnPath("--version", "dotnet") is null)
{
Assert.Inconclusive("No dotnet on the path, so nothing was compiled.");
return;
}

FunctionDeclaration plus = CompiledExemplar.Plus();
plus.Visibility = Visibility.Private;
FunctionDeclaration negate = CompiledExemplar.Negate();
negate.IsVirtual = true;
FunctionDeclaration toDouble = CompiledExemplar.ToDouble("self.x");
toDouble.Visibility = Visibility.Protected;

ClassDeclaration point = CompiledExemplar.Point();
point.Members.Add(plus);
point.Members.Add(negate);
point.Members.Add(toDouble);

SourceFile file = new("Generated");
file.Members.Add(point);

ToolchainHarness.InTemporaryDirectory(directory =>
{
string source = new CSharpGenerator().Generate(file);
Assert.Contains("// private: operator + is public, as every C# operator is", source, StringComparison.Ordinal, source);
Assert.Contains("// virtual: operator - is static", source, StringComparison.Ordinal, source);
Assert.Contains("// protected: ", source, StringComparison.Ordinal, source);

File.WriteAllText(Path.Combine(directory, "Generated.csproj"), Project);
File.WriteAllText(Path.Combine(directory, "Driver.cs"), OperatorDriver);
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}");
});
}
}
24 changes: 24 additions & 0 deletions Coder.Test/Languages/CSharpMemberModifierTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -136,4 +136,28 @@ public void StructDestructor_IsANote()
Assert.Contains("// ~Vec is a destructor, which a C# struct cannot declare.", code, StringComparison.Ordinal, code);
Assert.DoesNotContain("~Vec()", code, StringComparison.Ordinal, code);
}

/// <summary>
/// Tests that an abstract operator in a class is written as the public static operator C#
/// requires, with neither abstract nor its declared visibility, and a note saying so (#260).
/// </summary>
[TestMethod]
public void AbstractProtectedOperatorInAClass_IsPublicStaticWithANote()
{
ClassDeclaration shape = new("Shape");
FunctionDeclaration plus = CompiledExemplar.Plus();
plus.ReturnType = "Shape";
plus.Parameters[0].Type = "Shape";
plus.IsAbstract = true;
plus.Visibility = Visibility.Protected;
shape.Members.Add(plus);

string code = new CSharpGenerator().Generate(shape);

Assert.Contains("public static Shape operator +(", code, StringComparison.Ordinal, code);
Assert.DoesNotContain("abstract Shape", code, StringComparison.Ordinal, code);
Assert.DoesNotContain("protected static", code, StringComparison.Ordinal, code);
Assert.Contains("// abstract: operator + is static", code, StringComparison.Ordinal, code);
Assert.Contains("// protected: operator + is public", code, StringComparison.Ordinal, code);
}
}
41 changes: 37 additions & 4 deletions Coder/Languages/CSharpGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@
/// A member is emitted through the same dispatch as any other node, so a nested class, a method
/// and a field each come out through the emitter for their own shape.
/// </remarks>
private void GenerateClass(ClassDeclaration classDecl, CodeBlocker code)

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

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Refactor this method to reduce its Cognitive Complexity from 16 to the 15 allowed.

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

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Refactor this method to reduce its Cognitive Complexity from 16 to the 15 allowed.

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

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Refactor this method to reduce its Cognitive Complexity from 16 to the 15 allowed.

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

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Refactor this method to reduce its Cognitive Complexity from 16 to the 15 allowed.
{
bool aliasesWereHoisted = memberAliasesHoisted;
if (!aliasesWereHoisted)
Expand Down Expand Up @@ -368,7 +368,7 @@
/// The constants on <see cref="double"/>, which every file can name without a <c>using</c>.
/// </remarks>
protected override string SpellNonFiniteDouble(double value) =>
double.IsNaN(value) ? "double.NaN" : value > 0 ? "double.PositiveInfinity" : "double.NegativeInfinity";

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

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Extract this nested ternary operation into an independent statement.

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

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Extract this nested ternary operation into an independent statement.

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

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Extract this nested ternary operation into an independent statement.

/// <inheritdoc/>
/// <remarks>
Expand All @@ -376,7 +376,7 @@
/// <c>float</c> implicitly.
/// </remarks>
protected override string SpellNonFiniteSingle(float value) =>
float.IsNaN(value) ? "float.NaN" : value > 0 ? "float.PositiveInfinity" : "float.NegativeInfinity";

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

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Extract this nested ternary operation into an independent statement.

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

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Extract this nested ternary operation into an independent statement.

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

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Extract this nested ternary operation into an independent statement.

/// <summary>
/// Emits a namespace and its members.
Expand Down Expand Up @@ -973,9 +973,33 @@
WriteInexpressible(code, $"readonly: {name} does not modify its instance");
}

// C++ lets a member operator be private, protected or virtual; a C# operator is public and
// static and nothing else, so what it asked for is written down rather than lost.
if (IsOperator(function))
{
if (function.Visibility is not (Visibility.Unspecified or Visibility.Public))
{
WriteInexpressible(code, $"{SpellVisibility(function.Visibility)}: {name} is public, as every C# operator is");
}

if (enclosingType?.Kind != TypeDeclarationKind.Interface && (function.IsVirtual || function.IsAbstract))
{
string modifier = function.IsAbstract ? "abstract" : "virtual";
WriteInexpressible(code, $"{modifier}: {name} is static, which a C# operator outside an interface cannot override");
}
}

return true;
}

/// <summary>
/// Gets whether a declaration is one C# requires to be <c>public static</c>.
/// </summary>
/// <param name="function">The declaration being emitted.</param>
/// <returns>True for an operator or a conversion operator.</returns>
private static bool IsOperator(FunctionDeclaration function) =>
function.Kind is FunctionKind.Operator or FunctionKind.ConversionOperator;

/// <summary>
/// Writes the attributes a declaration earns.
/// </summary>
Expand Down Expand Up @@ -1010,28 +1034,37 @@
// A function nobody has given a visibility to is public: an inaccessible method is not what
// someone who wrote no modifier meant. A finalizer is the exception, because it takes no
// access modifier at all (CS0106): only the runtime calls it.
if (function.Kind != FunctionKind.Destructor)
// A user-defined operator must be public as well as static (CS0558), whatever it declared.
if (IsOperator(function))
{
code.Write("public ");
}
else if (function.Kind != FunctionKind.Destructor)
{
code.Write($"{SpellVisibility(function.Visibility) ?? DefaultVisibility} ");
}

if (function.IsStatic
|| ReferenceEquals(function, heldMember)
|| function.Kind is FunctionKind.Operator or FunctionKind.ConversionOperator)
|| IsOperator(function))
{
// A C# operator is always static, whether or not the declaration thought to say so.
code.Write("static ");
}

// An operator outside an interface can be neither virtual nor abstract (CS0106); the note
// written above the declaration says what was dropped.
bool canOverride = !IsOperator(function) || enclosingType?.Kind == TypeDeclarationKind.Interface;

// An interface member with no body is abstract already, and says so by having none.
if (function.IsAbstract)
{
if (enclosingType?.Kind != TypeDeclarationKind.Interface)
if (canOverride && enclosingType?.Kind != TypeDeclarationKind.Interface)
{
code.Write("abstract ");
}
}
else if (function.IsVirtual)
else if (function.IsVirtual && canOverride)
{
code.Write("virtual ");
}
Expand Down
Loading