diff --git a/Coder.Test/Languages/CompoundIntegerDivisionTests.cs b/Coder.Test/Languages/CompoundIntegerDivisionTests.cs new file mode 100644 index 0000000..9ce7507 --- /dev/null +++ b/Coder.Test/Languages/CompoundIntegerDivisionTests.cs @@ -0,0 +1,189 @@ +// Copyright (c) 2023-2026 ktsu-dev contributors + +namespace ktsu.Coder.Test.Languages; + +using System.Globalization; +using System.Text; +using ktsu.Coder.Ast; +using ktsu.Coder.Languages; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +/// +/// Tests that integer /= and %= mean the same thing in Python and JavaScript as in the C +/// family. +/// +/// +/// The compound-assignment counterpart of . Python's and JavaScript's +/// /= are true division, so a = 5; a /= 2 leaves 2.5, and Python's %= floors, +/// so a = -7; a %= 2 leaves 1 where the C family leaves -1. The generated code is +/// run rather than read. +/// +[TestClass] +public class CompoundIntegerDivisionTests +{ + private static readonly (int Left, int Right)[] Operands = [(-7, 2), (7, -2), (-7, -2), (7, 2), (-6, 3), (0, -5), (5, 2)]; + + /// + /// The functions under test, each of which applies a compound assignment to an integer and returns + /// it: to a parameter, to a typed local, with a literal divisor, and with a divisor that is a call, + /// which must not be made twice. + /// + private static IEnumerable Functions() + { + foreach (AssignmentOperator op in new[] { AssignmentOperator.DivideAssign, AssignmentOperator.ModuloAssign }) + { + string name = op == AssignmentOperator.DivideAssign ? "div" : "mod"; + + FunctionDeclaration parameters = new($"{name}_params") { ReturnType = new TypeReference("int") }; + parameters.Parameters.Add(new Parameter("a", "int")); + parameters.Parameters.Add(new Parameter("b", "int")); + parameters.Body.Add(new AssignmentStatement(new VariableReference("a"), new VariableReference("b"), op)); + parameters.Body.Add(new ReturnStatement(new VariableReference("a"))); + yield return parameters; + + FunctionDeclaration local = new($"{name}_local") { ReturnType = new TypeReference("int") }; + local.Parameters.Add(new Parameter("a", "int")); + local.Parameters.Add(new Parameter("b", "int")); + local.Body.Add(new VariableDeclaration("q", "int", new VariableReference("a"))); + local.Body.Add(new AssignmentStatement(new VariableReference("q"), new VariableReference("b"), op)); + local.Body.Add(new ReturnStatement(new VariableReference("q"))); + yield return local; + + FunctionDeclaration literal = new($"{name}_literal") { ReturnType = new TypeReference("int") }; + literal.Parameters.Add(new Parameter("a", "int")); + literal.Parameters.Add(new Parameter("b", "int")); + literal.Body.Add(new AssignmentStatement(new VariableReference("a"), new LiteralExpression(2), op)); + literal.Body.Add(new ReturnStatement(new VariableReference("a"))); + yield return literal; + + FunctionDeclaration call = new($"{name}_call") { ReturnType = new TypeReference("int") }; + call.Parameters.Add(new Parameter("a", "int")); + call.Parameters.Add(new Parameter("b", "int")); + CallExpression counted = new("counted") { ExpectedType = "int" }; + counted.Arguments.Add(new VariableReference("b")); + call.Body.Add(new AssignmentStatement(new VariableReference("a"), counted, op)); + call.Body.Add(new ReturnStatement(new VariableReference("a"))); + yield return call; + } + } + + private static int Expected(string function, int left, int right) + { + int divisor = function.EndsWith("_literal", StringComparison.Ordinal) ? 2 : right; + return function.StartsWith("div", StringComparison.Ordinal) ? left / divisor : left % divisor; + } + + /// + /// Tests that Python computes the C family's quotient and remainder, as an int, and makes + /// the divisor's call once. + /// + [TestMethod] + public void Python_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; + } + + PythonGenerator generator = new(); + StringBuilder module = new(); + module.AppendLine("calls = 0"); + module.AppendLine("def counted(x):"); + module.AppendLine(" global calls"); + module.AppendLine(" calls += 1"); + module.AppendLine(" return x"); + foreach (FunctionDeclaration function in Functions()) + { + module.AppendLine(generator.Generate(function)); + } + + foreach (FunctionDeclaration function in Functions()) + { + foreach ((int left, int right) in Operands) + { + string arguments = string.Create(CultureInfo.InvariantCulture, $"{left}, {right}"); + int expected = Expected(function.Name!, left, right); + module.AppendLine("calls = 0"); + module.AppendLine(CultureInfo.InvariantCulture, $"r = {function.Name}({arguments})"); + module.AppendLine(CultureInfo.InvariantCulture, $"assert type(r) is int and r == {expected}, f\"{function.Name}({arguments}) = {{r!r}}, expected {expected}\""); + if (function.Name!.EndsWith("_call", StringComparison.Ordinal)) + { + module.AppendLine(CultureInfo.InvariantCulture, $"assert calls == 1, f\"{function.Name}({arguments}) made {{calls}} calls\""); + } + } + } + + Run(python, "check.py", module.ToString()); + } + + /// + /// Tests that JavaScript computes the C family's quotient and remainder, and makes the divisor's + /// call once. + /// + [TestMethod] + public void JavaScript_MatchesTheCFamily() + { + string? node = ToolchainHarness.FindOnPath("--version", "node"); + if (node is null) + { + Assert.Inconclusive("No JavaScript runtime on the path, so nothing was run."); + return; + } + + JavaScriptGenerator generator = new(); + StringBuilder module = new(); + module.AppendLine("let calls = 0;"); + module.AppendLine("function counted(x) { calls++; return x; }"); + foreach (FunctionDeclaration function in Functions()) + { + module.AppendLine(generator.Generate(function)); + } + + foreach (FunctionDeclaration function in Functions()) + { + foreach ((int left, int right) in Operands) + { + string arguments = string.Create(CultureInfo.InvariantCulture, $"{left}, {right}"); + int expected = Expected(function.Name!, left, right); + + // Strict equality rather than Object.is: JavaScript's -0 is an integer zero to every + // arithmetic and comparison a consumer would make of it. + module.AppendLine(CultureInfo.InvariantCulture, $"{{ calls = 0; const r = {function.Name}({arguments}); if (r !== {expected}) {{ throw new Error(`{function.Name}({arguments}) = ${{r}}, expected {expected}`); }} if (calls > 1) {{ throw new Error(`{function.Name}({arguments}) made ${{calls}} calls`); }} }}"); + } + } + + Run(node, "check.js", module.ToString()); + } + + /// + /// Tests that a compound assignment the AST does not know to be on integers, and every other + /// compound operator, is left as it is. + /// + /// The generator to ask. + [TestMethod] + [DataRow("python")] + [DataRow("javascript")] + public void OtherCompoundAssignments_AreUnchanged(string language) + { + ILanguageGenerator generator = language == "python" ? new PythonGenerator() : new JavaScriptGenerator(); + + AssignmentStatement unknown = new(new VariableReference("a"), new VariableReference("b"), AssignmentOperator.DivideAssign); + AssignmentStatement doubles = new(new VariableReference("a"), new LiteralExpression(2.0), AssignmentOperator.DivideAssign); + AssignmentStatement add = new(new VariableReference("a"), new LiteralExpression(2), AssignmentOperator.AddAssign); + string end = language == "python" ? string.Empty : ";"; + + Assert.AreEqual($"a /= b{end}", generator.Generate(unknown).Trim()); + Assert.AreEqual($"a /= 2.0{end}", generator.Generate(doubles).Trim()); + Assert.AreEqual($"a += 2{end}", generator.Generate(add).Trim()); + } + + private static void Run(string runtime, string fileName, string source) => + ToolchainHarness.InTemporaryDirectory(directory => + { + File.WriteAllText(Path.Combine(directory, fileName), source); + (int exitCode, string output) = ToolchainHarness.Run(runtime, fileName, directory); + Assert.AreEqual(0, exitCode, $"{output}{Environment.NewLine}{source}"); + }); +} diff --git a/Coder/Languages/JavaScriptGenerator.cs b/Coder/Languages/JavaScriptGenerator.cs index ba57f49..f7a5cb5 100644 --- a/Coder/Languages/JavaScriptGenerator.cs +++ b/Coder/Languages/JavaScriptGenerator.cs @@ -655,6 +655,33 @@ protected override void GenerateBinary(BinaryExpression binary, CodeBlocker code code.Write(")"); } + /// + /// + /// x /= y is true division, the same as /, so on integers it gives 2.5 for + /// 5 /= 2 where the C family gives 2. When both sides are known to be integers the + /// assignment is written out as x = Math.trunc(x / y) through . + /// %= already matches the C family, and every other compound assignment is left as it is. + /// + protected override void GenerateAssignmentStatement(AssignmentStatement assignment, CodeBlocker code) + { + Ensure.NotNull(assignment); + Ensure.NotNull(code); + + BinaryExpression? binary = assignment.Operator == AssignmentOperator.DivideAssign + ? new(assignment.Target, BinaryOperator.Divide, assignment.Value) + : null; + if (binary is null || !IsIntegerArithmetic(binary)) + { + base.GenerateAssignmentStatement(assignment, code); + return; + } + + GenerateInternal(assignment.Target, code); + code.Write(" = "); + GenerateBinary(binary, code); + EndStatement(code); + } + /// /// Maps a binary operator to its JavaScript spelling. /// diff --git a/Coder/Languages/PythonGenerator.cs b/Coder/Languages/PythonGenerator.cs index 0260696..6353bcf 100644 --- a/Coder/Languages/PythonGenerator.cs +++ b/Coder/Languages/PythonGenerator.cs @@ -1018,6 +1018,40 @@ protected override void GenerateBinary(BinaryExpression binary, CodeBlocker code code.Write(")"); } + /// + /// + /// x /= y and x %= y are Python's true division and floored remainder, the same as + /// the binary operators, so on integers they give 2.5 for 5 /= 2 and 1 for + /// -7 %= 2 where the C family gives 2 and -1. When both sides are known to be + /// integers the assignment is written out as x = x / y, whose quotient or remainder + /// truncates. Every other compound assignment, and one on operands + /// the AST does not know to be integers, is left as it is. + /// + protected override void GenerateAssignmentStatement(AssignmentStatement assignment, CodeBlocker code) + { + Ensure.NotNull(assignment); + Ensure.NotNull(code); + + BinaryOperator? op = assignment.Operator switch + { + AssignmentOperator.DivideAssign => BinaryOperator.Divide, + AssignmentOperator.ModuloAssign => BinaryOperator.Modulo, + _ => null, + }; + + BinaryExpression? binary = op is null ? null : new(assignment.Target, op.Value, assignment.Value); + if (binary is null || !IsIntegerArithmetic(binary)) + { + base.GenerateAssignmentStatement(assignment, code); + return; + } + + GenerateInternal(assignment.Target, code); + code.Write(" = "); + GenerateBinary(binary, code); + EndStatement(code); + } + /// /// Writes the C family's truncating quotient or remainder of two integers in integer arithmetic. ///