ObjectInstance.cs 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  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 bool _initialized;
  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. }
  36. public Engine Engine => _engine;
  37. /// <summary>
  38. /// The prototype of this object.
  39. /// </summary>
  40. public ObjectInstance Prototype { get; set; }
  41. /// <summary>
  42. /// If true, own properties may be added to the
  43. /// object.
  44. /// </summary>
  45. public bool Extensible { get; set; }
  46. /// <summary>
  47. /// A String value indicating a specification defined
  48. /// classification of objects.
  49. /// </summary>
  50. public string Class => _class;
  51. public virtual IEnumerable<KeyValuePair<string, PropertyDescriptor>> GetOwnProperties()
  52. {
  53. EnsureInitialized();
  54. if (_properties != null)
  55. {
  56. foreach (var pair in _properties)
  57. {
  58. yield return pair;
  59. }
  60. }
  61. }
  62. protected virtual void AddProperty(in Key propertyName, PropertyDescriptor descriptor)
  63. {
  64. if (_properties == null)
  65. {
  66. _properties = new StringDictionarySlim<PropertyDescriptor>();
  67. }
  68. _properties[propertyName] = descriptor;
  69. }
  70. protected virtual bool TryGetProperty(in Key propertyName, out PropertyDescriptor descriptor)
  71. {
  72. if (_properties == null)
  73. {
  74. descriptor = null;
  75. return false;
  76. }
  77. return _properties.TryGetValue(propertyName, out descriptor);
  78. }
  79. public virtual bool HasOwnProperty(in Key propertyName)
  80. {
  81. EnsureInitialized();
  82. return _properties?.ContainsKey(propertyName) == true;
  83. }
  84. public virtual void RemoveOwnProperty(in Key propertyName)
  85. {
  86. EnsureInitialized();
  87. _properties?.Remove(propertyName);
  88. }
  89. /// <summary>
  90. /// Returns the value of the named property.
  91. /// http://www.ecma-international.org/ecma-262/5.1/#sec-8.12.3
  92. /// </summary>
  93. /// <param name="propertyName"></param>
  94. /// <returns></returns>
  95. public virtual JsValue Get(in Key propertyName)
  96. {
  97. var desc = GetProperty(propertyName);
  98. return UnwrapJsValue(desc);
  99. }
  100. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  101. internal JsValue UnwrapJsValue(PropertyDescriptor desc)
  102. {
  103. return UnwrapJsValue(desc, this);
  104. }
  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(in Key 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(in Key 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(in Key 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(in Key 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(in Key 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(in Key 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(in Key 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(in Key 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(in Key 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(in Key name, PropertyDescriptor value)
  636. {
  637. SetOwnProperty(name, value);
  638. }
  639. protected void EnsureInitialized()
  640. {
  641. if (!_initialized)
  642. {
  643. // we need to set flag eagerly to prevent wrong recursion
  644. _initialized = true;
  645. Initialize();
  646. }
  647. }
  648. protected virtual void Initialize()
  649. {
  650. }
  651. public override string ToString()
  652. {
  653. return TypeConverter.ToString(this);
  654. }
  655. public override object ToObject()
  656. {
  657. if (this is IObjectWrapper wrapper)
  658. {
  659. return wrapper.Target;
  660. }
  661. switch (Class)
  662. {
  663. case "Array":
  664. if (this is ArrayInstance arrayInstance)
  665. {
  666. var len = TypeConverter.ToInt32(arrayInstance.Get("length"));
  667. var result = new object[len];
  668. for (var k = 0; k < len; k++)
  669. {
  670. var pk = TypeConverter.ToString(k);
  671. var kpresent = arrayInstance.HasProperty(pk);
  672. if (kpresent)
  673. {
  674. var kvalue = arrayInstance.Get(pk);
  675. result[k] = kvalue.ToObject();
  676. }
  677. else
  678. {
  679. result[k] = null;
  680. }
  681. }
  682. return result;
  683. }
  684. break;
  685. case "String":
  686. if (this is StringInstance stringInstance)
  687. {
  688. return stringInstance.PrimitiveValue.ToString();
  689. }
  690. break;
  691. case "Date":
  692. if (this is DateInstance dateInstance)
  693. {
  694. return dateInstance.ToDateTime();
  695. }
  696. break;
  697. case "Boolean":
  698. if (this is BooleanInstance booleanInstance)
  699. {
  700. return ((JsBoolean) booleanInstance.PrimitiveValue)._value
  701. ? JsBoolean.BoxedTrue
  702. : JsBoolean.BoxedFalse;
  703. }
  704. break;
  705. case "Function":
  706. if (this is FunctionInstance function)
  707. {
  708. return (Func<JsValue, JsValue[], JsValue>) function.Call;
  709. }
  710. break;
  711. case "Number":
  712. if (this is NumberInstance numberInstance)
  713. {
  714. return numberInstance.NumberData._value;
  715. }
  716. break;
  717. case "RegExp":
  718. if (this is RegExpInstance regeExpInstance)
  719. {
  720. return regeExpInstance.Value;
  721. }
  722. break;
  723. case "Arguments":
  724. case "Object":
  725. #if __IOS__
  726. IDictionary<string, object> o = new DictionarySlim<string, object>();
  727. #else
  728. IDictionary<string, object> o = new ExpandoObject();
  729. #endif
  730. foreach (var p in GetOwnProperties())
  731. {
  732. if (!p.Value.Enumerable)
  733. {
  734. continue;
  735. }
  736. o.Add(p.Key, Get(p.Key).ToObject());
  737. }
  738. return o;
  739. }
  740. return this;
  741. }
  742. /// <summary>
  743. /// Handles the generic find of (callback[, thisArg])
  744. /// </summary>
  745. internal virtual bool FindWithCallback(
  746. JsValue[] arguments,
  747. out uint index,
  748. out JsValue value,
  749. bool visitUnassigned)
  750. {
  751. long GetLength()
  752. {
  753. var desc = GetProperty("length");
  754. var descValue = desc.Value;
  755. double len;
  756. if (desc.IsDataDescriptor() && !ReferenceEquals(descValue, null))
  757. {
  758. len = TypeConverter.ToNumber(descValue);
  759. }
  760. else
  761. {
  762. var getter = desc.Get ?? Undefined;
  763. if (getter.IsUndefined())
  764. {
  765. len = 0;
  766. }
  767. else
  768. {
  769. // if getter is not undefined it must be ICallable
  770. len = TypeConverter.ToNumber(((ICallable) getter).Call(this, Arguments.Empty));
  771. }
  772. }
  773. return (long) System.Math.Max(
  774. 0,
  775. System.Math.Min(len, ArrayPrototype.ArrayOperations.MaxArrayLikeLength));
  776. }
  777. bool TryGetValue(uint idx, out JsValue jsValue)
  778. {
  779. var property = TypeConverter.ToString(idx);
  780. var kPresent = HasProperty(property);
  781. jsValue = kPresent ? Get(property) : Undefined;
  782. return kPresent;
  783. }
  784. if (GetLength() == 0)
  785. {
  786. index = 0;
  787. value = Undefined;
  788. return false;
  789. }
  790. var callbackfn = arguments.At(0);
  791. var thisArg = arguments.At(1);
  792. var callable = GetCallable(callbackfn);
  793. var args = _engine._jsValueArrayPool.RentArray(3);
  794. args[2] = this;
  795. var length = GetLength();
  796. for (uint k = 0; k < length; k++)
  797. {
  798. if (TryGetValue(k, out var kvalue) || visitUnassigned)
  799. {
  800. args[0] = kvalue;
  801. args[1] = k;
  802. var testResult = callable.Call(thisArg, args);
  803. if (TypeConverter.ToBoolean(testResult))
  804. {
  805. index = k;
  806. value = kvalue;
  807. return true;
  808. }
  809. }
  810. }
  811. _engine._jsValueArrayPool.ReturnArray(args);
  812. index = 0;
  813. value = Undefined;
  814. return false;
  815. }
  816. protected ICallable GetCallable(JsValue source)
  817. {
  818. if (source is ICallable callable)
  819. {
  820. return callable;
  821. }
  822. ExceptionHelper.ThrowTypeError(_engine, "Argument must be callable");
  823. return null;
  824. }
  825. internal virtual bool IsConcatSpreadable => TryGetIsConcatSpreadable(out var isConcatSpreadable) && isConcatSpreadable;
  826. internal virtual bool IsArrayLike => TryGetValue("length", out var lengthValue)
  827. && lengthValue.IsNumber()
  828. && ((JsNumber) lengthValue)._value >= 0;
  829. protected bool TryGetIsConcatSpreadable(out bool isConcatSpreadable)
  830. {
  831. isConcatSpreadable = false;
  832. if (TryGetValue(GlobalSymbolRegistry.IsConcatSpreadable._value, out var isConcatSpreadableValue)
  833. && !ReferenceEquals(isConcatSpreadableValue, null)
  834. && !isConcatSpreadableValue.IsUndefined())
  835. {
  836. isConcatSpreadable = TypeConverter.ToBoolean(isConcatSpreadableValue);
  837. return true;
  838. }
  839. return false;
  840. }
  841. public override bool Equals(JsValue obj)
  842. {
  843. if (ReferenceEquals(null, obj))
  844. {
  845. return false;
  846. }
  847. if (!(obj is ObjectInstance s))
  848. {
  849. return false;
  850. }
  851. return Equals(s);
  852. }
  853. public bool Equals(ObjectInstance other)
  854. {
  855. if (ReferenceEquals(null, other))
  856. {
  857. return false;
  858. }
  859. if (ReferenceEquals(this, other))
  860. {
  861. return true;
  862. }
  863. return false;
  864. }
  865. }
  866. }