Symbol.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. * Copyright (c) 2020, Matthew Olsson <mattco@serenityos.org>
  3. * Copyright (c) 2022-2023, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibJS/Heap/Heap.h>
  8. #include <LibJS/Runtime/Symbol.h>
  9. #include <LibJS/Runtime/VM.h>
  10. namespace JS {
  11. JS_DEFINE_ALLOCATOR(Symbol);
  12. Symbol::Symbol(Optional<String> description, bool is_global)
  13. : m_description(move(description))
  14. , m_is_global(is_global)
  15. {
  16. }
  17. NonnullGCPtr<Symbol> Symbol::create(VM& vm, Optional<String> description, bool is_global)
  18. {
  19. return vm.heap().allocate<Symbol>(move(description), is_global);
  20. }
  21. // 20.4.3.3.1 SymbolDescriptiveString ( sym ), https://tc39.es/ecma262/#sec-symboldescriptivestring
  22. ErrorOr<String> Symbol::descriptive_string() const
  23. {
  24. // 1. Let desc be sym's [[Description]] value.
  25. // 2. If desc is undefined, set desc to the empty String.
  26. // 3. Assert: desc is a String.
  27. auto description = m_description.value_or(String {});
  28. // 4. Return the string-concatenation of "Symbol(", desc, and ")".
  29. return String::formatted("Symbol({})", description);
  30. }
  31. // 20.4.5.1 KeyForSymbol ( sym ), https://tc39.es/ecma262/#sec-keyforsymbol
  32. Optional<String> Symbol::key() const
  33. {
  34. // 1. For each element e of the GlobalSymbolRegistry List, do
  35. // a. If SameValue(e.[[Symbol]], sym) is true, return e.[[Key]].
  36. if (m_is_global) {
  37. // NOTE: Global symbols should always have a description string
  38. VERIFY(m_description.has_value());
  39. return m_description;
  40. }
  41. // 2. Assert: GlobalSymbolRegistry does not currently contain an entry for sym.
  42. // 3. Return undefined.
  43. return {};
  44. }
  45. }