GlobalObject.cpp 20 KB

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