Skip to content

Commit b1ae4ec

Browse files
committed
fix Ext_int.int32_pow to behave like JavaScript
1 parent db66fd0 commit b1ae4ec

File tree

4 files changed

+17
-10
lines changed

4 files changed

+17
-10
lines changed

compiler/ext/ext_int.ml

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,14 @@ let int32_unsigned_to_int (n : int32) : int =
3535
let i = Int32.to_int n in
3636
if i < 0 then i + move else i
3737

38-
let rec int32_pow (a : int32) = function
39-
| 0l -> 1l
40-
| 1l -> a
41-
| n ->
42-
let b = int32_pow a (Int32.div n 2l) in
43-
let b = Int32.mul b b in
44-
Int32.mul b (if Int32.rem n 2l = 0l then 1l else a)
38+
let int32_pow (x : int32) (y : int32) =
39+
let x_float = Int32.to_float x in
40+
let y_float = Int32.to_float y in
41+
let result = x_float ** y_float in
42+
let truncated =
43+
if result > 2147483647.0 || result < -2147483648.0 then
44+
let i = int_of_float result in
45+
i land 0xFFFFFFFF
46+
else int_of_float result
47+
in
48+
Int32.of_int truncated

tests/tests/src/exponentiation_test.mjs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,11 @@ eq("File \"exponentiation_test.res\", line 19, characters 5-12", -2147483648, in
3636

3737
eq("File \"exponentiation_test.res\", line 20, characters 5-12", 0, intPow(2, 32));
3838

39-
eq("File \"exponentiation_test.res\", line 21, characters 5-12", 1, intPow(2147483647, 2));
39+
eq("File \"exponentiation_test.res\", line 21, characters 5-12", 0, intPow(2147483647, 2));
4040

41-
eq("File \"exponentiation_test.res\", line 23, characters 5-12", 256, four ** four | 0);
41+
eq("File \"exponentiation_test.res\", line 22, characters 5-12", 0, intPow(-2147483648, 2));
42+
43+
eq("File \"exponentiation_test.res\", line 24, characters 5-12", 256, four ** four | 0);
4244

4345
Mt.from_pair_suites("Exponentiation_test", suites.contents);
4446

tests/tests/src/exponentiation_test.res

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ let () = {
1919
eq(__LOC__, -2 ** 31, intPow(-2, 31))
2020
eq(__LOC__, 2 ** 32, intPow(2, 32))
2121
eq(__LOC__, 2147483647 ** 2, intPow(2147483647, 2))
22+
eq(__LOC__, -2147483648 ** 2, intPow(-2147483648, 2))
2223

2324
eq(__LOC__, 4 ** 4, four ** four)
2425
}

tests/tests/src/unified_ops_test.mjs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ let pow2 = 2 ** 2;
6565

6666
let pow3 = 2n ** 2n;
6767

68-
let pow_overflow = 1;
68+
let pow_overflow = 0;
6969

7070
let int = 3;
7171

0 commit comments

Comments
 (0)