LibJS: Include the WeakMap key (not value) in non-weakable key errors

It is the key that cannot be held weakly, and thus the key that should
be include in the error message.
This commit is contained in:
Timothy Flynn 2025-10-02 15:56:48 -04:00 committed by Jelle Raaijmakers
parent fd3c69227f
commit 853e3ecf23
2 changed files with 6 additions and 4 deletions

View File

@ -115,7 +115,7 @@ JS_DEFINE_NATIVE_FUNCTION(WeakMapPrototype::set)
// 3. If CanBeHeldWeakly(key) is false, throw a TypeError exception.
if (!can_be_held_weakly(key))
return vm.throw_completion<TypeError>(ErrorType::CannotBeHeldWeakly, value.to_string_without_side_effects());
return vm.throw_completion<TypeError>(ErrorType::CannotBeHeldWeakly, key);
// 4. For each Record { [[Key]], [[Value]] } p of M.[[WeakMapData]], do
// a. If p.[[Key]] is not empty and SameValue(p.[[Key]], key) is true, then

View File

@ -14,10 +14,12 @@ test("basic functionality", () => {
test("invalid values", () => {
const weakMap = new WeakMap();
[-100, Infinity, NaN, "hello", 152n].forEach(value => {
[-100, Infinity, NaN, "hello", 152n].forEach(key => {
const suffix = typeof key === "bigint" ? "n" : "";
expect(() => {
weakMap.set(value, value);
}).toThrowWithMessage(TypeError, "cannot be held weakly");
weakMap.set(key, 1);
}).toThrowWithMessage(TypeError, `${key}${suffix} cannot be held weakly`);
});
});