ObjectInstance.cs 33 KB

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