ObjectInstance.cs 41 KB

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