LibJS: Move creation of global symbols into Symbol.for()

This is now according to the spec. Having a non-standard lookup API
that creates symbols on the fly doesn't seem ideal.
This commit is contained in:
Linus Groh 2022-12-06 21:06:56 +00:00
parent b821356ba6
commit f490ba13ff
Notes: sideshowbarker 2024-07-17 17:06:59 +09:00
3 changed files with 25 additions and 16 deletions

View file

@ -53,8 +53,27 @@ ThrowCompletionOr<Object*> SymbolConstructor::construct(FunctionObject&)
// 20.4.2.2 Symbol.for ( key ), https://tc39.es/ecma262/#sec-symbol.for
JS_DEFINE_NATIVE_FUNCTION(SymbolConstructor::for_)
{
auto description = TRY(vm.argument(0).to_string(vm));
return vm.get_global_symbol(description);
// 1. Let stringKey be ? ToString(key).
auto string_key = TRY(vm.argument(0).to_string(vm));
// 2. For each element e of the GlobalSymbolRegistry List, do
auto result = vm.global_symbol_registry().get(string_key);
if (result.has_value()) {
// a. If SameValue(e.[[Key]], stringKey) is true, return e.[[Symbol]].
return result.value();
}
// 3. Assert: GlobalSymbolRegistry does not currently contain an entry for stringKey.
VERIFY(!result.has_value());
// 4. Let newSymbol be a new unique Symbol value whose [[Description]] value is stringKey.
auto* new_symbol = js_symbol(vm, string_key, true);
// 5. Append the Record { [[Key]]: stringKey, [[Symbol]]: newSymbol } to the GlobalSymbolRegistry List.
vm.global_symbol_registry().set(string_key, *new_symbol);
// 6. Return newSymbol.
return new_symbol;
}
// 20.4.2.6 Symbol.keyFor ( sym ), https://tc39.es/ecma262/#sec-symbol.keyfor

View file

@ -231,17 +231,6 @@ void VM::gather_roots(HashTable<Cell*>& roots)
roots.set(finalization_registry);
}
Symbol* VM::get_global_symbol(DeprecatedString const& description)
{
auto result = m_global_symbol_registry.get(description);
if (result.has_value())
return result.value();
auto* new_global_symbol = js_symbol(*this, description, true);
m_global_symbol_registry.set(description, *new_global_symbol);
return new_global_symbol;
}
ThrowCompletionOr<Value> VM::named_evaluation_if_anonymous_function(ASTNode const& expression, FlyString const& name)
{
// 8.3.3 Static Semantics: IsAnonymousFunctionDefinition ( expr ), https://tc39.es/ecma262/#sec-isanonymousfunctiondefinition

View file

@ -73,9 +73,10 @@ public:
JS_ENUMERATE_WELL_KNOWN_SYMBOLS
#undef __JS_ENUMERATE
Symbol* get_global_symbol(DeprecatedString const& description);
HashMap<DeprecatedString, PrimitiveString*>& string_cache() { return m_string_cache; }
HashMap<DeprecatedString, PrimitiveString*>& string_cache()
{
return m_string_cache;
}
PrimitiveString& empty_string() { return *m_empty_string; }
PrimitiveString& single_ascii_character_string(u8 character)
{