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
59 changes: 59 additions & 0 deletions Coder.Test/Languages/PythonGeneratedSourceImportsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,65 @@ assert mutable.State
});
}

/// <summary>
/// Tests that a subclass declaring no constructor still accepts its base's arguments: one with
/// nothing to initialise inherits the base's constructor, and one with an instance-initialised
/// field forwards to it (#149).
/// </summary>
[TestMethod]
public void SubclassWithoutConstructor_AcceptsTheBaseConstructorsArguments()
{
string? python = ToolchainHarness.FindOnPath("--version", "python3", "python");
if (python is null)
{
Assert.Inconclusive("No Python interpreter on the path, so nothing was run.");
return;
}

SourceFile file = new("inherited");

// Base(x): self.x = x
ClassDeclaration baseClass = new("Base");
FunctionDeclaration constructor = new("Base") { Kind = FunctionKind.Constructor };
constructor.Parameters.Add(new Parameter("x", "int"));
constructor.Body.Add(new AssignmentStatement(new VariableReference("self.x"), new VariableReference("x")));
baseClass.Members.Add(constructor);
file.Members.Add(baseClass);

file.Members.Add(new ClassDeclaration("Derived") { BaseType = "Base" });

ClassDeclaration tagged = new("Tagged") { BaseType = "Base" };
tagged.Members.Add(new FieldDeclaration("tags", TypeReference.Parse("list<int>"))
{
InitialValue = new ConstructionExpression(),
});
file.Members.Add(tagged);

ToolchainHarness.InTemporaryDirectory(directory =>
{
string generated = new PythonGenerator().Generate(file);
File.WriteAllText(Path.Combine(directory, "inherited.py"), generated);
File.WriteAllText(
Path.Combine(directory, "driver.py"),
"""
import inherited

derived = inherited.Derived(5)
assert derived.x == 5, derived.x

first = inherited.Tagged(6)
second = inherited.Tagged(x=7)
assert first.x == 6, first.x
assert second.x == 7, second.x
first.tags.append(1)
assert second.tags == [], second.tags
""");

(int exitCode, string output) = ToolchainHarness.Run(python, "driver.py", directory);
Assert.AreEqual(0, exitCode, $"Python rejected the generated module:{Environment.NewLine}{output}{Environment.NewLine}{generated}");
});
}

/// <summary>
/// Tests that a module whose annotations name a class that does not exist yet can be loaded.
/// </summary>
Expand Down
15 changes: 10 additions & 5 deletions Coder/Languages/PythonGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,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 258 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 258 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 @@ -554,8 +554,10 @@
bool hasConstructor = classDecl.Members
.OfType<FunctionDeclaration>()
.Any(member => member.Kind == FunctionKind.Constructor);
bool synthesiseConstructor = !hasConstructor
&& (classDecl.BaseType is not null || instanceInitialisedFields.Count > 0);
// Python inherits a constructor, so a class with nothing of its own to initialise writes
// none and takes whatever its base takes. One written for a subclass would hide the base's
// and refuse its arguments.
bool synthesiseConstructor = !hasConstructor && instanceInitialisedFields.Count > 0;

if (classDecl.Members.Count == 0 && !synthesiseConstructor)
{
Expand All @@ -580,11 +582,14 @@

if (synthesiseConstructor)
{
code.WriteLine("def __init__(self):");
// A subclass's constructor passes on whatever it is given, so it still accepts what the
// base's constructor does and only adds the initialisers.
bool forwards = classDecl.BaseType is not null;
code.WriteLine(forwards ? "def __init__(self, *args, **kwargs):" : "def __init__(self):");
using IndentScope body = new(code);
if (classDecl.BaseType is not null)
if (forwards)
{
code.WriteLine("super().__init__()");
code.WriteLine("super().__init__(*args, **kwargs)");
}

WriteConstructorPrologue(classDecl, code, NeedsConstruction, WriteInstanceInitialiser);
Expand Down
Loading