Explorar el Código

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.
Linus Groh hace 2 años
padre
commit
f490ba13ff

+ 21 - 2
Userland/Libraries/LibJS/Runtime/SymbolConstructor.cpp

@@ -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

+ 0 - 11
Userland/Libraries/LibJS/Runtime/VM.cpp

@@ -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

+ 4 - 3
Userland/Libraries/LibJS/Runtime/VM.h

@@ -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)
     {