2
0
Эх сурвалжийг харах

[python] fixed modulo by negative number (#8846)

* [python] fixed modulo by negative number (closes #8845)

* add comment
Aleksandr Kuzmenko 6 жил өмнө
parent
commit
4cd9f45459

+ 2 - 2
src/generators/genpy.ml

@@ -1306,8 +1306,8 @@ 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) ->
-				(match e1.eexpr with
-				| TConst(TInt(x)) when (Int32.to_int x) >= 0 ->
+				(match e1.eexpr, e2.eexpr with
+				| TConst(TInt(x1)), TConst(TInt(x2)) when (Int32.to_int x1) >= 0 && (Int32.to_int x2) >= 0 ->
 					(* constant optimization *)
 					Printf.sprintf "%s %% %s" (print_expr pctx e1) (print_expr pctx e2)
 				| _ ->

+ 2 - 2
std/python/internal/HxOverrides.hx

@@ -142,12 +142,12 @@ class HxOverrides {
 
 	@:ifFeature("binop_%")
 	static public function modf(a:Float, b:Float) {
-		return Syntax.code("float('nan') if (b == 0.0) else a % b if a >= 0 else -(-a % b)");
+		return Syntax.code("float('nan') if (b == 0.0) else a % b if a >= 0 and b >= 0 else -(-a % b)");
 	}
 
 	@:ifFeature("binop_%")
 	static public function mod(a:Int, b:Int) {
-		return Syntax.code("a % b if a >= 0 else -(-a % b)");
+		return Syntax.code("a % b if a >= 0 and b >= 0 else -(-a % b)");
 	}
 
 	@:ifFeature("dynamic_array_read")

+ 12 - 0
tests/unit/src/unit/issues/Issue8845.hx

@@ -0,0 +1,12 @@
+package unit.issues;
+
+class Issue8845 extends unit.Test {
+	static var a = 255;
+	static var b = -8;
+
+	function test() {
+		// This is actually unspecified: https://haxe.org/manual/expression-operators-binops.html
+		// but happens to work on all targets
+		eq(7, a % b);
+	}
+}