GlobalObject.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/CharacterTypes.h>
  8. #include <AK/Hex.h>
  9. #include <AK/Platform.h>
  10. #include <AK/Utf8View.h>
  11. #include <LibJS/Console.h>
  12. #include <LibJS/Heap/DeferGC.h>
  13. #include <LibJS/Interpreter.h>
  14. #include <LibJS/Runtime/AbstractOperations.h>
  15. #include <LibJS/Runtime/AggregateErrorConstructor.h>
  16. #include <LibJS/Runtime/AggregateErrorPrototype.h>
  17. #include <LibJS/Runtime/ArrayBufferConstructor.h>
  18. #include <LibJS/Runtime/ArrayBufferPrototype.h>
  19. #include <LibJS/Runtime/ArrayConstructor.h>
  20. #include <LibJS/Runtime/ArrayIteratorPrototype.h>
  21. #include <LibJS/Runtime/ArrayPrototype.h>
  22. #include <LibJS/Runtime/AsyncFromSyncIteratorPrototype.h>
  23. #include <LibJS/Runtime/AsyncFunctionConstructor.h>
  24. #include <LibJS/Runtime/AsyncFunctionPrototype.h>
  25. #include <LibJS/Runtime/AsyncGeneratorFunctionConstructor.h>
  26. #include <LibJS/Runtime/AsyncGeneratorFunctionPrototype.h>
  27. #include <LibJS/Runtime/AsyncIteratorPrototype.h>
  28. #include <LibJS/Runtime/AtomicsObject.h>
  29. #include <LibJS/Runtime/BigIntConstructor.h>
  30. #include <LibJS/Runtime/BigIntPrototype.h>
  31. #include <LibJS/Runtime/BooleanConstructor.h>
  32. #include <LibJS/Runtime/BooleanPrototype.h>
  33. #include <LibJS/Runtime/ConsoleObject.h>
  34. #include <LibJS/Runtime/DataViewConstructor.h>
  35. #include <LibJS/Runtime/DataViewPrototype.h>
  36. #include <LibJS/Runtime/DateConstructor.h>
  37. #include <LibJS/Runtime/DatePrototype.h>
  38. #include <LibJS/Runtime/ErrorConstructor.h>
  39. #include <LibJS/Runtime/ErrorPrototype.h>
  40. #include <LibJS/Runtime/FinalizationRegistryConstructor.h>
  41. #include <LibJS/Runtime/FinalizationRegistryPrototype.h>
  42. #include <LibJS/Runtime/FunctionConstructor.h>
  43. #include <LibJS/Runtime/FunctionPrototype.h>
  44. #include <LibJS/Runtime/GeneratorFunctionConstructor.h>
  45. #include <LibJS/Runtime/GeneratorFunctionPrototype.h>
  46. #include <LibJS/Runtime/GeneratorObjectPrototype.h>
  47. #include <LibJS/Runtime/GlobalEnvironment.h>
  48. #include <LibJS/Runtime/GlobalObject.h>
  49. #include <LibJS/Runtime/Intl/DateTimeFormatConstructor.h>
  50. #include <LibJS/Runtime/Intl/DateTimeFormatPrototype.h>
  51. #include <LibJS/Runtime/Intl/DisplayNamesConstructor.h>
  52. #include <LibJS/Runtime/Intl/DisplayNamesPrototype.h>
  53. #include <LibJS/Runtime/Intl/Intl.h>
  54. #include <LibJS/Runtime/Intl/ListFormatConstructor.h>
  55. #include <LibJS/Runtime/Intl/ListFormatPrototype.h>
  56. #include <LibJS/Runtime/Intl/LocaleConstructor.h>
  57. #include <LibJS/Runtime/Intl/LocalePrototype.h>
  58. #include <LibJS/Runtime/Intl/NumberFormatConstructor.h>
  59. #include <LibJS/Runtime/Intl/NumberFormatPrototype.h>
  60. #include <LibJS/Runtime/IteratorPrototype.h>
  61. #include <LibJS/Runtime/JSONObject.h>
  62. #include <LibJS/Runtime/MapConstructor.h>
  63. #include <LibJS/Runtime/MapIteratorPrototype.h>
  64. #include <LibJS/Runtime/MapPrototype.h>
  65. #include <LibJS/Runtime/MathObject.h>
  66. #include <LibJS/Runtime/NativeFunction.h>
  67. #include <LibJS/Runtime/NumberConstructor.h>
  68. #include <LibJS/Runtime/NumberPrototype.h>
  69. #include <LibJS/Runtime/Object.h>
  70. #include <LibJS/Runtime/ObjectConstructor.h>
  71. #include <LibJS/Runtime/ObjectPrototype.h>
  72. #include <LibJS/Runtime/PromiseConstructor.h>
  73. #include <LibJS/Runtime/PromisePrototype.h>
  74. #include <LibJS/Runtime/ProxyConstructor.h>
  75. #include <LibJS/Runtime/Realm.h>
  76. #include <LibJS/Runtime/ReflectObject.h>
  77. #include <LibJS/Runtime/RegExpConstructor.h>
  78. #include <LibJS/Runtime/RegExpPrototype.h>
  79. #include <LibJS/Runtime/RegExpStringIteratorPrototype.h>
  80. #include <LibJS/Runtime/SetConstructor.h>
  81. #include <LibJS/Runtime/SetIteratorPrototype.h>
  82. #include <LibJS/Runtime/SetPrototype.h>
  83. #include <LibJS/Runtime/ShadowRealmConstructor.h>
  84. #include <LibJS/Runtime/ShadowRealmPrototype.h>
  85. #include <LibJS/Runtime/Shape.h>
  86. #include <LibJS/Runtime/StringConstructor.h>
  87. #include <LibJS/Runtime/StringIteratorPrototype.h>
  88. #include <LibJS/Runtime/StringPrototype.h>
  89. #include <LibJS/Runtime/SymbolConstructor.h>
  90. #include <LibJS/Runtime/SymbolPrototype.h>
  91. #include <LibJS/Runtime/Temporal/CalendarConstructor.h>
  92. #include <LibJS/Runtime/Temporal/CalendarPrototype.h>
  93. #include <LibJS/Runtime/Temporal/DurationConstructor.h>
  94. #include <LibJS/Runtime/Temporal/DurationPrototype.h>
  95. #include <LibJS/Runtime/Temporal/InstantConstructor.h>
  96. #include <LibJS/Runtime/Temporal/InstantPrototype.h>
  97. #include <LibJS/Runtime/Temporal/PlainDateConstructor.h>
  98. #include <LibJS/Runtime/Temporal/PlainDatePrototype.h>
  99. #include <LibJS/Runtime/Temporal/PlainDateTimeConstructor.h>
  100. #include <LibJS/Runtime/Temporal/PlainDateTimePrototype.h>
  101. #include <LibJS/Runtime/Temporal/PlainMonthDayConstructor.h>
  102. #include <LibJS/Runtime/Temporal/PlainMonthDayPrototype.h>
  103. #include <LibJS/Runtime/Temporal/PlainTimeConstructor.h>
  104. #include <LibJS/Runtime/Temporal/PlainTimePrototype.h>
  105. #include <LibJS/Runtime/Temporal/PlainYearMonthConstructor.h>
  106. #include <LibJS/Runtime/Temporal/PlainYearMonthPrototype.h>
  107. #include <LibJS/Runtime/Temporal/Temporal.h>
  108. #include <LibJS/Runtime/Temporal/TimeZoneConstructor.h>
  109. #include <LibJS/Runtime/Temporal/TimeZonePrototype.h>
  110. #include <LibJS/Runtime/Temporal/ZonedDateTimeConstructor.h>
  111. #include <LibJS/Runtime/Temporal/ZonedDateTimePrototype.h>
  112. #include <LibJS/Runtime/TypedArray.h>
  113. #include <LibJS/Runtime/TypedArrayConstructor.h>
  114. #include <LibJS/Runtime/TypedArrayPrototype.h>
  115. #include <LibJS/Runtime/Value.h>
  116. #include <LibJS/Runtime/WeakMapConstructor.h>
  117. #include <LibJS/Runtime/WeakMapPrototype.h>
  118. #include <LibJS/Runtime/WeakRefConstructor.h>
  119. #include <LibJS/Runtime/WeakRefPrototype.h>
  120. #include <LibJS/Runtime/WeakSetConstructor.h>
  121. #include <LibJS/Runtime/WeakSetPrototype.h>
  122. namespace JS {
  123. GlobalObject::GlobalObject()
  124. : Object(GlobalObjectTag::Tag)
  125. , m_console(make<Console>(*this))
  126. {
  127. }
  128. void GlobalObject::initialize_global_object()
  129. {
  130. auto& vm = this->vm();
  131. ensure_shape_is_unique();
  132. // These are done first since other prototypes depend on their presence.
  133. m_empty_object_shape = heap().allocate_without_global_object<Shape>(*this);
  134. m_object_prototype = heap().allocate_without_global_object<ObjectPrototype>(*this);
  135. m_function_prototype = heap().allocate_without_global_object<FunctionPrototype>(*this);
  136. m_new_object_shape = vm.heap().allocate_without_global_object<Shape>(*this);
  137. m_new_object_shape->set_prototype_without_transition(m_object_prototype);
  138. m_new_ordinary_function_prototype_object_shape = vm.heap().allocate_without_global_object<Shape>(*this);
  139. m_new_ordinary_function_prototype_object_shape->set_prototype_without_transition(m_object_prototype);
  140. m_new_ordinary_function_prototype_object_shape->add_property_without_transition(vm.names.constructor, Attribute::Writable | Attribute::Configurable);
  141. // Normally Heap::allocate() takes care of this, but these are allocated via allocate_without_global_object().
  142. static_cast<FunctionPrototype*>(m_function_prototype)->initialize(*this);
  143. static_cast<ObjectPrototype*>(m_object_prototype)->initialize(*this);
  144. Object::set_prototype(m_object_prototype);
  145. // This must be initialized before allocating AggregateErrorPrototype, which uses ErrorPrototype as its prototype.
  146. m_error_prototype = heap().allocate<ErrorPrototype>(*this, *this);
  147. #define __JS_ENUMERATE(ClassName, snake_name) \
  148. if (!m_##snake_name##_prototype) \
  149. m_##snake_name##_prototype = heap().allocate<ClassName##Prototype>(*this, *this);
  150. JS_ENUMERATE_ITERATOR_PROTOTYPES
  151. #undef __JS_ENUMERATE
  152. // %GeneratorFunction.prototype.prototype% must be initialized separately as it has no
  153. // companion constructor
  154. m_generator_object_prototype = heap().allocate<GeneratorObjectPrototype>(*this, *this);
  155. m_generator_object_prototype->define_direct_property(vm.names.constructor, m_generator_function_constructor, Attribute::Configurable);
  156. m_async_from_sync_iterator_prototype = heap().allocate<AsyncFromSyncIteratorPrototype>(*this, *this);
  157. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
  158. if (!m_##snake_name##_prototype) \
  159. m_##snake_name##_prototype = heap().allocate<PrototypeName>(*this, *this);
  160. JS_ENUMERATE_BUILTIN_TYPES
  161. #undef __JS_ENUMERATE
  162. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName) \
  163. if (!m_intl_##snake_name##_prototype) \
  164. m_intl_##snake_name##_prototype = heap().allocate<Intl::PrototypeName>(*this, *this);
  165. JS_ENUMERATE_INTL_OBJECTS
  166. #undef __JS_ENUMERATE
  167. // Must be allocated before `Intl::Intl` below.
  168. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName) \
  169. initialize_constructor(vm.names.ClassName, m_intl_##snake_name##_constructor, m_intl_##snake_name##_prototype);
  170. JS_ENUMERATE_INTL_OBJECTS
  171. #undef __JS_ENUMERATE
  172. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName) \
  173. if (!m_temporal_##snake_name##_prototype) \
  174. m_temporal_##snake_name##_prototype = heap().allocate<Temporal::PrototypeName>(*this, *this);
  175. JS_ENUMERATE_TEMPORAL_OBJECTS
  176. #undef __JS_ENUMERATE
  177. // Must be allocated before `Temporal::Temporal` below.
  178. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName) \
  179. initialize_constructor(vm.names.ClassName, m_temporal_##snake_name##_constructor, m_temporal_##snake_name##_prototype);
  180. JS_ENUMERATE_TEMPORAL_OBJECTS
  181. #undef __JS_ENUMERATE
  182. u8 attr = Attribute::Writable | Attribute::Configurable;
  183. define_native_function(vm.names.gc, gc, 0, attr);
  184. define_native_function(vm.names.isNaN, is_nan, 1, attr);
  185. define_native_function(vm.names.isFinite, is_finite, 1, attr);
  186. define_native_function(vm.names.parseFloat, parse_float, 1, attr);
  187. define_native_function(vm.names.parseInt, parse_int, 2, attr);
  188. define_native_function(vm.names.eval, eval, 1, attr);
  189. // 10.2.4.1 %ThrowTypeError% ( ), https://tc39.es/ecma262/#sec-%throwtypeerror%
  190. m_throw_type_error_function = NativeFunction::create(global_object(), {}, [](VM& vm, GlobalObject& global_object) {
  191. return vm.throw_completion<TypeError>(global_object, ErrorType::RestrictedFunctionPropertiesAccess);
  192. });
  193. m_throw_type_error_function->define_direct_property(vm.names.length, Value(0), 0);
  194. m_throw_type_error_function->define_direct_property(vm.names.name, js_string(vm, ""), 0);
  195. MUST(m_throw_type_error_function->internal_prevent_extensions());
  196. // 10.2.4 AddRestrictedFunctionProperties ( F, realm ), https://tc39.es/ecma262/#sec-addrestrictedfunctionproperties
  197. m_function_prototype->define_direct_accessor(vm.names.caller, m_throw_type_error_function, m_throw_type_error_function, Attribute::Configurable);
  198. m_function_prototype->define_direct_accessor(vm.names.arguments, m_throw_type_error_function, m_throw_type_error_function, Attribute::Configurable);
  199. define_native_function(vm.names.encodeURI, encode_uri, 1, attr);
  200. define_native_function(vm.names.decodeURI, decode_uri, 1, attr);
  201. define_native_function(vm.names.encodeURIComponent, encode_uri_component, 1, attr);
  202. define_native_function(vm.names.decodeURIComponent, decode_uri_component, 1, attr);
  203. define_native_function(vm.names.escape, escape, 1, attr);
  204. define_native_function(vm.names.unescape, unescape, 1, attr);
  205. define_direct_property(vm.names.NaN, js_nan(), 0);
  206. define_direct_property(vm.names.Infinity, js_infinity(), 0);
  207. define_direct_property(vm.names.undefined, js_undefined(), 0);
  208. define_direct_property(vm.names.globalThis, this, attr);
  209. define_direct_property(vm.names.console, heap().allocate<ConsoleObject>(*this, *this), attr);
  210. define_direct_property(vm.names.Atomics, heap().allocate<AtomicsObject>(*this, *this), attr);
  211. define_direct_property(vm.names.Math, heap().allocate<MathObject>(*this, *this), attr);
  212. define_direct_property(vm.names.JSON, heap().allocate<JSONObject>(*this, *this), attr);
  213. define_direct_property(vm.names.Reflect, heap().allocate<ReflectObject>(*this, *this), attr);
  214. define_direct_property(vm.names.Intl, heap().allocate<Intl::Intl>(*this, *this), attr);
  215. define_direct_property(vm.names.Temporal, heap().allocate<Temporal::Temporal>(*this, *this), attr);
  216. // This must be initialized before allocating AggregateErrorConstructor, which uses ErrorConstructor as its prototype.
  217. initialize_constructor(vm.names.Error, m_error_constructor, m_error_prototype);
  218. add_constructor(vm.names.AggregateError, m_aggregate_error_constructor, m_aggregate_error_prototype);
  219. add_constructor(vm.names.Array, m_array_constructor, m_array_prototype);
  220. add_constructor(vm.names.ArrayBuffer, m_array_buffer_constructor, m_array_buffer_prototype);
  221. add_constructor(vm.names.BigInt, m_bigint_constructor, m_bigint_prototype);
  222. add_constructor(vm.names.Boolean, m_boolean_constructor, m_boolean_prototype);
  223. add_constructor(vm.names.DataView, m_data_view_constructor, m_data_view_prototype);
  224. add_constructor(vm.names.Date, m_date_constructor, m_date_prototype);
  225. add_constructor(vm.names.Error, m_error_constructor, m_error_prototype);
  226. add_constructor(vm.names.FinalizationRegistry, m_finalization_registry_constructor, m_finalization_registry_prototype);
  227. add_constructor(vm.names.Function, m_function_constructor, m_function_prototype);
  228. add_constructor(vm.names.Map, m_map_constructor, m_map_prototype);
  229. add_constructor(vm.names.Number, m_number_constructor, m_number_prototype);
  230. add_constructor(vm.names.Object, m_object_constructor, m_object_prototype);
  231. add_constructor(vm.names.Promise, m_promise_constructor, m_promise_prototype);
  232. add_constructor(vm.names.Proxy, m_proxy_constructor, nullptr);
  233. add_constructor(vm.names.RegExp, m_regexp_constructor, m_regexp_prototype);
  234. add_constructor(vm.names.Set, m_set_constructor, m_set_prototype);
  235. add_constructor(vm.names.ShadowRealm, m_shadow_realm_constructor, m_shadow_realm_prototype);
  236. add_constructor(vm.names.String, m_string_constructor, m_string_prototype);
  237. add_constructor(vm.names.Symbol, m_symbol_constructor, m_symbol_prototype);
  238. add_constructor(vm.names.WeakMap, m_weak_map_constructor, m_weak_map_prototype);
  239. add_constructor(vm.names.WeakRef, m_weak_ref_constructor, m_weak_ref_prototype);
  240. add_constructor(vm.names.WeakSet, m_weak_set_constructor, m_weak_set_prototype);
  241. initialize_constructor(vm.names.TypedArray, m_typed_array_constructor, m_typed_array_prototype);
  242. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
  243. add_constructor(vm.names.ClassName, m_##snake_name##_constructor, m_##snake_name##_prototype);
  244. JS_ENUMERATE_NATIVE_ERRORS
  245. JS_ENUMERATE_TYPED_ARRAYS
  246. #undef __JS_ENUMERATE
  247. // The generator constructor cannot be initialized with add_constructor as it has no global binding
  248. m_generator_function_constructor = heap().allocate<GeneratorFunctionConstructor>(*this, *this);
  249. // 27.3.3.1 GeneratorFunction.prototype.constructor, https://tc39.es/ecma262/#sec-generatorfunction.prototype.constructor
  250. m_generator_function_prototype->define_direct_property(vm.names.constructor, m_generator_function_constructor, Attribute::Configurable);
  251. // The async generator constructor cannot be initialized with add_constructor as it has no global binding
  252. m_async_generator_function_constructor = heap().allocate<AsyncGeneratorFunctionConstructor>(*this, *this);
  253. // 27.4.3.1 AsyncGeneratorFunction.prototype.constructor, https://tc39.es/ecma262/#sec-asyncgeneratorfunction-prototype-constructor
  254. m_async_generator_function_prototype->define_direct_property(vm.names.constructor, m_async_generator_function_constructor, Attribute::Configurable);
  255. m_array_prototype_values_function = &m_array_prototype->get_without_side_effects(vm.names.values).as_function();
  256. m_eval_function = &get_without_side_effects(vm.names.eval).as_function();
  257. }
  258. GlobalObject::~GlobalObject()
  259. {
  260. }
  261. void GlobalObject::visit_edges(Visitor& visitor)
  262. {
  263. Base::visit_edges(visitor);
  264. visitor.visit(m_empty_object_shape);
  265. visitor.visit(m_new_object_shape);
  266. visitor.visit(m_new_ordinary_function_prototype_object_shape);
  267. visitor.visit(m_proxy_constructor);
  268. visitor.visit(m_generator_object_prototype);
  269. visitor.visit(m_array_prototype_values_function);
  270. visitor.visit(m_eval_function);
  271. visitor.visit(m_throw_type_error_function);
  272. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
  273. visitor.visit(m_##snake_name##_constructor); \
  274. visitor.visit(m_##snake_name##_prototype);
  275. JS_ENUMERATE_BUILTIN_TYPES
  276. #undef __JS_ENUMERATE
  277. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName) \
  278. visitor.visit(m_intl_##snake_name##_constructor); \
  279. visitor.visit(m_intl_##snake_name##_prototype);
  280. JS_ENUMERATE_INTL_OBJECTS
  281. #undef __JS_ENUMERATE
  282. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName) \
  283. visitor.visit(m_temporal_##snake_name##_constructor); \
  284. visitor.visit(m_temporal_##snake_name##_prototype);
  285. JS_ENUMERATE_TEMPORAL_OBJECTS
  286. #undef __JS_ENUMERATE
  287. #define __JS_ENUMERATE(ClassName, snake_name) \
  288. visitor.visit(m_##snake_name##_prototype);
  289. JS_ENUMERATE_ITERATOR_PROTOTYPES
  290. #undef __JS_ENUMERATE
  291. }
  292. Realm* GlobalObject::associated_realm()
  293. {
  294. return m_associated_realm;
  295. }
  296. void GlobalObject::set_associated_realm(Badge<Realm>, Realm& realm)
  297. {
  298. m_associated_realm = &realm;
  299. }
  300. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::gc)
  301. {
  302. #ifdef __serenity__
  303. dbgln("Forced garbage collection requested!");
  304. #endif
  305. vm.heap().collect_garbage();
  306. return js_undefined();
  307. }
  308. // 19.2.3 isNaN ( number ), https://tc39.es/ecma262/#sec-isnan-number
  309. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::is_nan)
  310. {
  311. return Value(TRY(vm.argument(0).to_number(global_object)).is_nan());
  312. }
  313. // 19.2.2 isFinite ( number ), https://tc39.es/ecma262/#sec-isfinite-number
  314. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::is_finite)
  315. {
  316. return Value(TRY(vm.argument(0).to_number(global_object)).is_finite_number());
  317. }
  318. // 19.2.4 parseFloat ( string ), https://tc39.es/ecma262/#sec-parsefloat-string
  319. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::parse_float)
  320. {
  321. if (vm.argument(0).is_number())
  322. return vm.argument(0);
  323. auto input_string = TRY(vm.argument(0).to_string(global_object));
  324. auto trimmed_string = input_string.trim_whitespace(TrimMode::Left);
  325. for (size_t length = trimmed_string.length(); length > 0; --length) {
  326. auto number = MUST(Value(js_string(vm, trimmed_string.substring(0, length))).to_number(global_object));
  327. if (!number.is_nan())
  328. return number;
  329. }
  330. return js_nan();
  331. }
  332. // 19.2.5 parseInt ( string, radix ), https://tc39.es/ecma262/#sec-parseint-string-radix
  333. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::parse_int)
  334. {
  335. auto input_string = TRY(vm.argument(0).to_string(global_object));
  336. // FIXME: There's a bunch of unnecessary string copying here.
  337. double sign = 1;
  338. auto s = input_string.trim_whitespace(TrimMode::Left);
  339. if (!s.is_empty() && s[0] == '-')
  340. sign = -1;
  341. if (!s.is_empty() && (s[0] == '+' || s[0] == '-'))
  342. s = s.substring(1, s.length() - 1);
  343. auto radix = TRY(vm.argument(1).to_i32(global_object));
  344. bool strip_prefix = true;
  345. if (radix != 0) {
  346. if (radix < 2 || radix > 36)
  347. return js_nan();
  348. if (radix != 16)
  349. strip_prefix = false;
  350. } else {
  351. radix = 10;
  352. }
  353. if (strip_prefix) {
  354. if (s.length() >= 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) {
  355. s = s.substring(2, s.length() - 2);
  356. radix = 16;
  357. }
  358. }
  359. auto parse_digit = [&](u32 code_point, i32 radix) -> Optional<i32> {
  360. if (!is_ascii_alphanumeric(code_point) || radix <= 0)
  361. return {};
  362. auto digit = parse_ascii_base36_digit(code_point);
  363. if (digit >= (u32)radix)
  364. return {};
  365. return digit;
  366. };
  367. bool had_digits = false;
  368. double number = 0;
  369. for (auto code_point : Utf8View(s)) {
  370. auto digit = parse_digit(code_point, radix);
  371. if (!digit.has_value())
  372. break;
  373. had_digits = true;
  374. number *= radix;
  375. number += digit.value();
  376. }
  377. if (!had_digits)
  378. return js_nan();
  379. return Value(sign * number);
  380. }
  381. // 19.2.1 eval ( x ), https://tc39.es/ecma262/#sec-eval-x
  382. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::eval)
  383. {
  384. return perform_eval(vm.argument(0), global_object, CallerMode::NonStrict, EvalMode::Indirect);
  385. }
  386. // 19.2.6.1.1 Encode ( string, unescapedSet ), https://tc39.es/ecma262/#sec-encode
  387. static ThrowCompletionOr<String> encode([[maybe_unused]] JS::GlobalObject& global_object, const String& string, StringView unescaped_set)
  388. {
  389. StringBuilder encoded_builder;
  390. for (unsigned char code_unit : string) {
  391. if (unescaped_set.contains(code_unit)) {
  392. encoded_builder.append(code_unit);
  393. continue;
  394. }
  395. // FIXME: check for unpaired surrogates and throw URIError
  396. encoded_builder.appendff("%{:02X}", code_unit);
  397. }
  398. return encoded_builder.build();
  399. }
  400. // 19.2.6.1.2 Decode ( string, reservedSet ), https://tc39.es/ecma262/#sec-decode
  401. static ThrowCompletionOr<String> decode(JS::GlobalObject& global_object, const String& string, StringView reserved_set)
  402. {
  403. StringBuilder decoded_builder;
  404. auto expected_continuation_bytes = 0;
  405. for (size_t k = 0; k < string.length(); k++) {
  406. auto code_unit = string[k];
  407. if (code_unit != '%') {
  408. if (expected_continuation_bytes > 0)
  409. return global_object.vm().throw_completion<URIError>(global_object, ErrorType::URIMalformed);
  410. decoded_builder.append(code_unit);
  411. continue;
  412. }
  413. if (k + 2 >= string.length())
  414. return global_object.vm().throw_completion<URIError>(global_object, ErrorType::URIMalformed);
  415. auto first_digit = decode_hex_digit(string[k + 1]);
  416. if (first_digit >= 16)
  417. return global_object.vm().throw_completion<URIError>(global_object, ErrorType::URIMalformed);
  418. auto second_digit = decode_hex_digit(string[k + 2]);
  419. if (second_digit >= 16)
  420. return global_object.vm().throw_completion<URIError>(global_object, ErrorType::URIMalformed);
  421. char decoded_code_unit = (first_digit << 4) | second_digit;
  422. k += 2;
  423. if (expected_continuation_bytes > 0) {
  424. decoded_builder.append(decoded_code_unit);
  425. expected_continuation_bytes--;
  426. continue;
  427. }
  428. if ((decoded_code_unit & 0x80) == 0) {
  429. if (reserved_set.contains(decoded_code_unit))
  430. decoded_builder.append(string.substring_view(k - 2, 3));
  431. else
  432. decoded_builder.append(decoded_code_unit);
  433. continue;
  434. }
  435. auto leading_ones = count_trailing_zeroes_32_safe(~decoded_code_unit) - 24;
  436. if (leading_ones == 1 || leading_ones > 4)
  437. return global_object.vm().throw_completion<URIError>(global_object, ErrorType::URIMalformed);
  438. decoded_builder.append(decoded_code_unit);
  439. expected_continuation_bytes = leading_ones - 1;
  440. }
  441. return decoded_builder.build();
  442. }
  443. // 19.2.6.4 encodeURI ( uri ), https://tc39.es/ecma262/#sec-encodeuri-uri
  444. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::encode_uri)
  445. {
  446. auto uri_string = TRY(vm.argument(0).to_string(global_object));
  447. auto encoded = TRY(encode(global_object, uri_string, ";/?:@&=+$,abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'()#"sv));
  448. return js_string(vm, move(encoded));
  449. }
  450. // 19.2.6.2 decodeURI ( encodedURI ), https://tc39.es/ecma262/#sec-decodeuri-encodeduri
  451. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::decode_uri)
  452. {
  453. auto uri_string = TRY(vm.argument(0).to_string(global_object));
  454. auto decoded = TRY(decode(global_object, uri_string, ";/?:@&=+$,#"sv));
  455. return js_string(vm, move(decoded));
  456. }
  457. // 19.2.6.5 encodeURIComponent ( uriComponent ), https://tc39.es/ecma262/#sec-encodeuricomponent-uricomponent
  458. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::encode_uri_component)
  459. {
  460. auto uri_string = TRY(vm.argument(0).to_string(global_object));
  461. auto encoded = TRY(encode(global_object, uri_string, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'()"sv));
  462. return js_string(vm, move(encoded));
  463. }
  464. // 19.2.6.3 decodeURIComponent ( encodedURIComponent ), https://tc39.es/ecma262/#sec-decodeuricomponent-encodeduricomponent
  465. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::decode_uri_component)
  466. {
  467. auto uri_string = TRY(vm.argument(0).to_string(global_object));
  468. auto decoded = TRY(decode(global_object, uri_string, ""sv));
  469. return js_string(vm, move(decoded));
  470. }
  471. // B.2.1.1 escape ( string ), https://tc39.es/ecma262/#sec-escape-string
  472. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::escape)
  473. {
  474. auto string = TRY(vm.argument(0).to_string(global_object));
  475. StringBuilder escaped;
  476. for (auto code_point : Utf8View(string)) {
  477. if (code_point < 256) {
  478. if ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*_+-./"sv.contains(code_point))
  479. escaped.append(code_point);
  480. else
  481. escaped.appendff("%{:02X}", code_point);
  482. continue;
  483. }
  484. escaped.appendff("%u{:04X}", code_point); // FIXME: Handle utf-16 surrogate pairs
  485. }
  486. return js_string(vm, escaped.build());
  487. }
  488. // B.2.1.2 unescape ( string ), https://tc39.es/ecma262/#sec-unescape-string
  489. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::unescape)
  490. {
  491. auto string = TRY(vm.argument(0).to_string(global_object));
  492. ssize_t length = string.length();
  493. StringBuilder unescaped(length);
  494. for (auto k = 0; k < length; ++k) {
  495. u32 code_point = string[k];
  496. if (code_point == '%') {
  497. 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])) {
  498. 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]);
  499. k += 5;
  500. } else if (k <= length - 3 && is_ascii_hex_digit(string[k + 1]) && is_ascii_hex_digit(string[k + 2])) {
  501. code_point = (parse_ascii_hex_digit(string[k + 1]) << 4) | parse_ascii_hex_digit(string[k + 2]);
  502. k += 2;
  503. }
  504. }
  505. unescaped.append_code_point(code_point);
  506. }
  507. return js_string(vm, unescaped.build());
  508. }
  509. }