GlobalObject.cpp 24 KB

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