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

/// <summary>
/// Compiles and runs what the Rust 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, and fields,
/// Compiles and runs what the Rust, C++ and Python 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>. Each name has to come out escaped where it is declared and spelled the
/// <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
/// same way wherever it is used, or the output either fails to parse or fails to resolve.
/// </summary>
/// <remarks>
Expand Down Expand Up @@ -116,6 +116,74 @@ public void Cpp_KeywordNamesCompileAndResolve()
});
}

/// <summary>
/// The Python driver. Python has no escape for a keyword either, so an escaped name has had an
/// underscore appended, and that is the name a caller uses.
/// </summary>
private const string PythonDriver = """


holder = Holder()
if holder.from_ != 3 or holder.lambda_ != 4:
raise SystemExit(1)
if holder.class_ != 1:
raise SystemExit(2)
if holder.total(5, 6) != 14:
raise SystemExit(3)
if Flag.None_ != 0 or Flag.All != 1:
raise SystemExit(4)
if def_(7) != 7:
raise SystemExit(5)

""";

/// <summary>
/// Tests that Python appends an underscore to a keyword-named field, property, parameter, local,
/// enumeration member and function, at their declarations and where they are used.
/// </summary>
[TestMethod]
public void Python_KeywordNamesRunAndResolve()
{
string? python = ToolchainHarness.FindOnPath("--version", "python3", "python");
if (python is null)
{
Assert.Inconclusive("No Python interpreter on the path, so nothing was run.");
return;
}

ToolchainHarness.InTemporaryDirectory(directory =>
{
string source = new PythonGenerator().Generate(PythonTypes()) + PythonDriver;
File.WriteAllText(Path.Combine(directory, "holder.py"), source);

(int ran, string output) = ToolchainHarness.Run(python, "holder.py", directory);
Assert.AreEqual(0, ran, $"the generated module failed, or a keyword-named member read back wrongly (driver check {ran}):{Environment.NewLine}{output}{Environment.NewLine}{source}");
});
}

/// <summary>
/// Tests that a Python reference keeps the literal words as written while escaping a keyword
/// that names a member.
/// </summary>
[TestMethod]
public void Python_ReferenceKeepsTheLiteralWordsAndEscapesTheMember()
{
FunctionDeclaration read = new("read") { ReturnType = "int" };
read.Body.Add(new VariableDeclaration("unused", "int", new VariableReference("None")));
read.Body.Add(new ReturnStatement(new VariableReference("self.from")));
ClassDeclaration holder = new("Holder");
holder.Members.Add(new VariableDeclaration("from", "int"));
holder.Members.Add(read);
SourceFile file = new("holder");
file.Members.Add(holder);

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

Assert.Contains("unused = None", source, StringComparison.Ordinal, source);
Assert.Contains("return self.from_", source, StringComparison.Ordinal, source);
Assert.DoesNotContain("None_", 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 @@ -155,6 +223,49 @@ public void Rust_PathKeywordNamesAreSuffixed()
Assert.DoesNotContain("r#super", source, StringComparison.Ordinal, source);
}

/// <summary>
/// Builds a class, an enumeration and a function whose names are Python keywords.
/// </summary>
/// <returns>The file to generate.</returns>
private static SourceFile PythonTypes()
{
ClassDeclaration holder = new("Holder");
holder.Members.Add(new VariableDeclaration("from", "int", new LiteralExpression<int>(3)));
holder.Members.Add(new VariableDeclaration("lambda", "int", new LiteralExpression<int>(4)));
holder.Members.Add(new PropertyDeclaration("class", "int")
{
GetterBody = { new ReturnStatement(new LiteralExpression<int>(1)) },
});

FunctionDeclaration total = new("total") { ReturnType = "int" };
total.Parameters.Add(new Parameter("in", "int"));
total.Parameters.Add(new Parameter("is", "int"));
total.Body.Add(new VariableDeclaration(
"pass",
"int",
new BinaryExpression(new VariableReference("in"), BinaryOperator.Add, new VariableReference("is"))));
total.Body.Add(new VariableDeclaration(
"del",
"int",
new BinaryExpression(new VariableReference("pass"), BinaryOperator.Add, new VariableReference("self.from"))));
total.Body.Add(new ReturnStatement(new VariableReference("del")));
holder.Members.Add(total);

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

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

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

/// <summary>
/// Builds a struct whose members are all named after a keyword of one target or the other.
/// </summary>
Expand Down
56 changes: 39 additions & 17 deletions Coder/Languages/PythonGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,28 @@
/// <returns>The keyword Python uses.</returns>
protected override string FormatBoolean(bool value) => value ? "True" : "False";

/// <inheritdoc/>
/// <remarks>
/// The hard keywords, which <c>keyword.kwlist</c> lists. The soft ones — <c>match</c>,
/// <c>case</c>, <c>type</c> and <c>_</c> — are keywords only where a statement starts with them
/// and are legal names everywhere else, so they are left alone. An escaped name has an underscore
/// appended, which is a rename: Python has no way to use a keyword as a name, and the trailing
/// underscore is the spelling PEP 8 gives for exactly this.
/// </remarks>
protected override IReadOnlySet<string> ReservedWords { get; } = new HashSet<string>(StringComparer.Ordinal)
{
"False", "None", "True", "and", "as", "assert", "async", "await", "break", "class", "continue", "def",
"del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import", "in", "is",
"lambda", "nonlocal", "not", "or", "pass", "raise", "return", "try", "while", "with", "yield",
};

/// <inheritdoc/>
/// <remarks>
/// The literal words, which a reference written as text means as Python means them. <c>self</c>
/// is not a keyword, so it needs no exception.
/// </remarks>
protected override bool IsReceiverWord(string word) => word is "True" or "False" or "None";

/// <summary>
/// Ends a statement. Python has no terminator, and the function body emits the line breaks, so
/// this deliberately writes nothing.
Expand Down Expand Up @@ -120,7 +142,7 @@
Ensure.NotNull(declaration);
Ensure.NotNull(code);

string name = declaration.Name ?? "value";
string name = EscapeIdentifier(declaration.Name ?? "value");
// The two spellings of a type: an annotation on a name is a colon, and on a function it is
// an arrow. Same type, and Python is particular about which goes where.
string annotation = declaration.Type is TypeReference type ? $": {PythonTypeFromGenericType(type)}" : string.Empty;
Expand Down Expand Up @@ -185,14 +207,14 @@
if (declaration.CanRead)
{
code.WriteLine("@staticmethod");
code.Write($"def {declaration.GetterName(NamingStyle.Snake)}(){result}:");
code.Write($"def {EscapeIdentifier(declaration.GetterName(NamingStyle.Snake))}(){result}:");
WriteAccessorBody(declaration, isSetter: false, code);
}

if (declaration.CanWrite)
{
code.WriteLine("@staticmethod");
code.Write($"def {declaration.SetterName(NamingStyle.Snake)}(value{annotation}) -> None:");
code.Write($"def {EscapeIdentifier(declaration.SetterName(NamingStyle.Snake))}(value{annotation}) -> None:");
WriteAccessorBody(declaration, isSetter: true, code);
}
}
Expand Down Expand Up @@ -269,7 +291,7 @@
/// <c>float("nan")</c> does not.
/// </remarks>
protected override string SpellNonFiniteDouble(double value) =>
double.IsNaN(value) ? "float(\"nan\")" : value > 0 ? "float(\"inf\")" : "float(\"-inf\")";

Check warning on line 294 in Coder/Languages/PythonGenerator.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 294 in Coder/Languages/PythonGenerator.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 294 in Coder/Languages/PythonGenerator.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 294 in Coder/Languages/PythonGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Extract this nested ternary operation into an independent statement.

/// <inheritdoc/>
protected override IEnumerable<string> RequiredImports(SourceFile file)
Expand Down Expand Up @@ -352,7 +374,7 @@
Ensure.NotNull(code);

WritePreamble(usingAlias, code, PreambleSite.Type);
code.WriteLine($"{usingAlias.Name} = {PythonTypeFromGenericType(usingAlias.AliasedType ?? new TypeReference("object"))}");
code.WriteLine($"{EscapeIdentifier(usingAlias.Name ?? string.Empty)} = {PythonTypeFromGenericType(usingAlias.AliasedType ?? new TypeReference("object"))}");
}

/// <inheritdoc/>
Expand Down Expand Up @@ -429,7 +451,7 @@

if (elements[index] is MemberInitialiser member)
{
code.Write($"{member.Name}=");
code.Write($"{EscapeIdentifier(member.Name ?? string.Empty)}=");
GenerateInternal(member.Value!, code);
continue;
}
Expand All @@ -456,7 +478,7 @@
Ensure.NotNull(code);

WritePreamble(enumDecl, code, PreambleSite.Enum);
code.WriteLine($"class {enumDecl.Name ?? "UnnamedEnum"}(IntEnum):");
code.WriteLine($"class {EscapeIdentifier(enumDecl.Name ?? "UnnamedEnum")}(IntEnum):");

using IndentScope body = new(code);
if (enumDecl.Members.Count == 0)
Expand All @@ -467,7 +489,7 @@

foreach ((EnumMember member, string value) in enumDecl.Members.Zip(EnumMemberValues(enumDecl)))
{
code.WriteLine($"{member.Name ?? "UNNAMED"} = {value}");
code.WriteLine($"{EscapeIdentifier(member.Name ?? "UNNAMED")} = {value}");
}
}

Expand All @@ -483,7 +505,7 @@
Ensure.NotNull(code);

WritePreamble(field, code, PreambleSite.Field);
code.Write(field.Name ?? "unnamed");
code.Write(EscapeIdentifier(field.Name ?? "unnamed"));

if (field.Type is TypeReference type)
{
Expand Down Expand Up @@ -545,7 +567,7 @@

if (globals.Count > 0)
{
code.WriteLine($"global {string.Join(", ", globals)}");
code.WriteLine($"global {string.Join(", ", globals.Select(EscapeIdentifier))}");
}
}

Expand All @@ -562,7 +584,7 @@
WriteTypeParametersDown(funcDecl.TypeParameters, code);

// Function signature
code.Write($"def {funcDecl.Name ?? "unnamed_function"}(");
code.Write($"def {EscapeIdentifier(funcDecl.Name ?? "unnamed_function")}(");
GenerateParameterList(funcDecl.Parameters, code);
code.Write(")");

Expand Down Expand Up @@ -625,7 +647,7 @@
// class generated on its own -- the same reason @dataclass is not written above.
WriteTypeParametersDown(classDecl.TypeParameters, code);

code.Write($"class {classDecl.Name ?? "UnnamedClass"}");
code.Write($"class {EscapeIdentifier(classDecl.Name ?? "UnnamedClass")}");

// Python inherits from as many things as it is given and has no separate notion of an
// interface, so the base and the interfaces are one list of bases -- which is what the
Expand Down Expand Up @@ -782,7 +804,7 @@

private void WriteInstanceInitialiser(FieldDeclaration field, CodeBlocker code)
{
code.Write($"self.{field.Name ?? "unnamed"} = ");
code.Write($"self.{EscapeIdentifier(field.Name ?? "unnamed")} = ");
GenerateInternal(field.InitialValue!, code);
code.WriteLine();
}
Expand Down Expand Up @@ -849,7 +871,7 @@
{
foreach (MemberInitialiser initialiser in method.Initialisers)
{
code.Write($"self.{initialiser.Name} = ");
code.Write($"self.{EscapeIdentifier(initialiser.Name ?? string.Empty)} = ");

if (initialiser.Value is not null)
{
Expand All @@ -873,11 +895,11 @@
/// A constructor and a destructor have fixed names in Python rather than the type's, so whatever
/// the declaration is called is ignored for those two.
/// </remarks>
private static string SpellMethodName(FunctionDeclaration method) => method.Kind switch
private string SpellMethodName(FunctionDeclaration method) => method.Kind switch
{
FunctionKind.Constructor => "__init__",
FunctionKind.Destructor => "__del__",
_ => method.Name ?? "unnamed_method",
_ => EscapeIdentifier(method.Name ?? "unnamed_method"),
};

/// <inheritdoc/>
Expand Down Expand Up @@ -946,7 +968,7 @@
Ensure.NotNull(parameter);
Ensure.NotNull(code);

code.Write(parameter.Name ?? $"param{position}");
code.Write(EscapeIdentifier(parameter.Name ?? $"param{position}"));

// Type hints are optional in Python, so they are emitted only when the AST carries one.
if (parameter.Type is not null)
Expand Down Expand Up @@ -1080,7 +1102,7 @@
Ensure.NotNull(code);
RegisterStaticType(varDecl);

code.Write(varDecl.Name);
code.Write(EscapeIdentifier(varDecl.Name));

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