LibJS: Throw RangeError on BigInt exponentiation with negative exponent

https://tc39.es/ecma262/#sec-numeric-types-bigint-exponentiate
This commit is contained in:
Linus Groh 2021-03-16 20:35:55 +01:00 committed by Andreas Kling
parent 11138f5c1f
commit fa6bce5087
3 changed files with 13 additions and 1 deletions

View file

@ -60,6 +60,7 @@
M(JsonBigInt, "Cannot serialize BigInt value to JSON") \
M(JsonCircular, "Cannot stringify circular object") \
M(JsonMalformed, "Malformed JSON string") \
M(NegativeExponent, "Exponent must be positive") \
M(NotA, "Not a {} object") \
M(NotAConstructor, "{} is not a constructor") \
M(NotAFunction, "{} is not a function") \

View file

@ -941,8 +941,13 @@ Value exp(GlobalObject& global_object, Value lhs, Value rhs)
return {};
if (both_number(lhs_numeric, rhs_numeric))
return Value(pow(lhs_numeric.as_double(), rhs_numeric.as_double()));
if (both_bigint(lhs_numeric, rhs_numeric))
if (both_bigint(lhs_numeric, rhs_numeric)) {
if (rhs_numeric.as_bigint().big_integer().is_negative()) {
vm.throw_exception<RangeError>(global_object, ErrorType::NegativeExponent);
return {};
}
return js_bigint(vm.heap(), Crypto::NumberTheory::Power(lhs_numeric.as_bigint().big_integer(), rhs_numeric.as_bigint().big_integer()));
}
vm.throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "exponentiation");
return {};
}

View file

@ -96,4 +96,10 @@ describe("errors", () => {
1n % 0n;
}).toThrowWithMessage(RangeError, "Division by zero");
});
test("negative exponent", () => {
expect(() => {
1n ** -1n;
}).toThrowWithMessage(RangeError, "Exponent must be positive");
});
});