GlobalObject.cpp 26 KB

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