ObjectInstance.cs 33 KB

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