2
0

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