Skip to content

Commit

Permalink
[python] fix modulo operator for negative numbers
Browse files Browse the repository at this point in the history
  • Loading branch information
frabbit committed Mar 25, 2015
1 parent b1ffbf7 commit c395276
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 3 deletions.
7 changes: 6 additions & 1 deletion genpy.ml
Original file line number Diff line number Diff line change
Expand Up @@ -1260,7 +1260,12 @@ module Printer = struct
Printf.sprintf "%s(%s,%s)" (third ops) (print_expr pctx e1) (print_expr pctx e2)
| _,_ -> Printf.sprintf "(%s %s %s)" (print_expr pctx e1) (snd ops) (print_expr pctx e2))
| TBinop(OpMod,e1,e2) when (is_type1 "" "Int")(e1.etype) && (is_type1 "" "Int")(e2.etype) ->
Printf.sprintf "(%s %% %s)" (print_expr pctx e1) (print_expr pctx e2)
(match e1.eexpr with
| TConst(TInt(x)) when (Int32.to_int x) >= 0 ->
(* constant optimization *)
Printf.sprintf "%s %% %s" (print_expr pctx e1) (print_expr pctx e2)
| _ ->
Printf.sprintf "HxOverrides.mod(%s, %s)" (print_expr pctx e1) (print_expr pctx e2))
| TBinop(OpMod,e1,e2) ->
Printf.sprintf "HxOverrides.modf(%s, %s)" (print_expr pctx e1) (print_expr pctx e2)
| TBinop(OpUShr,e1,e2) ->
Expand Down
2 changes: 1 addition & 1 deletion std/haxe/Int32.hx
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ abstract Int32(Int) from Int to Int {
// we might be on 64-bit php, so sign extend from 32-bit
return (x << extraBits) >> extraBits;
#elseif python
return (x + python.Syntax.opPow(2, 31)) % python.Syntax.opPow(2, 32) - python.Syntax.opPow(2, 31);
return python.Syntax.pythonCode("{0} % {1}", (x + python.Syntax.opPow(2, 31)), python.Syntax.opPow(2, 32)) - python.Syntax.opPow(2, 31);
#else
return (x);
#end
Expand Down
6 changes: 5 additions & 1 deletion std/python/internal/HxOverrides.hx
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,11 @@ class HxOverrides {

@:ifFeature("binop_%")
static public function modf(a:Float, b:Float) {
return Syntax.pythonCode("float('nan') if (b == 0.0) else a % b if a > 0 else -(-a % b)");
return Syntax.pythonCode("float('nan') if (b == 0.0) else a % b if a >= 0 else -(-a % b)");
}
@:ifFeature("binop_%")
static public function mod(a:Int, b:Int) {
return Syntax.pythonCode("a % b if a >= 0 else -(-a % b)");
}

@:ifFeature("dynamic_array_read")
Expand Down
20 changes: 20 additions & 0 deletions tests/unit/src/unit/issues/Issue4068.hx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package unit.issues;

class Issue4068 extends Test {
function test() {
eq(-30 % 100, -30);
eq(0 % 100, 0);
eq(-100 % 100, 0);
eq(-30.0 % 100.0, -30.0);
eq(30 % 100, 30);
eq(30.0 % 100.0, 30.0);

function i (x) return x;

eq(i(-30) % i(100), i(-30));
eq(i(0) % i(100), i(0));
eq(i(-100) % i(100), i(0) );
eq(i(30) % i(100), i(30));
}

}

0 comments on commit c395276

Please sign in to comment.