AbstractOperations.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  1. /*
  2. * Copyright (c) 2020-2022, Linus Groh <linusg@serenityos.org>
  3. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/CharacterTypes.h>
  8. #include <AK/Function.h>
  9. #include <AK/Optional.h>
  10. #include <AK/TemporaryChange.h>
  11. #include <AK/Utf16View.h>
  12. #include <LibJS/Bytecode/Interpreter.h>
  13. #include <LibJS/Interpreter.h>
  14. #include <LibJS/Parser.h>
  15. #include <LibJS/Runtime/AbstractOperations.h>
  16. #include <LibJS/Runtime/Accessor.h>
  17. #include <LibJS/Runtime/ArgumentsObject.h>
  18. #include <LibJS/Runtime/Array.h>
  19. #include <LibJS/Runtime/BoundFunction.h>
  20. #include <LibJS/Runtime/Completion.h>
  21. #include <LibJS/Runtime/DeclarativeEnvironment.h>
  22. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  23. #include <LibJS/Runtime/ErrorTypes.h>
  24. #include <LibJS/Runtime/FunctionEnvironment.h>
  25. #include <LibJS/Runtime/FunctionObject.h>
  26. #include <LibJS/Runtime/GlobalObject.h>
  27. #include <LibJS/Runtime/Object.h>
  28. #include <LibJS/Runtime/ObjectEnvironment.h>
  29. #include <LibJS/Runtime/PropertyDescriptor.h>
  30. #include <LibJS/Runtime/PropertyKey.h>
  31. #include <LibJS/Runtime/ProxyObject.h>
  32. #include <LibJS/Runtime/Reference.h>
  33. namespace JS {
  34. // 7.2.1 RequireObjectCoercible ( argument ), https://tc39.es/ecma262/#sec-requireobjectcoercible
  35. ThrowCompletionOr<Value> require_object_coercible(GlobalObject& global_object, Value value)
  36. {
  37. auto& vm = global_object.vm();
  38. if (value.is_nullish())
  39. return vm.throw_completion<TypeError>(global_object, ErrorType::NotObjectCoercible, value.to_string_without_side_effects());
  40. return value;
  41. }
  42. // 7.3.14 Call ( F, V [ , argumentsList ] ), https://tc39.es/ecma262/#sec-call
  43. ThrowCompletionOr<Value> call_impl(GlobalObject& global_object, Value function, Value this_value, Optional<MarkedValueList> arguments_list)
  44. {
  45. auto& vm = global_object.vm();
  46. // 1. If argumentsList is not present, set argumentsList to a new empty List.
  47. if (!arguments_list.has_value())
  48. arguments_list = MarkedValueList { global_object.heap() };
  49. // 2. If IsCallable(F) is false, throw a TypeError exception.
  50. if (!function.is_function())
  51. return vm.throw_completion<TypeError>(global_object, ErrorType::NotAFunction, function.to_string_without_side_effects());
  52. // 3. Return ? F.[[Call]](V, argumentsList).
  53. return function.as_function().internal_call(this_value, move(*arguments_list));
  54. }
  55. ThrowCompletionOr<Value> call_impl(GlobalObject& global_object, FunctionObject& function, Value this_value, Optional<MarkedValueList> arguments_list)
  56. {
  57. // 1. If argumentsList is not present, set argumentsList to a new empty List.
  58. if (!arguments_list.has_value())
  59. arguments_list = MarkedValueList { global_object.heap() };
  60. // 2. If IsCallable(F) is false, throw a TypeError exception.
  61. // Note: Called with a FunctionObject ref
  62. // 3. Return ? F.[[Call]](V, argumentsList).
  63. return function.internal_call(this_value, move(*arguments_list));
  64. }
  65. // 7.3.15 Construct ( F [ , argumentsList [ , newTarget ] ] ), https://tc39.es/ecma262/#sec-construct
  66. ThrowCompletionOr<Object*> construct(GlobalObject& global_object, FunctionObject& function, Optional<MarkedValueList> arguments_list, FunctionObject* new_target)
  67. {
  68. // 1. If newTarget is not present, set newTarget to F.
  69. if (!new_target)
  70. new_target = &function;
  71. // 2. If argumentsList is not present, set argumentsList to a new empty List.
  72. if (!arguments_list.has_value())
  73. arguments_list = MarkedValueList { global_object.heap() };
  74. // 3. Return ? F.[[Construct]](argumentsList, newTarget).
  75. return function.internal_construct(move(*arguments_list), *new_target);
  76. }
  77. // 7.3.19 LengthOfArrayLike ( obj ), https://tc39.es/ecma262/#sec-lengthofarraylike
  78. ThrowCompletionOr<size_t> length_of_array_like(GlobalObject& global_object, Object const& object)
  79. {
  80. auto& vm = global_object.vm();
  81. auto result = TRY(object.get(vm.names.length));
  82. return result.to_length(global_object);
  83. }
  84. // 7.3.20 CreateListFromArrayLike ( obj [ , elementTypes ] ), https://tc39.es/ecma262/#sec-createlistfromarraylike
  85. ThrowCompletionOr<MarkedValueList> create_list_from_array_like(GlobalObject& global_object, Value value, Function<ThrowCompletionOr<void>(Value)> check_value)
  86. {
  87. auto& vm = global_object.vm();
  88. auto& heap = global_object.heap();
  89. // 1. If elementTypes is not present, set elementTypes to « Undefined, Null, Boolean, String, Symbol, Number, BigInt, Object ».
  90. // 2. If Type(obj) is not Object, throw a TypeError exception.
  91. if (!value.is_object())
  92. return vm.throw_completion<TypeError>(global_object, ErrorType::NotAnObject, value.to_string_without_side_effects());
  93. auto& array_like = value.as_object();
  94. // 3. Let len be ? LengthOfArrayLike(obj).
  95. auto length = TRY(length_of_array_like(global_object, array_like));
  96. // 4. Let list be a new empty List.
  97. auto list = MarkedValueList { heap };
  98. // 5. Let index be 0.
  99. // 6. Repeat, while index < len,
  100. for (size_t i = 0; i < length; ++i) {
  101. // a. Let indexName be ! ToString(𝔽(index)).
  102. auto index_name = PropertyKey { i };
  103. // b. Let next be ? Get(obj, indexName).
  104. auto next = TRY(array_like.get(index_name));
  105. // c. If Type(next) is not an element of elementTypes, throw a TypeError exception.
  106. if (check_value)
  107. TRY(check_value(next));
  108. // d. Append next as the last element of list.
  109. list.append(next);
  110. }
  111. // 7. Return list.
  112. return ThrowCompletionOr(move(list));
  113. }
  114. // 7.3.23 SpeciesConstructor ( O, defaultConstructor ), https://tc39.es/ecma262/#sec-speciesconstructor
  115. ThrowCompletionOr<FunctionObject*> species_constructor(GlobalObject& global_object, Object const& object, FunctionObject& default_constructor)
  116. {
  117. auto& vm = global_object.vm();
  118. // 1. Let C be ? Get(O, "constructor").
  119. auto constructor = TRY(object.get(vm.names.constructor));
  120. // 2. If C is undefined, return defaultConstructor.
  121. if (constructor.is_undefined())
  122. return &default_constructor;
  123. // 3. If Type(C) is not Object, throw a TypeError exception.
  124. if (!constructor.is_object())
  125. return vm.throw_completion<TypeError>(global_object, ErrorType::NotAConstructor, constructor.to_string_without_side_effects());
  126. // 4. Let S be ? Get(C, @@species).
  127. auto species = TRY(constructor.as_object().get(*vm.well_known_symbol_species()));
  128. // 5. If S is either undefined or null, return defaultConstructor.
  129. if (species.is_nullish())
  130. return &default_constructor;
  131. // 6. If IsConstructor(S) is true, return S.
  132. if (species.is_constructor())
  133. return &species.as_function();
  134. // 7. Throw a TypeError exception.
  135. return vm.throw_completion<TypeError>(global_object, ErrorType::NotAConstructor, species.to_string_without_side_effects());
  136. }
  137. // 7.3.25 GetFunctionRealm ( obj ), https://tc39.es/ecma262/#sec-getfunctionrealm
  138. ThrowCompletionOr<Realm*> get_function_realm(GlobalObject& global_object, FunctionObject const& function)
  139. {
  140. auto& vm = global_object.vm();
  141. // 1. Assert: ! IsCallable(obj) is true.
  142. // 2. If obj has a [[Realm]] internal slot, then
  143. if (function.realm()) {
  144. // a. Return obj.[[Realm]].
  145. return function.realm();
  146. }
  147. // 3. If obj is a bound function exotic object, then
  148. if (is<BoundFunction>(function)) {
  149. auto& bound_function = static_cast<BoundFunction const&>(function);
  150. // a. Let target be obj.[[BoundTargetFunction]].
  151. auto& target = bound_function.bound_target_function();
  152. // b. Return ? GetFunctionRealm(target).
  153. return get_function_realm(global_object, target);
  154. }
  155. // 4. If obj is a Proxy exotic object, then
  156. if (is<ProxyObject>(function)) {
  157. auto& proxy = static_cast<ProxyObject const&>(function);
  158. // a. If obj.[[ProxyHandler]] is null, throw a TypeError exception.
  159. if (proxy.is_revoked())
  160. return vm.throw_completion<TypeError>(global_object, ErrorType::ProxyRevoked);
  161. // b. Let proxyTarget be obj.[[ProxyTarget]].
  162. auto& proxy_target = proxy.target();
  163. // c. Return ? GetFunctionRealm(proxyTarget).
  164. VERIFY(proxy_target.is_function());
  165. return get_function_realm(global_object, static_cast<FunctionObject const&>(proxy_target));
  166. }
  167. // 5. Return the current Realm Record.
  168. return vm.current_realm();
  169. }
  170. // 8.5.2.1 InitializeBoundName ( name, value, environment ), https://tc39.es/ecma262/#sec-initializeboundname
  171. ThrowCompletionOr<void> initialize_bound_name(GlobalObject& global_object, FlyString const& name, Value value, Environment* environment)
  172. {
  173. auto& vm = global_object.vm();
  174. // 1. If environment is not undefined, then
  175. if (environment) {
  176. // a. Perform environment.InitializeBinding(name, value).
  177. MUST(environment->initialize_binding(global_object, name, value));
  178. // b. Return NormalCompletion(undefined).
  179. return {};
  180. }
  181. // 2. Else,
  182. else {
  183. // a. Let lhs be ResolveBinding(name).
  184. // NOTE: Although the spec pretends resolve_binding cannot fail it can just not in this case.
  185. auto lhs = MUST(vm.resolve_binding(name));
  186. // b. Return ? PutValue(lhs, value).
  187. return TRY(lhs.put_value(global_object, value));
  188. }
  189. VERIFY_NOT_REACHED();
  190. }
  191. // 10.1.6.2 IsCompatiblePropertyDescriptor ( Extensible, Desc, Current ), https://tc39.es/ecma262/#sec-iscompatiblepropertydescriptor
  192. bool is_compatible_property_descriptor(bool extensible, PropertyDescriptor const& descriptor, Optional<PropertyDescriptor> const& current)
  193. {
  194. // 1. Return ValidateAndApplyPropertyDescriptor(undefined, undefined, Extensible, Desc, Current).
  195. return validate_and_apply_property_descriptor(nullptr, {}, extensible, descriptor, current);
  196. }
  197. // 10.1.6.3 ValidateAndApplyPropertyDescriptor ( O, P, extensible, Desc, current ), https://tc39.es/ecma262/#sec-validateandapplypropertydescriptor
  198. bool validate_and_apply_property_descriptor(Object* object, PropertyKey const& property_name, bool extensible, PropertyDescriptor const& descriptor, Optional<PropertyDescriptor> const& current)
  199. {
  200. // 1. Assert: If O is not undefined, then IsPropertyKey(P) is true.
  201. if (object)
  202. VERIFY(property_name.is_valid());
  203. // 2. If current is undefined, then
  204. if (!current.has_value()) {
  205. // a. If extensible is false, return false.
  206. if (!extensible)
  207. return false;
  208. // b. Assert: extensible is true.
  209. // c. If IsGenericDescriptor(Desc) is true or IsDataDescriptor(Desc) is true, then
  210. if (descriptor.is_generic_descriptor() || descriptor.is_data_descriptor()) {
  211. // i. If O is not undefined, create an own data property named P of object O whose [[Value]], [[Writable]],
  212. // [[Enumerable]], and [[Configurable]] attribute values are described by Desc.
  213. // If the value of an attribute field of Desc is absent, the attribute of the newly created property is set
  214. // to its default value.
  215. if (object) {
  216. auto value = descriptor.value.value_or(js_undefined());
  217. object->storage_set(property_name, { value, descriptor.attributes() });
  218. }
  219. }
  220. // d. Else,
  221. else {
  222. // i. Assert: ! IsAccessorDescriptor(Desc) is true.
  223. VERIFY(descriptor.is_accessor_descriptor());
  224. // ii. If O is not undefined, create an own accessor property named P of object O whose [[Get]], [[Set]],
  225. // [[Enumerable]], and [[Configurable]] attribute values are described by Desc.
  226. // If the value of an attribute field of Desc is absent, the attribute of the newly created property is set
  227. // to its default value.
  228. if (object) {
  229. auto accessor = Accessor::create(object->vm(), descriptor.get.value_or(nullptr), descriptor.set.value_or(nullptr));
  230. object->storage_set(property_name, { accessor, descriptor.attributes() });
  231. }
  232. }
  233. // e. Return true.
  234. return true;
  235. }
  236. // 3. If every field in Desc is absent, return true.
  237. if (descriptor.is_empty())
  238. return true;
  239. // 4. If current.[[Configurable]] is false, then
  240. if (!*current->configurable) {
  241. // a. If Desc.[[Configurable]] is present and its value is true, return false.
  242. if (descriptor.configurable.has_value() && *descriptor.configurable)
  243. return false;
  244. // b. If Desc.[[Enumerable]] is present and ! SameValue(Desc.[[Enumerable]], current.[[Enumerable]]) is false, return false.
  245. if (descriptor.enumerable.has_value() && *descriptor.enumerable != *current->enumerable)
  246. return false;
  247. }
  248. // 5. If ! IsGenericDescriptor(Desc) is true, then
  249. if (descriptor.is_generic_descriptor()) {
  250. // a. NOTE: No further validation is required.
  251. }
  252. // 6. Else if ! SameValue(! IsDataDescriptor(current), ! IsDataDescriptor(Desc)) is false, then
  253. else if (current->is_data_descriptor() != descriptor.is_data_descriptor()) {
  254. // a. If current.[[Configurable]] is false, return false.
  255. if (!*current->configurable)
  256. return false;
  257. // b. If IsDataDescriptor(current) is true, then
  258. if (current->is_data_descriptor()) {
  259. // If O is not undefined, convert the property named P of object O from a data property to an accessor property.
  260. // Preserve the existing values of the converted property's [[Configurable]] and [[Enumerable]] attributes and
  261. // set the rest of the property's attributes to their default values.
  262. if (object) {
  263. auto accessor = Accessor::create(object->vm(), nullptr, nullptr);
  264. object->storage_set(property_name, { accessor, current->attributes() });
  265. }
  266. }
  267. // c. Else,
  268. else {
  269. // If O is not undefined, convert the property named P of object O from an accessor property to a data property.
  270. // Preserve the existing values of the converted property's [[Configurable]] and [[Enumerable]] attributes and
  271. // set the rest of the property's attributes to their default values.
  272. if (object) {
  273. auto value = js_undefined();
  274. object->storage_set(property_name, { value, current->attributes() });
  275. }
  276. }
  277. }
  278. // 7. Else if IsDataDescriptor(current) and IsDataDescriptor(Desc) are both true, then
  279. else if (current->is_data_descriptor() && descriptor.is_data_descriptor()) {
  280. // a. If current.[[Configurable]] is false and current.[[Writable]] is false, then
  281. if (!*current->configurable && !*current->writable) {
  282. // i. If Desc.[[Writable]] is present and Desc.[[Writable]] is true, return false.
  283. if (descriptor.writable.has_value() && *descriptor.writable)
  284. return false;
  285. // ii. If Desc.[[Value]] is present and SameValue(Desc.[[Value]], current.[[Value]]) is false, return false.
  286. if (descriptor.value.has_value() && !same_value(*descriptor.value, *current->value))
  287. return false;
  288. // iii. Return true.
  289. return true;
  290. }
  291. }
  292. // 8. Else,
  293. else {
  294. // a. Assert: ! IsAccessorDescriptor(current) and ! IsAccessorDescriptor(Desc) are both true.
  295. VERIFY(current->is_accessor_descriptor());
  296. VERIFY(descriptor.is_accessor_descriptor());
  297. // b. If current.[[Configurable]] is false, then
  298. if (!*current->configurable) {
  299. // i. If Desc.[[Set]] is present and SameValue(Desc.[[Set]], current.[[Set]]) is false, return false.
  300. if (descriptor.set.has_value() && *descriptor.set != *current->set)
  301. return false;
  302. // ii. If Desc.[[Get]] is present and SameValue(Desc.[[Get]], current.[[Get]]) is false, return false.
  303. if (descriptor.get.has_value() && *descriptor.get != *current->get)
  304. return false;
  305. // iii. Return true.
  306. return true;
  307. }
  308. }
  309. // 9. If O is not undefined, then
  310. if (object) {
  311. // a. For each field of Desc that is present, set the corresponding attribute of the property named P of object O to the value of the field.
  312. Value value;
  313. if (descriptor.is_accessor_descriptor() || (current->is_accessor_descriptor() && !descriptor.is_data_descriptor())) {
  314. auto* getter = descriptor.get.value_or(current->get.value_or(nullptr));
  315. auto* setter = descriptor.set.value_or(current->set.value_or(nullptr));
  316. value = Accessor::create(object->vm(), getter, setter);
  317. } else {
  318. value = descriptor.value.value_or(current->value.value_or({}));
  319. }
  320. PropertyAttributes attributes;
  321. attributes.set_writable(descriptor.writable.value_or(current->writable.value_or(false)));
  322. attributes.set_enumerable(descriptor.enumerable.value_or(current->enumerable.value_or(false)));
  323. attributes.set_configurable(descriptor.configurable.value_or(current->configurable.value_or(false)));
  324. object->storage_set(property_name, { value, attributes });
  325. }
  326. // 10. Return true.
  327. return true;
  328. }
  329. // 10.1.14 GetPrototypeFromConstructor ( constructor, intrinsicDefaultProto ), https://tc39.es/ecma262/#sec-getprototypefromconstructor
  330. ThrowCompletionOr<Object*> get_prototype_from_constructor(GlobalObject& global_object, FunctionObject const& constructor, Object* (GlobalObject::*intrinsic_default_prototype)())
  331. {
  332. auto& vm = global_object.vm();
  333. // 1. Assert: intrinsicDefaultProto is this specification's name of an intrinsic object. The corresponding object must be an intrinsic that is intended to be used as the [[Prototype]] value of an object.
  334. // 2. Let proto be ? Get(constructor, "prototype").
  335. auto prototype = TRY(constructor.get(vm.names.prototype));
  336. // 3. If Type(proto) is not Object, then
  337. if (!prototype.is_object()) {
  338. // a. Let realm be ? GetFunctionRealm(constructor).
  339. auto* realm = TRY(get_function_realm(global_object, constructor));
  340. // b. Set proto to realm's intrinsic object named intrinsicDefaultProto.
  341. prototype = (realm->global_object().*intrinsic_default_prototype)();
  342. }
  343. // 4. Return proto.
  344. return &prototype.as_object();
  345. }
  346. // 9.1.2.2 NewDeclarativeEnvironment ( E ), https://tc39.es/ecma262/#sec-newdeclarativeenvironment
  347. DeclarativeEnvironment* new_declarative_environment(Environment& environment)
  348. {
  349. auto& global_object = environment.global_object();
  350. return global_object.heap().allocate<DeclarativeEnvironment>(global_object, &environment);
  351. }
  352. // 9.1.2.3 NewObjectEnvironment ( O, W, E ), https://tc39.es/ecma262/#sec-newobjectenvironment
  353. ObjectEnvironment* new_object_environment(Object& object, bool is_with_environment, Environment* environment)
  354. {
  355. auto& global_object = object.global_object();
  356. return global_object.heap().allocate<ObjectEnvironment>(global_object, object, is_with_environment ? ObjectEnvironment::IsWithEnvironment::Yes : ObjectEnvironment::IsWithEnvironment::No, environment);
  357. }
  358. // 9.1.2.4 NewFunctionEnvironment ( F, newTarget ), https://tc39.es/ecma262/#sec-newfunctionenvironment
  359. FunctionEnvironment* new_function_environment(ECMAScriptFunctionObject& function, Object* new_target)
  360. {
  361. auto& global_object = function.global_object();
  362. // 1. Let env be a new function Environment Record containing no bindings.
  363. auto* env = global_object.heap().allocate<FunctionEnvironment>(global_object, function.environment());
  364. // 2. Set env.[[FunctionObject]] to F.
  365. env->set_function_object(function);
  366. // 3. If F.[[ThisMode]] is lexical, set env.[[ThisBindingStatus]] to lexical.
  367. if (function.this_mode() == ECMAScriptFunctionObject::ThisMode::Lexical)
  368. env->set_this_binding_status(FunctionEnvironment::ThisBindingStatus::Lexical);
  369. // 4. Else, set env.[[ThisBindingStatus]] to uninitialized.
  370. else
  371. env->set_this_binding_status(FunctionEnvironment::ThisBindingStatus::Uninitialized);
  372. // 5. Set env.[[NewTarget]] to newTarget.
  373. env->set_new_target(new_target ?: js_undefined());
  374. // 6. Set env.[[OuterEnv]] to F.[[Environment]].
  375. // NOTE: Done in step 1 via the FunctionEnvironment constructor.
  376. // 7. Return env.
  377. return env;
  378. }
  379. // 9.2.1.1 NewPrivateEnvironment ( outerPrivEnv ), https://tc39.es/ecma262/#sec-newprivateenvironment
  380. PrivateEnvironment* new_private_environment(VM& vm, PrivateEnvironment* outer)
  381. {
  382. // 1. Let names be a new empty List.
  383. // 2. Return the PrivateEnvironment Record { [[OuterPrivateEnvironment]]: outerPrivEnv, [[Names]]: names }.
  384. return vm.heap().allocate<PrivateEnvironment>(vm.current_realm()->global_object(), outer);
  385. }
  386. // 9.4.3 GetThisEnvironment ( ), https://tc39.es/ecma262/#sec-getthisenvironment
  387. Environment& get_this_environment(VM& vm)
  388. {
  389. for (auto* env = vm.lexical_environment(); env; env = env->outer_environment()) {
  390. if (env->has_this_binding())
  391. return *env;
  392. }
  393. VERIFY_NOT_REACHED();
  394. }
  395. // 13.3.7.2 GetSuperConstructor ( ), https://tc39.es/ecma262/#sec-getsuperconstructor
  396. Object* get_super_constructor(VM& vm)
  397. {
  398. // 1. Let envRec be GetThisEnvironment().
  399. auto& env = get_this_environment(vm);
  400. // 2. Assert: envRec is a function Environment Record.
  401. // 3. Let activeFunction be envRec.[[FunctionObject]].
  402. // 4. Assert: activeFunction is an ECMAScript function object.
  403. auto& active_function = verify_cast<FunctionEnvironment>(env).function_object();
  404. // 5. Let superConstructor be ! activeFunction.[[GetPrototypeOf]]().
  405. auto* super_constructor = MUST(active_function.internal_get_prototype_of());
  406. // 6. Return superConstructor.
  407. return super_constructor;
  408. }
  409. // 13.3.7.3 MakeSuperPropertyReference ( actualThis, propertyKey, strict ), https://tc39.es/ecma262/#sec-makesuperpropertyreference
  410. ThrowCompletionOr<Reference> make_super_property_reference(GlobalObject& global_object, Value actual_this, PropertyKey const& property_key, bool strict)
  411. {
  412. auto& vm = global_object.vm();
  413. // 1. Let env be GetThisEnvironment().
  414. auto& env = verify_cast<FunctionEnvironment>(get_this_environment(vm));
  415. // 2. Assert: env.HasSuperBinding() is true.
  416. VERIFY(env.has_super_binding());
  417. // 3. Let baseValue be ? env.GetSuperBase().
  418. auto base_value = TRY(env.get_super_base());
  419. // 4. Let bv be ? RequireObjectCoercible(baseValue).
  420. auto bv = TRY(require_object_coercible(global_object, base_value));
  421. // 5. Return the Reference Record { [[Base]]: bv, [[ReferencedName]]: propertyKey, [[Strict]]: strict, [[ThisValue]]: actualThis }.
  422. // 6. NOTE: This returns a Super Reference Record.
  423. return Reference { bv, property_key, actual_this, strict };
  424. }
  425. // 19.2.1.1 PerformEval ( x, callerRealm, strictCaller, direct ), https://tc39.es/ecma262/#sec-performeval
  426. ThrowCompletionOr<Value> perform_eval(Value x, GlobalObject& caller_realm, CallerMode strict_caller, EvalMode direct)
  427. {
  428. VERIFY(direct == EvalMode::Direct || strict_caller == CallerMode::NonStrict);
  429. if (!x.is_string())
  430. return x;
  431. auto& vm = caller_realm.vm();
  432. auto& eval_realm = vm.running_execution_context().realm;
  433. auto& code_string = x.as_string();
  434. Parser parser { Lexer { code_string.string() } };
  435. auto program = parser.parse_program(strict_caller == CallerMode::Strict);
  436. if (parser.has_errors()) {
  437. auto& error = parser.errors()[0];
  438. return vm.throw_completion<SyntaxError>(caller_realm, error.to_string());
  439. }
  440. auto strict_eval = strict_caller == CallerMode::Strict;
  441. if (program->is_strict_mode())
  442. strict_eval = true;
  443. auto& running_context = vm.running_execution_context();
  444. Environment* lexical_environment;
  445. Environment* variable_environment;
  446. PrivateEnvironment* private_environment;
  447. if (direct == EvalMode::Direct) {
  448. lexical_environment = new_declarative_environment(*running_context.lexical_environment);
  449. variable_environment = running_context.variable_environment;
  450. private_environment = running_context.private_environment;
  451. } else {
  452. lexical_environment = new_declarative_environment(eval_realm->global_environment());
  453. variable_environment = &eval_realm->global_environment();
  454. private_environment = nullptr;
  455. }
  456. if (strict_eval)
  457. variable_environment = lexical_environment;
  458. if (direct == EvalMode::Direct && !strict_eval) {
  459. // NOTE: Non-strict direct eval() forces us to deoptimize variable accesses.
  460. // Mark the variable environment chain as screwed since we will not be able
  461. // to rely on cached environment coordinates from this point on.
  462. variable_environment->set_permanently_screwed_by_eval();
  463. }
  464. // 18. If runningContext is not already suspended, suspend runningContext.
  465. // FIXME: We don't have this concept yet.
  466. ExecutionContext eval_context(vm.heap());
  467. eval_context.realm = eval_realm;
  468. eval_context.variable_environment = variable_environment;
  469. eval_context.lexical_environment = lexical_environment;
  470. eval_context.private_environment = private_environment;
  471. TRY(vm.push_execution_context(eval_context, eval_realm->global_object()));
  472. ScopeGuard pop_guard = [&] {
  473. vm.pop_execution_context();
  474. };
  475. TRY(eval_declaration_instantiation(vm, eval_realm->global_object(), program, variable_environment, lexical_environment, private_environment, strict_eval));
  476. TemporaryChange scope_change_strict(vm.running_execution_context().is_strict_mode, strict_eval);
  477. Optional<Value> eval_result;
  478. if (auto* bytecode_interpreter = Bytecode::Interpreter::current()) {
  479. auto executable = JS::Bytecode::Generator::generate(program);
  480. executable.name = "eval"sv;
  481. if (JS::Bytecode::g_dump_bytecode)
  482. executable.dump();
  483. eval_result = TRY(bytecode_interpreter->run(executable));
  484. // Turn potentially empty JS::Value from the bytecode interpreter into an empty Optional
  485. if (eval_result.has_value() && eval_result->is_empty())
  486. eval_result = {};
  487. } else {
  488. auto& ast_interpreter = vm.interpreter();
  489. eval_result = TRY(program->execute(ast_interpreter, caller_realm));
  490. }
  491. return eval_result.value_or(js_undefined());
  492. }
  493. // 19.2.1.3 EvalDeclarationInstantiation ( body, varEnv, lexEnv, privateEnv, strict ), https://tc39.es/ecma262/#sec-evaldeclarationinstantiation
  494. ThrowCompletionOr<void> eval_declaration_instantiation(VM& vm, GlobalObject& global_object, Program const& program, Environment* variable_environment, Environment* lexical_environment, PrivateEnvironment* private_environment, bool strict)
  495. {
  496. // FIXME: I'm not sure if the global object is correct here. And this is quite a crucial spot!
  497. GlobalEnvironment* global_var_environment = variable_environment->is_global_environment() ? static_cast<GlobalEnvironment*>(variable_environment) : nullptr;
  498. if (!strict) {
  499. if (global_var_environment) {
  500. program.for_each_var_declared_name([&](auto const& name) {
  501. if (global_var_environment->has_lexical_declaration(name)) {
  502. vm.throw_exception<SyntaxError>(global_object, ErrorType::TopLevelVariableAlreadyDeclared, name);
  503. return IterationDecision::Break;
  504. }
  505. return IterationDecision::Continue;
  506. });
  507. }
  508. auto* this_environment = lexical_environment;
  509. while (this_environment != variable_environment) {
  510. if (!is<ObjectEnvironment>(*this_environment)) {
  511. program.for_each_var_declared_name([&](auto const& name) {
  512. if (MUST(this_environment->has_binding(name))) {
  513. vm.throw_exception<SyntaxError>(global_object, ErrorType::TopLevelVariableAlreadyDeclared, name);
  514. return IterationDecision::Break;
  515. }
  516. // FIXME: NOTE: Annex B.3.4 defines alternate semantics for the above step.
  517. // In particular it only throw the syntax error if it is not an environment from a catchclause.
  518. return IterationDecision::Continue;
  519. });
  520. if (auto* exception = vm.exception())
  521. return throw_completion(exception->value());
  522. }
  523. this_environment = this_environment->outer_environment();
  524. VERIFY(this_environment);
  525. }
  526. }
  527. // FIXME: Add Private identifiers check here.
  528. HashTable<FlyString> declared_function_names;
  529. Vector<FunctionDeclaration const&> functions_to_initialize;
  530. program.for_each_var_function_declaration_in_reverse_order([&](FunctionDeclaration const& function) {
  531. if (declared_function_names.set(function.name()) != AK::HashSetResult::InsertedNewEntry)
  532. return IterationDecision::Continue;
  533. if (global_var_environment) {
  534. auto function_definable_or_error = global_var_environment->can_declare_global_function(function.name());
  535. if (function_definable_or_error.is_error())
  536. return IterationDecision::Break;
  537. auto function_definable = function_definable_or_error.release_value();
  538. if (!function_definable) {
  539. vm.throw_exception<TypeError>(global_object, ErrorType::CannotDeclareGlobalFunction, function.name());
  540. return IterationDecision::Break;
  541. }
  542. }
  543. functions_to_initialize.append(function);
  544. return IterationDecision::Continue;
  545. });
  546. if (auto* exception = vm.exception())
  547. return throw_completion(exception->value());
  548. if (!strict) {
  549. // The spec here uses 'declaredVarNames' but that has not been declared yet.
  550. HashTable<FlyString> hoisted_functions;
  551. program.for_each_function_hoistable_with_annexB_extension([&](FunctionDeclaration& function_declaration) {
  552. auto& function_name = function_declaration.name();
  553. auto* this_environment = lexical_environment;
  554. while (this_environment != variable_environment) {
  555. if (!is<ObjectEnvironment>(*this_environment) && MUST(this_environment->has_binding(function_name)))
  556. return IterationDecision::Continue;
  557. this_environment = this_environment->outer_environment();
  558. VERIFY(this_environment);
  559. }
  560. if (global_var_environment) {
  561. if (global_var_environment->has_lexical_declaration(function_name))
  562. return IterationDecision::Continue;
  563. auto var_definable_or_error = global_var_environment->can_declare_global_var(function_name);
  564. if (var_definable_or_error.is_error())
  565. return IterationDecision::Break;
  566. auto var_definable = var_definable_or_error.release_value();
  567. if (!var_definable)
  568. return IterationDecision::Continue;
  569. }
  570. if (!declared_function_names.contains(function_name) && !hoisted_functions.contains(function_name)) {
  571. if (global_var_environment) {
  572. auto result = global_var_environment->create_global_var_binding(function_name, true);
  573. if (result.is_error())
  574. return IterationDecision::Break;
  575. } else {
  576. if (!MUST(variable_environment->has_binding(function_name))) {
  577. MUST(variable_environment->create_mutable_binding(global_object, function_name, true));
  578. MUST(variable_environment->initialize_binding(global_object, function_name, js_undefined()));
  579. }
  580. }
  581. hoisted_functions.set(function_name);
  582. }
  583. function_declaration.set_should_do_additional_annexB_steps();
  584. return IterationDecision::Continue;
  585. });
  586. if (auto* exception = vm.exception())
  587. return throw_completion(exception->value());
  588. }
  589. HashTable<FlyString> declared_var_names;
  590. program.for_each_var_scoped_variable_declaration([&](VariableDeclaration const& declaration) {
  591. declaration.for_each_bound_name([&](auto const& name) {
  592. if (!declared_function_names.contains(name)) {
  593. if (global_var_environment) {
  594. auto variable_definable_or_error = global_var_environment->can_declare_global_var(name);
  595. if (variable_definable_or_error.is_error())
  596. return IterationDecision::Break;
  597. auto variable_definable = variable_definable_or_error.release_value();
  598. if (!variable_definable) {
  599. vm.throw_exception<TypeError>(global_object, ErrorType::CannotDeclareGlobalVariable, name);
  600. return IterationDecision::Break;
  601. }
  602. }
  603. declared_var_names.set(name);
  604. }
  605. return IterationDecision::Continue;
  606. });
  607. if (vm.exception())
  608. return IterationDecision::Break;
  609. return IterationDecision::Continue;
  610. });
  611. if (auto* exception = vm.exception())
  612. return throw_completion(exception->value());
  613. // 14. NOTE: No abnormal terminations occur after this algorithm step unless varEnv is a global Environment Record and the global object is a Proxy exotic object.
  614. program.for_each_lexically_scoped_declaration([&](Declaration const& declaration) {
  615. declaration.for_each_bound_name([&](auto const& name) {
  616. if (declaration.is_constant_declaration())
  617. (void)lexical_environment->create_immutable_binding(global_object, name, true);
  618. else
  619. (void)lexical_environment->create_mutable_binding(global_object, name, false);
  620. if (vm.exception())
  621. return IterationDecision::Break;
  622. return IterationDecision::Continue;
  623. });
  624. if (vm.exception())
  625. return IterationDecision::Break;
  626. return IterationDecision::Continue;
  627. });
  628. if (auto* exception = vm.exception())
  629. return throw_completion(exception->value());
  630. for (auto& declaration : functions_to_initialize) {
  631. auto* function = ECMAScriptFunctionObject::create(global_object, declaration.name(), declaration.source_text(), declaration.body(), declaration.parameters(), declaration.function_length(), lexical_environment, private_environment, declaration.kind(), declaration.is_strict_mode(), declaration.might_need_arguments_object());
  632. if (global_var_environment) {
  633. TRY(global_var_environment->create_global_function_binding(declaration.name(), function, true));
  634. } else {
  635. auto binding_exists = MUST(variable_environment->has_binding(declaration.name()));
  636. if (!binding_exists) {
  637. TRY(variable_environment->create_mutable_binding(global_object, declaration.name(), true));
  638. TRY(variable_environment->initialize_binding(global_object, declaration.name(), function));
  639. } else {
  640. TRY(variable_environment->set_mutable_binding(global_object, declaration.name(), function, false));
  641. }
  642. }
  643. }
  644. for (auto& var_name : declared_var_names) {
  645. if (global_var_environment) {
  646. TRY(global_var_environment->create_global_var_binding(var_name, true));
  647. } else {
  648. auto binding_exists = MUST(variable_environment->has_binding(var_name));
  649. if (!binding_exists) {
  650. TRY(variable_environment->create_mutable_binding(global_object, var_name, true));
  651. TRY(variable_environment->initialize_binding(global_object, var_name, js_undefined()));
  652. }
  653. }
  654. }
  655. return {};
  656. }
  657. // 10.4.4.6 CreateUnmappedArgumentsObject ( argumentsList ), https://tc39.es/ecma262/#sec-createunmappedargumentsobject
  658. Object* create_unmapped_arguments_object(GlobalObject& global_object, Span<Value> arguments)
  659. {
  660. auto& vm = global_object.vm();
  661. // 1. Let len be the number of elements in argumentsList.
  662. auto length = arguments.size();
  663. // 2. Let obj be ! OrdinaryObjectCreate(%Object.prototype%, « [[ParameterMap]] »).
  664. // 3. Set obj.[[ParameterMap]] to undefined.
  665. auto* object = Object::create(global_object, global_object.object_prototype());
  666. object->set_has_parameter_map();
  667. // 4. Perform DefinePropertyOrThrow(obj, "length", PropertyDescriptor { [[Value]]: 𝔽(len), [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
  668. MUST(object->define_property_or_throw(vm.names.length, { .value = Value(length), .writable = true, .enumerable = false, .configurable = true }));
  669. // 5. Let index be 0.
  670. // 6. Repeat, while index < len,
  671. for (size_t index = 0; index < length; ++index) {
  672. // a. Let val be argumentsList[index].
  673. auto value = arguments[index];
  674. // b. Perform ! CreateDataPropertyOrThrow(obj, ! ToString(𝔽(index)), val).
  675. MUST(object->create_data_property_or_throw(index, value));
  676. // c. Set index to index + 1.
  677. }
  678. // 7. Perform ! DefinePropertyOrThrow(obj, @@iterator, PropertyDescriptor { [[Value]]: %Array.prototype.values%, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
  679. auto* array_prototype_values = global_object.array_prototype_values_function();
  680. MUST(object->define_property_or_throw(*vm.well_known_symbol_iterator(), { .value = array_prototype_values, .writable = true, .enumerable = false, .configurable = true }));
  681. // 8. Perform ! DefinePropertyOrThrow(obj, "callee", PropertyDescriptor { [[Get]]: %ThrowTypeError%, [[Set]]: %ThrowTypeError%, [[Enumerable]]: false, [[Configurable]]: false }).
  682. auto* throw_type_error = global_object.throw_type_error_function();
  683. MUST(object->define_property_or_throw(vm.names.callee, { .get = throw_type_error, .set = throw_type_error, .enumerable = false, .configurable = false }));
  684. // 9. Return obj.
  685. return object;
  686. }
  687. // 10.4.4.7 CreateMappedArgumentsObject ( func, formals, argumentsList, env ), https://tc39.es/ecma262/#sec-createmappedargumentsobject
  688. Object* create_mapped_arguments_object(GlobalObject& global_object, FunctionObject& function, Vector<FunctionNode::Parameter> const& formals, Span<Value> arguments, Environment& environment)
  689. {
  690. auto& vm = global_object.vm();
  691. // 1. Assert: formals does not contain a rest parameter, any binding patterns, or any initializers. It may contain duplicate identifiers.
  692. // 2. Let len be the number of elements in argumentsList.
  693. VERIFY(arguments.size() <= NumericLimits<i32>::max());
  694. i32 length = static_cast<i32>(arguments.size());
  695. // 3. Let obj be ! MakeBasicObject(« [[Prototype]], [[Extensible]], [[ParameterMap]] »).
  696. // 4. Set obj.[[GetOwnProperty]] as specified in 10.4.4.1.
  697. // 5. Set obj.[[DefineOwnProperty]] as specified in 10.4.4.2.
  698. // 6. Set obj.[[Get]] as specified in 10.4.4.3.
  699. // 7. Set obj.[[Set]] as specified in 10.4.4.4.
  700. // 8. Set obj.[[Delete]] as specified in 10.4.4.5.
  701. // 9. Set obj.[[Prototype]] to %Object.prototype%.
  702. auto* object = vm.heap().allocate<ArgumentsObject>(global_object, global_object, environment);
  703. VERIFY(!vm.exception());
  704. // 14. Let index be 0.
  705. // 15. Repeat, while index < len,
  706. for (i32 index = 0; index < length; ++index) {
  707. // a. Let val be argumentsList[index].
  708. auto value = arguments[index];
  709. // b. Perform ! CreateDataPropertyOrThrow(obj, ! ToString(𝔽(index)), val).
  710. MUST(object->create_data_property_or_throw(index, value));
  711. // c. Set index to index + 1.
  712. }
  713. // 16. Perform ! DefinePropertyOrThrow(obj, "length", PropertyDescriptor { [[Value]]: 𝔽(len), [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
  714. MUST(object->define_property_or_throw(vm.names.length, { .value = Value(length), .writable = true, .enumerable = false, .configurable = true }));
  715. // 17. Let mappedNames be a new empty List.
  716. HashTable<FlyString> mapped_names;
  717. // 18. Set index to numberOfParameters - 1.
  718. // 19. Repeat, while index ≥ 0,
  719. VERIFY(formals.size() <= NumericLimits<i32>::max());
  720. for (i32 index = static_cast<i32>(formals.size()) - 1; index >= 0; --index) {
  721. // a. Let name be parameterNames[index].
  722. auto const& name = formals[index].binding.get<FlyString>();
  723. // b. If name is not an element of mappedNames, then
  724. if (mapped_names.contains(name))
  725. continue;
  726. // i. Add name as an element of the list mappedNames.
  727. mapped_names.set(name);
  728. // ii. If index < len, then
  729. if (index < length) {
  730. // 1. Let g be MakeArgGetter(name, env).
  731. // 2. Let p be MakeArgSetter(name, env).
  732. // 3. Perform map.[[DefineOwnProperty]](! ToString(𝔽(index)), PropertyDescriptor { [[Set]]: p, [[Get]]: g, [[Enumerable]]: false, [[Configurable]]: true }).
  733. object->parameter_map().define_native_accessor(
  734. PropertyKey { index },
  735. [&environment, name](VM&, GlobalObject& global_object_getter) -> JS::ThrowCompletionOr<Value> {
  736. return MUST(environment.get_binding_value(global_object_getter, name, false));
  737. },
  738. [&environment, name](VM& vm, GlobalObject& global_object_setter) {
  739. MUST(environment.set_mutable_binding(global_object_setter, name, vm.argument(0), false));
  740. return js_undefined();
  741. },
  742. Attribute::Configurable);
  743. }
  744. }
  745. // 20. Perform ! DefinePropertyOrThrow(obj, @@iterator, PropertyDescriptor { [[Value]]: %Array.prototype.values%, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
  746. auto* array_prototype_values = global_object.array_prototype_values_function();
  747. MUST(object->define_property_or_throw(*vm.well_known_symbol_iterator(), { .value = array_prototype_values, .writable = true, .enumerable = false, .configurable = true }));
  748. // 21. Perform ! DefinePropertyOrThrow(obj, "callee", PropertyDescriptor { [[Value]]: func, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
  749. MUST(object->define_property_or_throw(vm.names.callee, { .value = &function, .writable = true, .enumerable = false, .configurable = true }));
  750. // 22. Return obj.
  751. return object;
  752. }
  753. // 7.1.21 CanonicalNumericIndexString ( argument ), https://tc39.es/ecma262/#sec-canonicalnumericindexstring
  754. Value canonical_numeric_index_string(GlobalObject& global_object, PropertyKey const& property_name)
  755. {
  756. // NOTE: If the property name is a number type (An implementation-defined optimized
  757. // property key type), it can be treated as a string property that has already been
  758. // converted successfully into a canonical numeric index.
  759. VERIFY(property_name.is_string() || property_name.is_number());
  760. if (property_name.is_number())
  761. return Value(property_name.as_number());
  762. // 1. Assert: Type(argument) is String.
  763. auto argument = Value(js_string(global_object.vm(), property_name.as_string()));
  764. // 2. If argument is "-0", return -0𝔽.
  765. if (argument.as_string().string() == "-0")
  766. return Value(-0.0);
  767. // 3. Let n be ! ToNumber(argument).
  768. auto n = MUST(argument.to_number(global_object));
  769. // 4. If SameValue(! ToString(n), argument) is false, return undefined.
  770. if (!same_value(MUST(n.to_primitive_string(global_object)), argument))
  771. return js_undefined();
  772. // 5. Return n.
  773. return n;
  774. }
  775. // 22.1.3.17.1 GetSubstitution ( matched, str, position, captures, namedCaptures, replacement ), https://tc39.es/ecma262/#sec-getsubstitution
  776. ThrowCompletionOr<String> get_substitution(GlobalObject& global_object, Utf16View const& matched, Utf16View const& str, size_t position, Span<Value> captures, Value named_captures, Value replacement)
  777. {
  778. auto replace_string = TRY(replacement.to_utf16_string(global_object));
  779. auto replace_view = replace_string.view();
  780. StringBuilder result;
  781. for (size_t i = 0; i < replace_view.length_in_code_units(); ++i) {
  782. u16 curr = replace_view.code_unit_at(i);
  783. if ((curr != '$') || (i + 1 >= replace_view.length_in_code_units())) {
  784. result.append(curr);
  785. continue;
  786. }
  787. u16 next = replace_view.code_unit_at(i + 1);
  788. if (next == '$') {
  789. result.append('$');
  790. ++i;
  791. } else if (next == '&') {
  792. result.append(matched);
  793. ++i;
  794. } else if (next == '`') {
  795. auto substring = str.substring_view(0, position);
  796. result.append(substring);
  797. ++i;
  798. } else if (next == '\'') {
  799. auto tail_pos = position + matched.length_in_code_units();
  800. if (tail_pos < str.length_in_code_units()) {
  801. auto substring = str.substring_view(tail_pos);
  802. result.append(substring);
  803. }
  804. ++i;
  805. } else if (is_ascii_digit(next)) {
  806. bool is_two_digits = (i + 2 < replace_view.length_in_code_units()) && is_ascii_digit(replace_view.code_unit_at(i + 2));
  807. auto capture_postition_string = replace_view.substring_view(i + 1, is_two_digits ? 2 : 1).to_utf8();
  808. auto capture_position = capture_postition_string.to_uint();
  809. if (capture_position.has_value() && (*capture_position > 0) && (*capture_position <= captures.size())) {
  810. auto& value = captures[*capture_position - 1];
  811. if (!value.is_undefined()) {
  812. auto value_string = TRY(value.to_string(global_object));
  813. result.append(value_string);
  814. }
  815. i += is_two_digits ? 2 : 1;
  816. } else {
  817. result.append(curr);
  818. }
  819. } else if (next == '<') {
  820. auto start_position = i + 2;
  821. Optional<size_t> end_position;
  822. for (size_t j = start_position; j < replace_view.length_in_code_units(); ++j) {
  823. if (replace_view.code_unit_at(j) == '>') {
  824. end_position = j;
  825. break;
  826. }
  827. }
  828. if (named_captures.is_undefined() || !end_position.has_value()) {
  829. result.append(curr);
  830. } else {
  831. auto group_name_view = replace_view.substring_view(start_position, *end_position - start_position);
  832. auto group_name = group_name_view.to_utf8(Utf16View::AllowInvalidCodeUnits::Yes);
  833. auto capture = TRY(named_captures.as_object().get(group_name));
  834. if (!capture.is_undefined()) {
  835. auto capture_string = TRY(capture.to_string(global_object));
  836. result.append(capture_string);
  837. }
  838. i = *end_position;
  839. }
  840. } else {
  841. result.append(curr);
  842. }
  843. }
  844. return result.build();
  845. }
  846. }