From c9c25875f4b2bddb958e43ffbb974577f63ab9df Mon Sep 17 00:00:00 2001 From: Matthew Edmondson Date: Fri, 30 Oct 2026 06:39:46 +0000 Subject: [PATCH] Wrap Python's ~ on unsigned and << on fixed-width integers to the C family's width [patch] Python integers are unbounded, so ~x on a uint or ulong was negative and x << n on an int, uint, long or ulong never wrapped, disagreeing with every other target. ~ on uint/ulong is now masked to its width, << on the four fixed-width types (and <<=) is masked or wrapped back into the signed range, keyed on the left operand's static type. ~ on signed integers already matched two's complement and is unchanged. Fixes #351 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017vfJW6NRQ27ovPhjARcxRW --- .../WideIntegerBitwiseOperatorTests.cs | 84 +++++++++++++++- Coder/Languages/PythonGenerator.cs | 96 ++++++++++++++++++- 2 files changed, 172 insertions(+), 8 deletions(-) diff --git a/Coder.Test/Languages/WideIntegerBitwiseOperatorTests.cs b/Coder.Test/Languages/WideIntegerBitwiseOperatorTests.cs index 959d6f4..8478e0c 100644 --- a/Coder.Test/Languages/WideIntegerBitwiseOperatorTests.cs +++ b/Coder.Test/Languages/WideIntegerBitwiseOperatorTests.cs @@ -10,13 +10,15 @@ namespace ktsu.Coder.Test.Languages; /// /// Tests that the bitwise and shift operators on a long, ulong or uint give C#'s -/// answer in JavaScript (#256). +/// answer in JavaScript (#256), and that ~ and << on the fixed-width integers give it +/// in Python (#351). /// /// /// JavaScript converts the operands of these operators to a signed 32-bit integer, so /// 1 | 4294967296 was 1 and a uint of three billion shifted right by one was -/// negative. The generated code is run rather than read, since the wrong answer is a number like the -/// right one. +/// negative. Python's integers are unbounded, so ~ on a uint was negative and +/// 1 << 31 on an int did not wrap. The generated code is run rather than read, since the +/// wrong answer is a number like the right one. /// [TestClass] public class WideIntegerBitwiseOperatorTests @@ -43,6 +45,22 @@ private sealed record Case(string Name, string Type, string Input, string Expect new("xor_assign_uint", "uint", "2147483648", Invariant(2147483648U ^ 1U), f => Assigning(f, AssignmentOperator.BitwiseXorAssign, new LiteralExpression(1))), ]; + /// + /// Python only: results past 2^53 are rounded by JavaScript's number conversion, which #256 accepted. + /// + private static readonly Case[] FixedWidthCases = + [ + new("not_uint_5", "uint", "5", Invariant(~5U), f => Returning(f, new UnaryExpression(UnaryOperator.BitwiseNot, X()))), + new("not_ulong", "ulong", "5", Invariant(~5UL), f => Returning(f, new UnaryExpression(UnaryOperator.BitwiseNot, X()))), + new("not_int", "int", "5", Invariant(~5), f => Returning(f, new UnaryExpression(UnaryOperator.BitwiseNot, X()))), + new("shl_int", "int", "1", Invariant(1 << 31), f => Returning(f, new BinaryExpression(X(), BinaryOperator.LeftShift, new LiteralExpression(31)))), + new("shl_int_overflow", "int", "3", Invariant(3 << 31), f => Returning(f, new BinaryExpression(X(), BinaryOperator.LeftShift, new LiteralExpression(31)))), + new("shl_long_wrap", "long", "1", Invariant(1L << 63), f => Returning(f, new BinaryExpression(X(), BinaryOperator.LeftShift, new LiteralExpression(63)))), + new("shl_ulong", "ulong", "3", Invariant(3UL << 63), f => Returning(f, new BinaryExpression(X(), BinaryOperator.LeftShift, new LiteralExpression(63)))), + new("shl_assign_int", "int", "1", Invariant(1 << 31), f => Assigning(f, AssignmentOperator.LeftShiftAssign, new LiteralExpression(31))), + new("shl_assign_uint", "uint", "2147483649", Invariant(2147483649U << 1), f => Assigning(f, AssignmentOperator.LeftShiftAssign, new LiteralExpression(1))), + ]; + private static string Invariant(long value) => value.ToString(CultureInfo.InvariantCulture); private static string Invariant(ulong value) => value.ToString(CultureInfo.InvariantCulture); @@ -62,10 +80,12 @@ private static FunctionDeclaration Assigning(FunctionDeclaration function, Assig return function; } - private static SourceFile File() + private static SourceFile File() => File(Cases); + + private static SourceFile File(IEnumerable cases) { SourceFile file = new("main"); - foreach (Case entry in Cases) + foreach (Case entry in cases) { FunctionDeclaration function = new(entry.Name) { ReturnType = new TypeReference(entry.Type) }; function.Parameters.Add(new Parameter("x", entry.Type)); @@ -107,6 +127,60 @@ public void JavaScript_WideIntegerBitwiseOperators_MatchCSharp() }); } + /// + /// Tests that the Python output computes ~ and << at the width the operands declare. + /// + [TestMethod] + public void Python_FixedWidthBitwiseOperators_MatchCSharp() + { + string? python = ToolchainHarness.FindOnPath("--version", "python3", "python"); + if (python is null) + { + Assert.Inconclusive("No Python interpreter on the path, so nothing was run."); + return; + } + + Case[] cases = [.. Cases, .. FixedWidthCases]; + string source = new PythonGenerator().Generate(File(cases)); + StringBuilder module = new(source); + module.AppendLine(); + StringBuilder expected = new(); + foreach (Case entry in cases) + { + module.AppendLine(FormattableString.Invariant($"print(f\"{entry.Name} {{{entry.Name}({entry.Input})}}\")")); + expected.Append(FormattableString.Invariant($"{entry.Name} {entry.Expected}\n")); + } + + ToolchainHarness.InTemporaryDirectory(directory => + { + System.IO.File.WriteAllText(Path.Combine(directory, "check.py"), module.ToString()); + (int exitCode, string output) = ToolchainHarness.Run(python, "check.py", directory); + Assert.AreEqual(0, exitCode, $"{output}{Environment.NewLine}{source}"); + Assert.AreEqual(expected.ToString().Trim(), output.Trim().ReplaceLineEndings("\n"), source); + }); + } + + /// + /// Tests that ~ on a signed integer, and the operators other than <<, are written as before in Python. + /// + [TestMethod] + public void Python_SignedNotAndOtherOperators_AreNotWrapped() + { + SourceFile file = new("main"); + FunctionDeclaration function = new("mask") { ReturnType = new TypeReference("int") }; + function.Parameters.Add(new Parameter("a", "int")); + function.Body.Add(new ReturnStatement(new BinaryExpression(new VariableReference("a"), BinaryOperator.RightShift, new LiteralExpression(1)))); + function.Body.Add(new ReturnStatement(new BinaryExpression(new VariableReference("u"), BinaryOperator.LeftShift, new VariableReference("a")))); + function.Body.Add(new ReturnStatement(new UnaryExpression(UnaryOperator.BitwiseNot, new VariableReference("a")))); + file.Members.Add(function); + + string python = new PythonGenerator().Generate(file); + Assert.Contains("(a >> 1)", python, StringComparison.Ordinal, python); + Assert.Contains("(u << a)", python, StringComparison.Ordinal, python); + Assert.Contains("(~a)", python, StringComparison.Ordinal, python); + Assert.DoesNotContain("0xFFFFFFFF", python, StringComparison.Ordinal, python); + } + /// /// Tests that a 64-bit operation is written in BigInt and a uint one is read back unsigned. /// diff --git a/Coder/Languages/PythonGenerator.cs b/Coder/Languages/PythonGenerator.cs index 2ce67d5..31c3175 100644 --- a/Coder/Languages/PythonGenerator.cs +++ b/Coder/Languages/PythonGenerator.cs @@ -1142,6 +1142,12 @@ protected override void GenerateBinary(BinaryExpression binary, CodeBlocker code Ensure.NotNull(binary); Ensure.NotNull(code); + if (binary.Operator == BinaryOperator.LeftShift && IntegerWidthOf(StaticType(binary.Left)) is IntegerWidth width) + { + WriteWrapped(width, code, () => base.GenerateBinary(binary, code)); + return; + } + if (binary.Operator is not (BinaryOperator.Divide or BinaryOperator.Modulo) || !IsIntegerArithmetic(binary)) { base.GenerateBinary(binary, code); @@ -1171,8 +1177,9 @@ protected override void GenerateBinary(BinaryExpression binary, CodeBlocker code /// 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. + /// truncates. x <<= n on a fixed-width integer is written + /// out the same way, so the result is wrapped to the width (#351). 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) { @@ -1183,11 +1190,15 @@ protected override void GenerateAssignmentStatement(AssignmentStatement assignme { AssignmentOperator.DivideAssign => BinaryOperator.Divide, AssignmentOperator.ModuloAssign => BinaryOperator.Modulo, + AssignmentOperator.LeftShiftAssign => BinaryOperator.LeftShift, _ => null, }; BinaryExpression? binary = op is null ? null : new(assignment.Target, op.Value, assignment.Value); - if (binary is null || !IsIntegerArithmetic(binary)) + bool writtenOut = binary is not null && (binary.Operator == BinaryOperator.LeftShift + ? IntegerWidthOf(StaticType(binary.Left)) is not null + : IsIntegerArithmetic(binary)); + if (binary is null || !writtenOut) { base.GenerateAssignmentStatement(assignment, code); return; @@ -1237,6 +1248,85 @@ private static void WriteTruncated(CodeBlocker code, bool divide, Action left, A } } + /// + /// + /// Python's integers are unbounded, so ~ on a uint or ulong gives a negative + /// number where the C family gives a large positive one (#351). The result is masked back to the + /// operand's width. ~ on a signed integer already matches two's complement and is left as it is. + /// + protected override void GenerateUnary(UnaryExpression unary, CodeBlocker code) + { + Ensure.NotNull(unary); + Ensure.NotNull(code); + + if (unary.Operator == UnaryOperator.BitwiseNot + && IntegerWidthOf(StaticType(unary.Operand)) is IntegerWidth width + && width is IntegerWidth.Unsigned32 or IntegerWidth.Unsigned64) + { + WriteWrapped(width, code, () => base.GenerateUnary(unary, code)); + return; + } + + base.GenerateUnary(unary, code); + } + + /// + /// The fixed-width integer types whose overflow Python's unbounded integers do not reproduce. + /// + private enum IntegerWidth + { + /// int. + Signed32, + + /// uint. + Unsigned32, + + /// long. + Signed64, + + /// ulong. + Unsigned64, + } + + private static IntegerWidth? IntegerWidthOf(TypeReference? type) => + type is { IsArray: false, Indirection: TypeIndirection.None, TypeArguments.Count: 0 } + ? type.Name switch + { + "int" => IntegerWidth.Signed32, + "uint" => IntegerWidth.Unsigned32, + "long" => IntegerWidth.Signed64, + "ulong" => IntegerWidth.Unsigned64, + _ => null, + } + : null; + + /// + /// Writes a value wrapped to a fixed width, the way the C family's arithmetic wraps it. + /// + /// The width to wrap to. + /// The writer to emit into. + /// Writes the unbounded value, which is read once. + /// + /// An unsigned value is masked to its width. A signed one is offset by half the range, masked, and + /// offset back, which keeps the low bits and reads the top one as the sign. + /// + private static void WriteWrapped(IntegerWidth width, CodeBlocker code, Action value) + { + string mask = width is IntegerWidth.Signed32 or IntegerWidth.Unsigned32 ? "0xFFFFFFFF" : "0xFFFFFFFFFFFFFFFF"; + if (width is IntegerWidth.Unsigned32 or IntegerWidth.Unsigned64) + { + code.Write("("); + value(); + code.Write($" & {mask})"); + return; + } + + string half = width == IntegerWidth.Signed32 ? "0x80000000" : "0x8000000000000000"; + code.Write("((("); + value(); + code.Write($" + {half}) & {mask}) - {half})"); + } + private static bool IsReadTwiceSafely(Expression operand) => operand is VariableReference or LiteralExpression