Symbol.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. Symbol::Symbol(Optional<String> description, bool is_global)
  12. : m_description(move(description))
  13. , m_is_global(is_global)
  14. {
  15. }
  16. NonnullGCPtr<Symbol> Symbol::create(VM& vm, Optional<String> description, bool is_global)
  17. {
  18. return vm.heap().allocate_without_realm<Symbol>(move(description), is_global);
  19. }
  20. // 20.4.3.3.1 SymbolDescriptiveString ( sym ), https://tc39.es/ecma262/#sec-symboldescriptivestring
  21. ErrorOr<String> Symbol::descriptive_string() const
  22. {
  23. // 1. Let desc be sym's [[Description]] value.
  24. // 2. If desc is undefined, set desc to the empty String.
  25. // 3. Assert: desc is a String.
  26. auto description = m_description.value_or(String {});
  27. // 4. Return the string-concatenation of "Symbol(", desc, and ")".
  28. return String::formatted("Symbol({})", description);
  29. }
  30. // 20.4.5.1 KeyForSymbol ( sym ), https://tc39.es/ecma262/#sec-keyforsymbol
  31. Optional<String> Symbol::key() const
  32. {
  33. // 1. For each element e of the GlobalSymbolRegistry List, do
  34. // a. If SameValue(e.[[Symbol]], sym) is true, return e.[[Key]].
  35. if (m_is_global) {
  36. // NOTE: Global symbols should always have a description string
  37. VERIFY(m_description.has_value());
  38. return m_description;
  39. }
  40. // 2. Assert: GlobalSymbolRegistry does not currently contain an entry for sym.
  41. // 3. Return undefined.
  42. return {};
  43. }
  44. }