ObjectInstance.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Dynamic;
  4. using System.Runtime.CompilerServices;
  5. using Jint.Collections;
  6. using Jint.Native.Array;
  7. using Jint.Native.Boolean;
  8. using Jint.Native.Date;
  9. using Jint.Native.Function;
  10. using Jint.Native.Number;
  11. using Jint.Native.RegExp;
  12. using Jint.Native.String;
  13. using Jint.Native.Symbol;
  14. using Jint.Runtime;
  15. using Jint.Runtime.Descriptors;
  16. using Jint.Runtime.Descriptors.Specialized;
  17. using Jint.Runtime.Interop;
  18. using Jint.Runtime.Interpreter.Expressions;
  19. namespace Jint.Native.Object
  20. {
  21. public class ObjectInstance : JsValue, IEquatable<ObjectInstance>
  22. {
  23. internal StringDictionarySlim<PropertyDescriptor> _properties;
  24. private bool _initialized;
  25. internal ObjectInstance _prototype;
  26. private readonly string _class;
  27. protected readonly Engine _engine;
  28. public ObjectInstance(Engine engine) : this(engine, "Object")
  29. {
  30. }
  31. protected ObjectInstance(Engine engine, string objectClass) : base(Types.Object)
  32. {
  33. _engine = engine;
  34. _class = objectClass;
  35. Extensible = true;
  36. }
  37. public Engine Engine => _engine;
  38. /// <summary>
  39. /// The prototype of this object.
  40. /// </summary>
  41. public ObjectInstance Prototype => GetPrototypeOf();
  42. /// <summary>
  43. /// If true, own properties may be added to the
  44. /// object.
  45. /// </summary>
  46. public virtual bool Extensible { get; private set; }
  47. /// <summary>
  48. /// A String value indicating a specification defined
  49. /// classification of objects.
  50. /// </summary>
  51. public string Class => _class;
  52. public virtual IEnumerable<KeyValuePair<Key, PropertyDescriptor>> GetOwnProperties()
  53. {
  54. EnsureInitialized();
  55. if (_properties != null)
  56. {
  57. foreach (var pair in _properties)
  58. {
  59. yield return pair;
  60. }
  61. }
  62. }
  63. internal virtual List<JsValue> GetOwnPropertyKeys(Types types)
  64. {
  65. EnsureInitialized();
  66. if (_properties == null)
  67. {
  68. return new List<JsValue>();
  69. }
  70. var keys = new List<JsValue>(_properties.Count);
  71. var propertyKeys = new List<JsValue>();
  72. List<JsValue> symbolKeys = null;
  73. foreach (var pair in _properties)
  74. {
  75. if ((pair.Key.Type & types) == 0)
  76. {
  77. continue;
  78. }
  79. var isArrayIndex = ulong.TryParse(pair.Key, out var index);
  80. if (pair.Key.Type != Types.Symbol)
  81. {
  82. if (isArrayIndex)
  83. {
  84. keys.Add(pair.Key);
  85. }
  86. else
  87. {
  88. propertyKeys.Add(pair.Key);
  89. }
  90. }
  91. else
  92. {
  93. symbolKeys ??= new List<JsValue>();
  94. symbolKeys.Add(pair.Key);
  95. }
  96. }
  97. keys.Sort((v1, v2) => TypeConverter.ToNumber(v1).CompareTo(TypeConverter.ToNumber(v2)));
  98. keys.AddRange(propertyKeys);
  99. if (symbolKeys != null)
  100. {
  101. keys.AddRange(symbolKeys);
  102. }
  103. return keys;
  104. }
  105. protected virtual void AddProperty(in Key propertyName, PropertyDescriptor descriptor)
  106. {
  107. if (_properties == null)
  108. {
  109. _properties = new StringDictionarySlim<PropertyDescriptor>();
  110. }
  111. _properties[propertyName] = descriptor;
  112. }
  113. protected virtual bool TryGetProperty(in Key propertyName, out PropertyDescriptor descriptor)
  114. {
  115. if (_properties == null)
  116. {
  117. descriptor = null;
  118. return false;
  119. }
  120. return _properties.TryGetValue(propertyName, out descriptor);
  121. }
  122. public virtual bool HasOwnProperty(in Key propertyName)
  123. {
  124. EnsureInitialized();
  125. return _properties?.ContainsKey(propertyName) == true;
  126. }
  127. public virtual void RemoveOwnProperty(in Key propertyName)
  128. {
  129. EnsureInitialized();
  130. _properties?.Remove(propertyName);
  131. }
  132. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  133. public JsValue Get(in Key propertyName)
  134. {
  135. return Get(propertyName, this);
  136. }
  137. /// <summary>
  138. /// Returns the value of the named property.
  139. /// http://www.ecma-international.org/ecma-262/5.1/#sec-8.12.3
  140. /// </summary>
  141. public virtual JsValue Get(in Key propertyName, JsValue receiver)
  142. {
  143. var desc = GetProperty(propertyName);
  144. return UnwrapJsValue(desc, receiver);
  145. }
  146. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  147. internal JsValue UnwrapJsValue(PropertyDescriptor desc)
  148. {
  149. return UnwrapJsValue(desc, this);
  150. }
  151. internal static JsValue UnwrapJsValue(PropertyDescriptor desc, JsValue thisObject)
  152. {
  153. if (desc == PropertyDescriptor.Undefined)
  154. {
  155. return Undefined;
  156. }
  157. var value = (desc._flags & PropertyFlag.CustomJsValue) != 0
  158. ? desc.CustomValue
  159. : desc._value;
  160. // IsDataDescriptor inlined
  161. if ((desc._flags & (PropertyFlag.WritableSet | PropertyFlag.Writable)) != 0
  162. || !ReferenceEquals(value, null))
  163. {
  164. return value ?? Undefined;
  165. }
  166. var getter = desc.Get ?? Undefined;
  167. if (getter.IsUndefined())
  168. {
  169. return Undefined;
  170. }
  171. // if getter is not undefined it must be ICallable
  172. var callable = getter.TryCast<ICallable>();
  173. return callable.Call(thisObject, Arguments.Empty);
  174. }
  175. /// <summary>
  176. /// Returns the Property Descriptor of the named
  177. /// own property of this object, or undefined if
  178. /// absent.
  179. /// http://www.ecma-international.org/ecma-262/5.1/#sec-8.12.1
  180. /// </summary>
  181. /// <param name="propertyName"></param>
  182. /// <returns></returns>
  183. public virtual PropertyDescriptor GetOwnProperty(in Key propertyName)
  184. {
  185. EnsureInitialized();
  186. PropertyDescriptor descriptor = null;
  187. _properties?.TryGetValue(propertyName, out descriptor);
  188. return descriptor ?? PropertyDescriptor.Undefined;
  189. }
  190. protected internal virtual void SetOwnProperty(in Key propertyName, PropertyDescriptor desc)
  191. {
  192. EnsureInitialized();
  193. if (_properties == null)
  194. {
  195. _properties = new StringDictionarySlim<PropertyDescriptor>();
  196. }
  197. _properties[propertyName] = desc;
  198. }
  199. /// <summary>
  200. /// http://www.ecma-international.org/ecma-262/5.1/#sec-8.12.2
  201. /// </summary>
  202. /// <param name="propertyName"></param>
  203. /// <returns></returns>
  204. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  205. public PropertyDescriptor GetProperty(in Key propertyName)
  206. {
  207. var prop = GetOwnProperty(propertyName);
  208. if (prop != PropertyDescriptor.Undefined)
  209. {
  210. return prop;
  211. }
  212. return Prototype?.GetProperty(propertyName) ?? PropertyDescriptor.Undefined;
  213. }
  214. public bool TryGetValue(in Key propertyName, out JsValue value)
  215. {
  216. value = Undefined;
  217. var desc = GetOwnProperty(propertyName);
  218. if (desc != null && desc != PropertyDescriptor.Undefined)
  219. {
  220. if (desc == PropertyDescriptor.Undefined)
  221. {
  222. return false;
  223. }
  224. var descValue = desc.Value;
  225. if (desc.WritableSet && !ReferenceEquals(descValue, null))
  226. {
  227. value = descValue;
  228. return true;
  229. }
  230. var getter = desc.Get ?? Undefined;
  231. if (getter.IsUndefined())
  232. {
  233. value = Undefined;
  234. return false;
  235. }
  236. // if getter is not undefined it must be ICallable
  237. var callable = getter.TryCast<ICallable>();
  238. value = callable.Call(this, Arguments.Empty);
  239. return true;
  240. }
  241. if (ReferenceEquals(Prototype, null))
  242. {
  243. return false;
  244. }
  245. return Prototype.TryGetValue(propertyName, out value);
  246. }
  247. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  248. public bool Set(Key p, JsValue v, bool throwOnError)
  249. {
  250. if (!Set(p, v, this) && throwOnError)
  251. {
  252. ExceptionHelper.ThrowTypeError(_engine);
  253. }
  254. return true;
  255. }
  256. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  257. public bool Set(in Key propertyName, JsValue value)
  258. {
  259. return Set(propertyName, value, this);
  260. }
  261. /// <summary>
  262. /// http://www.ecma-international.org/ecma-262/#sec-ordinary-object-internal-methods-and-internal-slots-set-p-v-receiver
  263. /// </summary>
  264. public virtual bool Set(in Key propertyName, JsValue value, JsValue receiver)
  265. {
  266. var ownDesc = GetOwnProperty(propertyName);
  267. if (ownDesc == PropertyDescriptor.Undefined)
  268. {
  269. var parent = GetPrototypeOf();
  270. if (!(parent is null))
  271. {
  272. return parent.Set(propertyName, value, receiver);
  273. }
  274. else
  275. {
  276. ownDesc = new PropertyDescriptor(Undefined, PropertyFlag.ConfigurableEnumerableWritable);
  277. }
  278. }
  279. if (ownDesc.IsDataDescriptor())
  280. {
  281. if (!ownDesc.Writable)
  282. {
  283. return false;
  284. }
  285. if (!(receiver is ObjectInstance oi))
  286. {
  287. return false;
  288. }
  289. var existingDescriptor = oi.GetOwnProperty(propertyName);
  290. if (existingDescriptor != PropertyDescriptor.Undefined)
  291. {
  292. if (existingDescriptor.IsAccessorDescriptor())
  293. {
  294. return false;
  295. }
  296. if (!existingDescriptor.Writable)
  297. {
  298. return false;
  299. }
  300. var valueDesc = new PropertyDescriptor(value, PropertyFlag.None);
  301. return oi.DefineOwnProperty(propertyName, valueDesc);
  302. }
  303. else
  304. {
  305. return oi.CreateDataProperty(propertyName, value);
  306. }
  307. }
  308. if (!(ownDesc.Set is ICallable setter))
  309. {
  310. return false;
  311. }
  312. setter.Call(receiver, new[] {value});
  313. return true;
  314. }
  315. /// <summary>
  316. /// Returns a Boolean value indicating whether a
  317. /// [[Put]] operation with PropertyName can be
  318. /// performed.
  319. /// http://www.ecma-international.org/ecma-262/5.1/#sec-8.12.4
  320. /// </summary>
  321. public bool CanPut(in Key propertyName)
  322. {
  323. var desc = GetOwnProperty(propertyName);
  324. if (desc != PropertyDescriptor.Undefined)
  325. {
  326. if (desc.IsAccessorDescriptor())
  327. {
  328. var set = desc.Set;
  329. if (ReferenceEquals(set, null) || set.IsUndefined())
  330. {
  331. return false;
  332. }
  333. return true;
  334. }
  335. return desc.Writable;
  336. }
  337. if (ReferenceEquals(Prototype, null))
  338. {
  339. return Extensible;
  340. }
  341. var inherited = Prototype.GetProperty(propertyName);
  342. if (inherited == PropertyDescriptor.Undefined)
  343. {
  344. return Extensible;
  345. }
  346. if (inherited.IsAccessorDescriptor())
  347. {
  348. var set = inherited.Set;
  349. if (ReferenceEquals(set, null) || set.IsUndefined())
  350. {
  351. return false;
  352. }
  353. return true;
  354. }
  355. if (!Extensible)
  356. {
  357. return false;
  358. }
  359. return inherited.Writable;
  360. }
  361. /// <summary>
  362. /// http://www.ecma-international.org/ecma-262/#sec-ordinary-object-internal-methods-and-internal-slots-hasproperty-p
  363. /// </summary>
  364. public virtual bool HasProperty(in Key propertyName)
  365. {
  366. var hasOwn = GetOwnProperty(propertyName);
  367. if (hasOwn != PropertyDescriptor.Undefined)
  368. {
  369. return true;
  370. }
  371. var parent = GetPrototypeOf();
  372. if (parent != null)
  373. {
  374. return parent.HasProperty(propertyName);
  375. }
  376. return false;
  377. }
  378. /// <summary>
  379. /// http://www.ecma-international.org/ecma-262/#sec-deletepropertyorthrow
  380. /// </summary>
  381. public bool DeletePropertyOrThrow(in Key propertyName)
  382. {
  383. if (!Delete(propertyName))
  384. {
  385. ExceptionHelper.ThrowTypeError(Engine);
  386. }
  387. return true;
  388. }
  389. /// <summary>
  390. /// Removes the specified named own property
  391. /// from the object. The flag controls failure
  392. /// handling.
  393. /// </summary>
  394. public virtual bool Delete(in Key propertyName)
  395. {
  396. var desc = GetOwnProperty(propertyName);
  397. if (desc == PropertyDescriptor.Undefined)
  398. {
  399. return true;
  400. }
  401. if (desc.Configurable)
  402. {
  403. RemoveOwnProperty(propertyName);
  404. return true;
  405. }
  406. return false;
  407. }
  408. public bool DefinePropertyOrThrow(in Key propertyName, PropertyDescriptor desc)
  409. {
  410. if (!DefineOwnProperty(propertyName, desc))
  411. {
  412. ExceptionHelper.ThrowTypeError(_engine);
  413. }
  414. return true;
  415. }
  416. /// <summary>
  417. /// Creates or alters the named own property to
  418. /// have the state described by a Property
  419. /// Descriptor. The flag controls failure handling.
  420. /// </summary>
  421. public virtual bool DefineOwnProperty(in Key propertyName, PropertyDescriptor desc)
  422. {
  423. var current = GetOwnProperty(propertyName);
  424. var extensible = Extensible;
  425. if (current == desc)
  426. {
  427. return true;
  428. }
  429. return ValidateAndApplyPropertyDescriptor(this, propertyName, extensible, desc, current);
  430. }
  431. /// <summary>
  432. /// http://www.ecma-international.org/ecma-262/#sec-validateandapplypropertydescriptor
  433. /// </summary>
  434. protected static bool ValidateAndApplyPropertyDescriptor(ObjectInstance o, in Key propertyName, bool extensible, PropertyDescriptor desc, PropertyDescriptor current)
  435. {
  436. var descValue = desc.Value;
  437. if (current == PropertyDescriptor.Undefined)
  438. {
  439. if (!extensible)
  440. {
  441. return false;
  442. }
  443. if (o is object)
  444. {
  445. if (desc.IsGenericDescriptor() || desc.IsDataDescriptor())
  446. {
  447. PropertyDescriptor propertyDescriptor;
  448. if ((desc._flags & PropertyFlag.ConfigurableEnumerableWritable) == PropertyFlag.ConfigurableEnumerableWritable)
  449. {
  450. propertyDescriptor = new PropertyDescriptor(descValue ?? Undefined, PropertyFlag.ConfigurableEnumerableWritable);
  451. }
  452. else if ((desc._flags & PropertyFlag.ConfigurableEnumerableWritable) == 0)
  453. {
  454. propertyDescriptor = new PropertyDescriptor(descValue ?? Undefined, PropertyFlag.AllForbidden);
  455. }
  456. else
  457. {
  458. propertyDescriptor = new PropertyDescriptor(desc)
  459. {
  460. Value = descValue ?? Undefined
  461. };
  462. }
  463. o.SetOwnProperty(propertyName, propertyDescriptor);
  464. }
  465. else
  466. {
  467. o.SetOwnProperty(propertyName, new GetSetPropertyDescriptor(desc));
  468. }
  469. }
  470. return true;
  471. }
  472. // Step 3
  473. var currentGet = current.Get;
  474. var currentSet = current.Set;
  475. var currentValue = current.Value;
  476. if ((current._flags & PropertyFlag.ConfigurableSet | PropertyFlag.EnumerableSet | PropertyFlag.WritableSet) == 0 &&
  477. ReferenceEquals(currentGet, null) &&
  478. ReferenceEquals(currentSet, null) &&
  479. ReferenceEquals(currentValue, null))
  480. {
  481. return true;
  482. }
  483. // Step 6
  484. var descGet = desc.Get;
  485. var descSet = desc.Set;
  486. if (
  487. current.Configurable == desc.Configurable && current.ConfigurableSet == desc.ConfigurableSet &&
  488. current.Writable == desc.Writable && current.WritableSet == desc.WritableSet &&
  489. current.Enumerable == desc.Enumerable && current.EnumerableSet == desc.EnumerableSet &&
  490. ((ReferenceEquals(currentGet, null) && ReferenceEquals(descGet, null)) || (!ReferenceEquals(currentGet, null) && !ReferenceEquals(descGet, null) && JintExpression.SameValue(currentGet, descGet))) &&
  491. ((ReferenceEquals(currentSet, null) && ReferenceEquals(descSet, null)) || (!ReferenceEquals(currentSet, null) && !ReferenceEquals(descSet, null) && JintExpression.SameValue(currentSet, descSet))) &&
  492. ((ReferenceEquals(currentValue, null) && ReferenceEquals(descValue, null)) || (!ReferenceEquals(currentValue, null) && !ReferenceEquals(descValue, null) && JintBinaryExpression.StrictlyEqual(currentValue, descValue)))
  493. )
  494. {
  495. return true;
  496. }
  497. if (!current.Configurable)
  498. {
  499. if (desc.Configurable)
  500. {
  501. return false;
  502. }
  503. if (desc.EnumerableSet && (desc.Enumerable != current.Enumerable))
  504. {
  505. return false;
  506. }
  507. }
  508. if (!desc.IsGenericDescriptor())
  509. {
  510. if (current.IsDataDescriptor() != desc.IsDataDescriptor())
  511. {
  512. if (!current.Configurable)
  513. {
  514. return false;
  515. }
  516. if (o is object)
  517. {
  518. var flags = current.Flags & ~(PropertyFlag.Writable | PropertyFlag.WritableSet);
  519. if (current.IsDataDescriptor())
  520. {
  521. o.SetOwnProperty(propertyName, current = new GetSetPropertyDescriptor(
  522. get: Undefined,
  523. set: Undefined,
  524. flags
  525. ));
  526. }
  527. else
  528. {
  529. o.SetOwnProperty(propertyName, current = new PropertyDescriptor(
  530. value: Undefined,
  531. flags
  532. ));
  533. }
  534. }
  535. }
  536. else if (current.IsDataDescriptor() && desc.IsDataDescriptor())
  537. {
  538. if (!current.Configurable)
  539. {
  540. if (!current.Writable && desc.Writable)
  541. {
  542. return false;
  543. }
  544. if (!current.Writable)
  545. {
  546. if (!ReferenceEquals(descValue, null) && !JintExpression.SameValue(descValue, currentValue))
  547. {
  548. return false;
  549. }
  550. }
  551. }
  552. }
  553. else if (current.IsAccessorDescriptor() && desc.IsAccessorDescriptor())
  554. {
  555. if (!current.Configurable)
  556. {
  557. if ((!ReferenceEquals(descSet, null) && !JintExpression.SameValue(descSet, currentSet ?? Undefined))
  558. ||
  559. (!ReferenceEquals(descGet, null) && !JintExpression.SameValue(descGet, currentGet ?? Undefined)))
  560. {
  561. return false;
  562. }
  563. }
  564. }
  565. }
  566. if (o is object)
  567. {
  568. if (!ReferenceEquals(descValue, null))
  569. {
  570. current.Value = descValue;
  571. }
  572. if (desc.WritableSet)
  573. {
  574. current.Writable = desc.Writable;
  575. }
  576. if (desc.EnumerableSet)
  577. {
  578. current.Enumerable = desc.Enumerable;
  579. }
  580. if (desc.ConfigurableSet)
  581. {
  582. current.Configurable = desc.Configurable;
  583. }
  584. PropertyDescriptor mutable = null;
  585. if (!ReferenceEquals(descGet, null))
  586. {
  587. mutable = new GetSetPropertyDescriptor(mutable ?? current);
  588. ((GetSetPropertyDescriptor) mutable).SetGet(descGet);
  589. }
  590. if (!ReferenceEquals(descSet, null))
  591. {
  592. mutable = new GetSetPropertyDescriptor(mutable ?? current);
  593. ((GetSetPropertyDescriptor) mutable).SetSet(descSet);
  594. }
  595. if (mutable != null)
  596. {
  597. // replace old with new type that supports get and set
  598. o.FastSetProperty(propertyName, mutable);
  599. }
  600. }
  601. return true;
  602. }
  603. /// <summary>
  604. /// Optimized version of [[Put]] when the property is known to be undeclared already
  605. /// </summary>
  606. /// <param name="name"></param>
  607. /// <param name="value"></param>
  608. /// <param name="writable"></param>
  609. /// <param name="configurable"></param>
  610. /// <param name="enumerable"></param>
  611. public void FastAddProperty(string name, JsValue value, bool writable, bool enumerable, bool configurable)
  612. {
  613. SetOwnProperty(name, new PropertyDescriptor(value, writable, enumerable, configurable));
  614. }
  615. /// <summary>
  616. /// Optimized version of [[Put]] when the property is known to be already declared
  617. /// </summary>
  618. /// <param name="name"></param>
  619. /// <param name="value"></param>
  620. public void FastSetProperty(in Key name, PropertyDescriptor value)
  621. {
  622. SetOwnProperty(name, value);
  623. }
  624. protected void EnsureInitialized()
  625. {
  626. if (!_initialized)
  627. {
  628. // we need to set flag eagerly to prevent wrong recursion
  629. _initialized = true;
  630. Initialize();
  631. }
  632. }
  633. protected virtual void Initialize()
  634. {
  635. }
  636. public override string ToString()
  637. {
  638. return TypeConverter.ToString(this);
  639. }
  640. public override object ToObject()
  641. {
  642. if (this is IObjectWrapper wrapper)
  643. {
  644. return wrapper.Target;
  645. }
  646. switch (Class)
  647. {
  648. case "Array":
  649. if (this is ArrayInstance arrayInstance)
  650. {
  651. var len = TypeConverter.ToInt32(arrayInstance.Get("length", arrayInstance));
  652. var result = new object[len];
  653. for (var k = 0; k < len; k++)
  654. {
  655. var pk = TypeConverter.ToString(k);
  656. var kpresent = arrayInstance.HasProperty(pk);
  657. if (kpresent)
  658. {
  659. var kvalue = arrayInstance.Get(pk, arrayInstance);
  660. result[k] = kvalue.ToObject();
  661. }
  662. else
  663. {
  664. result[k] = null;
  665. }
  666. }
  667. return result;
  668. }
  669. break;
  670. case "String":
  671. if (this is StringInstance stringInstance)
  672. {
  673. return stringInstance.PrimitiveValue.ToString();
  674. }
  675. break;
  676. case "Date":
  677. if (this is DateInstance dateInstance)
  678. {
  679. return dateInstance.ToDateTime();
  680. }
  681. break;
  682. case "Boolean":
  683. if (this is BooleanInstance booleanInstance)
  684. {
  685. return ((JsBoolean) booleanInstance.PrimitiveValue)._value
  686. ? JsBoolean.BoxedTrue
  687. : JsBoolean.BoxedFalse;
  688. }
  689. break;
  690. case "Function":
  691. if (this is FunctionInstance function)
  692. {
  693. return (Func<JsValue, JsValue[], JsValue>) function.Call;
  694. }
  695. break;
  696. case "Number":
  697. if (this is NumberInstance numberInstance)
  698. {
  699. return numberInstance.NumberData._value;
  700. }
  701. break;
  702. case "RegExp":
  703. if (this is RegExpInstance regeExpInstance)
  704. {
  705. return regeExpInstance.Value;
  706. }
  707. break;
  708. case "Arguments":
  709. case "Object":
  710. #if __IOS__
  711. IDictionary<string, object> o = new DictionarySlim<string, object>();
  712. #else
  713. IDictionary<string, object> o = new ExpandoObject();
  714. #endif
  715. foreach (var p in GetOwnProperties())
  716. {
  717. if (!p.Value.Enumerable)
  718. {
  719. continue;
  720. }
  721. o.Add(p.Key, Get(p.Key, this).ToObject());
  722. }
  723. return o;
  724. }
  725. return this;
  726. }
  727. /// <summary>
  728. /// Handles the generic find of (callback[, thisArg])
  729. /// </summary>
  730. internal virtual bool FindWithCallback(
  731. JsValue[] arguments,
  732. out uint index,
  733. out JsValue value,
  734. bool visitUnassigned)
  735. {
  736. long GetLength()
  737. {
  738. var desc = GetProperty("length");
  739. var descValue = desc.Value;
  740. double len;
  741. if (desc.IsDataDescriptor() && !ReferenceEquals(descValue, null))
  742. {
  743. len = TypeConverter.ToNumber(descValue);
  744. }
  745. else
  746. {
  747. var getter = desc.Get ?? Undefined;
  748. if (getter.IsUndefined())
  749. {
  750. len = 0;
  751. }
  752. else
  753. {
  754. // if getter is not undefined it must be ICallable
  755. len = TypeConverter.ToNumber(((ICallable) getter).Call(this, Arguments.Empty));
  756. }
  757. }
  758. return (long) System.Math.Max(
  759. 0,
  760. System.Math.Min(len, ArrayOperations.MaxArrayLikeLength));
  761. }
  762. bool TryGetValue(uint idx, out JsValue jsValue)
  763. {
  764. var property = TypeConverter.ToString(idx);
  765. var kPresent = HasProperty(property);
  766. jsValue = kPresent ? Get(property, this) : Undefined;
  767. return kPresent;
  768. }
  769. if (GetLength() == 0)
  770. {
  771. index = 0;
  772. value = Undefined;
  773. return false;
  774. }
  775. var callbackfn = arguments.At(0);
  776. var thisArg = arguments.At(1);
  777. var callable = GetCallable(callbackfn);
  778. var args = _engine._jsValueArrayPool.RentArray(3);
  779. args[2] = this;
  780. var length = GetLength();
  781. for (uint k = 0; k < length; k++)
  782. {
  783. if (TryGetValue(k, out var kvalue) || visitUnassigned)
  784. {
  785. args[0] = kvalue;
  786. args[1] = k;
  787. var testResult = callable.Call(thisArg, args);
  788. if (TypeConverter.ToBoolean(testResult))
  789. {
  790. index = k;
  791. value = kvalue;
  792. return true;
  793. }
  794. }
  795. }
  796. _engine._jsValueArrayPool.ReturnArray(args);
  797. index = 0;
  798. value = Undefined;
  799. return false;
  800. }
  801. protected ICallable GetCallable(JsValue source)
  802. {
  803. if (source is ICallable callable)
  804. {
  805. return callable;
  806. }
  807. ExceptionHelper.ThrowTypeError(_engine, "Argument must be callable");
  808. return null;
  809. }
  810. internal bool IsConcatSpreadable
  811. {
  812. get
  813. {
  814. var spreadable = Get(GlobalSymbolRegistry.IsConcatSpreadable, this);
  815. if (!spreadable.IsUndefined())
  816. {
  817. return TypeConverter.ToBoolean(spreadable);
  818. }
  819. return IsArray();
  820. }
  821. }
  822. internal virtual bool IsArrayLike => TryGetValue("length", out var lengthValue)
  823. && lengthValue.IsNumber()
  824. && ((JsNumber) lengthValue)._value >= 0;
  825. public virtual JsValue PreventExtensions()
  826. {
  827. Extensible = false;
  828. return JsBoolean.True;
  829. }
  830. protected virtual ObjectInstance GetPrototypeOf()
  831. {
  832. return _prototype;
  833. }
  834. /// <summary>
  835. /// https://tc39.es/ecma262/#sec-ordinarysetprototypeof
  836. /// </summary>
  837. public virtual bool SetPrototypeOf(JsValue value)
  838. {
  839. if (!value.IsObject() && !value.IsNull())
  840. {
  841. ExceptionHelper.ThrowArgumentException();
  842. }
  843. var current = _prototype ?? Null;
  844. if (ReferenceEquals(value, current))
  845. {
  846. return true;
  847. }
  848. if (!Extensible)
  849. {
  850. return false;
  851. }
  852. if (value.IsNull())
  853. {
  854. _prototype = null;
  855. return true;
  856. }
  857. // validate chain
  858. var p = value as ObjectInstance;
  859. bool done = false;
  860. while (!done)
  861. {
  862. if (p is null)
  863. {
  864. done = true;
  865. }
  866. else if (ReferenceEquals(p, this))
  867. {
  868. return false;
  869. }
  870. else
  871. {
  872. p = p._prototype;
  873. }
  874. }
  875. _prototype = value as ObjectInstance;
  876. return true;
  877. }
  878. /// <summary>
  879. /// http://www.ecma-international.org/ecma-262/#sec-createdatapropertyorthrow
  880. /// </summary>
  881. internal bool CreateDataProperty(Key p, JsValue v)
  882. {
  883. var newDesc = new PropertyDescriptor(v, PropertyFlag.ConfigurableEnumerableWritable);
  884. return DefineOwnProperty(p, newDesc);
  885. }
  886. /// <summary>
  887. /// http://www.ecma-international.org/ecma-262/#sec-createdataproperty
  888. /// </summary>
  889. internal bool CreateDataPropertyOrThrow( Key p, JsValue v)
  890. {
  891. if (!CreateDataProperty(p, v))
  892. {
  893. ExceptionHelper.ThrowTypeError(_engine);
  894. }
  895. return true;
  896. }
  897. public override bool Equals(JsValue obj)
  898. {
  899. if (ReferenceEquals(null, obj))
  900. {
  901. return false;
  902. }
  903. if (!(obj is ObjectInstance s))
  904. {
  905. return false;
  906. }
  907. return Equals(s);
  908. }
  909. public bool Equals(ObjectInstance other)
  910. {
  911. if (ReferenceEquals(null, other))
  912. {
  913. return false;
  914. }
  915. if (ReferenceEquals(this, other))
  916. {
  917. return true;
  918. }
  919. return false;
  920. }
  921. }
  922. }