GlobalObject.cpp 23 KB

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