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
84 changes: 79 additions & 5 deletions Coder.Test/Languages/WideIntegerBitwiseOperatorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,15 @@ namespace ktsu.Coder.Test.Languages;

/// <summary>
/// Tests that the bitwise and shift operators on a <c>long</c>, <c>ulong</c> or <c>uint</c> give C#'s
/// answer in JavaScript (#256).
/// answer in JavaScript (#256), and that <c>~</c> and <c>&lt;&lt;</c> on the fixed-width integers give it
/// in Python (#351).
/// </summary>
/// <remarks>
/// JavaScript converts the operands of these operators to a signed 32-bit integer, so
/// <c>1 | 4294967296</c> was <c>1</c> and a <c>uint</c> 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 <c>~</c> on a <c>uint</c> was negative and
/// <c>1 &lt;&lt; 31</c> on an <c>int</c> did not wrap. The generated code is run rather than read, since the
/// wrong answer is a number like the right one.
/// </remarks>
[TestClass]
public class WideIntegerBitwiseOperatorTests
Expand All @@ -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<int>(1))),
];

/// <summary>
/// Python only: results past 2^53 are rounded by JavaScript's number conversion, which #256 accepted.
/// </summary>
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<int>(31)))),
new("shl_int_overflow", "int", "3", Invariant(3 << 31), f => Returning(f, new BinaryExpression(X(), BinaryOperator.LeftShift, new LiteralExpression<int>(31)))),
new("shl_long_wrap", "long", "1", Invariant(1L << 63), f => Returning(f, new BinaryExpression(X(), BinaryOperator.LeftShift, new LiteralExpression<int>(63)))),
new("shl_ulong", "ulong", "3", Invariant(3UL << 63), f => Returning(f, new BinaryExpression(X(), BinaryOperator.LeftShift, new LiteralExpression<int>(63)))),
new("shl_assign_int", "int", "1", Invariant(1 << 31), f => Assigning(f, AssignmentOperator.LeftShiftAssign, new LiteralExpression<int>(31))),
new("shl_assign_uint", "uint", "2147483649", Invariant(2147483649U << 1), f => Assigning(f, AssignmentOperator.LeftShiftAssign, new LiteralExpression<int>(1))),
];

private static string Invariant(long value) => value.ToString(CultureInfo.InvariantCulture);

private static string Invariant(ulong value) => value.ToString(CultureInfo.InvariantCulture);
Expand All @@ -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<Case> 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));
Expand Down Expand Up @@ -107,6 +127,60 @@ public void JavaScript_WideIntegerBitwiseOperators_MatchCSharp()
});
}

/// <summary>
/// Tests that the Python output computes <c>~</c> and <c>&lt;&lt;</c> at the width the operands declare.
/// </summary>
[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);
});
}

/// <summary>
/// Tests that <c>~</c> on a signed integer, and the operators other than <c>&lt;&lt;</c>, are written as before in Python.
/// </summary>
[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<int>(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);
}

/// <summary>
/// Tests that a 64-bit operation is written in BigInt and a <c>uint</c> one is read back unsigned.
/// </summary>
Expand Down
96 changes: 93 additions & 3 deletions Coder/Languages/PythonGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,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 294 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 294 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 294 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 294 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 @@ -1142,6 +1142,12 @@
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);
Expand Down Expand Up @@ -1171,8 +1177,9 @@
/// the binary operators, so on integers they give <c>2.5</c> for <c>5 /= 2</c> and <c>1</c> for
/// <c>-7 %= 2</c> where the C family gives <c>2</c> and <c>-1</c>. When both sides are known to be
/// integers the assignment is written out as <c>x = x / y</c>, whose quotient or remainder
/// <see cref="GenerateBinary"/> truncates. Every other compound assignment, and one on operands
/// the AST does not know to be integers, is left as it is.
/// <see cref="GenerateBinary"/> truncates. <c>x &lt;&lt;= n</c> 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.
/// </remarks>
protected override void GenerateAssignmentStatement(AssignmentStatement assignment, CodeBlocker code)
{
Expand All @@ -1183,11 +1190,15 @@
{
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;
Expand Down Expand Up @@ -1237,6 +1248,85 @@
}
}

/// <inheritdoc/>
/// <remarks>
/// Python's integers are unbounded, so <c>~</c> on a <c>uint</c> or <c>ulong</c> gives a negative
/// number where the C family gives a large positive one (#351). The result is masked back to the
/// operand's width. <c>~</c> on a signed integer already matches two's complement and is left as it is.
/// </remarks>
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);
}

/// <summary>
/// The fixed-width integer types whose overflow Python's unbounded integers do not reproduce.
/// </summary>
private enum IntegerWidth
{
/// <summary><c>int</c>.</summary>
Signed32,

/// <summary><c>uint</c>.</summary>
Unsigned32,

/// <summary><c>long</c>.</summary>
Signed64,

/// <summary><c>ulong</c>.</summary>
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;

/// <summary>
/// Writes a value wrapped to a fixed width, the way the C family's arithmetic wraps it.
/// </summary>
/// <param name="width">The width to wrap to.</param>
/// <param name="code">The writer to emit into.</param>
/// <param name="value">Writes the unbounded value, which is read once.</param>
/// <remarks>
/// 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.
/// </remarks>
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<int>
Expand Down
Loading