GlobalObject.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2022, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/BuiltinWrappers.h>
  8. #include <AK/CharacterTypes.h>
  9. #include <AK/Hex.h>
  10. #include <AK/UnicodeUtils.h>
  11. #include <AK/Utf16View.h>
  12. #include <AK/Utf8View.h>
  13. #include <LibJS/Console.h>
  14. #include <LibJS/Heap/DeferGC.h>
  15. #include <LibJS/Interpreter.h>
  16. #include <LibJS/Runtime/AbstractOperations.h>
  17. #include <LibJS/Runtime/AggregateErrorConstructor.h>
  18. #include <LibJS/Runtime/ArrayBufferConstructor.h>
  19. #include <LibJS/Runtime/ArrayConstructor.h>
  20. #include <LibJS/Runtime/ArrayPrototype.h>
  21. #include <LibJS/Runtime/AsyncFunctionConstructor.h>
  22. #include <LibJS/Runtime/AsyncGeneratorFunctionConstructor.h>
  23. #include <LibJS/Runtime/AsyncGeneratorPrototype.h>
  24. #include <LibJS/Runtime/AtomicsObject.h>
  25. #include <LibJS/Runtime/BigIntConstructor.h>
  26. #include <LibJS/Runtime/BooleanConstructor.h>
  27. #include <LibJS/Runtime/ConsoleObject.h>
  28. #include <LibJS/Runtime/DataViewConstructor.h>
  29. #include <LibJS/Runtime/DateConstructor.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/JSONObject.h>
  50. #include <LibJS/Runtime/MapConstructor.h>
  51. #include <LibJS/Runtime/MathObject.h>
  52. #include <LibJS/Runtime/NumberConstructor.h>
  53. #include <LibJS/Runtime/Object.h>
  54. #include <LibJS/Runtime/ObjectConstructor.h>
  55. #include <LibJS/Runtime/PromiseConstructor.h>
  56. #include <LibJS/Runtime/ProxyConstructor.h>
  57. #include <LibJS/Runtime/Realm.h>
  58. #include <LibJS/Runtime/ReflectObject.h>
  59. #include <LibJS/Runtime/RegExpConstructor.h>
  60. #include <LibJS/Runtime/SetConstructor.h>
  61. #include <LibJS/Runtime/ShadowRealmConstructor.h>
  62. #include <LibJS/Runtime/Shape.h>
  63. #include <LibJS/Runtime/StringConstructor.h>
  64. #include <LibJS/Runtime/StringPrototype.h>
  65. #include <LibJS/Runtime/SymbolConstructor.h>
  66. #include <LibJS/Runtime/Temporal/CalendarConstructor.h>
  67. #include <LibJS/Runtime/Temporal/DurationConstructor.h>
  68. #include <LibJS/Runtime/Temporal/InstantConstructor.h>
  69. #include <LibJS/Runtime/Temporal/PlainDateConstructor.h>
  70. #include <LibJS/Runtime/Temporal/PlainDateTimeConstructor.h>
  71. #include <LibJS/Runtime/Temporal/PlainMonthDayConstructor.h>
  72. #include <LibJS/Runtime/Temporal/PlainTimeConstructor.h>
  73. #include <LibJS/Runtime/Temporal/PlainYearMonthConstructor.h>
  74. #include <LibJS/Runtime/Temporal/Temporal.h>
  75. #include <LibJS/Runtime/Temporal/TimeZoneConstructor.h>
  76. #include <LibJS/Runtime/Temporal/ZonedDateTimeConstructor.h>
  77. #include <LibJS/Runtime/TypedArray.h>
  78. #include <LibJS/Runtime/Value.h>
  79. #include <LibJS/Runtime/WeakMapConstructor.h>
  80. #include <LibJS/Runtime/WeakRefConstructor.h>
  81. #include <LibJS/Runtime/WeakSetConstructor.h>
  82. namespace JS {
  83. GlobalObject::GlobalObject(Realm& realm)
  84. : Object(GlobalObjectTag::Tag, realm)
  85. , m_console(make<Console>(realm.vm()))
  86. {
  87. }
  88. // 9.3.4 SetDefaultGlobalBindings ( realmRec ), https://tc39.es/ecma262/#sec-setdefaultglobalbindings
  89. void GlobalObject::initialize_global_object(Realm& realm)
  90. {
  91. auto& vm = this->vm();
  92. ensure_shape_is_unique();
  93. Object::set_prototype(realm.intrinsics().object_prototype());
  94. u8 attr = Attribute::Writable | Attribute::Configurable;
  95. // 19.2 Function Properties of the Global Object, https://tc39.es/ecma262/#sec-function-properties-of-the-global-object
  96. define_native_function(realm, vm.names.eval, eval, 1, attr);
  97. define_native_function(realm, vm.names.isFinite, is_finite, 1, attr);
  98. define_native_function(realm, vm.names.isNaN, is_nan, 1, attr);
  99. define_native_function(realm, vm.names.parseFloat, parse_float, 1, attr);
  100. define_native_function(realm, vm.names.parseInt, parse_int, 2, attr);
  101. define_native_function(realm, vm.names.decodeURI, decode_uri, 1, attr);
  102. define_native_function(realm, vm.names.decodeURIComponent, decode_uri_component, 1, attr);
  103. define_native_function(realm, vm.names.encodeURI, encode_uri, 1, attr);
  104. define_native_function(realm, vm.names.encodeURIComponent, encode_uri_component, 1, attr);
  105. // 19.1 Value Properties of the Global Object, https://tc39.es/ecma262/#sec-value-properties-of-the-global-object
  106. define_direct_property(vm.names.globalThis, this, attr);
  107. define_direct_property(vm.names.Infinity, js_infinity(), 0);
  108. define_direct_property(vm.names.NaN, js_nan(), 0);
  109. define_direct_property(vm.names.undefined, js_undefined(), 0);
  110. // 19.3 Constructor Properties of the Global Object, https://tc39.es/ecma262/#sec-constructor-properties-of-the-global-object
  111. define_direct_property(vm.names.AggregateError, realm.intrinsics().aggregate_error_constructor(), attr);
  112. define_direct_property(vm.names.Array, realm.intrinsics().array_constructor(), attr);
  113. define_direct_property(vm.names.ArrayBuffer, realm.intrinsics().array_buffer_constructor(), attr);
  114. define_direct_property(vm.names.BigInt, realm.intrinsics().bigint_constructor(), attr);
  115. define_direct_property(vm.names.BigInt64Array, realm.intrinsics().big_int64_array_constructor(), attr);
  116. define_direct_property(vm.names.BigUint64Array, realm.intrinsics().big_uint64_array_constructor(), attr);
  117. define_direct_property(vm.names.Boolean, realm.intrinsics().boolean_constructor(), attr);
  118. define_direct_property(vm.names.DataView, realm.intrinsics().data_view_constructor(), attr);
  119. define_direct_property(vm.names.Date, realm.intrinsics().date_constructor(), attr);
  120. define_direct_property(vm.names.Error, realm.intrinsics().error_constructor(), attr);
  121. define_direct_property(vm.names.EvalError, realm.intrinsics().eval_error_constructor(), attr);
  122. define_direct_property(vm.names.FinalizationRegistry, realm.intrinsics().finalization_registry_constructor(), attr);
  123. define_direct_property(vm.names.Float32Array, realm.intrinsics().float32_array_constructor(), attr);
  124. define_direct_property(vm.names.Float64Array, realm.intrinsics().float64_array_constructor(), attr);
  125. define_direct_property(vm.names.Function, realm.intrinsics().function_constructor(), attr);
  126. define_direct_property(vm.names.Int8Array, realm.intrinsics().int8_array_constructor(), attr);
  127. define_direct_property(vm.names.Int16Array, realm.intrinsics().int16_array_constructor(), attr);
  128. define_direct_property(vm.names.Int32Array, realm.intrinsics().int32_array_constructor(), attr);
  129. define_direct_property(vm.names.Map, realm.intrinsics().map_constructor(), attr);
  130. define_direct_property(vm.names.Number, realm.intrinsics().number_constructor(), attr);
  131. define_direct_property(vm.names.Object, realm.intrinsics().object_constructor(), attr);
  132. define_direct_property(vm.names.Promise, realm.intrinsics().promise_constructor(), attr);
  133. define_direct_property(vm.names.Proxy, realm.intrinsics().proxy_constructor(), attr);
  134. define_direct_property(vm.names.RangeError, realm.intrinsics().range_error_constructor(), attr);
  135. define_direct_property(vm.names.ReferenceError, realm.intrinsics().reference_error_constructor(), attr);
  136. define_direct_property(vm.names.RegExp, realm.intrinsics().regexp_constructor(), attr);
  137. define_direct_property(vm.names.Set, realm.intrinsics().set_constructor(), attr);
  138. define_direct_property(vm.names.ShadowRealm, realm.intrinsics().shadow_realm_constructor(), attr);
  139. define_direct_property(vm.names.String, realm.intrinsics().string_constructor(), attr);
  140. define_direct_property(vm.names.Symbol, realm.intrinsics().symbol_constructor(), attr);
  141. define_direct_property(vm.names.SyntaxError, realm.intrinsics().syntax_error_constructor(), attr);
  142. define_direct_property(vm.names.TypeError, realm.intrinsics().type_error_constructor(), attr);
  143. define_direct_property(vm.names.Uint8Array, realm.intrinsics().uint8_array_constructor(), attr);
  144. define_direct_property(vm.names.Uint8ClampedArray, realm.intrinsics().uint8_clamped_array_constructor(), attr);
  145. define_direct_property(vm.names.Uint16Array, realm.intrinsics().uint16_array_constructor(), attr);
  146. define_direct_property(vm.names.Uint32Array, realm.intrinsics().uint32_array_constructor(), attr);
  147. define_direct_property(vm.names.URIError, realm.intrinsics().uri_error_constructor(), attr);
  148. define_direct_property(vm.names.WeakMap, realm.intrinsics().weak_map_constructor(), attr);
  149. define_direct_property(vm.names.WeakRef, realm.intrinsics().weak_ref_constructor(), attr);
  150. define_direct_property(vm.names.WeakSet, realm.intrinsics().weak_set_constructor(), attr);
  151. // 19.4 Other Properties of the Global Object, https://tc39.es/ecma262/#sec-other-properties-of-the-global-object
  152. define_direct_property(vm.names.Atomics, heap().allocate<AtomicsObject>(realm, realm), attr);
  153. define_direct_property(vm.names.Intl, heap().allocate<Intl::Intl>(realm, realm), attr);
  154. define_direct_property(vm.names.JSON, heap().allocate<JSONObject>(realm, realm), attr);
  155. define_direct_property(vm.names.Math, heap().allocate<MathObject>(realm, realm), attr);
  156. define_direct_property(vm.names.Reflect, heap().allocate<ReflectObject>(realm, realm), attr);
  157. define_direct_property(vm.names.Temporal, heap().allocate<Temporal::Temporal>(realm, realm), attr);
  158. // B.2.1 Additional Properties of the Global Object, https://tc39.es/ecma262/#sec-additional-properties-of-the-global-object
  159. define_native_function(realm, vm.names.escape, escape, 1, attr);
  160. define_native_function(realm, vm.names.unescape, unescape, 1, attr);
  161. // Non-standard
  162. define_direct_property(vm.names.InternalError, realm.intrinsics().internal_error_constructor(), attr);
  163. define_direct_property(vm.names.console, heap().allocate<ConsoleObject>(realm, realm), attr);
  164. define_native_function(realm, vm.names.gc, gc, 0, attr);
  165. // Assign intrinsics and functions that depend on the GlobalObject's native functions
  166. realm.intrinsics().m_eval_function = &get_without_side_effects(vm.names.eval).as_function();
  167. realm.intrinsics().m_number_constructor->define_direct_property(vm.names.parseInt, get_without_side_effects(vm.names.parseInt), attr);
  168. realm.intrinsics().m_number_constructor->define_direct_property(vm.names.parseFloat, get_without_side_effects(vm.names.parseFloat), attr);
  169. }
  170. GlobalObject::~GlobalObject() = default;
  171. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::gc)
  172. {
  173. #ifdef __serenity__
  174. dbgln("Forced garbage collection requested!");
  175. #endif
  176. vm.heap().collect_garbage();
  177. return js_undefined();
  178. }
  179. // 19.2.3 isNaN ( number ), https://tc39.es/ecma262/#sec-isnan-number
  180. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::is_nan)
  181. {
  182. return Value(TRY(vm.argument(0).to_number(vm)).is_nan());
  183. }
  184. // 19.2.2 isFinite ( number ), https://tc39.es/ecma262/#sec-isfinite-number
  185. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::is_finite)
  186. {
  187. return Value(TRY(vm.argument(0).to_number(vm)).is_finite_number());
  188. }
  189. // 19.2.4 parseFloat ( string ), https://tc39.es/ecma262/#sec-parsefloat-string
  190. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::parse_float)
  191. {
  192. if (vm.argument(0).is_number())
  193. return vm.argument(0);
  194. auto input_string = TRY(vm.argument(0).to_string(vm));
  195. auto trimmed_string = MUST(trim_string(vm, js_string(vm, input_string), TrimMode::Left));
  196. for (size_t length = trimmed_string.length(); length > 0; --length) {
  197. auto number = MUST(Value(js_string(vm, trimmed_string.substring(0, length))).to_number(vm));
  198. if (!number.is_nan())
  199. return number;
  200. }
  201. return js_nan();
  202. }
  203. // 19.2.5 parseInt ( string, radix ), https://tc39.es/ecma262/#sec-parseint-string-radix
  204. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::parse_int)
  205. {
  206. // 1. Let inputString be ? ToString(string).
  207. auto input_string = TRY(vm.argument(0).to_string(vm));
  208. // 2. Let S be ! TrimString(inputString, start).
  209. auto string = MUST(trim_string(vm, js_string(vm, input_string), TrimMode::Left));
  210. // 3. Let sign be 1.
  211. auto sign = 1;
  212. // 4. If S is not empty and the first code unit of S is the code unit 0x002D (HYPHEN-MINUS), set sign to -1.
  213. if (!string.is_empty() && string[0] == 0x2D)
  214. sign = -1;
  215. // 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.
  216. auto trimmed_view = string.view();
  217. if (!string.is_empty() && (string[0] == 0x2B || string[0] == 0x2D))
  218. trimmed_view = trimmed_view.substring_view(1);
  219. // 6. Let R be ℝ(? ToInt32(radix)).
  220. auto radix = TRY(vm.argument(1).to_i32(vm));
  221. // 7. Let stripPrefix be true.
  222. auto strip_prefix = true;
  223. // 8. If R ≠ 0, then
  224. if (radix != 0) {
  225. // a. If R < 2 or R > 36, return NaN.
  226. if (radix < 2 || radix > 36)
  227. return js_nan();
  228. // b. If R ≠ 16, set stripPrefix to false.
  229. if (radix != 16)
  230. strip_prefix = false;
  231. }
  232. // 9. Else,
  233. else {
  234. // a. Set R to 10.
  235. radix = 10;
  236. }
  237. // 10. If stripPrefix is true, then
  238. if (strip_prefix) {
  239. // a. If the length of S is at least 2 and the first two code units of S are either "0x" or "0X", then
  240. if (trimmed_view.length() >= 2 && trimmed_view.substring_view(0, 2).equals_ignoring_case("0x"sv)) {
  241. // i. Remove the first two code units from S.
  242. trimmed_view = trimmed_view.substring_view(2);
  243. // ii. Set R to 16.
  244. radix = 16;
  245. }
  246. }
  247. // 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.
  248. // 12. Let Z be the substring of S from 0 to end.
  249. // 13. If Z is empty, return NaN.
  250. // 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.)
  251. auto parse_digit = [&](u32 code_point) -> Optional<u32> {
  252. if (!is_ascii_alphanumeric(code_point))
  253. return {};
  254. auto digit = parse_ascii_base36_digit(code_point);
  255. if (digit >= (u32)radix)
  256. return {};
  257. return digit;
  258. };
  259. bool had_digits = false;
  260. double number = 0;
  261. for (auto code_point : Utf8View(trimmed_view)) {
  262. auto digit = parse_digit(code_point);
  263. if (!digit.has_value())
  264. break;
  265. had_digits = true;
  266. number *= radix;
  267. number += digit.value();
  268. }
  269. if (!had_digits)
  270. return js_nan();
  271. // 15. If mathInt = 0, then
  272. // a. If sign = -1, return -0𝔽.
  273. // b. Return +0𝔽.
  274. // 16. Return 𝔽(sign × mathInt).
  275. return Value(sign * number);
  276. }
  277. // 19.2.1 eval ( x ), https://tc39.es/ecma262/#sec-eval-x
  278. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::eval)
  279. {
  280. return perform_eval(vm, vm.argument(0), CallerMode::NonStrict, EvalMode::Indirect);
  281. }
  282. // 19.2.6.1.1 Encode ( string, unescapedSet ), https://tc39.es/ecma262/#sec-encode
  283. static ThrowCompletionOr<String> encode(VM& vm, String const& string, StringView unescaped_set)
  284. {
  285. auto utf16_string = Utf16String(string);
  286. // 1. Let strLen be the length of string.
  287. auto string_length = utf16_string.length_in_code_units();
  288. // 2. Let R be the empty String.
  289. StringBuilder encoded_builder;
  290. // 3. Let k be 0.
  291. auto k = 0u;
  292. // 4. Repeat,
  293. while (k < string_length) {
  294. // a. If k = strLen, return R.
  295. // Handled below
  296. // b. Let C be the code unit at index k within string.
  297. auto code_unit = utf16_string.code_unit_at(k);
  298. // c. If C is in unescapedSet, then
  299. // NOTE: We assume the unescaped set only contains ascii characters as unescaped_set is a StringView.
  300. if (code_unit < 0x80 && unescaped_set.contains(code_unit)) {
  301. // i. Set k to k + 1.
  302. k++;
  303. // ii. Set R to the string-concatenation of R and C.
  304. encoded_builder.append(code_unit);
  305. }
  306. // d. Else,
  307. else {
  308. // i. Let cp be CodePointAt(string, k).
  309. auto code_point = code_point_at(utf16_string.view(), k);
  310. // ii. If cp.[[IsUnpairedSurrogate]] is true, throw a URIError exception.
  311. if (code_point.is_unpaired_surrogate)
  312. return vm.throw_completion<URIError>(ErrorType::URIMalformed);
  313. // iii. Set k to k + cp.[[CodeUnitCount]].
  314. k += code_point.code_unit_count;
  315. // iv. Let Octets be the List of octets resulting by applying the UTF-8 transformation to cp.[[CodePoint]].
  316. // v. For each element octet of Octets, do
  317. auto nwritten = AK::UnicodeUtils::code_point_to_utf8(code_point.code_point, [&encoded_builder](u8 octet) {
  318. // 1. Set R to the string-concatenation of:
  319. // * R
  320. // * "%"
  321. // * the String representation of octet, formatted as a two-digit uppercase hexadecimal number, padded to the left with a zero if necessary
  322. encoded_builder.appendff("%{:02X}", octet);
  323. });
  324. VERIFY(nwritten > 0);
  325. }
  326. }
  327. return encoded_builder.build();
  328. }
  329. // 19.2.6.1.2 Decode ( string, reservedSet ), https://tc39.es/ecma262/#sec-decode
  330. static ThrowCompletionOr<String> decode(VM& vm, String const& string, StringView reserved_set)
  331. {
  332. StringBuilder decoded_builder;
  333. auto code_point_start_offset = 0u;
  334. auto expected_continuation_bytes = 0;
  335. for (size_t k = 0; k < string.length(); k++) {
  336. auto code_unit = string[k];
  337. if (code_unit != '%') {
  338. if (expected_continuation_bytes > 0)
  339. return vm.throw_completion<URIError>(ErrorType::URIMalformed);
  340. decoded_builder.append(code_unit);
  341. continue;
  342. }
  343. if (k + 2 >= string.length())
  344. return vm.throw_completion<URIError>(ErrorType::URIMalformed);
  345. auto first_digit = decode_hex_digit(string[k + 1]);
  346. if (first_digit >= 16)
  347. return vm.throw_completion<URIError>(ErrorType::URIMalformed);
  348. auto second_digit = decode_hex_digit(string[k + 2]);
  349. if (second_digit >= 16)
  350. return vm.throw_completion<URIError>(ErrorType::URIMalformed);
  351. u8 decoded_code_unit = (first_digit << 4) | second_digit;
  352. k += 2;
  353. if (expected_continuation_bytes > 0) {
  354. decoded_builder.append(decoded_code_unit);
  355. expected_continuation_bytes--;
  356. if (expected_continuation_bytes == 0 && !Utf8View(decoded_builder.string_view().substring_view(code_point_start_offset)).validate())
  357. return vm.throw_completion<URIError>(ErrorType::URIMalformed);
  358. continue;
  359. }
  360. if ((decoded_code_unit & 0x80) == 0) {
  361. if (reserved_set.contains(decoded_code_unit))
  362. decoded_builder.append(string.substring_view(k - 2, 3));
  363. else
  364. decoded_builder.append(decoded_code_unit);
  365. continue;
  366. }
  367. auto leading_ones = count_leading_zeroes_safe(static_cast<u8>(~decoded_code_unit));
  368. if (leading_ones == 1 || leading_ones > 4)
  369. return vm.throw_completion<URIError>(ErrorType::URIMalformed);
  370. code_point_start_offset = decoded_builder.length();
  371. decoded_builder.append(decoded_code_unit);
  372. expected_continuation_bytes = leading_ones - 1;
  373. }
  374. if (expected_continuation_bytes > 0)
  375. return vm.throw_completion<URIError>(ErrorType::URIMalformed);
  376. return decoded_builder.build();
  377. }
  378. // 19.2.6.4 encodeURI ( uri ), https://tc39.es/ecma262/#sec-encodeuri-uri
  379. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::encode_uri)
  380. {
  381. auto uri_string = TRY(vm.argument(0).to_string(vm));
  382. auto encoded = TRY(encode(vm, uri_string, ";/?:@&=+$,abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'()#"sv));
  383. return js_string(vm, move(encoded));
  384. }
  385. // 19.2.6.2 decodeURI ( encodedURI ), https://tc39.es/ecma262/#sec-decodeuri-encodeduri
  386. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::decode_uri)
  387. {
  388. auto uri_string = TRY(vm.argument(0).to_string(vm));
  389. auto decoded = TRY(decode(vm, uri_string, ";/?:@&=+$,#"sv));
  390. return js_string(vm, move(decoded));
  391. }
  392. // 19.2.6.5 encodeURIComponent ( uriComponent ), https://tc39.es/ecma262/#sec-encodeuricomponent-uricomponent
  393. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::encode_uri_component)
  394. {
  395. auto uri_string = TRY(vm.argument(0).to_string(vm));
  396. auto encoded = TRY(encode(vm, uri_string, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'()"sv));
  397. return js_string(vm, move(encoded));
  398. }
  399. // 19.2.6.3 decodeURIComponent ( encodedURIComponent ), https://tc39.es/ecma262/#sec-decodeuricomponent-encodeduricomponent
  400. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::decode_uri_component)
  401. {
  402. auto uri_string = TRY(vm.argument(0).to_string(vm));
  403. auto decoded = TRY(decode(vm, uri_string, ""sv));
  404. return js_string(vm, move(decoded));
  405. }
  406. // B.2.1.1 escape ( string ), https://tc39.es/ecma262/#sec-escape-string
  407. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::escape)
  408. {
  409. auto string = TRY(vm.argument(0).to_string(vm));
  410. StringBuilder escaped;
  411. for (auto code_point : utf8_to_utf16(string)) {
  412. if (code_point < 256) {
  413. if ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*_+-./"sv.contains(code_point))
  414. escaped.append(code_point);
  415. else
  416. escaped.appendff("%{:02X}", code_point);
  417. continue;
  418. }
  419. escaped.appendff("%u{:04X}", code_point);
  420. }
  421. return js_string(vm, escaped.build());
  422. }
  423. // B.2.1.2 unescape ( string ), https://tc39.es/ecma262/#sec-unescape-string
  424. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::unescape)
  425. {
  426. auto string = TRY(vm.argument(0).to_string(vm));
  427. ssize_t length = string.length();
  428. StringBuilder unescaped(length);
  429. for (auto k = 0; k < length; ++k) {
  430. u32 code_point = string[k];
  431. if (code_point == '%') {
  432. 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])) {
  433. 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]);
  434. k += 5;
  435. } else if (k <= length - 3 && is_ascii_hex_digit(string[k + 1]) && is_ascii_hex_digit(string[k + 2])) {
  436. code_point = (parse_ascii_hex_digit(string[k + 1]) << 4) | parse_ascii_hex_digit(string[k + 2]);
  437. k += 2;
  438. }
  439. }
  440. unescaped.append_code_point(code_point);
  441. }
  442. return js_string(vm, unescaped.build());
  443. }
  444. }