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
134 changes: 133 additions & 1 deletion Coder.Test/Languages/CallResultIntegerDivisionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ namespace ktsu.Coder.Test.Languages;

/// <summary>
/// Tests that a call to a function declared beside it is known to return what that function says, so
/// Python and JavaScript divide its result the way the C family does (#273).
/// Python and JavaScript divide its result the way the C family does (#273), whether it is a free
/// function or a method on a receiver of a known class (#280).
/// </summary>
/// <remarks>
/// <c>twice(a) / 4</c> with <c>twice</c> declared <c>int</c> is <c>-3</c> for <c>a = -7</c> in C, C++,
Expand Down Expand Up @@ -150,6 +151,137 @@ public void UnknownOrOverloadedCallee_StaysTrueDivision()
Assert.DoesNotContain("Math.trunc", javascript, StringComparison.Ordinal, javascript);
}

/// <summary>
/// A file holding <c>class Box { int doubled(int a) }</c> and, for <c>/</c> and <c>%</c>, a function
/// taking a <c>Box b</c> that divides <c>b.doubled(a)</c> once into a typed local and once in a return
/// (#280).
/// </summary>
private static SourceFile ReceiverFile()
{
SourceFile file = new("calls");

ClassDeclaration box = new("Box");
FunctionDeclaration doubled = new("doubled") { ReturnType = new TypeReference("int") };
doubled.Parameters.Add(new Parameter("a", "int"));
doubled.Body.Add(new ReturnStatement(new BinaryExpression(new VariableReference("a"), BinaryOperator.Multiply, Literal.Number(2))));
box.Members.Add(doubled);
file.Members.Add(box);

foreach ((string name, BinaryOperator op) in new[] { ("half", BinaryOperator.Divide), ("rest", BinaryOperator.Modulo) })
{
FunctionDeclaration local = new($"{name}_local") { ReturnType = new TypeReference("int") };
local.Parameters.Add(new Parameter("b", "Box"));
local.Parameters.Add(new Parameter("a", "int"));
local.Body.Add(new VariableDeclaration("t", "int", Doubled()));
local.Body.Add(new AssignmentStatement(new VariableReference("t"), new BinaryExpression(Doubled(), op, Literal.Number(4))));
local.Body.Add(new ReturnStatement(new VariableReference("t")));
file.Members.Add(local);

FunctionDeclaration returned = new($"{name}_return") { ReturnType = new TypeReference("int") };
returned.Parameters.Add(new Parameter("b", "Box"));
returned.Parameters.Add(new Parameter("a", "int"));
returned.Body.Add(new ReturnStatement(new BinaryExpression(Doubled(), op, Literal.Number(4))));
file.Members.Add(returned);
}

return file;

static CallExpression Doubled()
{
CallExpression call = new(new VariableReference("b"), "doubled");
call.Arguments.Add(new VariableReference("a"));
return call;
}
}

/// <summary>
/// Tests that Python truncates a division and a remainder of an <c>int</c> method's result on a
/// receiver of a known class.
/// </summary>
[TestMethod]
public void Python_MethodCallResultOnATypedReceiver_MatchesTheCFamily()
{
string? python = ToolchainHarness.FindOnPath("--version", "python3", "python");
if (python is null)
{
Assert.Inconclusive("No Python interpreter on the path, so nothing was run.");
return;
}

StringBuilder module = new(new PythonGenerator().Generate(ReceiverFile()));
module.AppendLine();
foreach ((string function, int argument, int expected) in Cases())
{
module.AppendLine(FormattableString.Invariant($"r = {function}(Box(), {argument})"));
module.AppendLine(FormattableString.Invariant($"assert type(r) is int and r == {expected}, f\"{function}({argument}) = {{r!r}}, expected {expected}\""));
}

Run(python, "check.py", module.ToString());
}

/// <summary>
/// Tests that JavaScript truncates a division and a remainder of an <c>int</c> method's result on a
/// receiver of a known class.
/// </summary>
[TestMethod]
public void JavaScript_MethodCallResultOnATypedReceiver_MatchesTheCFamily()
{
string? node = ToolchainHarness.FindOnPath("--version", "node");
if (node is null)
{
Assert.Inconclusive("No JavaScript runtime on the path, so nothing was run.");
return;
}

StringBuilder module = new(new JavaScriptGenerator().Generate(ReceiverFile()));
module.AppendLine();
foreach ((string function, int argument, int expected) in Cases())
{
module.AppendLine(FormattableString.Invariant($"{{ const r = {function}(new Box(), {argument}); if (r !== {expected}) {{ throw new Error(`{function}({argument}) = ${{r}}, expected {expected}`); }} }}"));
}

Run(node, "check.js", module.ToString());
}

/// <summary>
/// Tests that a method call on an untyped receiver, on a class not declared in the tree, or naming an
/// overloaded method is still of unknown type, so its division is left as the target's own.
/// </summary>
[TestMethod]
public void UntypedReceiverUnknownClassOrOverloadedMethod_StaysTrueDivision()
{
SourceFile file = new("calls");

ClassDeclaration box = new("Box");
FunctionDeclaration first = new("size") { ReturnType = new TypeReference("int") };
first.Body.Add(new ReturnStatement(Literal.Number(1)));
box.Members.Add(first);
FunctionDeclaration second = new("size") { ReturnType = new TypeReference("double") };
second.Parameters.Add(new Parameter("scale", "double"));
second.Body.Add(new ReturnStatement(new VariableReference("scale")));
box.Members.Add(second);
FunctionDeclaration count = new("count") { ReturnType = new TypeReference("int") };
count.Body.Add(new ReturnStatement(Literal.Number(1)));
box.Members.Add(count);
file.Members.Add(box);

FunctionDeclaration divides = new("divides") { ReturnType = new TypeReference("int") };
divides.Parameters.Add(new Parameter("b", "Box"));
divides.Parameters.Add(new Parameter("e", "Elsewhere"));
divides.Body.Add(new ReturnStatement(new BinaryExpression(new CallExpression(new VariableReference("b"), "size"), BinaryOperator.Divide, Literal.Number(4))));
divides.Body.Add(new ReturnStatement(new BinaryExpression(new CallExpression(new VariableReference("e"), "count"), BinaryOperator.Divide, Literal.Number(4))));
divides.Body.Add(new ReturnStatement(new BinaryExpression(new CallExpression(new VariableReference("u"), "count"), BinaryOperator.Divide, Literal.Number(4))));
file.Members.Add(divides);

string python = new PythonGenerator().Generate(file);
Assert.Contains("(b.size() / 4)", python, StringComparison.Ordinal, python);
Assert.Contains("(e.count() / 4)", python, StringComparison.Ordinal, python);
Assert.Contains("(u.count() / 4)", python, StringComparison.Ordinal, python);

string javascript = new JavaScriptGenerator().Generate(file);
Assert.DoesNotContain("Math.trunc", javascript, StringComparison.Ordinal, javascript);
}

private static void Run(string runtime, string fileName, string source) =>
ToolchainHarness.InTemporaryDirectory(directory =>
{
Expand Down
40 changes: 40 additions & 0 deletions Coder/Languages/StandardLanguageGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@
/// without this its body has no scope and a typed local or the setter's value is not known to be
/// an integer.
/// </remarks>
protected IDisposable OpenStaticTypeScope(PropertyDeclaration property, bool isSetter, string valueName = "value")

Check warning on line 109 in Coder/Languages/StandardLanguageGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

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

Check warning on line 109 in Coder/Languages/StandardLanguageGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

All 'OpenStaticTypeScope' method overloads should be adjacent.

Check warning on line 109 in Coder/Languages/StandardLanguageGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

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

Check warning on line 109 in Coder/Languages/StandardLanguageGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

All 'OpenStaticTypeScope' method overloads should be adjacent.

Check warning on line 109 in Coder/Languages/StandardLanguageGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

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

Check warning on line 109 in Coder/Languages/StandardLanguageGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

All 'OpenStaticTypeScope' method overloads should be adjacent.
{
Ensure.NotNull(property);
Ensure.NotNull(valueName);
Expand Down Expand Up @@ -195,7 +195,7 @@
return null;
}

return left == "double" || right == "double" ? "double" : "float";

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

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

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

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

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

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

private static string? FloatingTypeName(TypeReference? type) =>
Expand Down Expand Up @@ -345,6 +345,8 @@
return construction.Type;
case CallExpression { Receiver: null } call:
return DeclaredReturnType(call.Callee);
case CallExpression { Receiver: Expression receiver } call:
return DeclaredMethodReturnType(StaticType(receiver), call.Callee);
case ConditionalExpression conditional:
return Promoted(StaticType(conditional.WhenTrue), StaticType(conditional.WhenFalse));
case BinaryExpression binary when binary.Operator is BinaryOperator.Equal
Expand Down Expand Up @@ -410,6 +412,44 @@
return matches.Length == 1 ? matches[0].ReturnType : null;
}

/// <summary>
/// Reads the return type of the one method a call on a receiver of a known type can name.
/// </summary>
/// <param name="receiverType">The receiver's type, or null when it is unknown.</param>
/// <param name="callee">The name the call is written with.</param>
/// <returns>
/// The method's return type, or null when the receiver's type is unknown, is not exactly one class
/// in what is being generated, or that class has no method or more than one with the name.
/// </returns>
/// <remarks>
/// The receiver-less case (#273) left <c>b.size() / 2</c> of unknown type, so Python and JavaScript
/// still divided it truly although <c>Box.size</c> is declared <c>int</c> (#280). Only the class's
/// own members are looked at: a method it inherits, an overload, or a class declared outside the
/// tree could return something else, so each keeps the type unknown.
/// </remarks>
private TypeReference? DeclaredMethodReturnType(TypeReference? receiverType, string callee)
{
if (GenerationRoot is null || receiverType is null or { IsArray: true } || string.IsNullOrEmpty(callee))
{
return null;
}

ClassDeclaration[] classes = [.. SelfAndDescendants(GenerationRoot)
.OfType<ClassDeclaration>()
.Where(declaration => declaration.Name == receiverType.Name)
.Take(2)];
if (classes.Length != 1)
{
return null;
}

FunctionDeclaration[] matches = [.. classes[0].Members
.OfType<FunctionDeclaration>()
.Where(function => function.Name == callee)
.Take(2)];
return matches.Length == 1 ? matches[0].ReturnType : null;
}

/// <summary>
/// The numeric types in the order a mixed operation widens to, narrowest first.
/// </summary>
Expand Down
Loading