ObjectInstance.cs 31 KB

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