ObjectInstance.cs 43 KB

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