Reference.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/DeclarativeEnvironment.h>
  7. #include <LibJS/Runtime/Error.h>
  8. #include <LibJS/Runtime/GlobalObject.h>
  9. #include <LibJS/Runtime/Reference.h>
  10. namespace JS {
  11. // 6.2.4.6 PutValue ( V, W ), https://tc39.es/ecma262/#sec-putvalue
  12. ThrowCompletionOr<void> Reference::put_value(VM& vm, Value value)
  13. {
  14. // 1. ReturnIfAbrupt(V).
  15. // 2. ReturnIfAbrupt(W).
  16. // 3. If V is not a Reference Record, throw a ReferenceError exception.
  17. if (!is_valid_reference())
  18. return vm.throw_completion<ReferenceError>(ErrorType::InvalidLeftHandAssignment);
  19. // 4. If IsUnresolvableReference(V) is true, then
  20. if (is_unresolvable()) {
  21. // a. If V.[[Strict]] is true, throw a ReferenceError exception.
  22. if (m_strict)
  23. return throw_reference_error(vm);
  24. // b. Let globalObj be GetGlobalObject().
  25. auto& global_object = vm.get_global_object();
  26. // c. Perform ? Set(globalObj, V.[[ReferencedName]], W, false).
  27. TRY(global_object.set(m_name, value, Object::ShouldThrowExceptions::No));
  28. // Return unused.
  29. return {};
  30. }
  31. // 5. If IsPropertyReference(V) is true, then
  32. if (is_property_reference()) {
  33. // a. Let baseObj be ? ToObject(V.[[Base]]).
  34. auto* base_obj = TRY(m_base_value.to_object(vm));
  35. // b. If IsPrivateReference(V) is true, then
  36. if (is_private_reference()) {
  37. // i. Return ? PrivateSet(baseObj, V.[[ReferencedName]], W).
  38. return base_obj->private_set(m_private_name, value);
  39. }
  40. // c. Let succeeded be ? baseObj.[[Set]](V.[[ReferencedName]], W, GetThisValue(V)).
  41. auto succeeded = TRY(base_obj->internal_set(m_name, value, get_this_value()));
  42. // d. If succeeded is false and V.[[Strict]] is true, throw a TypeError exception.
  43. if (!succeeded && m_strict)
  44. return vm.throw_completion<TypeError>(ErrorType::ReferenceNullishSetProperty, m_name, m_base_value.to_string_without_side_effects());
  45. // e. Return unused.
  46. return {};
  47. }
  48. // 6. Else,
  49. // a. Let base be V.[[Base]].
  50. // b. Assert: base is an Environment Record.
  51. VERIFY(m_base_type == BaseType::Environment);
  52. VERIFY(m_base_environment);
  53. // c. Return ? base.SetMutableBinding(V.[[ReferencedName]], W, V.[[Strict]]) (see 9.1).
  54. if (m_environment_coordinate.has_value() && m_environment_coordinate->index != EnvironmentCoordinate::global_marker)
  55. return static_cast<DeclarativeEnvironment*>(m_base_environment)->set_mutable_binding_direct(vm, m_environment_coordinate->index, value, m_strict);
  56. else
  57. return m_base_environment->set_mutable_binding(vm, m_name.as_string(), value, m_strict);
  58. }
  59. Completion Reference::throw_reference_error(VM& vm) const
  60. {
  61. if (!m_name.is_valid())
  62. return vm.throw_completion<ReferenceError>(ErrorType::ReferenceUnresolvable);
  63. else
  64. return vm.throw_completion<ReferenceError>(ErrorType::UnknownIdentifier, m_name.to_string_or_symbol().to_display_string());
  65. }
  66. // 6.2.4.5 GetValue ( V ), https://tc39.es/ecma262/#sec-getvalue
  67. ThrowCompletionOr<Value> Reference::get_value(VM& vm) const
  68. {
  69. auto& realm = *vm.current_realm();
  70. // 1. ReturnIfAbrupt(V).
  71. // 2. If V is not a Reference Record, return V.
  72. // 3. If IsUnresolvableReference(V) is true, throw a ReferenceError exception.
  73. if (!is_valid_reference() || is_unresolvable())
  74. return throw_reference_error(vm);
  75. // 4. If IsPropertyReference(V) is true, then
  76. if (is_property_reference()) {
  77. // a. Let baseObj be ? ToObject(V.[[Base]]).
  78. // NOTE: Deferred as an optimization; we might not actually need to create an object.
  79. // b. If IsPrivateReference(V) is true, then
  80. if (is_private_reference()) {
  81. // FIXME: We need to be able to specify the receiver for this
  82. // if we want to use it in error messages in future
  83. // as things currently stand this does the "wrong thing" but
  84. // the error is unobservable
  85. auto* base_obj = TRY(m_base_value.to_object(vm));
  86. // i. Return ? PrivateGet(baseObj, V.[[ReferencedName]]).
  87. return base_obj->private_get(m_private_name);
  88. }
  89. // OPTIMIZATION: For various primitives we can avoid actually creating a new object for them.
  90. Object* base_obj = nullptr;
  91. if (m_base_value.is_string()) {
  92. auto string_value = TRY(m_base_value.as_string().get(vm, m_name));
  93. if (string_value.has_value())
  94. return *string_value;
  95. base_obj = realm.intrinsics().string_prototype();
  96. } else if (m_base_value.is_number())
  97. base_obj = realm.intrinsics().number_prototype();
  98. else if (m_base_value.is_boolean())
  99. base_obj = realm.intrinsics().boolean_prototype();
  100. else
  101. base_obj = TRY(m_base_value.to_object(vm));
  102. // c. Return ? baseObj.[[Get]](V.[[ReferencedName]], GetThisValue(V)).
  103. return base_obj->internal_get(m_name, get_this_value());
  104. }
  105. // 5. Else,
  106. // a. Let base be V.[[Base]].
  107. // b. Assert: base is an Environment Record.
  108. VERIFY(m_base_type == BaseType::Environment);
  109. VERIFY(m_base_environment);
  110. // c. Return ? base.GetBindingValue(V.[[ReferencedName]], V.[[Strict]]) (see 9.1).
  111. if (m_environment_coordinate.has_value() && m_environment_coordinate->index != EnvironmentCoordinate::global_marker)
  112. return static_cast<DeclarativeEnvironment*>(m_base_environment)->get_binding_value_direct(vm, m_environment_coordinate->index, m_strict);
  113. return m_base_environment->get_binding_value(vm, m_name.as_string(), m_strict);
  114. }
  115. // 13.5.1.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-delete-operator-runtime-semantics-evaluation
  116. ThrowCompletionOr<bool> Reference::delete_(VM& vm)
  117. {
  118. // 13.5.1.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-delete-operator-runtime-semantics-evaluation
  119. // UnaryExpression : delete UnaryExpression
  120. // NOTE: The following steps have already been evaluated by the time we get here:
  121. // 1. Let ref be the result of evaluating UnaryExpression.
  122. // 2. ReturnIfAbrupt(ref).
  123. // 3. If ref is not a Reference Record, return true.
  124. // 4. If IsUnresolvableReference(ref) is true, then
  125. if (is_unresolvable()) {
  126. // a. Assert: ref.[[Strict]] is false.
  127. VERIFY(!m_strict);
  128. // b. Return true.
  129. return true;
  130. }
  131. // 5. If IsPropertyReference(ref) is true, then
  132. if (is_property_reference()) {
  133. // a. Assert: IsPrivateReference(ref) is false.
  134. VERIFY(!is_private_reference());
  135. // b. If IsSuperReference(ref) is true, throw a ReferenceError exception.
  136. if (is_super_reference())
  137. return vm.throw_completion<ReferenceError>(ErrorType::UnsupportedDeleteSuperProperty);
  138. // c. Let baseObj be ! ToObject(ref.[[Base]]).
  139. auto* base_obj = MUST(m_base_value.to_object(vm));
  140. // d. Let deleteStatus be ? baseObj.[[Delete]](ref.[[ReferencedName]]).
  141. bool delete_status = TRY(base_obj->internal_delete(m_name));
  142. // e. If deleteStatus is false and ref.[[Strict]] is true, throw a TypeError exception.
  143. if (!delete_status && m_strict)
  144. return vm.throw_completion<TypeError>(ErrorType::ReferenceNullishDeleteProperty, m_name, m_base_value.to_string_without_side_effects());
  145. // f. Return deleteStatus.
  146. return delete_status;
  147. }
  148. // 6. Else,
  149. // a. Let base be ref.[[Base]].
  150. // b. Assert: base is an Environment Record.
  151. VERIFY(m_base_type == BaseType::Environment);
  152. // c. Return ? base.DeleteBinding(ref.[[ReferencedName]]).
  153. return m_base_environment->delete_binding(vm, m_name.as_string());
  154. }
  155. DeprecatedString Reference::to_deprecated_string() const
  156. {
  157. StringBuilder builder;
  158. builder.append("Reference { Base="sv);
  159. switch (m_base_type) {
  160. case BaseType::Unresolvable:
  161. builder.append("Unresolvable"sv);
  162. break;
  163. case BaseType::Environment:
  164. builder.appendff("{}", base_environment().class_name());
  165. break;
  166. case BaseType::Value:
  167. if (m_base_value.is_empty())
  168. builder.append("<empty>"sv);
  169. else
  170. builder.appendff("{}", m_base_value.to_string_without_side_effects());
  171. break;
  172. }
  173. builder.append(", ReferencedName="sv);
  174. if (!m_name.is_valid())
  175. builder.append("<invalid>"sv);
  176. else if (m_name.is_symbol())
  177. builder.appendff("{}", m_name.as_symbol()->to_deprecated_string());
  178. else
  179. builder.appendff("{}", m_name.to_string());
  180. builder.appendff(", Strict={}", m_strict);
  181. builder.appendff(", ThisValue=");
  182. if (m_this_value.is_empty())
  183. builder.append("<empty>"sv);
  184. else
  185. builder.appendff("{}", m_this_value.to_string_without_side_effects());
  186. builder.append(" }"sv);
  187. return builder.to_deprecated_string();
  188. }
  189. // 6.2.4.8 InitializeReferencedBinding ( V, W ), https://tc39.es/ecma262/#sec-object.prototype.hasownproperty
  190. // 1.2.1.1 InitializeReferencedBinding ( V, W, hint ), https://tc39.es/proposal-explicit-resource-management/#sec-initializereferencedbinding
  191. ThrowCompletionOr<void> Reference::initialize_referenced_binding(VM& vm, Value value, Environment::InitializeBindingHint hint) const
  192. {
  193. VERIFY(!is_unresolvable());
  194. VERIFY(m_base_type == BaseType::Environment);
  195. return m_base_environment->initialize_binding(vm, m_name.as_string(), value, hint);
  196. }
  197. // 6.2.4.9 MakePrivateReference ( baseValue, privateIdentifier ), https://tc39.es/ecma262/#sec-makeprivatereference
  198. Reference make_private_reference(VM& vm, Value base_value, DeprecatedFlyString const& private_identifier)
  199. {
  200. // 1. Let privEnv be the running execution context's PrivateEnvironment.
  201. auto* private_environment = vm.running_execution_context().private_environment;
  202. // 2. Assert: privEnv is not null.
  203. VERIFY(private_environment);
  204. // 3. Let privateName be ResolvePrivateIdentifier(privEnv, privateIdentifier).
  205. auto private_name = private_environment->resolve_private_identifier(private_identifier);
  206. // 4. Return the Reference Record { [[Base]]: baseValue, [[ReferencedName]]: privateName, [[Strict]]: true, [[ThisValue]]: empty }.
  207. return Reference { base_value, private_name };
  208. }
  209. }