GlobalObject.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020, Linus Groh <mail@linusgroh.de>
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright notice, this
  10. * list of conditions and the following disclaimer.
  11. *
  12. * 2. Redistributions in binary form must reproduce the above copyright notice,
  13. * this list of conditions and the following disclaimer in the documentation
  14. * and/or other materials provided with the distribution.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  17. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  20. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  21. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  22. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  23. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  24. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  25. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include <AK/TemporaryChange.h>
  28. #include <AK/Utf8View.h>
  29. #include <LibJS/Console.h>
  30. #include <LibJS/Heap/DeferGC.h>
  31. #include <LibJS/Interpreter.h>
  32. #include <LibJS/Lexer.h>
  33. #include <LibJS/Parser.h>
  34. #include <LibJS/Runtime/ArrayBufferConstructor.h>
  35. #include <LibJS/Runtime/ArrayBufferPrototype.h>
  36. #include <LibJS/Runtime/ArrayConstructor.h>
  37. #include <LibJS/Runtime/ArrayIteratorPrototype.h>
  38. #include <LibJS/Runtime/ArrayPrototype.h>
  39. #include <LibJS/Runtime/BigIntConstructor.h>
  40. #include <LibJS/Runtime/BigIntPrototype.h>
  41. #include <LibJS/Runtime/BooleanConstructor.h>
  42. #include <LibJS/Runtime/BooleanPrototype.h>
  43. #include <LibJS/Runtime/ConsoleObject.h>
  44. #include <LibJS/Runtime/DateConstructor.h>
  45. #include <LibJS/Runtime/DatePrototype.h>
  46. #include <LibJS/Runtime/ErrorConstructor.h>
  47. #include <LibJS/Runtime/ErrorPrototype.h>
  48. #include <LibJS/Runtime/FunctionConstructor.h>
  49. #include <LibJS/Runtime/FunctionPrototype.h>
  50. #include <LibJS/Runtime/GlobalObject.h>
  51. #include <LibJS/Runtime/IteratorPrototype.h>
  52. #include <LibJS/Runtime/JSONObject.h>
  53. #include <LibJS/Runtime/MathObject.h>
  54. #include <LibJS/Runtime/NativeFunction.h>
  55. #include <LibJS/Runtime/NumberConstructor.h>
  56. #include <LibJS/Runtime/NumberPrototype.h>
  57. #include <LibJS/Runtime/Object.h>
  58. #include <LibJS/Runtime/ObjectConstructor.h>
  59. #include <LibJS/Runtime/ObjectPrototype.h>
  60. #include <LibJS/Runtime/PromiseConstructor.h>
  61. #include <LibJS/Runtime/PromisePrototype.h>
  62. #include <LibJS/Runtime/ProxyConstructor.h>
  63. #include <LibJS/Runtime/ReflectObject.h>
  64. #include <LibJS/Runtime/RegExpConstructor.h>
  65. #include <LibJS/Runtime/RegExpPrototype.h>
  66. #include <LibJS/Runtime/Shape.h>
  67. #include <LibJS/Runtime/StringConstructor.h>
  68. #include <LibJS/Runtime/StringIteratorPrototype.h>
  69. #include <LibJS/Runtime/StringPrototype.h>
  70. #include <LibJS/Runtime/SymbolConstructor.h>
  71. #include <LibJS/Runtime/SymbolPrototype.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 <ctype.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. set_prototype(m_object_prototype);
  99. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
  100. if (!m_##snake_name##_prototype) \
  101. m_##snake_name##_prototype = heap().allocate<PrototypeName>(*this, *this);
  102. JS_ENUMERATE_BUILTIN_TYPES
  103. #undef __JS_ENUMERATE
  104. #define __JS_ENUMERATE(ClassName, snake_name) \
  105. if (!m_##snake_name##_prototype) \
  106. m_##snake_name##_prototype = heap().allocate<ClassName##Prototype>(*this, *this);
  107. JS_ENUMERATE_ITERATOR_PROTOTYPES
  108. #undef __JS_ENUMERATE
  109. u8 attr = Attribute::Writable | Attribute::Configurable;
  110. define_native_function(vm.names.gc, gc, 0, attr);
  111. define_native_function(vm.names.isNaN, is_nan, 1, attr);
  112. define_native_function(vm.names.isFinite, is_finite, 1, attr);
  113. define_native_function(vm.names.parseFloat, parse_float, 1, attr);
  114. define_native_function(vm.names.parseInt, parse_int, 1, attr);
  115. define_native_function(vm.names.eval, eval, 1, attr);
  116. define_property(vm.names.NaN, js_nan(), 0);
  117. define_property(vm.names.Infinity, js_infinity(), 0);
  118. define_property(vm.names.undefined, js_undefined(), 0);
  119. define_property(vm.names.globalThis, this, attr);
  120. define_property(vm.names.console, heap().allocate<ConsoleObject>(*this, *this), attr);
  121. define_property(vm.names.Math, heap().allocate<MathObject>(*this, *this), attr);
  122. define_property(vm.names.JSON, heap().allocate<JSONObject>(*this, *this), attr);
  123. define_property(vm.names.Reflect, heap().allocate<ReflectObject>(*this, *this), attr);
  124. add_constructor(vm.names.Array, m_array_constructor, m_array_prototype);
  125. add_constructor(vm.names.ArrayBuffer, m_array_buffer_constructor, m_array_buffer_prototype);
  126. add_constructor(vm.names.BigInt, m_bigint_constructor, m_bigint_prototype);
  127. add_constructor(vm.names.Boolean, m_boolean_constructor, m_boolean_prototype);
  128. add_constructor(vm.names.Date, m_date_constructor, m_date_prototype);
  129. add_constructor(vm.names.Error, m_error_constructor, m_error_prototype);
  130. add_constructor(vm.names.Function, m_function_constructor, m_function_prototype);
  131. add_constructor(vm.names.Number, m_number_constructor, m_number_prototype);
  132. add_constructor(vm.names.Object, m_object_constructor, m_object_prototype);
  133. add_constructor(vm.names.Promise, m_promise_constructor, m_promise_prototype);
  134. add_constructor(vm.names.Proxy, m_proxy_constructor, nullptr);
  135. add_constructor(vm.names.RegExp, m_regexp_constructor, m_regexp_prototype);
  136. add_constructor(vm.names.String, m_string_constructor, m_string_prototype);
  137. add_constructor(vm.names.Symbol, m_symbol_constructor, m_symbol_prototype);
  138. initialize_constructor(vm.names.TypedArray, m_typed_array_constructor, m_typed_array_prototype);
  139. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
  140. add_constructor(vm.names.ClassName, m_##snake_name##_constructor, m_##snake_name##_prototype);
  141. JS_ENUMERATE_ERROR_SUBCLASSES
  142. JS_ENUMERATE_TYPED_ARRAYS
  143. #undef __JS_ENUMERATE
  144. }
  145. GlobalObject::~GlobalObject()
  146. {
  147. }
  148. void GlobalObject::visit_edges(Visitor& visitor)
  149. {
  150. Base::visit_edges(visitor);
  151. visitor.visit(m_empty_object_shape);
  152. visitor.visit(m_new_object_shape);
  153. visitor.visit(m_new_script_function_prototype_object_shape);
  154. visitor.visit(m_proxy_constructor);
  155. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
  156. visitor.visit(m_##snake_name##_constructor); \
  157. visitor.visit(m_##snake_name##_prototype);
  158. JS_ENUMERATE_ERROR_SUBCLASSES
  159. JS_ENUMERATE_BUILTIN_TYPES
  160. #undef __JS_ENUMERATE
  161. #define __JS_ENUMERATE(ClassName, snake_name) \
  162. visitor.visit(m_##snake_name##_prototype);
  163. JS_ENUMERATE_ITERATOR_PROTOTYPES
  164. #undef __JS_ENUMERATE
  165. }
  166. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::gc)
  167. {
  168. dbgln("Forced garbage collection requested!");
  169. vm.heap().collect_garbage();
  170. return js_undefined();
  171. }
  172. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::is_nan)
  173. {
  174. auto number = vm.argument(0).to_number(global_object);
  175. if (vm.exception())
  176. return {};
  177. return Value(number.is_nan());
  178. }
  179. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::is_finite)
  180. {
  181. auto number = vm.argument(0).to_number(global_object);
  182. if (vm.exception())
  183. return {};
  184. return Value(number.is_finite_number());
  185. }
  186. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::parse_float)
  187. {
  188. if (vm.argument(0).is_number())
  189. return vm.argument(0);
  190. auto string = vm.argument(0).to_string(global_object);
  191. if (vm.exception())
  192. return {};
  193. for (size_t length = string.length(); length > 0; --length) {
  194. // This can't throw, so no exception check is fine.
  195. auto number = Value(js_string(vm, string.substring(0, length))).to_number(global_object);
  196. if (!number.is_nan())
  197. return number;
  198. }
  199. return js_nan();
  200. }
  201. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::parse_int)
  202. {
  203. // 18.2.5 parseInt ( string, radix )
  204. auto input_string = vm.argument(0).to_string(global_object);
  205. if (vm.exception())
  206. return {};
  207. // FIXME: There's a bunch of unnecessary string copying here.
  208. double sign = 1;
  209. auto s = input_string.trim_whitespace(TrimMode::Left);
  210. if (!s.is_empty() && s[0] == '-')
  211. sign = -1;
  212. if (!s.is_empty() && (s[0] == '+' || s[0] == '-'))
  213. s = s.substring(1, s.length() - 1);
  214. auto radix = vm.argument(1).to_i32(global_object);
  215. if (vm.exception())
  216. return {};
  217. bool strip_prefix = true;
  218. if (radix != 0) {
  219. if (radix < 2 || radix > 36)
  220. return js_nan();
  221. if (radix != 16)
  222. strip_prefix = false;
  223. } else {
  224. radix = 10;
  225. }
  226. if (strip_prefix) {
  227. if (s.length() >= 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) {
  228. s = s.substring(2, s.length() - 2);
  229. radix = 16;
  230. }
  231. }
  232. auto parse_digit = [&](u32 codepoint, i32 radix) -> Optional<i32> {
  233. i32 digit = -1;
  234. if (isdigit(codepoint))
  235. digit = codepoint - '0';
  236. else if (islower(codepoint))
  237. digit = 10 + (codepoint - 'a');
  238. else if (isupper(codepoint))
  239. digit = 10 + (codepoint - 'A');
  240. if (digit == -1 || digit >= radix)
  241. return {};
  242. return digit;
  243. };
  244. bool had_digits = false;
  245. double number = 0;
  246. for (auto codepoint : Utf8View(s)) {
  247. auto digit = parse_digit(codepoint, radix);
  248. if (!digit.has_value())
  249. break;
  250. had_digits = true;
  251. number *= radix;
  252. number += digit.value();
  253. }
  254. if (!had_digits)
  255. return js_nan();
  256. return Value(sign * number);
  257. }
  258. Optional<Variable> GlobalObject::get_from_scope(const FlyString& name) const
  259. {
  260. auto value = get(name);
  261. if (value.is_empty())
  262. return {};
  263. return Variable { value, DeclarationKind::Var };
  264. }
  265. void GlobalObject::put_to_scope(const FlyString& name, Variable variable)
  266. {
  267. put(name, variable.value);
  268. }
  269. bool GlobalObject::has_this_binding() const
  270. {
  271. return true;
  272. }
  273. Value GlobalObject::get_this_binding(GlobalObject&) const
  274. {
  275. return Value(this);
  276. }
  277. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::eval)
  278. {
  279. if (!vm.argument(0).is_string())
  280. return vm.argument(0);
  281. auto& code_string = vm.argument(0).as_string();
  282. JS::Parser parser { JS::Lexer { code_string.string() } };
  283. auto program = parser.parse_program();
  284. if (parser.has_errors()) {
  285. auto& error = parser.errors()[0];
  286. vm.throw_exception<SyntaxError>(global_object, error.to_string());
  287. return {};
  288. }
  289. auto& caller_frame = vm.call_stack().at(vm.call_stack().size() - 2);
  290. TemporaryChange scope_change(vm.call_frame().scope, caller_frame->scope);
  291. vm.interpreter().execute_statement(global_object, program);
  292. if (vm.exception())
  293. return {};
  294. return vm.last_value();
  295. }
  296. }