GlobalObject.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <andreas@ladybird.org>
  3. * Copyright (c) 2020-2023, 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/FloatingPointStringConversions.h>
  10. #include <AK/Hex.h>
  11. #include <AK/UnicodeUtils.h>
  12. #include <AK/Utf16View.h>
  13. #include <AK/Utf8View.h>
  14. #include <LibGC/DeferGC.h>
  15. #include <LibJS/Runtime/AbstractOperations.h>
  16. #include <LibJS/Runtime/AggregateErrorConstructor.h>
  17. #include <LibJS/Runtime/ArrayBufferConstructor.h>
  18. #include <LibJS/Runtime/ArrayConstructor.h>
  19. #include <LibJS/Runtime/ArrayPrototype.h>
  20. #include <LibJS/Runtime/AsyncFunctionConstructor.h>
  21. #include <LibJS/Runtime/AsyncGeneratorFunctionConstructor.h>
  22. #include <LibJS/Runtime/AsyncGeneratorPrototype.h>
  23. #include <LibJS/Runtime/AtomicsObject.h>
  24. #include <LibJS/Runtime/BigIntConstructor.h>
  25. #include <LibJS/Runtime/BooleanConstructor.h>
  26. #include <LibJS/Runtime/ConsoleObject.h>
  27. #include <LibJS/Runtime/DataViewConstructor.h>
  28. #include <LibJS/Runtime/DateConstructor.h>
  29. #include <LibJS/Runtime/DisposableStackConstructor.h>
  30. #include <LibJS/Runtime/ErrorConstructor.h>
  31. #include <LibJS/Runtime/FinalizationRegistryConstructor.h>
  32. #include <LibJS/Runtime/FinalizationRegistryPrototype.h>
  33. #include <LibJS/Runtime/FunctionConstructor.h>
  34. #include <LibJS/Runtime/GeneratorFunctionConstructor.h>
  35. #include <LibJS/Runtime/GeneratorPrototype.h>
  36. #include <LibJS/Runtime/GlobalEnvironment.h>
  37. #include <LibJS/Runtime/GlobalObject.h>
  38. #include <LibJS/Runtime/Intl/CollatorConstructor.h>
  39. #include <LibJS/Runtime/Intl/DateTimeFormatConstructor.h>
  40. #include <LibJS/Runtime/Intl/DisplayNamesConstructor.h>
  41. #include <LibJS/Runtime/Intl/DurationFormatConstructor.h>
  42. #include <LibJS/Runtime/Intl/Intl.h>
  43. #include <LibJS/Runtime/Intl/ListFormatConstructor.h>
  44. #include <LibJS/Runtime/Intl/LocaleConstructor.h>
  45. #include <LibJS/Runtime/Intl/NumberFormatConstructor.h>
  46. #include <LibJS/Runtime/Intl/PluralRulesConstructor.h>
  47. #include <LibJS/Runtime/Intl/RelativeTimeFormatConstructor.h>
  48. #include <LibJS/Runtime/Intl/SegmenterConstructor.h>
  49. #include <LibJS/Runtime/IteratorConstructor.h>
  50. #include <LibJS/Runtime/JSONObject.h>
  51. #include <LibJS/Runtime/MapConstructor.h>
  52. #include <LibJS/Runtime/MathObject.h>
  53. #include <LibJS/Runtime/NumberConstructor.h>
  54. #include <LibJS/Runtime/Object.h>
  55. #include <LibJS/Runtime/ObjectConstructor.h>
  56. #include <LibJS/Runtime/PromiseConstructor.h>
  57. #include <LibJS/Runtime/ProxyConstructor.h>
  58. #include <LibJS/Runtime/Realm.h>
  59. #include <LibJS/Runtime/ReflectObject.h>
  60. #include <LibJS/Runtime/RegExpConstructor.h>
  61. #include <LibJS/Runtime/SetConstructor.h>
  62. #include <LibJS/Runtime/ShadowRealmConstructor.h>
  63. #include <LibJS/Runtime/Shape.h>
  64. #include <LibJS/Runtime/SharedArrayBufferConstructor.h>
  65. #include <LibJS/Runtime/StringConstructor.h>
  66. #include <LibJS/Runtime/StringPrototype.h>
  67. #include <LibJS/Runtime/SuppressedErrorConstructor.h>
  68. #include <LibJS/Runtime/SymbolConstructor.h>
  69. #include <LibJS/Runtime/Temporal/CalendarConstructor.h>
  70. #include <LibJS/Runtime/Temporal/DurationConstructor.h>
  71. #include <LibJS/Runtime/Temporal/InstantConstructor.h>
  72. #include <LibJS/Runtime/Temporal/PlainDateConstructor.h>
  73. #include <LibJS/Runtime/Temporal/PlainDateTimeConstructor.h>
  74. #include <LibJS/Runtime/Temporal/PlainMonthDayConstructor.h>
  75. #include <LibJS/Runtime/Temporal/PlainTimeConstructor.h>
  76. #include <LibJS/Runtime/Temporal/PlainYearMonthConstructor.h>
  77. #include <LibJS/Runtime/Temporal/Temporal.h>
  78. #include <LibJS/Runtime/Temporal/TimeZoneConstructor.h>
  79. #include <LibJS/Runtime/Temporal/ZonedDateTimeConstructor.h>
  80. #include <LibJS/Runtime/TypedArray.h>
  81. #include <LibJS/Runtime/Value.h>
  82. #include <LibJS/Runtime/ValueInlines.h>
  83. #include <LibJS/Runtime/WeakMapConstructor.h>
  84. #include <LibJS/Runtime/WeakRefConstructor.h>
  85. #include <LibJS/Runtime/WeakSetConstructor.h>
  86. namespace JS {
  87. GC_DEFINE_ALLOCATOR(GlobalObject);
  88. GlobalObject::GlobalObject(Realm& realm)
  89. : Object(GlobalObjectTag::Tag, realm)
  90. {
  91. Object::set_prototype(realm.intrinsics().object_prototype());
  92. }
  93. // 9.3.3 SetDefaultGlobalBindings ( realmRec ), https://tc39.es/ecma262/#sec-setdefaultglobalbindings
  94. void set_default_global_bindings(Realm& realm)
  95. {
  96. auto& vm = realm.vm();
  97. // 1. Let global be realmRec.[[GlobalObject]].
  98. auto& global = realm.global_object();
  99. // 2. For each property of the Global Object specified in clause 19, do
  100. // a. Let name be the String value of the property name.
  101. // b. Let desc be the fully populated data Property Descriptor for the property, containing the specified attributes for the property.
  102. // For properties listed in 19.2, 19.3, or 19.4 the value of the [[Value]] attribute is the corresponding intrinsic object from realmRec.
  103. // c. Perform ? DefinePropertyOrThrow(global, name, desc).
  104. // NOTE: This function is infallible as we set properties directly; property clashes in global object construction are not expected.
  105. u8 attr = Attribute::Writable | Attribute::Configurable;
  106. // 19.2 Function Properties of the Global Object, https://tc39.es/ecma262/#sec-function-properties-of-the-global-object
  107. global.define_direct_property(vm.names.eval, realm.intrinsics().eval_function(), attr);
  108. global.define_direct_property(vm.names.isFinite, realm.intrinsics().is_finite_function(), attr);
  109. global.define_direct_property(vm.names.isNaN, realm.intrinsics().is_nan_function(), attr);
  110. global.define_direct_property(vm.names.parseFloat, realm.intrinsics().parse_float_function(), attr);
  111. global.define_direct_property(vm.names.parseInt, realm.intrinsics().parse_int_function(), attr);
  112. global.define_direct_property(vm.names.decodeURI, realm.intrinsics().decode_uri_function(), attr);
  113. global.define_direct_property(vm.names.decodeURIComponent, realm.intrinsics().decode_uri_component_function(), attr);
  114. global.define_direct_property(vm.names.encodeURI, realm.intrinsics().encode_uri_function(), attr);
  115. global.define_direct_property(vm.names.encodeURIComponent, realm.intrinsics().encode_uri_component_function(), attr);
  116. // 19.1 Value Properties of the Global Object, https://tc39.es/ecma262/#sec-value-properties-of-the-global-object
  117. global.define_direct_property(vm.names.globalThis, &global, attr);
  118. global.define_direct_property(vm.names.Infinity, js_infinity(), 0);
  119. global.define_direct_property(vm.names.NaN, js_nan(), 0);
  120. global.define_direct_property(vm.names.undefined, js_undefined(), 0);
  121. // 19.3 Constructor Properties of the Global Object, https://tc39.es/ecma262/#sec-constructor-properties-of-the-global-object
  122. global.define_intrinsic_accessor(vm.names.AggregateError, attr, [](auto& realm) -> Value { return realm.intrinsics().aggregate_error_constructor(); });
  123. global.define_intrinsic_accessor(vm.names.Array, attr, [](auto& realm) -> Value { return realm.intrinsics().array_constructor(); });
  124. global.define_intrinsic_accessor(vm.names.ArrayBuffer, attr, [](auto& realm) -> Value { return realm.intrinsics().array_buffer_constructor(); });
  125. global.define_intrinsic_accessor(vm.names.BigInt, attr, [](auto& realm) -> Value { return realm.intrinsics().bigint_constructor(); });
  126. global.define_intrinsic_accessor(vm.names.BigInt64Array, attr, [](auto& realm) -> Value { return realm.intrinsics().big_int64_array_constructor(); });
  127. global.define_intrinsic_accessor(vm.names.BigUint64Array, attr, [](auto& realm) -> Value { return realm.intrinsics().big_uint64_array_constructor(); });
  128. global.define_intrinsic_accessor(vm.names.Boolean, attr, [](auto& realm) -> Value { return realm.intrinsics().boolean_constructor(); });
  129. global.define_intrinsic_accessor(vm.names.DataView, attr, [](auto& realm) -> Value { return realm.intrinsics().data_view_constructor(); });
  130. global.define_intrinsic_accessor(vm.names.Date, attr, [](auto& realm) -> Value { return realm.intrinsics().date_constructor(); });
  131. global.define_intrinsic_accessor(vm.names.DisposableStack, attr, [](auto& realm) -> Value { return realm.intrinsics().disposable_stack_constructor(); });
  132. global.define_intrinsic_accessor(vm.names.Error, attr, [](auto& realm) -> Value { return realm.intrinsics().error_constructor(); });
  133. global.define_intrinsic_accessor(vm.names.EvalError, attr, [](auto& realm) -> Value { return realm.intrinsics().eval_error_constructor(); });
  134. global.define_intrinsic_accessor(vm.names.FinalizationRegistry, attr, [](auto& realm) -> Value { return realm.intrinsics().finalization_registry_constructor(); });
  135. global.define_intrinsic_accessor(vm.names.Float16Array, attr, [](auto& realm) -> Value { return realm.intrinsics().float16_array_constructor(); });
  136. global.define_intrinsic_accessor(vm.names.Float32Array, attr, [](auto& realm) -> Value { return realm.intrinsics().float32_array_constructor(); });
  137. global.define_intrinsic_accessor(vm.names.Float64Array, attr, [](auto& realm) -> Value { return realm.intrinsics().float64_array_constructor(); });
  138. global.define_intrinsic_accessor(vm.names.Function, attr, [](auto& realm) -> Value { return realm.intrinsics().function_constructor(); });
  139. global.define_intrinsic_accessor(vm.names.Int8Array, attr, [](auto& realm) -> Value { return realm.intrinsics().int8_array_constructor(); });
  140. global.define_intrinsic_accessor(vm.names.Int16Array, attr, [](auto& realm) -> Value { return realm.intrinsics().int16_array_constructor(); });
  141. global.define_intrinsic_accessor(vm.names.Int32Array, attr, [](auto& realm) -> Value { return realm.intrinsics().int32_array_constructor(); });
  142. global.define_intrinsic_accessor(vm.names.Iterator, attr, [](auto& realm) -> Value { return realm.intrinsics().iterator_constructor(); });
  143. global.define_intrinsic_accessor(vm.names.Map, attr, [](auto& realm) -> Value { return realm.intrinsics().map_constructor(); });
  144. global.define_intrinsic_accessor(vm.names.Number, attr, [](auto& realm) -> Value { return realm.intrinsics().number_constructor(); });
  145. global.define_intrinsic_accessor(vm.names.Object, attr, [](auto& realm) -> Value { return realm.intrinsics().object_constructor(); });
  146. global.define_intrinsic_accessor(vm.names.Promise, attr, [](auto& realm) -> Value { return realm.intrinsics().promise_constructor(); });
  147. global.define_intrinsic_accessor(vm.names.Proxy, attr, [](auto& realm) -> Value { return realm.intrinsics().proxy_constructor(); });
  148. global.define_intrinsic_accessor(vm.names.RangeError, attr, [](auto& realm) -> Value { return realm.intrinsics().range_error_constructor(); });
  149. global.define_intrinsic_accessor(vm.names.ReferenceError, attr, [](auto& realm) -> Value { return realm.intrinsics().reference_error_constructor(); });
  150. global.define_intrinsic_accessor(vm.names.RegExp, attr, [](auto& realm) -> Value { return realm.intrinsics().regexp_constructor(); });
  151. global.define_intrinsic_accessor(vm.names.Set, attr, [](auto& realm) -> Value { return realm.intrinsics().set_constructor(); });
  152. global.define_intrinsic_accessor(vm.names.ShadowRealm, attr, [](auto& realm) -> Value { return realm.intrinsics().shadow_realm_constructor(); });
  153. global.define_intrinsic_accessor(vm.names.SharedArrayBuffer, attr, [](auto& realm) -> Value { return realm.intrinsics().shared_array_buffer_constructor(); });
  154. global.define_intrinsic_accessor(vm.names.String, attr, [](auto& realm) -> Value { return realm.intrinsics().string_constructor(); });
  155. global.define_intrinsic_accessor(vm.names.SuppressedError, attr, [](auto& realm) -> Value { return realm.intrinsics().suppressed_error_constructor(); });
  156. global.define_intrinsic_accessor(vm.names.Symbol, attr, [](auto& realm) -> Value { return realm.intrinsics().symbol_constructor(); });
  157. global.define_intrinsic_accessor(vm.names.SyntaxError, attr, [](auto& realm) -> Value { return realm.intrinsics().syntax_error_constructor(); });
  158. global.define_intrinsic_accessor(vm.names.TypeError, attr, [](auto& realm) -> Value { return realm.intrinsics().type_error_constructor(); });
  159. global.define_intrinsic_accessor(vm.names.Uint8Array, attr, [](auto& realm) -> Value { return realm.intrinsics().uint8_array_constructor(); });
  160. global.define_intrinsic_accessor(vm.names.Uint8ClampedArray, attr, [](auto& realm) -> Value { return realm.intrinsics().uint8_clamped_array_constructor(); });
  161. global.define_intrinsic_accessor(vm.names.Uint16Array, attr, [](auto& realm) -> Value { return realm.intrinsics().uint16_array_constructor(); });
  162. global.define_intrinsic_accessor(vm.names.Uint32Array, attr, [](auto& realm) -> Value { return realm.intrinsics().uint32_array_constructor(); });
  163. global.define_intrinsic_accessor(vm.names.URIError, attr, [](auto& realm) -> Value { return realm.intrinsics().uri_error_constructor(); });
  164. global.define_intrinsic_accessor(vm.names.WeakMap, attr, [](auto& realm) -> Value { return realm.intrinsics().weak_map_constructor(); });
  165. global.define_intrinsic_accessor(vm.names.WeakRef, attr, [](auto& realm) -> Value { return realm.intrinsics().weak_ref_constructor(); });
  166. global.define_intrinsic_accessor(vm.names.WeakSet, attr, [](auto& realm) -> Value { return realm.intrinsics().weak_set_constructor(); });
  167. // 19.4 Other Properties of the Global Object, https://tc39.es/ecma262/#sec-other-properties-of-the-global-object
  168. global.define_intrinsic_accessor(vm.names.Atomics, attr, [](auto& realm) -> Value { return realm.intrinsics().atomics_object(); });
  169. global.define_intrinsic_accessor(vm.names.Intl, attr, [](auto& realm) -> Value { return realm.intrinsics().intl_object(); });
  170. global.define_intrinsic_accessor(vm.names.JSON, attr, [](auto& realm) -> Value { return realm.intrinsics().json_object(); });
  171. global.define_intrinsic_accessor(vm.names.Math, attr, [](auto& realm) -> Value { return realm.intrinsics().math_object(); });
  172. global.define_intrinsic_accessor(vm.names.Reflect, attr, [](auto& realm) -> Value { return realm.intrinsics().reflect_object(); });
  173. global.define_intrinsic_accessor(vm.names.Temporal, attr, [](auto& realm) -> Value { return realm.intrinsics().temporal_object(); });
  174. // B.2.1 Additional Properties of the Global Object, https://tc39.es/ecma262/#sec-additional-properties-of-the-global-object
  175. global.define_direct_property(vm.names.escape, realm.intrinsics().escape_function(), attr);
  176. global.define_direct_property(vm.names.unescape, realm.intrinsics().unescape_function(), attr);
  177. // Non-standard
  178. global.define_direct_property(vm.names.InternalError, realm.intrinsics().internal_error_constructor(), attr);
  179. global.define_direct_property(vm.names.console, realm.intrinsics().console_object(), attr);
  180. // 3. Return unused.
  181. }
  182. void GlobalObject::initialize(Realm& realm)
  183. {
  184. Base::initialize(realm);
  185. auto& vm = this->vm();
  186. // Non-standard
  187. u8 attr = Attribute::Writable | Attribute::Configurable;
  188. define_native_function(realm, vm.names.gc, gc, 0, attr);
  189. }
  190. GlobalObject::~GlobalObject() = default;
  191. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::gc)
  192. {
  193. vm.heap().collect_garbage();
  194. return js_undefined();
  195. }
  196. // 19.2.1 eval ( x ), https://tc39.es/ecma262/#sec-eval-x
  197. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::eval)
  198. {
  199. auto x = vm.argument(0);
  200. // 1. Return ? PerformEval(x, false, false).
  201. return perform_eval(vm, x, CallerMode::NonStrict, EvalMode::Indirect);
  202. }
  203. // 19.2.2 isFinite ( number ), https://tc39.es/ecma262/#sec-isfinite-number
  204. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::is_finite)
  205. {
  206. auto number = vm.argument(0);
  207. // 1. Let num be ? ToNumber(number).
  208. auto num = TRY(number.to_number(vm));
  209. // 2. If num is not finite, return false.
  210. // 3. Otherwise, return true.
  211. return Value(num.is_finite_number());
  212. }
  213. // 19.2.3 isNaN ( number ), https://tc39.es/ecma262/#sec-isnan-number
  214. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::is_nan)
  215. {
  216. auto number = vm.argument(0);
  217. // 1. Let num be ? ToNumber(number).
  218. auto num = TRY(number.to_number(vm));
  219. // 2. If num is NaN, return true.
  220. // 3. Otherwise, return false.
  221. return Value(num.is_nan());
  222. }
  223. // 19.2.4 parseFloat ( string ), https://tc39.es/ecma262/#sec-parsefloat-string
  224. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::parse_float)
  225. {
  226. auto string = vm.argument(0);
  227. // OPTIMIZATION: We can skip the number-to-string-to-number round trip when the value is already a number.
  228. if (string.is_number())
  229. return string;
  230. // 1. Let inputString be ? ToString(string).
  231. auto input_string = TRY(string.to_string(vm));
  232. // 2. Let trimmedString be ! TrimString(inputString, start).
  233. auto trimmed_string = MUST(trim_string(vm, PrimitiveString::create(vm, move(input_string)), TrimMode::Left));
  234. if (trimmed_string.is_empty())
  235. return js_nan();
  236. // 3. If neither trimmedString nor any prefix of trimmedString satisfies the syntax of a StrDecimalLiteral (see 7.1.4.1), return NaN.
  237. // 4. Let numberString be the longest prefix of trimmedString, which might be trimmedString itself, that satisfies the syntax of a StrDecimalLiteral.
  238. // 5. Let parsedNumber be ParseText(StringToCodePoints(numberString), StrDecimalLiteral).
  239. // 6. Assert: parsedNumber is a Parse Node.
  240. // 7. Return StringNumericValue of parsedNumber.
  241. auto trimmed_string_view = trimmed_string.bytes_as_string_view();
  242. auto const* begin = trimmed_string_view.characters_without_null_termination();
  243. auto const* end = begin + trimmed_string_view.length();
  244. auto parsed_number = parse_first_floating_point<double>(begin, end);
  245. if (parsed_number.parsed_value())
  246. return parsed_number.value;
  247. auto first_code_point = *trimmed_string.code_points().begin();
  248. if (first_code_point == '-' || first_code_point == '+')
  249. trimmed_string_view = trimmed_string_view.substring_view(1);
  250. if (trimmed_string_view.starts_with("Infinity"sv, AK::CaseSensitivity::CaseSensitive)) {
  251. // Only an immediate - means we should return negative infinity
  252. return first_code_point == '-' ? js_negative_infinity() : js_infinity();
  253. }
  254. return js_nan();
  255. }
  256. // 19.2.5 parseInt ( string, radix ), https://tc39.es/ecma262/#sec-parseint-string-radix
  257. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::parse_int)
  258. {
  259. auto string = vm.argument(0);
  260. // 1. Let inputString be ? ToString(string).
  261. auto input_string = TRY(string.to_string(vm));
  262. // 2. Let S be ! TrimString(inputString, start).
  263. String trimmed_string;
  264. // OPTIMIZATION: We can skip the trimming step when the value already starts with an alphanumeric ASCII character.
  265. if (input_string.is_empty() || is_ascii_alphanumeric(input_string.bytes_as_string_view()[0])) {
  266. trimmed_string = input_string;
  267. } else {
  268. trimmed_string = MUST(trim_string(vm, PrimitiveString::create(vm, move(input_string)), TrimMode::Left));
  269. }
  270. // 3. Let sign be 1.
  271. auto sign = 1;
  272. // 4. If S is not empty and the first code unit of S is the code unit 0x002D (HYPHEN-MINUS), set sign to -1.
  273. auto first_code_point = trimmed_string.is_empty() ? OptionalNone {} : Optional<u32> { *trimmed_string.code_points().begin() };
  274. if (first_code_point == 0x2Du)
  275. sign = -1;
  276. // 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.
  277. auto trimmed_view = trimmed_string.bytes_as_string_view();
  278. if (first_code_point == 0x2Bu || first_code_point == 0x2Du)
  279. trimmed_view = trimmed_view.substring_view(1);
  280. // 6. Let R be ℝ(? ToInt32(radix)).
  281. auto radix = TRY(vm.argument(1).to_i32(vm));
  282. // 7. Let stripPrefix be true.
  283. auto strip_prefix = true;
  284. // 8. If R ≠ 0, then
  285. if (radix != 0) {
  286. // a. If R < 2 or R > 36, return NaN.
  287. if (radix < 2 || radix > 36)
  288. return js_nan();
  289. // b. If R ≠ 16, set stripPrefix to false.
  290. if (radix != 16)
  291. strip_prefix = false;
  292. }
  293. // 9. Else,
  294. else {
  295. // a. Set R to 10.
  296. radix = 10;
  297. }
  298. // 10. If stripPrefix is true, then
  299. if (strip_prefix) {
  300. // a. If the length of S is at least 2 and the first two code units of S are either "0x" or "0X", then
  301. if (trimmed_view.length() >= 2 && trimmed_view.substring_view(0, 2).equals_ignoring_ascii_case("0x"sv)) {
  302. // i. Remove the first two code units from S.
  303. trimmed_view = trimmed_view.substring_view(2);
  304. // ii. Set R to 16.
  305. radix = 16;
  306. }
  307. }
  308. // 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.
  309. // 12. Let Z be the substring of S from 0 to end.
  310. // 13. If Z is empty, return NaN.
  311. // 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.)
  312. auto parse_digit = [&](u32 code_point) -> Optional<u32> {
  313. if (!is_ascii_alphanumeric(code_point))
  314. return {};
  315. auto digit = parse_ascii_base36_digit(code_point);
  316. if (digit >= (u32)radix)
  317. return {};
  318. return digit;
  319. };
  320. bool had_digits = false;
  321. double number = 0;
  322. for (auto code_point : Utf8View(trimmed_view)) {
  323. auto digit = parse_digit(code_point);
  324. if (!digit.has_value())
  325. break;
  326. had_digits = true;
  327. number *= radix;
  328. number += digit.value();
  329. }
  330. if (!had_digits)
  331. return js_nan();
  332. // 15. If mathInt = 0, then
  333. // a. If sign = -1, return -0𝔽.
  334. // b. Return +0𝔽.
  335. // 16. Return 𝔽(sign × mathInt).
  336. return Value(sign * number);
  337. }
  338. // 19.2.6.5 Encode ( string, extraUnescaped ), https://tc39.es/ecma262/#sec-encode
  339. static ThrowCompletionOr<ByteString> encode(VM& vm, ByteString const& string, StringView unescaped_set)
  340. {
  341. auto utf16_string = Utf16String::create(string);
  342. // 1. Let strLen be the length of string.
  343. auto string_length = utf16_string.length_in_code_units();
  344. // 2. Let R be the empty String.
  345. StringBuilder encoded_builder;
  346. // 3. Let alwaysUnescaped be the string-concatenation of the ASCII word characters and "-.!~*'()".
  347. // 4. Let unescapedSet be the string-concatenation of alwaysUnescaped and extraUnescaped.
  348. // OPTIMIZATION: We pass in the entire unescapedSet as a StringView to avoid an extra allocation.
  349. // 5. Let k be 0.
  350. auto k = 0u;
  351. // 6. Repeat,
  352. while (k < string_length) {
  353. // a. If k = strLen, return R.
  354. // Handled below
  355. // b. Let C be the code unit at index k within string.
  356. auto code_unit = utf16_string.code_unit_at(k);
  357. // c. If C is in unescapedSet, then
  358. // NOTE: We assume the unescaped set only contains ascii characters as unescaped_set is a StringView.
  359. if (code_unit < 0x80 && unescaped_set.contains(static_cast<char>(code_unit))) {
  360. // i. Set k to k + 1.
  361. k++;
  362. // ii. Set R to the string-concatenation of R and C.
  363. encoded_builder.append(code_unit);
  364. }
  365. // d. Else,
  366. else {
  367. // i. Let cp be CodePointAt(string, k).
  368. auto code_point = code_point_at(utf16_string.view(), k);
  369. // ii. If cp.[[IsUnpairedSurrogate]] is true, throw a URIError exception.
  370. if (code_point.is_unpaired_surrogate)
  371. return vm.throw_completion<URIError>(ErrorType::URIMalformed);
  372. // iii. Set k to k + cp.[[CodeUnitCount]].
  373. k += code_point.code_unit_count;
  374. // iv. Let Octets be the List of octets resulting by applying the UTF-8 transformation to cp.[[CodePoint]].
  375. // v. For each element octet of Octets, do
  376. auto nwritten = AK::UnicodeUtils::code_point_to_utf8(code_point.code_point, [&encoded_builder](u8 octet) {
  377. // 1. Let hex be the String representation of octet, formatted as an uppercase hexadecimal number.
  378. // 2. Set R to the string-concatenation of R, "%", and ! StringPad(hex, 2𝔽, "0", start).
  379. encoded_builder.appendff("%{:02X}", octet);
  380. });
  381. VERIFY(nwritten > 0);
  382. }
  383. }
  384. return encoded_builder.to_byte_string();
  385. }
  386. // 19.2.6.6 Decode ( string, preserveEscapeSet ), https://tc39.es/ecma262/#sec-decode
  387. // FIXME: Add spec comments to this implementation. It deviates a lot, so that's a bit tricky.
  388. static ThrowCompletionOr<ByteString> decode(VM& vm, ByteString const& string, StringView reserved_set)
  389. {
  390. StringBuilder decoded_builder;
  391. auto code_point_start_offset = 0u;
  392. auto expected_continuation_bytes = 0;
  393. for (size_t k = 0; k < string.length(); k++) {
  394. auto code_unit = string[k];
  395. if (code_unit != '%') {
  396. if (expected_continuation_bytes > 0)
  397. return vm.throw_completion<URIError>(ErrorType::URIMalformed);
  398. decoded_builder.append(code_unit);
  399. continue;
  400. }
  401. if (k + 2 >= string.length())
  402. return vm.throw_completion<URIError>(ErrorType::URIMalformed);
  403. auto first_digit = decode_hex_digit(string[k + 1]);
  404. if (first_digit >= 16)
  405. return vm.throw_completion<URIError>(ErrorType::URIMalformed);
  406. auto second_digit = decode_hex_digit(string[k + 2]);
  407. if (second_digit >= 16)
  408. return vm.throw_completion<URIError>(ErrorType::URIMalformed);
  409. u8 decoded_code_unit = (first_digit << 4) | second_digit;
  410. k += 2;
  411. if (expected_continuation_bytes > 0) {
  412. decoded_builder.append(decoded_code_unit);
  413. expected_continuation_bytes--;
  414. if (expected_continuation_bytes == 0 && !Utf8View(decoded_builder.string_view().substring_view(code_point_start_offset)).validate())
  415. return vm.throw_completion<URIError>(ErrorType::URIMalformed);
  416. continue;
  417. }
  418. if (decoded_code_unit < 0x80) {
  419. if (reserved_set.contains(static_cast<char>(decoded_code_unit)))
  420. decoded_builder.append(string.substring_view(k - 2, 3));
  421. else
  422. decoded_builder.append(decoded_code_unit);
  423. continue;
  424. }
  425. auto leading_ones = count_leading_zeroes_safe(static_cast<u8>(~decoded_code_unit));
  426. if (leading_ones == 1 || leading_ones > 4)
  427. return vm.throw_completion<URIError>(ErrorType::URIMalformed);
  428. code_point_start_offset = decoded_builder.length();
  429. decoded_builder.append(decoded_code_unit);
  430. expected_continuation_bytes = leading_ones - 1;
  431. }
  432. if (expected_continuation_bytes > 0)
  433. return vm.throw_completion<URIError>(ErrorType::URIMalformed);
  434. return decoded_builder.to_byte_string();
  435. }
  436. // 19.2.6.1 decodeURI ( encodedURI ), https://tc39.es/ecma262/#sec-decodeuri-encodeduri
  437. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::decode_uri)
  438. {
  439. // 1. Let uriString be ? ToString(encodedURI).
  440. auto uri_string = TRY(vm.argument(0).to_byte_string(vm));
  441. // 2. Let preserveEscapeSet be ";/?:@&=+$,#".
  442. // 3. Return ? Decode(uriString, preserveEscapeSet).
  443. auto decoded = TRY(decode(vm, uri_string, ";/?:@&=+$,#"sv));
  444. return PrimitiveString::create(vm, move(decoded));
  445. }
  446. // 19.2.6.2 decodeURIComponent ( encodedURIComponent ), https://tc39.es/ecma262/#sec-decodeuricomponent-encodeduricomponent
  447. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::decode_uri_component)
  448. {
  449. auto encoded_uri_component = vm.argument(0);
  450. // 1. Let componentString be ? ToString(encodedURIComponent).
  451. auto uri_string = TRY(encoded_uri_component.to_byte_string(vm));
  452. // 2. Let preserveEscapeSet be the empty String.
  453. // 3. Return ? Decode(componentString, preserveEscapeSet).
  454. auto decoded = TRY(decode(vm, uri_string, ""sv));
  455. return PrimitiveString::create(vm, move(decoded));
  456. }
  457. // 19.2.6.3 encodeURI ( uri ), https://tc39.es/ecma262/#sec-encodeuri-uri
  458. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::encode_uri)
  459. {
  460. auto uri = vm.argument(0);
  461. // 1. Let uriString be ? ToString(uri).
  462. auto uri_string = TRY(uri.to_byte_string(vm));
  463. // 2. Let extraUnescaped be ";/?:@&=+$,#".
  464. // 3. Return ? Encode(uriString, extraUnescaped).
  465. auto encoded = TRY(encode(vm, uri_string, ";/?:@&=+$,abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'()#"sv));
  466. return PrimitiveString::create(vm, move(encoded));
  467. }
  468. // 19.2.6.4 encodeURIComponent ( uriComponent ), https://tc39.es/ecma262/#sec-encodeuricomponent-uricomponent
  469. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::encode_uri_component)
  470. {
  471. auto uri_component = vm.argument(0);
  472. // 1. Let componentString be ? ToString(uriComponent).
  473. auto uri_string = TRY(uri_component.to_byte_string(vm));
  474. // 2. Let extraUnescaped be the empty String.
  475. // 3. Return ? Encode(componentString, extraUnescaped).
  476. auto encoded = TRY(encode(vm, uri_string, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'()"sv));
  477. return PrimitiveString::create(vm, move(encoded));
  478. }
  479. // B.2.1.1 escape ( string ), https://tc39.es/ecma262/#sec-escape-string
  480. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::escape)
  481. {
  482. // 1. Set string to ? ToString(string).
  483. auto string = TRY(vm.argument(0).to_byte_string(vm));
  484. // 3. Let R be the empty String.
  485. StringBuilder escaped;
  486. // 4. Let unescapedSet be the string-concatenation of the ASCII word characters and "@*+-./".
  487. auto unescaped_set = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*_+-./"sv;
  488. // 2. Let length be the length of string.
  489. // 5. Let k be 0.
  490. // 6. Repeat, while k < length,
  491. for (auto code_point : TRY_OR_THROW_OOM(vm, utf8_to_utf16(string))) {
  492. // a. Let char be the code unit at index k within string.
  493. // b. If unescapedSet contains char, then
  494. // NOTE: We know unescapedSet is ASCII-only, so ensure we have an ASCII codepoint before casting to char.
  495. if (is_ascii(code_point) && unescaped_set.contains(static_cast<char>(code_point))) {
  496. // i. Let S be the String value containing the single code unit char.
  497. escaped.append(code_point);
  498. }
  499. // c. Else,
  500. // i. Let n be the numeric value of char.
  501. // ii. If n < 256, then
  502. else if (code_point < 256) {
  503. // 1. Let hex be the String representation of n, formatted as an uppercase hexadecimal number.
  504. // 2. Let S be the string-concatenation of "%" and ! StringPad(hex, 2𝔽, "0", start).
  505. escaped.appendff("%{:02X}", code_point);
  506. }
  507. // iii. Else,
  508. else {
  509. // 1. Let hex be the String representation of n, formatted as an uppercase hexadecimal number.
  510. // 2. Let S be the string-concatenation of "%u" and ! StringPad(hex, 4𝔽, "0", start).
  511. escaped.appendff("%u{:04X}", code_point);
  512. }
  513. // d. Set R to the string-concatenation of R and S.
  514. // e. Set k to k + 1.
  515. }
  516. // 7. Return R.
  517. return PrimitiveString::create(vm, escaped.to_byte_string());
  518. }
  519. // B.2.1.2 unescape ( string ), https://tc39.es/ecma262/#sec-unescape-string
  520. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::unescape)
  521. {
  522. // 1. Set string to ? ToString(string).
  523. auto string = TRY(vm.argument(0).to_byte_string(vm));
  524. // 2. Let length be the length of string.
  525. ssize_t length = string.length();
  526. // 3. Let R be the empty String.
  527. StringBuilder unescaped(length);
  528. // 4. Let k be 0.
  529. // 5. Repeat, while k ≠ length,
  530. for (auto k = 0; k < length; ++k) {
  531. // a. Let c be the code unit at index k within string.
  532. u32 code_point = string[k];
  533. // b. If c is the code unit 0x0025 (PERCENT SIGN), then
  534. if (code_point == '%') {
  535. // i. Let hexEscape be the empty String.
  536. // ii. Let skip be 0.
  537. // iii. If k ≤ length - 6 and the code unit at index k + 1 within string is the code unit 0x0075 (LATIN SMALL LETTER U), then
  538. 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])) {
  539. // 1. Set hexEscape to the substring of string from k + 2 to k + 6.
  540. 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]);
  541. // 2. Set skip to 5.
  542. k += 5;
  543. }
  544. // iv. Else if k ≤ length - 3, then
  545. else if (k <= length - 3 && is_ascii_hex_digit(string[k + 1]) && is_ascii_hex_digit(string[k + 2])) {
  546. // 1. Set hexEscape to the substring of string from k + 1 to k + 3.
  547. code_point = (parse_ascii_hex_digit(string[k + 1]) << 4) | parse_ascii_hex_digit(string[k + 2]);
  548. // 2. Set skip to 2.
  549. k += 2;
  550. }
  551. // v. If hexEscape can be interpreted as an expansion of HexDigits[~Sep], then
  552. // 1. Let hexIntegerLiteral be the string-concatenation of "0x" and hexEscape.
  553. // 2. Let n be ! ToNumber(hexIntegerLiteral).
  554. // 3. Set c to the code unit whose value is ℝ(n).
  555. // 4. Set k to k + skip.
  556. // NOTE: All of this is already done in the branches above.
  557. }
  558. // c. Set R to the string-concatenation of R and c.
  559. unescaped.append_code_point(code_point);
  560. // d. Set k to k + 1.
  561. }
  562. // 6. Return R.
  563. return PrimitiveString::create(vm, unescaped.to_byte_string());
  564. }
  565. }