Object.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/String.h>
  27. #include <LibJS/Heap/Heap.h>
  28. #include <LibJS/Interpreter.h>
  29. #include <LibJS/Runtime/Accessor.h>
  30. #include <LibJS/Runtime/Array.h>
  31. #include <LibJS/Runtime/Error.h>
  32. #include <LibJS/Runtime/GlobalObject.h>
  33. #include <LibJS/Runtime/NativeFunction.h>
  34. #include <LibJS/Runtime/NativeProperty.h>
  35. #include <LibJS/Runtime/Object.h>
  36. #include <LibJS/Runtime/Shape.h>
  37. #include <LibJS/Runtime/StringObject.h>
  38. #include <LibJS/Runtime/Value.h>
  39. namespace JS {
  40. Object* Object::create_empty(Interpreter&, GlobalObject& global_object)
  41. {
  42. return global_object.heap().allocate<Object>(global_object.object_prototype());
  43. }
  44. Object::Object(Object* prototype)
  45. {
  46. if (prototype) {
  47. m_shape = interpreter().global_object().empty_object_shape();
  48. set_prototype(prototype);
  49. } else {
  50. m_shape = interpreter().heap().allocate<Shape>();
  51. }
  52. }
  53. Object::~Object()
  54. {
  55. }
  56. Object* Object::prototype()
  57. {
  58. return shape().prototype();
  59. }
  60. const Object* Object::prototype() const
  61. {
  62. return shape().prototype();
  63. }
  64. void Object::set_prototype(Object* new_prototype)
  65. {
  66. if (prototype() == new_prototype)
  67. return;
  68. if (shape().is_unique()) {
  69. shape().set_prototype_without_transition(new_prototype);
  70. return;
  71. }
  72. m_shape = m_shape->create_prototype_transition(new_prototype);
  73. }
  74. bool Object::has_prototype(const Object* prototype) const
  75. {
  76. for (auto* object = this->prototype(); object; object = object->prototype()) {
  77. if (object == prototype)
  78. return true;
  79. }
  80. return false;
  81. }
  82. Value Object::get_own_property(const Object& this_object, const FlyString& property_name) const
  83. {
  84. auto metadata = shape().lookup(property_name);
  85. if (!metadata.has_value())
  86. return {};
  87. auto value_here = m_storage[metadata.value().offset];
  88. ASSERT(!value_here.is_empty());
  89. if (value_here.is_accessor()) {
  90. return value_here.as_accessor().call_getter(Value(const_cast<Object*>(this)));
  91. }
  92. if (value_here.is_object() && value_here.as_object().is_native_property()) {
  93. auto& native_property = static_cast<const NativeProperty&>(value_here.as_object());
  94. auto& interpreter = const_cast<Object*>(this)->interpreter();
  95. auto& call_frame = interpreter.push_call_frame();
  96. call_frame.this_value = const_cast<Object*>(&this_object);
  97. auto result = native_property.get(interpreter);
  98. interpreter.pop_call_frame();
  99. return result;
  100. }
  101. return value_here;
  102. }
  103. Value Object::get_own_properties(const Object& this_object, GetOwnPropertyMode kind, u8 attributes) const
  104. {
  105. auto* properties_array = Array::create(interpreter().global_object());
  106. // FIXME: Support generic iterables
  107. if (this_object.is_string_object()) {
  108. auto str = static_cast<const StringObject&>(this_object).primitive_string().string();
  109. for (size_t i = 0; i < str.length(); ++i) {
  110. if (kind == GetOwnPropertyMode::Key) {
  111. properties_array->put_by_index(i, js_string(interpreter(), String::number(i)));
  112. } else if (kind == GetOwnPropertyMode::Value) {
  113. properties_array->put_by_index(i, js_string(interpreter(), String::format("%c", str[i])));
  114. } else {
  115. auto* entry_array = Array::create(interpreter().global_object());
  116. entry_array->put_by_index(0, js_string(interpreter(), String::number(i)));
  117. entry_array->put_by_index(1, js_string(interpreter(), String::format("%c", str[i])));
  118. properties_array->put_by_index(i, entry_array);
  119. }
  120. }
  121. return properties_array;
  122. }
  123. size_t property_index = 0;
  124. for (size_t i = 0; i < m_elements.size(); ++i) {
  125. if (m_elements.at(i).is_empty())
  126. continue;
  127. if (kind == GetOwnPropertyMode::Key) {
  128. properties_array->put_by_index(property_index, js_string(interpreter(), String::number(i)));
  129. } else if (kind == GetOwnPropertyMode::Value) {
  130. properties_array->put_by_index(property_index, m_elements.at(i));
  131. } else {
  132. auto* entry_array = Array::create(interpreter().global_object());
  133. entry_array->put_by_index(0, js_string(interpreter(), String::number(i)));
  134. entry_array->put_by_index(1, m_elements.at(i));
  135. properties_array->put_by_index(property_index, entry_array);
  136. }
  137. ++property_index;
  138. }
  139. for (auto& it : this_object.shape().property_table_ordered()) {
  140. if (it.value.attributes & attributes) {
  141. size_t offset = it.value.offset + property_index;
  142. if (kind == GetOwnPropertyMode::Key) {
  143. properties_array->put_by_index(offset, js_string(interpreter(), it.key));
  144. } else if (kind == GetOwnPropertyMode::Value) {
  145. properties_array->put_by_index(offset, this_object.get(it.key));
  146. } else {
  147. auto* entry_array = Array::create(interpreter().global_object());
  148. entry_array->put_by_index(0, js_string(interpreter(), it.key));
  149. entry_array->put_by_index(1, this_object.get(it.key));
  150. properties_array->put_by_index(offset, entry_array);
  151. }
  152. }
  153. }
  154. return properties_array;
  155. }
  156. Value Object::get_own_property_descriptor(const FlyString& property_name) const
  157. {
  158. auto metadata = shape().lookup(property_name);
  159. if (!metadata.has_value())
  160. return js_undefined();
  161. auto value = get(property_name);
  162. if (interpreter().exception())
  163. return {};
  164. auto* descriptor = Object::create_empty(interpreter(), interpreter().global_object());
  165. descriptor->put("enumerable", Value((metadata.value().attributes & Attribute::Enumerable) != 0));
  166. descriptor->put("configurable", Value((metadata.value().attributes & Attribute::Configurable) != 0));
  167. if (value.is_accessor()) {
  168. auto& pair = value.as_accessor();
  169. descriptor->put("get", pair.getter());
  170. descriptor->put("set", pair.setter());
  171. } else {
  172. descriptor->put("value", value.value_or(js_undefined()));
  173. descriptor->put("writable", Value((metadata.value().attributes & Attribute::Writable) != 0));
  174. }
  175. return descriptor;
  176. }
  177. void Object::set_shape(Shape& new_shape)
  178. {
  179. m_storage.resize(new_shape.property_count());
  180. m_shape = &new_shape;
  181. }
  182. bool Object::define_property(const FlyString& property_name, const Object& descriptor, bool throw_exceptions)
  183. {
  184. bool is_accessor_property = descriptor.has_property("get") || descriptor.has_property("set");
  185. u8 configurable = descriptor.get("configurable").value_or(Value(false)).to_boolean() * Attribute::Configurable;
  186. if (interpreter().exception())
  187. return {};
  188. u8 enumerable = descriptor.get("enumerable").value_or(Value(false)).to_boolean() * Attribute::Enumerable;
  189. if (interpreter().exception())
  190. return {};
  191. u8 attributes = configurable | enumerable;
  192. if (is_accessor_property) {
  193. if (descriptor.has_property("value") || descriptor.has_property("writable")) {
  194. if (throw_exceptions)
  195. interpreter().throw_exception<TypeError>("Accessor property descriptors cannot specify a value or writable key");
  196. return false;
  197. }
  198. auto getter = descriptor.get("get");
  199. if (interpreter().exception())
  200. return {};
  201. auto setter = descriptor.get("set");
  202. if (interpreter().exception())
  203. return {};
  204. if (!(getter.is_empty() || getter.is_undefined() || getter.is_function())) {
  205. interpreter().throw_exception<TypeError>("Accessor descriptor's 'get' field must be a function or undefined");
  206. return false;
  207. }
  208. if (!(setter.is_empty() || setter.is_undefined() || setter.is_function())) {
  209. interpreter().throw_exception<TypeError>("Accessor descriptor's 'set' field must be a function or undefined");
  210. return false;
  211. }
  212. // FIXME: Throw a TypeError if the setter does not take any arguments
  213. dbg() << "Defining new property " << property_name << " with accessor descriptor { attributes=" << attributes
  214. << " , getter=" << (getter.is_empty() ? "<empty>" : getter.to_string_without_side_effects())
  215. << ", setter=" << (setter.is_empty() ? "<empty>" : setter.to_string_without_side_effects()) << "}";
  216. return put_own_property(*this, property_name, attributes, Accessor::create(interpreter(), getter, setter), PutOwnPropertyMode::DefineProperty, throw_exceptions);
  217. }
  218. auto value = descriptor.get("value");
  219. if (interpreter().exception())
  220. return {};
  221. u8 writable = descriptor.get("writable").value_or(Value(false)).to_boolean() * Attribute::Writable;
  222. if (interpreter().exception())
  223. return {};
  224. attributes |= writable;
  225. dbg() << "Defining new property " << property_name << " with data descriptor { attributes=" << attributes
  226. << ", value=" << (value.is_empty() ? "<empty>" : value.to_string_without_side_effects()) << " }";
  227. return put_own_property(*this, property_name, attributes, value, PutOwnPropertyMode::DefineProperty, throw_exceptions);
  228. }
  229. bool Object::put_own_property(Object& this_object, const FlyString& property_name, u8 attributes, Value value, PutOwnPropertyMode mode, bool throw_exceptions)
  230. {
  231. ASSERT(!(mode == PutOwnPropertyMode::Put && value.is_accessor()));
  232. if (value.is_accessor()) {
  233. auto& accessor = value.as_accessor();
  234. if (accessor.getter().is_function())
  235. attributes |= Attribute::HasGet;
  236. if (accessor.setter().is_function())
  237. attributes |= Attribute::HasSet;
  238. }
  239. auto metadata = shape().lookup(property_name);
  240. bool new_property = !metadata.has_value();
  241. if (new_property) {
  242. if (!m_shape->is_unique() && shape().property_count() > 100) {
  243. // If you add more than 100 properties to an object, let's stop doing
  244. // transitions to avoid filling up the heap with shapes.
  245. ensure_shape_is_unique();
  246. }
  247. if (m_shape->is_unique()) {
  248. m_shape->add_property_to_unique_shape(property_name, attributes);
  249. m_storage.resize(m_shape->property_count());
  250. } else {
  251. set_shape(*m_shape->create_put_transition(property_name, attributes));
  252. }
  253. metadata = shape().lookup(property_name);
  254. ASSERT(metadata.has_value());
  255. }
  256. if (!new_property && mode == PutOwnPropertyMode::DefineProperty && !(metadata.value().attributes & Attribute::Configurable) && attributes != metadata.value().attributes) {
  257. dbg() << "Disallow reconfig of non-configurable property";
  258. if (throw_exceptions)
  259. interpreter().throw_exception<TypeError>(String::format("Cannot change attributes of non-configurable property '%s'", property_name.characters()));
  260. return false;
  261. }
  262. if (mode == PutOwnPropertyMode::DefineProperty && attributes != metadata.value().attributes) {
  263. if (m_shape->is_unique()) {
  264. m_shape->reconfigure_property_in_unique_shape(property_name, attributes);
  265. } else {
  266. set_shape(*m_shape->create_configure_transition(property_name, attributes));
  267. }
  268. metadata = shape().lookup(property_name);
  269. dbg() << "Reconfigured property " << property_name << ", new shape says offset is " << metadata.value().offset << " and my storage capacity is " << m_storage.size();
  270. }
  271. auto value_here = m_storage[metadata.value().offset];
  272. if (!new_property && mode == PutOwnPropertyMode::Put && !value_here.is_accessor() && !(metadata.value().attributes & Attribute::Writable)) {
  273. dbg() << "Disallow write to non-writable property";
  274. return false;
  275. }
  276. if (value.is_empty())
  277. return true;
  278. if (value_here.is_object() && value_here.as_object().is_native_property()) {
  279. auto& native_property = static_cast<NativeProperty&>(value_here.as_object());
  280. auto& interpreter = const_cast<Object*>(this)->interpreter();
  281. auto& call_frame = interpreter.push_call_frame();
  282. call_frame.this_value = &this_object;
  283. native_property.set(interpreter, value);
  284. interpreter.pop_call_frame();
  285. } else {
  286. m_storage[metadata.value().offset] = value;
  287. }
  288. return true;
  289. }
  290. Value Object::delete_property(PropertyName property_name)
  291. {
  292. ASSERT(property_name.is_valid());
  293. if (property_name.is_number()) {
  294. if (property_name.as_number() < static_cast<i32>(elements().size())) {
  295. elements()[property_name.as_number()] = {};
  296. return Value(true);
  297. }
  298. return Value(true);
  299. }
  300. auto metadata = shape().lookup(property_name.as_string());
  301. if (!metadata.has_value())
  302. return Value(true);
  303. if (!(metadata.value().attributes & Attribute::Configurable))
  304. return Value(false);
  305. size_t deleted_offset = metadata.value().offset;
  306. ensure_shape_is_unique();
  307. shape().remove_property_from_unique_shape(property_name.as_string(), deleted_offset);
  308. m_storage.remove(deleted_offset);
  309. return Value(true);
  310. }
  311. void Object::ensure_shape_is_unique()
  312. {
  313. if (shape().is_unique())
  314. return;
  315. m_shape = m_shape->create_unique_clone();
  316. }
  317. Value Object::get_by_index(i32 property_index) const
  318. {
  319. if (property_index < 0)
  320. return get(String::number(property_index));
  321. const Object* object = this;
  322. while (object) {
  323. if (is_string_object()) {
  324. auto& string = static_cast<const StringObject*>(this)->primitive_string().string();
  325. if (property_index < (i32)string.length())
  326. return js_string(heap(), string.substring(property_index, 1));
  327. return js_undefined();
  328. }
  329. if (static_cast<size_t>(property_index) < object->m_elements.size()) {
  330. auto value = object->m_elements[property_index];
  331. if (value.is_empty())
  332. return {};
  333. return value;
  334. }
  335. object = object->prototype();
  336. }
  337. return {};
  338. }
  339. Value Object::get(const FlyString& property_name) const
  340. {
  341. bool ok;
  342. i32 property_index = property_name.to_int(ok);
  343. if (ok && property_index >= 0)
  344. return get_by_index(property_index);
  345. const Object* object = this;
  346. while (object) {
  347. auto value = object->get_own_property(*this, property_name);
  348. if (!value.is_empty())
  349. return value;
  350. object = object->prototype();
  351. }
  352. return {};
  353. }
  354. Value Object::get(PropertyName property_name) const
  355. {
  356. if (property_name.is_number())
  357. return get_by_index(property_name.as_number());
  358. return get(property_name.as_string());
  359. }
  360. bool Object::put_by_index(i32 property_index, Value value, u8 attributes)
  361. {
  362. ASSERT(!value.is_empty());
  363. if (property_index < 0)
  364. return put(String::number(property_index), value, attributes);
  365. // FIXME: Implement some kind of sparse storage for arrays with huge indices.
  366. // Also: Take attributes into account here
  367. if (static_cast<size_t>(property_index) >= m_elements.size())
  368. m_elements.resize(property_index + 1);
  369. m_elements[property_index] = value;
  370. return true;
  371. }
  372. bool Object::put(const FlyString& property_name, Value value, u8 attributes)
  373. {
  374. ASSERT(!value.is_empty());
  375. bool ok;
  376. i32 property_index = property_name.to_int(ok);
  377. if (ok && property_index >= 0)
  378. return put_by_index(property_index, value, attributes);
  379. // If there's a setter in the prototype chain, we go to the setter.
  380. // Otherwise, it goes in the own property storage.
  381. Object* object = this;
  382. while (object) {
  383. auto metadata = object->shape().lookup(property_name);
  384. if (metadata.has_value()) {
  385. auto value_here = object->m_storage[metadata.value().offset];
  386. if (value_here.is_accessor()) {
  387. value_here.as_accessor().call_setter(Value(this), value);
  388. return true;
  389. }
  390. if (value_here.is_object() && value_here.as_object().is_native_property()) {
  391. auto& native_property = static_cast<NativeProperty&>(value_here.as_object());
  392. auto& interpreter = const_cast<Object*>(this)->interpreter();
  393. auto& call_frame = interpreter.push_call_frame();
  394. call_frame.this_value = this;
  395. native_property.set(interpreter, value);
  396. interpreter.pop_call_frame();
  397. return true;
  398. }
  399. }
  400. object = object->prototype();
  401. }
  402. return put_own_property(*this, property_name, attributes, value, PutOwnPropertyMode::Put);
  403. }
  404. bool Object::put(PropertyName property_name, Value value, u8 attributes)
  405. {
  406. if (property_name.is_number())
  407. return put_by_index(property_name.as_number(), value, attributes);
  408. return put(property_name.as_string(), value, attributes);
  409. }
  410. bool Object::put_native_function(const FlyString& property_name, AK::Function<Value(Interpreter&)> native_function, i32 length, u8 attributes)
  411. {
  412. auto* function = NativeFunction::create(interpreter(), interpreter().global_object(), property_name, move(native_function));
  413. function->put("length", Value(length), Attribute::Configurable);
  414. function->put("name", js_string(heap(), property_name), Attribute::Configurable);
  415. return put(property_name, function, attributes);
  416. }
  417. bool Object::put_native_property(const FlyString& property_name, AK::Function<Value(Interpreter&)> getter, AK::Function<void(Interpreter&, Value)> setter, u8 attributes)
  418. {
  419. return put(property_name, heap().allocate<NativeProperty>(move(getter), move(setter)), attributes);
  420. }
  421. void Object::visit_children(Cell::Visitor& visitor)
  422. {
  423. Cell::visit_children(visitor);
  424. visitor.visit(m_shape);
  425. for (auto& value : m_storage)
  426. visitor.visit(value);
  427. for (auto& value : m_elements)
  428. visitor.visit(value);
  429. }
  430. bool Object::has_property(const FlyString& property_name) const
  431. {
  432. const Object* object = this;
  433. while (object) {
  434. if (object->has_own_property(property_name))
  435. return true;
  436. object = object->prototype();
  437. }
  438. return false;
  439. }
  440. bool Object::has_own_property(const FlyString& property_name) const
  441. {
  442. bool ok;
  443. i32 property_index = property_name.to_int(ok);
  444. if (ok && property_index >= 0) {
  445. if (is_string_object())
  446. return property_index < (i32) static_cast<const StringObject*>(this)->primitive_string().string().length();
  447. if (static_cast<size_t>(property_index) >= m_elements.size())
  448. return false;
  449. return !m_elements[property_index].is_empty();
  450. }
  451. return shape().lookup(property_name).has_value();
  452. }
  453. Value Object::to_primitive(PreferredType preferred_type) const
  454. {
  455. Value result = js_undefined();
  456. switch (preferred_type) {
  457. case PreferredType::Default:
  458. case PreferredType::Number: {
  459. result = value_of();
  460. if (result.is_object()) {
  461. result = to_string();
  462. }
  463. break;
  464. }
  465. case PreferredType::String: {
  466. result = to_string();
  467. if (result.is_object())
  468. result = value_of();
  469. break;
  470. }
  471. }
  472. ASSERT(!result.is_object());
  473. return result;
  474. }
  475. Value Object::to_string() const
  476. {
  477. auto to_string_property = get("toString");
  478. if (to_string_property.is_function()) {
  479. auto& to_string_function = to_string_property.as_function();
  480. auto& interpreter = const_cast<Object*>(this)->interpreter();
  481. auto to_string_result = interpreter.call(to_string_function, const_cast<Object*>(this));
  482. if (to_string_result.is_object())
  483. interpreter.throw_exception<TypeError>("Cannot convert object to string");
  484. if (interpreter.exception())
  485. return {};
  486. auto* string = to_string_result.to_primitive_string(interpreter);
  487. if (interpreter.exception())
  488. return {};
  489. return string;
  490. }
  491. return js_string(heap(), String::format("[object %s]", class_name()));
  492. }
  493. }