GlobalObject.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2022, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/BuiltinWrappers.h>
  8. #include <AK/CharacterTypes.h>
  9. #include <AK/Hex.h>
  10. #include <AK/Platform.h>
  11. #include <AK/UnicodeUtils.h>
  12. #include <AK/Utf16View.h>
  13. #include <AK/Utf8View.h>
  14. #include <LibJS/Console.h>
  15. #include <LibJS/Heap/DeferGC.h>
  16. #include <LibJS/Interpreter.h>
  17. #include <LibJS/Runtime/AbstractOperations.h>
  18. #include <LibJS/Runtime/AggregateErrorConstructor.h>
  19. #include <LibJS/Runtime/AggregateErrorPrototype.h>
  20. #include <LibJS/Runtime/ArrayBufferConstructor.h>
  21. #include <LibJS/Runtime/ArrayBufferPrototype.h>
  22. #include <LibJS/Runtime/ArrayConstructor.h>
  23. #include <LibJS/Runtime/ArrayIteratorPrototype.h>
  24. #include <LibJS/Runtime/ArrayPrototype.h>
  25. #include <LibJS/Runtime/AsyncFromSyncIteratorPrototype.h>
  26. #include <LibJS/Runtime/AsyncFunctionConstructor.h>
  27. #include <LibJS/Runtime/AsyncFunctionPrototype.h>
  28. #include <LibJS/Runtime/AsyncGeneratorFunctionConstructor.h>
  29. #include <LibJS/Runtime/AsyncGeneratorFunctionPrototype.h>
  30. #include <LibJS/Runtime/AsyncGeneratorPrototype.h>
  31. #include <LibJS/Runtime/AsyncIteratorPrototype.h>
  32. #include <LibJS/Runtime/AtomicsObject.h>
  33. #include <LibJS/Runtime/BigIntConstructor.h>
  34. #include <LibJS/Runtime/BigIntPrototype.h>
  35. #include <LibJS/Runtime/BooleanConstructor.h>
  36. #include <LibJS/Runtime/BooleanPrototype.h>
  37. #include <LibJS/Runtime/ConsoleObject.h>
  38. #include <LibJS/Runtime/DataViewConstructor.h>
  39. #include <LibJS/Runtime/DataViewPrototype.h>
  40. #include <LibJS/Runtime/DateConstructor.h>
  41. #include <LibJS/Runtime/DatePrototype.h>
  42. #include <LibJS/Runtime/ErrorConstructor.h>
  43. #include <LibJS/Runtime/ErrorPrototype.h>
  44. #include <LibJS/Runtime/FinalizationRegistryConstructor.h>
  45. #include <LibJS/Runtime/FinalizationRegistryPrototype.h>
  46. #include <LibJS/Runtime/FunctionConstructor.h>
  47. #include <LibJS/Runtime/FunctionPrototype.h>
  48. #include <LibJS/Runtime/GeneratorFunctionConstructor.h>
  49. #include <LibJS/Runtime/GeneratorFunctionPrototype.h>
  50. #include <LibJS/Runtime/GeneratorPrototype.h>
  51. #include <LibJS/Runtime/GlobalEnvironment.h>
  52. #include <LibJS/Runtime/GlobalObject.h>
  53. #include <LibJS/Runtime/Intl/CollatorConstructor.h>
  54. #include <LibJS/Runtime/Intl/CollatorPrototype.h>
  55. #include <LibJS/Runtime/Intl/DateTimeFormatConstructor.h>
  56. #include <LibJS/Runtime/Intl/DateTimeFormatPrototype.h>
  57. #include <LibJS/Runtime/Intl/DisplayNamesConstructor.h>
  58. #include <LibJS/Runtime/Intl/DisplayNamesPrototype.h>
  59. #include <LibJS/Runtime/Intl/DurationFormatConstructor.h>
  60. #include <LibJS/Runtime/Intl/DurationFormatPrototype.h>
  61. #include <LibJS/Runtime/Intl/Intl.h>
  62. #include <LibJS/Runtime/Intl/ListFormatConstructor.h>
  63. #include <LibJS/Runtime/Intl/ListFormatPrototype.h>
  64. #include <LibJS/Runtime/Intl/LocaleConstructor.h>
  65. #include <LibJS/Runtime/Intl/LocalePrototype.h>
  66. #include <LibJS/Runtime/Intl/NumberFormatConstructor.h>
  67. #include <LibJS/Runtime/Intl/NumberFormatPrototype.h>
  68. #include <LibJS/Runtime/Intl/PluralRulesConstructor.h>
  69. #include <LibJS/Runtime/Intl/PluralRulesPrototype.h>
  70. #include <LibJS/Runtime/Intl/RelativeTimeFormatConstructor.h>
  71. #include <LibJS/Runtime/Intl/RelativeTimeFormatPrototype.h>
  72. #include <LibJS/Runtime/Intl/SegmentIteratorPrototype.h>
  73. #include <LibJS/Runtime/Intl/SegmenterConstructor.h>
  74. #include <LibJS/Runtime/Intl/SegmenterPrototype.h>
  75. #include <LibJS/Runtime/Intl/SegmentsPrototype.h>
  76. #include <LibJS/Runtime/IteratorPrototype.h>
  77. #include <LibJS/Runtime/JSONObject.h>
  78. #include <LibJS/Runtime/MapConstructor.h>
  79. #include <LibJS/Runtime/MapIteratorPrototype.h>
  80. #include <LibJS/Runtime/MapPrototype.h>
  81. #include <LibJS/Runtime/MathObject.h>
  82. #include <LibJS/Runtime/NativeFunction.h>
  83. #include <LibJS/Runtime/NumberConstructor.h>
  84. #include <LibJS/Runtime/NumberPrototype.h>
  85. #include <LibJS/Runtime/Object.h>
  86. #include <LibJS/Runtime/ObjectConstructor.h>
  87. #include <LibJS/Runtime/ObjectPrototype.h>
  88. #include <LibJS/Runtime/PromiseConstructor.h>
  89. #include <LibJS/Runtime/PromisePrototype.h>
  90. #include <LibJS/Runtime/ProxyConstructor.h>
  91. #include <LibJS/Runtime/Realm.h>
  92. #include <LibJS/Runtime/ReflectObject.h>
  93. #include <LibJS/Runtime/RegExpConstructor.h>
  94. #include <LibJS/Runtime/RegExpPrototype.h>
  95. #include <LibJS/Runtime/RegExpStringIteratorPrototype.h>
  96. #include <LibJS/Runtime/SetConstructor.h>
  97. #include <LibJS/Runtime/SetIteratorPrototype.h>
  98. #include <LibJS/Runtime/SetPrototype.h>
  99. #include <LibJS/Runtime/ShadowRealmConstructor.h>
  100. #include <LibJS/Runtime/ShadowRealmPrototype.h>
  101. #include <LibJS/Runtime/Shape.h>
  102. #include <LibJS/Runtime/StringConstructor.h>
  103. #include <LibJS/Runtime/StringIteratorPrototype.h>
  104. #include <LibJS/Runtime/StringPrototype.h>
  105. #include <LibJS/Runtime/SymbolConstructor.h>
  106. #include <LibJS/Runtime/SymbolPrototype.h>
  107. #include <LibJS/Runtime/Temporal/CalendarConstructor.h>
  108. #include <LibJS/Runtime/Temporal/CalendarPrototype.h>
  109. #include <LibJS/Runtime/Temporal/DurationConstructor.h>
  110. #include <LibJS/Runtime/Temporal/DurationPrototype.h>
  111. #include <LibJS/Runtime/Temporal/InstantConstructor.h>
  112. #include <LibJS/Runtime/Temporal/InstantPrototype.h>
  113. #include <LibJS/Runtime/Temporal/PlainDateConstructor.h>
  114. #include <LibJS/Runtime/Temporal/PlainDatePrototype.h>
  115. #include <LibJS/Runtime/Temporal/PlainDateTimeConstructor.h>
  116. #include <LibJS/Runtime/Temporal/PlainDateTimePrototype.h>
  117. #include <LibJS/Runtime/Temporal/PlainMonthDayConstructor.h>
  118. #include <LibJS/Runtime/Temporal/PlainMonthDayPrototype.h>
  119. #include <LibJS/Runtime/Temporal/PlainTimeConstructor.h>
  120. #include <LibJS/Runtime/Temporal/PlainTimePrototype.h>
  121. #include <LibJS/Runtime/Temporal/PlainYearMonthConstructor.h>
  122. #include <LibJS/Runtime/Temporal/PlainYearMonthPrototype.h>
  123. #include <LibJS/Runtime/Temporal/Temporal.h>
  124. #include <LibJS/Runtime/Temporal/TimeZoneConstructor.h>
  125. #include <LibJS/Runtime/Temporal/TimeZonePrototype.h>
  126. #include <LibJS/Runtime/Temporal/ZonedDateTimeConstructor.h>
  127. #include <LibJS/Runtime/Temporal/ZonedDateTimePrototype.h>
  128. #include <LibJS/Runtime/TypedArray.h>
  129. #include <LibJS/Runtime/TypedArrayConstructor.h>
  130. #include <LibJS/Runtime/TypedArrayPrototype.h>
  131. #include <LibJS/Runtime/Value.h>
  132. #include <LibJS/Runtime/WeakMapConstructor.h>
  133. #include <LibJS/Runtime/WeakMapPrototype.h>
  134. #include <LibJS/Runtime/WeakRefConstructor.h>
  135. #include <LibJS/Runtime/WeakRefPrototype.h>
  136. #include <LibJS/Runtime/WeakSetConstructor.h>
  137. #include <LibJS/Runtime/WeakSetPrototype.h>
  138. namespace JS {
  139. GlobalObject::GlobalObject(Realm& realm)
  140. : Object(GlobalObjectTag::Tag, realm)
  141. , m_console(make<Console>(*this))
  142. {
  143. }
  144. void GlobalObject::initialize_global_object()
  145. {
  146. auto& vm = this->vm();
  147. ensure_shape_is_unique();
  148. // These are done first since other prototypes depend on their presence.
  149. VERIFY(associated_realm());
  150. auto& realm = *associated_realm();
  151. m_empty_object_shape = heap().allocate_without_global_object<Shape>(realm);
  152. m_object_prototype = heap().allocate_without_global_object<ObjectPrototype>(realm);
  153. m_function_prototype = heap().allocate_without_global_object<FunctionPrototype>(realm);
  154. m_new_object_shape = vm.heap().allocate_without_global_object<Shape>(realm);
  155. m_new_object_shape->set_prototype_without_transition(m_object_prototype);
  156. m_new_ordinary_function_prototype_object_shape = vm.heap().allocate_without_global_object<Shape>(realm);
  157. m_new_ordinary_function_prototype_object_shape->set_prototype_without_transition(m_object_prototype);
  158. m_new_ordinary_function_prototype_object_shape->add_property_without_transition(vm.names.constructor, Attribute::Writable | Attribute::Configurable);
  159. // Normally Heap::allocate() takes care of this, but these are allocated via allocate_without_global_object().
  160. static_cast<FunctionPrototype*>(m_function_prototype)->initialize(realm);
  161. static_cast<ObjectPrototype*>(m_object_prototype)->initialize(realm);
  162. Object::set_prototype(m_object_prototype);
  163. // This must be initialized before allocating AggregateErrorPrototype, which uses ErrorPrototype as its prototype.
  164. m_error_prototype = heap().allocate<ErrorPrototype>(*this, realm);
  165. #define __JS_ENUMERATE(ClassName, snake_name) \
  166. if (!m_##snake_name##_prototype) \
  167. m_##snake_name##_prototype = heap().allocate<ClassName##Prototype>(*this, realm);
  168. JS_ENUMERATE_ITERATOR_PROTOTYPES
  169. #undef __JS_ENUMERATE
  170. // These must be initialized separately as they have no companion constructor
  171. m_async_from_sync_iterator_prototype = heap().allocate<AsyncFromSyncIteratorPrototype>(*this, realm);
  172. m_async_generator_prototype = heap().allocate<AsyncGeneratorPrototype>(*this, realm);
  173. m_generator_prototype = heap().allocate<GeneratorPrototype>(*this, realm);
  174. m_intl_segments_prototype = heap().allocate<Intl::SegmentsPrototype>(*this, realm);
  175. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
  176. if (!m_##snake_name##_prototype) \
  177. m_##snake_name##_prototype = heap().allocate<PrototypeName>(*this, realm);
  178. JS_ENUMERATE_BUILTIN_TYPES
  179. #undef __JS_ENUMERATE
  180. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName) \
  181. if (!m_intl_##snake_name##_prototype) \
  182. m_intl_##snake_name##_prototype = heap().allocate<Intl::PrototypeName>(*this, realm);
  183. JS_ENUMERATE_INTL_OBJECTS
  184. #undef __JS_ENUMERATE
  185. // Must be allocated before `Intl::Intl` below.
  186. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName) \
  187. initialize_constructor(vm.names.ClassName, m_intl_##snake_name##_constructor, m_intl_##snake_name##_prototype);
  188. JS_ENUMERATE_INTL_OBJECTS
  189. #undef __JS_ENUMERATE
  190. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName) \
  191. if (!m_temporal_##snake_name##_prototype) \
  192. m_temporal_##snake_name##_prototype = heap().allocate<Temporal::PrototypeName>(*this, realm);
  193. JS_ENUMERATE_TEMPORAL_OBJECTS
  194. #undef __JS_ENUMERATE
  195. // Must be allocated before `Temporal::Temporal` below.
  196. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName) \
  197. initialize_constructor(vm.names.ClassName, m_temporal_##snake_name##_constructor, m_temporal_##snake_name##_prototype);
  198. JS_ENUMERATE_TEMPORAL_OBJECTS
  199. #undef __JS_ENUMERATE
  200. u8 attr = Attribute::Writable | Attribute::Configurable;
  201. define_native_function(vm.names.gc, gc, 0, attr);
  202. define_native_function(vm.names.isNaN, is_nan, 1, attr);
  203. define_native_function(vm.names.isFinite, is_finite, 1, attr);
  204. define_native_function(vm.names.parseFloat, parse_float, 1, attr);
  205. define_native_function(vm.names.parseInt, parse_int, 2, attr);
  206. define_native_function(vm.names.eval, eval, 1, attr);
  207. // 10.2.4.1 %ThrowTypeError% ( ), https://tc39.es/ecma262/#sec-%throwtypeerror%
  208. m_throw_type_error_function = NativeFunction::create(global_object(), {}, [](VM& vm, GlobalObject& global_object) {
  209. return vm.throw_completion<TypeError>(global_object, ErrorType::RestrictedFunctionPropertiesAccess);
  210. });
  211. m_throw_type_error_function->define_direct_property(vm.names.length, Value(0), 0);
  212. m_throw_type_error_function->define_direct_property(vm.names.name, js_string(vm, ""), 0);
  213. MUST(m_throw_type_error_function->internal_prevent_extensions());
  214. // 10.2.4 AddRestrictedFunctionProperties ( F, realm ), https://tc39.es/ecma262/#sec-addrestrictedfunctionproperties
  215. m_function_prototype->define_direct_accessor(vm.names.caller, m_throw_type_error_function, m_throw_type_error_function, Attribute::Configurable);
  216. m_function_prototype->define_direct_accessor(vm.names.arguments, m_throw_type_error_function, m_throw_type_error_function, Attribute::Configurable);
  217. define_native_function(vm.names.encodeURI, encode_uri, 1, attr);
  218. define_native_function(vm.names.decodeURI, decode_uri, 1, attr);
  219. define_native_function(vm.names.encodeURIComponent, encode_uri_component, 1, attr);
  220. define_native_function(vm.names.decodeURIComponent, decode_uri_component, 1, attr);
  221. define_native_function(vm.names.escape, escape, 1, attr);
  222. define_native_function(vm.names.unescape, unescape, 1, attr);
  223. define_direct_property(vm.names.NaN, js_nan(), 0);
  224. define_direct_property(vm.names.Infinity, js_infinity(), 0);
  225. define_direct_property(vm.names.undefined, js_undefined(), 0);
  226. define_direct_property(vm.names.globalThis, this, attr);
  227. define_direct_property(vm.names.console, heap().allocate<ConsoleObject>(*this, realm), attr);
  228. define_direct_property(vm.names.Atomics, heap().allocate<AtomicsObject>(*this, realm), attr);
  229. define_direct_property(vm.names.Math, heap().allocate<MathObject>(*this, realm), attr);
  230. define_direct_property(vm.names.JSON, heap().allocate<JSONObject>(*this, realm), attr);
  231. define_direct_property(vm.names.Reflect, heap().allocate<ReflectObject>(*this, realm), attr);
  232. define_direct_property(vm.names.Intl, heap().allocate<Intl::Intl>(*this, realm), attr);
  233. define_direct_property(vm.names.Temporal, heap().allocate<Temporal::Temporal>(*this, realm), attr);
  234. // This must be initialized before allocating AggregateErrorConstructor, which uses ErrorConstructor as its prototype.
  235. initialize_constructor(vm.names.Error, m_error_constructor, m_error_prototype);
  236. add_constructor(vm.names.AggregateError, m_aggregate_error_constructor, m_aggregate_error_prototype);
  237. add_constructor(vm.names.Array, m_array_constructor, m_array_prototype);
  238. add_constructor(vm.names.ArrayBuffer, m_array_buffer_constructor, m_array_buffer_prototype);
  239. add_constructor(vm.names.BigInt, m_bigint_constructor, m_bigint_prototype);
  240. add_constructor(vm.names.Boolean, m_boolean_constructor, m_boolean_prototype);
  241. add_constructor(vm.names.DataView, m_data_view_constructor, m_data_view_prototype);
  242. add_constructor(vm.names.Date, m_date_constructor, m_date_prototype);
  243. add_constructor(vm.names.Error, m_error_constructor, m_error_prototype);
  244. add_constructor(vm.names.FinalizationRegistry, m_finalization_registry_constructor, m_finalization_registry_prototype);
  245. add_constructor(vm.names.Function, m_function_constructor, m_function_prototype);
  246. add_constructor(vm.names.Map, m_map_constructor, m_map_prototype);
  247. add_constructor(vm.names.Number, m_number_constructor, m_number_prototype);
  248. add_constructor(vm.names.Object, m_object_constructor, m_object_prototype);
  249. add_constructor(vm.names.Promise, m_promise_constructor, m_promise_prototype);
  250. add_constructor(vm.names.Proxy, m_proxy_constructor, nullptr);
  251. add_constructor(vm.names.RegExp, m_regexp_constructor, m_regexp_prototype);
  252. add_constructor(vm.names.Set, m_set_constructor, m_set_prototype);
  253. add_constructor(vm.names.ShadowRealm, m_shadow_realm_constructor, m_shadow_realm_prototype);
  254. add_constructor(vm.names.String, m_string_constructor, m_string_prototype);
  255. add_constructor(vm.names.Symbol, m_symbol_constructor, m_symbol_prototype);
  256. add_constructor(vm.names.WeakMap, m_weak_map_constructor, m_weak_map_prototype);
  257. add_constructor(vm.names.WeakRef, m_weak_ref_constructor, m_weak_ref_prototype);
  258. add_constructor(vm.names.WeakSet, m_weak_set_constructor, m_weak_set_prototype);
  259. initialize_constructor(vm.names.TypedArray, m_typed_array_constructor, m_typed_array_prototype);
  260. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
  261. add_constructor(vm.names.ClassName, m_##snake_name##_constructor, m_##snake_name##_prototype);
  262. JS_ENUMERATE_NATIVE_ERRORS
  263. JS_ENUMERATE_TYPED_ARRAYS
  264. #undef __JS_ENUMERATE
  265. // NOTE: These constructors cannot be initialized with add_constructor as they have no global binding.
  266. initialize_constructor(vm.names.GeneratorFunction, m_generator_function_constructor, m_generator_function_prototype, Attribute::Configurable);
  267. initialize_constructor(vm.names.AsyncGeneratorFunction, m_async_generator_function_constructor, m_async_generator_function_prototype, Attribute::Configurable);
  268. initialize_constructor(vm.names.AsyncFunction, m_async_function_constructor, m_async_function_prototype, Attribute::Configurable);
  269. // 27.5.1.1 Generator.prototype.constructor, https://tc39.es/ecma262/#sec-generator.prototype.constructor
  270. m_generator_prototype->define_direct_property(vm.names.constructor, m_generator_function_prototype, Attribute::Configurable);
  271. // 27.6.1.1 AsyncGenerator.prototype.constructor, https://tc39.es/ecma262/#sec-asyncgenerator-prototype-constructor
  272. m_async_generator_prototype->define_direct_property(vm.names.constructor, m_async_generator_function_prototype, Attribute::Configurable);
  273. m_array_prototype_values_function = &m_array_prototype->get_without_side_effects(vm.names.values).as_function();
  274. m_date_constructor_now_function = &m_date_constructor->get_without_side_effects(vm.names.now).as_function();
  275. m_eval_function = &get_without_side_effects(vm.names.eval).as_function();
  276. m_json_parse_function = &get_without_side_effects(vm.names.JSON).as_object().get_without_side_effects(vm.names.parse).as_function();
  277. m_object_prototype_to_string_function = &m_object_prototype->get_without_side_effects(vm.names.toString).as_function();
  278. }
  279. GlobalObject::~GlobalObject() = default;
  280. void GlobalObject::visit_edges(Visitor& visitor)
  281. {
  282. Base::visit_edges(visitor);
  283. visitor.visit(m_empty_object_shape);
  284. visitor.visit(m_new_object_shape);
  285. visitor.visit(m_new_ordinary_function_prototype_object_shape);
  286. visitor.visit(m_proxy_constructor);
  287. visitor.visit(m_async_from_sync_iterator_prototype);
  288. visitor.visit(m_async_generator_prototype);
  289. visitor.visit(m_generator_prototype);
  290. visitor.visit(m_intl_segments_prototype);
  291. visitor.visit(m_array_prototype_values_function);
  292. visitor.visit(m_date_constructor_now_function);
  293. visitor.visit(m_eval_function);
  294. visitor.visit(m_json_parse_function);
  295. visitor.visit(m_object_prototype_to_string_function);
  296. visitor.visit(m_throw_type_error_function);
  297. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
  298. visitor.visit(m_##snake_name##_constructor); \
  299. visitor.visit(m_##snake_name##_prototype);
  300. JS_ENUMERATE_BUILTIN_TYPES
  301. #undef __JS_ENUMERATE
  302. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName) \
  303. visitor.visit(m_intl_##snake_name##_constructor); \
  304. visitor.visit(m_intl_##snake_name##_prototype);
  305. JS_ENUMERATE_INTL_OBJECTS
  306. #undef __JS_ENUMERATE
  307. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName) \
  308. visitor.visit(m_temporal_##snake_name##_constructor); \
  309. visitor.visit(m_temporal_##snake_name##_prototype);
  310. JS_ENUMERATE_TEMPORAL_OBJECTS
  311. #undef __JS_ENUMERATE
  312. #define __JS_ENUMERATE(ClassName, snake_name) \
  313. visitor.visit(m_##snake_name##_prototype);
  314. JS_ENUMERATE_ITERATOR_PROTOTYPES
  315. #undef __JS_ENUMERATE
  316. }
  317. Realm* GlobalObject::associated_realm()
  318. {
  319. return m_associated_realm;
  320. }
  321. void GlobalObject::set_associated_realm(Realm& realm)
  322. {
  323. VERIFY(&realm == &shape().realm());
  324. m_associated_realm = &realm;
  325. }
  326. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::gc)
  327. {
  328. #ifdef __serenity__
  329. dbgln("Forced garbage collection requested!");
  330. #endif
  331. vm.heap().collect_garbage();
  332. return js_undefined();
  333. }
  334. // 19.2.3 isNaN ( number ), https://tc39.es/ecma262/#sec-isnan-number
  335. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::is_nan)
  336. {
  337. return Value(TRY(vm.argument(0).to_number(global_object)).is_nan());
  338. }
  339. // 19.2.2 isFinite ( number ), https://tc39.es/ecma262/#sec-isfinite-number
  340. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::is_finite)
  341. {
  342. return Value(TRY(vm.argument(0).to_number(global_object)).is_finite_number());
  343. }
  344. // 19.2.4 parseFloat ( string ), https://tc39.es/ecma262/#sec-parsefloat-string
  345. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::parse_float)
  346. {
  347. if (vm.argument(0).is_number())
  348. return vm.argument(0);
  349. auto input_string = TRY(vm.argument(0).to_string(global_object));
  350. auto trimmed_string = MUST(trim_string(global_object, js_string(vm, input_string), TrimMode::Left));
  351. for (size_t length = trimmed_string.length(); length > 0; --length) {
  352. auto number = MUST(Value(js_string(vm, trimmed_string.substring(0, length))).to_number(global_object));
  353. if (!number.is_nan())
  354. return number;
  355. }
  356. return js_nan();
  357. }
  358. // 19.2.5 parseInt ( string, radix ), https://tc39.es/ecma262/#sec-parseint-string-radix
  359. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::parse_int)
  360. {
  361. // 1. Let inputString be ? ToString(string).
  362. auto input_string = TRY(vm.argument(0).to_string(global_object));
  363. // 2. Let S be ! TrimString(inputString, start).
  364. auto string = MUST(trim_string(global_object, js_string(vm, input_string), TrimMode::Left));
  365. // 3. Let sign be 1.
  366. auto sign = 1;
  367. // 4. If S is not empty and the first code unit of S is the code unit 0x002D (HYPHEN-MINUS), set sign to -1.
  368. if (!string.is_empty() && string[0] == 0x2D)
  369. sign = -1;
  370. // 5. If S is not empty and the first code unit of S is the code unit 0x002B (PLUS SIGN) or the code unit 0x002D (HYPHEN-MINUS), remove the first code unit from S.
  371. auto trimmed_view = string.view();
  372. if (!string.is_empty() && (string[0] == 0x2B || string[0] == 0x2D))
  373. trimmed_view = trimmed_view.substring_view(1);
  374. // 6. Let R be ℝ(? ToInt32(radix)).
  375. auto radix = TRY(vm.argument(1).to_i32(global_object));
  376. // 7. Let stripPrefix be true.
  377. auto strip_prefix = true;
  378. // 8. If R ≠ 0, then
  379. if (radix != 0) {
  380. // a. If R < 2 or R > 36, return NaN.
  381. if (radix < 2 || radix > 36)
  382. return js_nan();
  383. // b. If R ≠ 16, set stripPrefix to false.
  384. if (radix != 16)
  385. strip_prefix = false;
  386. }
  387. // 9. Else,
  388. else {
  389. // a. Set R to 10.
  390. radix = 10;
  391. }
  392. // 10. If stripPrefix is true, then
  393. if (strip_prefix) {
  394. // a. If the length of S is at least 2 and the first two code units of S are either "0x" or "0X", then
  395. if (trimmed_view.length() >= 2 && trimmed_view.substring_view(0, 2).equals_ignoring_case("0x"sv)) {
  396. // i. Remove the first two code units from S.
  397. trimmed_view = trimmed_view.substring_view(2);
  398. // ii. Set R to 16.
  399. radix = 16;
  400. }
  401. }
  402. // 11. If S contains a code unit that is not a radix-R digit, let end be the index within S of the first such code unit; otherwise, let end be the length of S.
  403. // 12. Let Z be the substring of S from 0 to end.
  404. // 13. If Z is empty, return NaN.
  405. // 14. Let mathInt be the integer value that is represented by Z in radix-R notation, using the letters A-Z and a-z for digits with values 10 through 35. (However, if R is 10 and Z contains more than 20 significant digits, every significant digit after the 20th may be replaced by a 0 digit, at the option of the implementation; and if R is not 2, 4, 8, 10, 16, or 32, then mathInt may be an implementation-approximated integer representing the integer value denoted by Z in radix-R notation.)
  406. auto parse_digit = [&](u32 code_point) -> Optional<u32> {
  407. if (!is_ascii_alphanumeric(code_point))
  408. return {};
  409. auto digit = parse_ascii_base36_digit(code_point);
  410. if (digit >= (u32)radix)
  411. return {};
  412. return digit;
  413. };
  414. bool had_digits = false;
  415. double number = 0;
  416. for (auto code_point : Utf8View(trimmed_view)) {
  417. auto digit = parse_digit(code_point);
  418. if (!digit.has_value())
  419. break;
  420. had_digits = true;
  421. number *= radix;
  422. number += digit.value();
  423. }
  424. if (!had_digits)
  425. return js_nan();
  426. // 15. If mathInt = 0, then
  427. // a. If sign = -1, return -0𝔽.
  428. // b. Return +0𝔽.
  429. // 16. Return 𝔽(sign × mathInt).
  430. return Value(sign * number);
  431. }
  432. // 19.2.1 eval ( x ), https://tc39.es/ecma262/#sec-eval-x
  433. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::eval)
  434. {
  435. return perform_eval(global_object, vm.argument(0), CallerMode::NonStrict, EvalMode::Indirect);
  436. }
  437. // 19.2.6.1.1 Encode ( string, unescapedSet ), https://tc39.es/ecma262/#sec-encode
  438. static ThrowCompletionOr<String> encode(GlobalObject& global_object, String const& string, StringView unescaped_set)
  439. {
  440. auto& vm = global_object.vm();
  441. auto utf16_string = Utf16String(string);
  442. // 1. Let strLen be the length of string.
  443. auto string_length = utf16_string.length_in_code_units();
  444. // 2. Let R be the empty String.
  445. StringBuilder encoded_builder;
  446. // 3. Let k be 0.
  447. auto k = 0u;
  448. // 4. Repeat,
  449. while (k < string_length) {
  450. // a. If k = strLen, return R.
  451. // Handled below
  452. // b. Let C be the code unit at index k within string.
  453. auto code_unit = utf16_string.code_unit_at(k);
  454. // c. If C is in unescapedSet, then
  455. // NOTE: We assume the unescaped set only contains ascii characters as unescaped_set is a StringView.
  456. if (code_unit < 0x80 && unescaped_set.contains(code_unit)) {
  457. // i. Set k to k + 1.
  458. k++;
  459. // ii. Set R to the string-concatenation of R and C.
  460. encoded_builder.append(code_unit);
  461. }
  462. // d. Else,
  463. else {
  464. // i. Let cp be CodePointAt(string, k).
  465. auto code_point = code_point_at(utf16_string.view(), k);
  466. // ii. If cp.[[IsUnpairedSurrogate]] is true, throw a URIError exception.
  467. if (code_point.is_unpaired_surrogate)
  468. return vm.throw_completion<URIError>(global_object, ErrorType::URIMalformed);
  469. // iii. Set k to k + cp.[[CodeUnitCount]].
  470. k += code_point.code_unit_count;
  471. // iv. Let Octets be the List of octets resulting by applying the UTF-8 transformation to cp.[[CodePoint]].
  472. // v. For each element octet of Octets, do
  473. auto nwritten = AK::UnicodeUtils::code_point_to_utf8(code_point.code_point, [&encoded_builder](u8 octet) {
  474. // 1. Set R to the string-concatenation of:
  475. // * R
  476. // * "%"
  477. // * the String representation of octet, formatted as a two-digit uppercase hexadecimal number, padded to the left with a zero if necessary
  478. encoded_builder.appendff("%{:02X}", octet);
  479. });
  480. VERIFY(nwritten > 0);
  481. }
  482. }
  483. return encoded_builder.build();
  484. }
  485. // 19.2.6.1.2 Decode ( string, reservedSet ), https://tc39.es/ecma262/#sec-decode
  486. static ThrowCompletionOr<String> decode(GlobalObject& global_object, String const& string, StringView reserved_set)
  487. {
  488. StringBuilder decoded_builder;
  489. auto code_point_start_offset = 0u;
  490. auto expected_continuation_bytes = 0;
  491. for (size_t k = 0; k < string.length(); k++) {
  492. auto code_unit = string[k];
  493. if (code_unit != '%') {
  494. if (expected_continuation_bytes > 0)
  495. return global_object.vm().throw_completion<URIError>(global_object, ErrorType::URIMalformed);
  496. decoded_builder.append(code_unit);
  497. continue;
  498. }
  499. if (k + 2 >= string.length())
  500. return global_object.vm().throw_completion<URIError>(global_object, ErrorType::URIMalformed);
  501. auto first_digit = decode_hex_digit(string[k + 1]);
  502. if (first_digit >= 16)
  503. return global_object.vm().throw_completion<URIError>(global_object, ErrorType::URIMalformed);
  504. auto second_digit = decode_hex_digit(string[k + 2]);
  505. if (second_digit >= 16)
  506. return global_object.vm().throw_completion<URIError>(global_object, ErrorType::URIMalformed);
  507. u8 decoded_code_unit = (first_digit << 4) | second_digit;
  508. k += 2;
  509. if (expected_continuation_bytes > 0) {
  510. decoded_builder.append(decoded_code_unit);
  511. expected_continuation_bytes--;
  512. if (expected_continuation_bytes == 0 && !Utf8View(decoded_builder.string_view().substring_view(code_point_start_offset)).validate())
  513. return global_object.vm().throw_completion<URIError>(global_object, ErrorType::URIMalformed);
  514. continue;
  515. }
  516. if ((decoded_code_unit & 0x80) == 0) {
  517. if (reserved_set.contains(decoded_code_unit))
  518. decoded_builder.append(string.substring_view(k - 2, 3));
  519. else
  520. decoded_builder.append(decoded_code_unit);
  521. continue;
  522. }
  523. auto leading_ones = count_leading_zeroes_safe(static_cast<u8>(~decoded_code_unit));
  524. if (leading_ones == 1 || leading_ones > 4)
  525. return global_object.vm().throw_completion<URIError>(global_object, ErrorType::URIMalformed);
  526. code_point_start_offset = decoded_builder.length();
  527. decoded_builder.append(decoded_code_unit);
  528. expected_continuation_bytes = leading_ones - 1;
  529. }
  530. if (expected_continuation_bytes > 0)
  531. return global_object.vm().throw_completion<URIError>(global_object, ErrorType::URIMalformed);
  532. return decoded_builder.build();
  533. }
  534. // 19.2.6.4 encodeURI ( uri ), https://tc39.es/ecma262/#sec-encodeuri-uri
  535. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::encode_uri)
  536. {
  537. auto uri_string = TRY(vm.argument(0).to_string(global_object));
  538. auto encoded = TRY(encode(global_object, uri_string, ";/?:@&=+$,abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'()#"sv));
  539. return js_string(vm, move(encoded));
  540. }
  541. // 19.2.6.2 decodeURI ( encodedURI ), https://tc39.es/ecma262/#sec-decodeuri-encodeduri
  542. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::decode_uri)
  543. {
  544. auto uri_string = TRY(vm.argument(0).to_string(global_object));
  545. auto decoded = TRY(decode(global_object, uri_string, ";/?:@&=+$,#"sv));
  546. return js_string(vm, move(decoded));
  547. }
  548. // 19.2.6.5 encodeURIComponent ( uriComponent ), https://tc39.es/ecma262/#sec-encodeuricomponent-uricomponent
  549. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::encode_uri_component)
  550. {
  551. auto uri_string = TRY(vm.argument(0).to_string(global_object));
  552. auto encoded = TRY(encode(global_object, uri_string, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'()"sv));
  553. return js_string(vm, move(encoded));
  554. }
  555. // 19.2.6.3 decodeURIComponent ( encodedURIComponent ), https://tc39.es/ecma262/#sec-decodeuricomponent-encodeduricomponent
  556. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::decode_uri_component)
  557. {
  558. auto uri_string = TRY(vm.argument(0).to_string(global_object));
  559. auto decoded = TRY(decode(global_object, uri_string, ""sv));
  560. return js_string(vm, move(decoded));
  561. }
  562. // B.2.1.1 escape ( string ), https://tc39.es/ecma262/#sec-escape-string
  563. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::escape)
  564. {
  565. auto string = TRY(vm.argument(0).to_string(global_object));
  566. StringBuilder escaped;
  567. for (auto code_point : utf8_to_utf16(string)) {
  568. if (code_point < 256) {
  569. if ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*_+-./"sv.contains(code_point))
  570. escaped.append(code_point);
  571. else
  572. escaped.appendff("%{:02X}", code_point);
  573. continue;
  574. }
  575. escaped.appendff("%u{:04X}", code_point);
  576. }
  577. return js_string(vm, escaped.build());
  578. }
  579. // B.2.1.2 unescape ( string ), https://tc39.es/ecma262/#sec-unescape-string
  580. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::unescape)
  581. {
  582. auto string = TRY(vm.argument(0).to_string(global_object));
  583. ssize_t length = string.length();
  584. StringBuilder unescaped(length);
  585. for (auto k = 0; k < length; ++k) {
  586. u32 code_point = string[k];
  587. if (code_point == '%') {
  588. if (k <= length - 6 && string[k + 1] == 'u' && is_ascii_hex_digit(string[k + 2]) && is_ascii_hex_digit(string[k + 3]) && is_ascii_hex_digit(string[k + 4]) && is_ascii_hex_digit(string[k + 5])) {
  589. code_point = (parse_ascii_hex_digit(string[k + 2]) << 12) | (parse_ascii_hex_digit(string[k + 3]) << 8) | (parse_ascii_hex_digit(string[k + 4]) << 4) | parse_ascii_hex_digit(string[k + 5]);
  590. k += 5;
  591. } else if (k <= length - 3 && is_ascii_hex_digit(string[k + 1]) && is_ascii_hex_digit(string[k + 2])) {
  592. code_point = (parse_ascii_hex_digit(string[k + 1]) << 4) | parse_ascii_hex_digit(string[k + 2]);
  593. k += 2;
  594. }
  595. }
  596. unescaped.append_code_point(code_point);
  597. }
  598. return js_string(vm, unescaped.build());
  599. }
  600. }