diff --git a/Coder.Test/Languages/CallResultIntegerDivisionTests.cs b/Coder.Test/Languages/CallResultIntegerDivisionTests.cs index dbd7507..de1a414 100644 --- a/Coder.Test/Languages/CallResultIntegerDivisionTests.cs +++ b/Coder.Test/Languages/CallResultIntegerDivisionTests.cs @@ -9,7 +9,8 @@ namespace ktsu.Coder.Test.Languages; /// /// 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). /// /// /// twice(a) / 4 with twice declared int is -3 for a = -7 in C, C++, @@ -150,6 +151,137 @@ public void UnknownOrOverloadedCallee_StaysTrueDivision() Assert.DoesNotContain("Math.trunc", javascript, StringComparison.Ordinal, javascript); } + /// + /// A file holding class Box { int doubled(int a) } and, for / and %, a function + /// taking a Box b that divides b.doubled(a) once into a typed local and once in a return + /// (#280). + /// + 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; + } + } + + /// + /// Tests that Python truncates a division and a remainder of an int method's result on a + /// receiver of a known class. + /// + [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()); + } + + /// + /// Tests that JavaScript truncates a division and a remainder of an int method's result on a + /// receiver of a known class. + /// + [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()); + } + + /// + /// 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. + /// + [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 => { diff --git a/Coder/Languages/StandardLanguageGenerator.cs b/Coder/Languages/StandardLanguageGenerator.cs index 6e0f174..cf824e8 100644 --- a/Coder/Languages/StandardLanguageGenerator.cs +++ b/Coder/Languages/StandardLanguageGenerator.cs @@ -345,6 +345,8 @@ protected void RegisterStaticType(VariableDeclaration declaration) 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 @@ -410,6 +412,44 @@ or BinaryOperator.LogicalAnd return matches.Length == 1 ? matches[0].ReturnType : null; } + /// + /// Reads the return type of the one method a call on a receiver of a known type can name. + /// + /// The receiver's type, or null when it is unknown. + /// The name the call is written with. + /// + /// 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. + /// + /// + /// The receiver-less case (#273) left b.size() / 2 of unknown type, so Python and JavaScript + /// still divided it truly although Box.size is declared int (#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. + /// + 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() + .Where(declaration => declaration.Name == receiverType.Name) + .Take(2)]; + if (classes.Length != 1) + { + return null; + } + + FunctionDeclaration[] matches = [.. classes[0].Members + .OfType() + .Where(function => function.Name == callee) + .Take(2)]; + return matches.Length == 1 ? matches[0].ReturnType : null; + } + /// /// The numeric types in the order a mixed operation widens to, narrowest first. ///