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
144 changes: 143 additions & 1 deletion Coder.Test/Languages/ReservedWordIdentifierTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ namespace ktsu.Coder.Test.Languages;
using Microsoft.VisualStudio.TestTools.UnitTesting;

/// <summary>
/// Compiles and runs what the Rust, C++ and Python generators write for names that are keywords of
/// Compiles and runs what the Rust, C++, Python and C# generators write for names that are keywords of
/// the target: a property called <c>Type</c> or <c>Default</c>, which are ordinary C# names, fields,
/// parameters and locals called <c>where</c>, <c>virtual</c>, <c>match</c>, <c>delete</c>,
/// <c>loop</c> and <c>new</c>, and, for Python, an enumeration member called <c>None</c>. Each name has to come out escaped where it is declared and spelled the
Expand Down Expand Up @@ -184,6 +184,95 @@ public void Python_ReferenceKeepsTheLiteralWordsAndEscapesTheMember()
Assert.DoesNotContain("None_", source, StringComparison.Ordinal, source);
}

/// <summary>
/// The project the generated C# is built as: a program, so the driver can check what it reads back.
/// </summary>
private const string CSharpProject = """
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>disable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
</PropertyGroup>
</Project>
""";

/// <summary>
/// The C# driver. <c>@</c> is how a C# caller names a keyword, so it reads the escaped names back
/// exactly as a user of the generated type would.
/// </summary>
private const string CSharpDriver = """
public static class Program
{
public static int Main()
{
Holder holder = Holder.make();
if (holder.@class != 9 || holder.@event != 4) { return 1; }
if (holder.@default != 1) { return 2; }
if (holder.total(5, 6) != 20) { return 3; }
if ((int)Flag.@null != 0 || (int)Flag.All != 1) { return 4; }
if (Globals.@return(7) != 7) { return 5; }
if (Globals.widest() != int.MaxValue) { return 6; }
return 0;
}
}
""";

/// <summary>
/// Tests that C# writes a keyword-named field, property, parameter, local, enumeration member,
/// function and designated member as a verbatim identifier, at their declarations and where they
/// are used, and keeps a built-in type's keyword leading a member access as written.
/// </summary>
[TestMethod]
public void CSharp_KeywordNamesCompileAndResolve()
{
if (ToolchainHarness.FindOnPath("--version", "dotnet") is null)
{
Assert.Inconclusive("No dotnet on the path, so nothing was compiled.");
return;
}

ToolchainHarness.InTemporaryDirectory(directory =>
{
string source = new CSharpGenerator().Generate(CSharpTypes());
File.WriteAllText(Path.Combine(directory, "Holder.csproj"), CSharpProject);
File.WriteAllText(Path.Combine(directory, "Program.cs"), CSharpDriver);
File.WriteAllText(Path.Combine(directory, "Holder.cs"), source);

(int ran, string output) = ToolchainHarness.Run("dotnet", "run -nologo", directory);
Assert.AreEqual(0, ran, $"C# rejected the generated source, or a keyword-named member read back wrongly (driver check {ran}):{Environment.NewLine}{output}{Environment.NewLine}{source}");
});
}

/// <summary>
/// Tests that a C# reference keeps the receiver and the literal words as written while escaping
/// a keyword that names a member.
/// </summary>
[TestMethod]
public void CSharp_ReferenceKeepsTheReceiverAndLiteralsAndEscapesTheMember()
{
FunctionDeclaration read = new("read") { ReturnType = "int" };
read.Body.Add(new VariableDeclaration("unused", "object", new VariableReference("null")));
read.Body.Add(new VariableDeclaration("empty", "string", new VariableReference("string.Empty")));
read.Body.Add(new ReturnStatement(new VariableReference("this.base")));
ClassDeclaration holder = new("Holder");
holder.Members.Add(new VariableDeclaration("base", "int"));
holder.Members.Add(read);
SourceFile file = new("holder");
file.Members.Add(holder);

string source = new CSharpGenerator().Generate(file);

Assert.Contains("int @base", source, StringComparison.Ordinal, source);
Assert.Contains("return this.@base;", source, StringComparison.Ordinal, source);
Assert.Contains("= null;", source, StringComparison.Ordinal, source);
Assert.Contains("= string.Empty;", source, StringComparison.Ordinal, source);
Assert.DoesNotContain("@this", source, StringComparison.Ordinal, source);
Assert.DoesNotContain("@null", source, StringComparison.Ordinal, source);
Assert.DoesNotContain("@string", source, StringComparison.Ordinal, source);
}

/// <summary>
/// Tests that a reference keeps a receiver as written and escapes only the plain names after it.
/// </summary>
Expand Down Expand Up @@ -266,6 +355,59 @@ private static SourceFile PythonTypes()
return file;
}

/// <summary>
/// Builds a class, an enumeration and functions whose names are C# keywords.
/// </summary>
/// <returns>The file to generate.</returns>
private static SourceFile CSharpTypes()
{
ClassDeclaration holder = new("Holder");
holder.Members.Add(new VariableDeclaration("class", "int", new LiteralExpression<int>(3)) { Visibility = Visibility.Public });
holder.Members.Add(new VariableDeclaration("event", "int", new LiteralExpression<int>(4)) { Visibility = Visibility.Public });
holder.Members.Add(new PropertyDeclaration("default", "int")
{
GetterBody = { new ReturnStatement(new LiteralExpression<int>(1)) },
});

ConstructionExpression built = new(new TypeReference("Holder"));
built.Arguments.Add(new MemberInitialiser("class", new LiteralExpression<int>(9)));
FunctionDeclaration make = new("make") { ReturnType = "Holder", IsStatic = true };
make.Body.Add(new ReturnStatement(built));
holder.Members.Add(make);

FunctionDeclaration total = new("total") { ReturnType = "int" };
total.Parameters.Add(new Parameter("in", "int"));
total.Parameters.Add(new Parameter("out", "int"));
total.Body.Add(new VariableDeclaration(
"lock",
"int",
new BinaryExpression(new VariableReference("in"), BinaryOperator.Add, new VariableReference("out"))));
total.Body.Add(new VariableDeclaration(
"fixed",
"int",
new BinaryExpression(new VariableReference("lock"), BinaryOperator.Add, new VariableReference("this.class"))));
total.Body.Add(new ReturnStatement(new VariableReference("fixed")));
holder.Members.Add(total);

EnumDeclaration flag = new("Flag");
flag.Members.Add(new EnumMember("null"));
flag.Members.Add(new EnumMember("All"));

FunctionDeclaration identity = new("return") { ReturnType = "int" };
identity.Parameters.Add(new Parameter("params", "int"));
identity.Body.Add(new ReturnStatement(new VariableReference("params")));

FunctionDeclaration widest = new("widest") { ReturnType = "int" };
widest.Body.Add(new ReturnStatement(new VariableReference("int.MaxValue")));

SourceFile file = new("holder");
file.Members.Add(holder);
file.Members.Add(flag);
file.Members.Add(identity);
file.Members.Add(widest);
return file;
}

/// <summary>
/// Builds a struct whose members are all named after a keyword of one target or the other.
/// </summary>
Expand Down
82 changes: 72 additions & 10 deletions Coder/Languages/CSharpGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@
switch (node)
{
case VariableReference varRef:
code.Write(varRef.Name);
code.Write(SpellReference(varRef.Name));
break;
case LiteralExpression<string> stringLit:
code.Write($"\"{EscapeString(stringLit.Value ?? string.Empty)}\"");
Expand Down Expand Up @@ -205,6 +205,68 @@
code.Write(")");
}

/// <inheritdoc/>
/// <remarks>
/// The reserved keywords. The contextual ones — <c>var</c>, <c>value</c>, <c>where</c>,
/// <c>record</c>, <c>nameof</c> and the rest — are keywords only where the grammar expects one
/// and are legal names everywhere else, so they are left alone.
/// </remarks>
protected override IReadOnlySet<string> ReservedWords { get; } = new HashSet<string>(StringComparer.Ordinal)
{
"abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const",
"continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit",

Check warning on line 217 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.

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

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Define a constant instead of using this literal 'double' 5 times.

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Coder&issues=AaGe3E7AOnKJvo_QzVU_&open=AaGe3E7AOnKJvo_QzVU_&pullRequest=441
"extern", "false", "finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int",

Check warning on line 218 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.

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

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Define a constant instead of using this literal 'float' 5 times.

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Coder&issues=AaGe3E7AOnKJvo_QzVVA&open=AaGe3E7AOnKJvo_QzVVA&pullRequest=441
"interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out",

Check warning on line 219 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.

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

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Define a constant instead of using this literal 'object' 4 times.

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Coder&issues=AaGe3E7AOnKJvo_QzVVB&open=AaGe3E7AOnKJvo_QzVVB&pullRequest=441
"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 221 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' 4 times.

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

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Define a constant instead of using this literal 'string' 4 times.

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Coder&issues=AaGe3E7AOnKJvo_QzVVC&open=AaGe3E7AOnKJvo_QzVVC&pullRequest=441
"typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void", "volatile", "while",
};

/// <inheritdoc/>
/// <remarks>
/// C# has a real escape, the verbatim identifier, so nothing is renamed: <c>default</c> is
/// declared and used as <c>@default</c>, and a caller written in C# names it that way too.
/// </remarks>
protected override string EscapeIdentifier(string name)
{
Ensure.NotNull(name);
return ReservedWords.Contains(name) ? $"@{name}" : name;
}

/// <inheritdoc/>
/// <remarks>
/// <c>this</c> and <c>base</c> name the receiver, and <c>true</c>, <c>false</c> and <c>null</c>
/// are the literals a reference written as text means by them.
/// </remarks>
protected override bool IsReceiverWord(string word) => word is "this" or "base" or "true" or "false" or "null";

/// <summary>
/// Spells a reference, escaping its keyword-named segments as their declarations were.
/// </summary>
/// <param name="reference">The reference's text.</param>
/// <returns>The reference as C# writes it.</returns>
/// <remarks>
/// A built-in type's keyword leading a member access — <c>int.MaxValue</c>,
/// <c>string.Empty</c> — names the type, so it is kept as written. On its own it can only be a
/// declared name, and is escaped like one.
/// </remarks>
private string SpellReference(string reference)
{
int dot = reference.IndexOf('.', StringComparison.Ordinal);
return dot > 0 && BuiltInTypeKeywords.Contains(reference[..dot])
? $"{reference[..dot]}.{EscapeReference(reference[(dot + 1)..])}"
: EscapeReference(reference);
}

/// <summary>
/// The keywords that are also the names of built-in types.
/// </summary>
private static readonly HashSet<string> BuiltInTypeKeywords = new(StringComparer.Ordinal)
{
"bool", "byte", "char", "decimal", "double", "float", "int", "long", "object", "sbyte", "short", "string",
"uint", "ulong", "ushort",
};

/// <inheritdoc/>
/// <remarks>
/// <c>&lt;&lt;=</c> and <c>&gt;&gt;=</c> take an <c>int</c> count for the same reason a shift does, so their
Expand Down Expand Up @@ -320,7 +382,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 385 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 21 to the 15 allowed.
{
bool aliasesWereHoisted = memberAliasesHoisted;
if (!aliasesWereHoisted)
Expand Down Expand Up @@ -619,7 +681,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 684 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 @@ -627,7 +689,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 692 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 @@ -698,7 +760,7 @@
/// CS0103 (#279). The import is fully qualified because it is resolved from the scope it is in.
/// </para>
/// </remarks>
private void GenerateScopeMembers(IEnumerable<AstNode> members, string holderName, CodeBlocker code)

Check warning on line 763 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 18 to the 15 allowed.
{
AstNode[] declared = [.. members];
FunctionDeclaration[] lodged = LodgeScopeOperators(declared);
Expand Down Expand Up @@ -1024,7 +1086,7 @@
{
if (argument is MemberInitialiser designated)
{
code.Write($"{designated.Name} = ");
code.Write($"{EscapeIdentifier(designated.Name ?? string.Empty)} = ");
GenerateInternal(designated.Value!, code);
return;
}
Expand Down Expand Up @@ -1058,7 +1120,7 @@
using Scope members = new(code);
foreach (EnumMember member in enumDecl.Members)
{
code.Write(member.Name ?? "Unnamed");
code.Write(EscapeIdentifier(member.Name ?? "Unnamed"));

if (member.Value is not null)
{
Expand Down Expand Up @@ -1086,7 +1148,7 @@
string type = property.Type is TypeReference declared ? MapToCSType(declared) : "object";
string modifiers = property.IsStatic ? " static" : string.Empty;

code.Write($"{SpellVisibility(property.Visibility) ?? DefaultVisibility}{modifiers} {type} {property.Name ?? "Value"}");
code.Write($"{SpellVisibility(property.Visibility) ?? DefaultVisibility}{modifiers} {type} {EscapeIdentifier(property.Name ?? "Value")}");

// init rather than set where the declaration asked for it: the two differ only in when the
// call is legal, and nothing else here has a word for the difference. A readonly struct asks
Expand Down Expand Up @@ -1175,7 +1237,7 @@
code.Write("readonly ");
}

code.Write($"{MapToCSType(field.Type ?? new TypeReference(UnknownTypeName))} {field.Name}");
code.Write($"{MapToCSType(field.Type ?? new TypeReference(UnknownTypeName))} {EscapeIdentifier(field.Name ?? string.Empty)}");

if (field.InitialValue is not null)
{
Expand Down Expand Up @@ -1251,7 +1313,7 @@
/// <c>= default</c> means there.
/// </para>
/// </remarks>
private void GenerateFunction(FunctionDeclaration function, CodeBlocker code, ClassDeclaration? enclosingType)

Check warning on line 1316 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 21 to the 15 allowed.
{
WritePreamble(function, code, enclosingType is null ? PreambleSite.Function : PreambleSite.Method);

Expand Down Expand Up @@ -1375,7 +1437,7 @@
// value value-initialises the member, as C++'s `x()` does, and `default` is C#'s spelling.
foreach (MemberInitialiser initialiser in function.Initialisers)
{
code.Write($"this.{initialiser.Name} = ");
code.Write($"this.{EscapeIdentifier(initialiser.Name ?? string.Empty)} = ");

if (initialiser.Value is not null)
{
Expand All @@ -1398,7 +1460,7 @@
/// <param name="enclosingType">The type it belongs to, when it belongs to one.</param>
/// <param name="code">The writer to emit into.</param>
/// <returns>False when the note stands in for the whole declaration, so nothing else is written.</returns>
private bool WriteMemberNotes(FunctionDeclaration function, string name, ClassDeclaration? enclosingType, CodeBlocker code)

Check warning on line 1463 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 17 to the 15 allowed.
{
// A struct cannot have a finalizer (CS0575), so the destructor is written down rather than
// declared, the way a member C# expresses by not declaring it is.
Expand Down Expand Up @@ -1632,7 +1694,7 @@
/// <param name="function">The declaration being emitted.</param>
/// <param name="enclosingType">The name of the type it belongs to, when it belongs to one.</param>
/// <returns>The name as C# writes it.</returns>
private static string SpellFunctionName(FunctionDeclaration function, string? enclosingType)
private string SpellFunctionName(FunctionDeclaration function, string? enclosingType)
{
string typeName = enclosingType ?? function.Name ?? "UnnamedType";

Expand All @@ -1643,13 +1705,13 @@
FunctionKind.Operator => $"operator {function.Name}",
FunctionKind.ConversionOperator =>
$"{(function.IsExplicit ? "explicit" : "implicit")} operator {MapToCSType(function.ReturnType ?? new TypeReference(UnknownTypeName))}",
_ => function.Name ?? "UnnamedFunction",
_ => EscapeIdentifier(function.Name ?? "UnnamedFunction"),
};
}

private void GenerateParameter(Parameter parameter, CodeBlocker code)
{
code.Write($"{MapToCSType(parameter.Type ?? new TypeReference(UnknownTypeName))} {parameter.Name}");
code.Write($"{MapToCSType(parameter.Type ?? new TypeReference(UnknownTypeName))} {EscapeIdentifier(parameter.Name ?? string.Empty)}");

if (parameter.IsOptional && parameter.DefaultValue is Expression value)
{
Expand Down Expand Up @@ -1864,7 +1926,7 @@
code.Write("static ");
}

code.Write($"{type} {varDecl.Name}");
code.Write($"{type} {EscapeIdentifier(varDecl.Name)}");

if (varDecl.InitialValue != null)
{
Expand Down
Loading