GlobalObject.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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/ProxyConstructor.h>
  61. #include <LibJS/Runtime/ReflectObject.h>
  62. #include <LibJS/Runtime/RegExpConstructor.h>
  63. #include <LibJS/Runtime/RegExpPrototype.h>
  64. #include <LibJS/Runtime/Shape.h>
  65. #include <LibJS/Runtime/StringConstructor.h>
  66. #include <LibJS/Runtime/StringIteratorPrototype.h>
  67. #include <LibJS/Runtime/StringPrototype.h>
  68. #include <LibJS/Runtime/SymbolConstructor.h>
  69. #include <LibJS/Runtime/SymbolPrototype.h>
  70. #include <LibJS/Runtime/TypedArray.h>
  71. #include <LibJS/Runtime/TypedArrayConstructor.h>
  72. #include <LibJS/Runtime/TypedArrayPrototype.h>
  73. #include <LibJS/Runtime/Value.h>
  74. #include <ctype.h>
  75. namespace JS {
  76. GlobalObject::GlobalObject()
  77. : ScopeObject(GlobalObjectTag::Tag)
  78. , m_console(make<Console>(*this))
  79. {
  80. }
  81. void GlobalObject::initialize_global_object()
  82. {
  83. auto& vm = this->vm();
  84. ensure_shape_is_unique();
  85. // These are done first since other prototypes depend on their presence.
  86. m_empty_object_shape = heap().allocate_without_global_object<Shape>(*this);
  87. m_object_prototype = heap().allocate_without_global_object<ObjectPrototype>(*this);
  88. m_function_prototype = heap().allocate_without_global_object<FunctionPrototype>(*this);
  89. m_new_object_shape = vm.heap().allocate_without_global_object<Shape>(*this);
  90. m_new_object_shape->set_prototype_without_transition(m_object_prototype);
  91. m_new_script_function_prototype_object_shape = vm.heap().allocate_without_global_object<Shape>(*this);
  92. m_new_script_function_prototype_object_shape->set_prototype_without_transition(m_object_prototype);
  93. m_new_script_function_prototype_object_shape->add_property_without_transition(vm.names.constructor, Attribute::Writable | Attribute::Configurable);
  94. static_cast<FunctionPrototype*>(m_function_prototype)->initialize(*this);
  95. static_cast<ObjectPrototype*>(m_object_prototype)->initialize(*this);
  96. set_prototype(m_object_prototype);
  97. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
  98. if (!m_##snake_name##_prototype) \
  99. m_##snake_name##_prototype = heap().allocate<PrototypeName>(*this, *this);
  100. JS_ENUMERATE_BUILTIN_TYPES
  101. #undef __JS_ENUMERATE
  102. #define __JS_ENUMERATE(ClassName, snake_name) \
  103. if (!m_##snake_name##_prototype) \
  104. m_##snake_name##_prototype = heap().allocate<ClassName##Prototype>(*this, *this);
  105. JS_ENUMERATE_ITERATOR_PROTOTYPES
  106. #undef __JS_ENUMERATE
  107. u8 attr = Attribute::Writable | Attribute::Configurable;
  108. define_native_function(vm.names.gc, gc, 0, attr);
  109. define_native_function(vm.names.isNaN, is_nan, 1, attr);
  110. define_native_function(vm.names.isFinite, is_finite, 1, attr);
  111. define_native_function(vm.names.parseFloat, parse_float, 1, attr);
  112. define_native_function(vm.names.parseInt, parse_int, 1, attr);
  113. define_native_function(vm.names.eval, eval, 1, attr);
  114. define_property(vm.names.NaN, js_nan(), 0);
  115. define_property(vm.names.Infinity, js_infinity(), 0);
  116. define_property(vm.names.undefined, js_undefined(), 0);
  117. define_property(vm.names.globalThis, this, attr);
  118. define_property(vm.names.console, heap().allocate<ConsoleObject>(*this, *this), attr);
  119. define_property(vm.names.Math, heap().allocate<MathObject>(*this, *this), attr);
  120. define_property(vm.names.JSON, heap().allocate<JSONObject>(*this, *this), attr);
  121. define_property(vm.names.Reflect, heap().allocate<ReflectObject>(*this, *this), attr);
  122. add_constructor(vm.names.Array, m_array_constructor, m_array_prototype);
  123. add_constructor(vm.names.ArrayBuffer, m_array_buffer_constructor, m_array_buffer_prototype);
  124. add_constructor(vm.names.BigInt, m_bigint_constructor, m_bigint_prototype);
  125. add_constructor(vm.names.Boolean, m_boolean_constructor, m_boolean_prototype);
  126. add_constructor(vm.names.Date, m_date_constructor, m_date_prototype);
  127. add_constructor(vm.names.Error, m_error_constructor, m_error_prototype);
  128. add_constructor(vm.names.Function, m_function_constructor, m_function_prototype);
  129. add_constructor(vm.names.Number, m_number_constructor, m_number_prototype);
  130. add_constructor(vm.names.Object, m_object_constructor, m_object_prototype);
  131. add_constructor(vm.names.Proxy, m_proxy_constructor, nullptr);
  132. add_constructor(vm.names.RegExp, m_regexp_constructor, m_regexp_prototype);
  133. add_constructor(vm.names.String, m_string_constructor, m_string_prototype);
  134. add_constructor(vm.names.Symbol, m_symbol_constructor, m_symbol_prototype);
  135. initialize_constructor(vm.names.TypedArray, m_typed_array_constructor, m_typed_array_prototype);
  136. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
  137. add_constructor(vm.names.ClassName, m_##snake_name##_constructor, m_##snake_name##_prototype);
  138. JS_ENUMERATE_ERROR_SUBCLASSES
  139. JS_ENUMERATE_TYPED_ARRAYS
  140. #undef __JS_ENUMERATE
  141. }
  142. GlobalObject::~GlobalObject()
  143. {
  144. }
  145. void GlobalObject::visit_edges(Visitor& visitor)
  146. {
  147. Base::visit_edges(visitor);
  148. visitor.visit(m_empty_object_shape);
  149. visitor.visit(m_new_object_shape);
  150. visitor.visit(m_new_script_function_prototype_object_shape);
  151. visitor.visit(m_proxy_constructor);
  152. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
  153. visitor.visit(m_##snake_name##_constructor); \
  154. visitor.visit(m_##snake_name##_prototype);
  155. JS_ENUMERATE_ERROR_SUBCLASSES
  156. JS_ENUMERATE_BUILTIN_TYPES
  157. #undef __JS_ENUMERATE
  158. #define __JS_ENUMERATE(ClassName, snake_name) \
  159. visitor.visit(m_##snake_name##_prototype);
  160. JS_ENUMERATE_ITERATOR_PROTOTYPES
  161. #undef __JS_ENUMERATE
  162. }
  163. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::gc)
  164. {
  165. dbgln("Forced garbage collection requested!");
  166. vm.heap().collect_garbage();
  167. return js_undefined();
  168. }
  169. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::is_nan)
  170. {
  171. auto number = vm.argument(0).to_number(global_object);
  172. if (vm.exception())
  173. return {};
  174. return Value(number.is_nan());
  175. }
  176. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::is_finite)
  177. {
  178. auto number = vm.argument(0).to_number(global_object);
  179. if (vm.exception())
  180. return {};
  181. return Value(number.is_finite_number());
  182. }
  183. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::parse_float)
  184. {
  185. if (vm.argument(0).is_number())
  186. return vm.argument(0);
  187. auto string = vm.argument(0).to_string(global_object);
  188. if (vm.exception())
  189. return {};
  190. for (size_t length = string.length(); length > 0; --length) {
  191. // This can't throw, so no exception check is fine.
  192. auto number = Value(js_string(vm, string.substring(0, length))).to_number(global_object);
  193. if (!number.is_nan())
  194. return number;
  195. }
  196. return js_nan();
  197. }
  198. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::parse_int)
  199. {
  200. // 18.2.5 parseInt ( string, radix )
  201. auto input_string = vm.argument(0).to_string(global_object);
  202. if (vm.exception())
  203. return {};
  204. // FIXME: There's a bunch of unnecessary string copying here.
  205. double sign = 1;
  206. auto s = input_string.trim_whitespace(TrimMode::Left);
  207. if (!s.is_empty() && s[0] == '-')
  208. sign = -1;
  209. if (!s.is_empty() && (s[0] == '+' || s[0] == '-'))
  210. s = s.substring(1, s.length() - 1);
  211. auto radix = vm.argument(1).to_i32(global_object);
  212. if (vm.exception())
  213. return {};
  214. bool strip_prefix = true;
  215. if (radix != 0) {
  216. if (radix < 2 || radix > 36)
  217. return js_nan();
  218. if (radix != 16)
  219. strip_prefix = false;
  220. } else {
  221. radix = 10;
  222. }
  223. if (strip_prefix) {
  224. if (s.length() >= 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) {
  225. s = s.substring(2, s.length() - 2);
  226. radix = 16;
  227. }
  228. }
  229. auto parse_digit = [&](u32 codepoint, i32 radix) -> Optional<i32> {
  230. i32 digit = -1;
  231. if (isdigit(codepoint))
  232. digit = codepoint - '0';
  233. else if (islower(codepoint))
  234. digit = 10 + (codepoint - 'a');
  235. else if (isupper(codepoint))
  236. digit = 10 + (codepoint - 'A');
  237. if (digit == -1 || digit >= radix)
  238. return {};
  239. return digit;
  240. };
  241. bool had_digits = false;
  242. double number = 0;
  243. for (auto codepoint : Utf8View(s)) {
  244. auto digit = parse_digit(codepoint, radix);
  245. if (!digit.has_value())
  246. break;
  247. had_digits = true;
  248. number *= radix;
  249. number += digit.value();
  250. }
  251. if (!had_digits)
  252. return js_nan();
  253. return Value(sign * number);
  254. }
  255. Optional<Variable> GlobalObject::get_from_scope(const FlyString& name) const
  256. {
  257. auto value = get(name);
  258. if (value.is_empty())
  259. return {};
  260. return Variable { value, DeclarationKind::Var };
  261. }
  262. void GlobalObject::put_to_scope(const FlyString& name, Variable variable)
  263. {
  264. put(name, variable.value);
  265. }
  266. bool GlobalObject::has_this_binding() const
  267. {
  268. return true;
  269. }
  270. Value GlobalObject::get_this_binding(GlobalObject&) const
  271. {
  272. return Value(this);
  273. }
  274. JS_DEFINE_NATIVE_FUNCTION(GlobalObject::eval)
  275. {
  276. auto code = vm.argument(0).to_string(global_object);
  277. if (code.is_null())
  278. return {};
  279. JS::Parser parser { JS::Lexer { code } };
  280. auto program = parser.parse_program();
  281. if (parser.has_errors()) {
  282. auto& error = parser.errors()[0];
  283. vm.throw_exception<SyntaxError>(global_object, error.to_string());
  284. return {};
  285. }
  286. auto& caller_frame = vm.call_stack().at(vm.call_stack().size() - 2);
  287. TemporaryChange scope_change(vm.call_frame().scope, caller_frame->scope);
  288. vm.interpreter().execute_statement(global_object, program);
  289. if (vm.exception())
  290. return {};
  291. return vm.last_value();
  292. }
  293. }