ObjectInstance.cs 37 KB

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