2020-04-29 23:25:21 -07:00
|
|
|
/*
|
2021-04-22 16:53:07 -07:00
|
|
|
* Copyright (c) 2020, Matthew Olsson <mattco@serenityos.org>
|
2023-02-11 15:51:44 +00:00
|
|
|
* Copyright (c) 2022-2023, Linus Groh <linusg@serenityos.org>
|
2020-04-29 23:25:21 -07:00
|
|
|
*
|
2021-04-22 01:24:48 -07:00
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
2020-04-29 23:25:21 -07:00
|
|
|
*/
|
|
|
|
|
2024-11-15 04:01:23 +13:00
|
|
|
#include <LibGC/Heap.h>
|
2020-04-29 23:25:21 -07:00
|
|
|
#include <LibJS/Runtime/Symbol.h>
|
2020-09-27 20:18:30 +02:00
|
|
|
#include <LibJS/Runtime/VM.h>
|
2020-04-29 23:25:21 -07:00
|
|
|
|
|
|
|
namespace JS {
|
|
|
|
|
2024-11-15 04:01:23 +13:00
|
|
|
GC_DEFINE_ALLOCATOR(Symbol);
|
2023-12-23 15:15:27 +01:00
|
|
|
|
2023-02-11 16:14:41 +00:00
|
|
|
Symbol::Symbol(Optional<String> description, bool is_global)
|
2020-04-29 23:25:21 -07:00
|
|
|
: m_description(move(description))
|
|
|
|
, m_is_global(is_global)
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
2024-11-15 04:01:23 +13:00
|
|
|
GC::Ref<Symbol> Symbol::create(VM& vm, Optional<String> description, bool is_global)
|
2020-04-29 23:25:21 -07:00
|
|
|
{
|
2024-11-14 06:13:46 +13:00
|
|
|
return vm.heap().allocate<Symbol>(move(description), is_global);
|
2020-09-22 16:18:51 +02:00
|
|
|
}
|
|
|
|
|
2023-02-11 15:51:44 +00:00
|
|
|
// 20.4.3.3.1 SymbolDescriptiveString ( sym ), https://tc39.es/ecma262/#sec-symboldescriptivestring
|
2023-02-11 16:14:41 +00:00
|
|
|
ErrorOr<String> Symbol::descriptive_string() const
|
2023-02-11 15:51:44 +00:00
|
|
|
{
|
|
|
|
// 1. Let desc be sym's [[Description]] value.
|
|
|
|
// 2. If desc is undefined, set desc to the empty String.
|
|
|
|
// 3. Assert: desc is a String.
|
2023-02-11 16:14:41 +00:00
|
|
|
auto description = m_description.value_or(String {});
|
2023-02-11 15:51:44 +00:00
|
|
|
|
|
|
|
// 4. Return the string-concatenation of "Symbol(", desc, and ")".
|
2023-02-11 16:14:41 +00:00
|
|
|
return String::formatted("Symbol({})", description);
|
2023-02-11 15:51:44 +00:00
|
|
|
}
|
|
|
|
|
2023-04-12 23:12:54 +02:00
|
|
|
// 20.4.5.1 KeyForSymbol ( sym ), https://tc39.es/ecma262/#sec-keyforsymbol
|
|
|
|
Optional<String> Symbol::key() const
|
|
|
|
{
|
|
|
|
// 1. For each element e of the GlobalSymbolRegistry List, do
|
|
|
|
// a. If SameValue(e.[[Symbol]], sym) is true, return e.[[Key]].
|
|
|
|
if (m_is_global) {
|
|
|
|
// NOTE: Global symbols should always have a description string
|
|
|
|
VERIFY(m_description.has_value());
|
|
|
|
return m_description;
|
|
|
|
}
|
|
|
|
|
|
|
|
// 2. Assert: GlobalSymbolRegistry does not currently contain an entry for sym.
|
|
|
|
// 3. Return undefined.
|
|
|
|
return {};
|
|
|
|
}
|
|
|
|
|
2020-04-29 23:25:21 -07:00
|
|
|
}
|