ObjectInstance.cs 33 KB

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