ObjectInstance.cs 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378
  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 = GetOwnProperty(property);
  270. if (desc != PropertyDescriptor.Undefined)
  271. {
  272. return UnwrapJsValue(desc, receiver);
  273. }
  274. return Prototype?.Get(property, receiver) ?? Undefined;
  275. }
  276. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  277. internal JsValue UnwrapJsValue(PropertyDescriptor desc)
  278. {
  279. return UnwrapJsValue(desc, this);
  280. }
  281. internal static JsValue UnwrapJsValue(PropertyDescriptor desc, JsValue thisObject)
  282. {
  283. var value = (desc._flags & PropertyFlag.CustomJsValue) != 0
  284. ? desc.CustomValue
  285. : desc._value;
  286. // IsDataDescriptor inlined
  287. if ((desc._flags & (PropertyFlag.WritableSet | PropertyFlag.Writable)) != 0 || value is not null)
  288. {
  289. return value ?? Undefined;
  290. }
  291. return UnwrapFromGetter(desc, thisObject);
  292. }
  293. /// <summary>
  294. /// A rarer case.
  295. /// </summary>
  296. [MethodImpl(MethodImplOptions.NoInlining)]
  297. private static JsValue UnwrapFromGetter(PropertyDescriptor desc, JsValue thisObject)
  298. {
  299. var getter = desc.Get ?? Undefined;
  300. if (getter.IsUndefined())
  301. {
  302. return Undefined;
  303. }
  304. var functionInstance = (FunctionInstance) getter;
  305. return functionInstance._engine.Call(functionInstance, thisObject, Arguments.Empty, expression: null);
  306. }
  307. /// <summary>
  308. /// Returns the Property Descriptor of the named
  309. /// own property of this object, or undefined if
  310. /// absent.
  311. /// http://www.ecma-international.org/ecma-262/5.1/#sec-8.12.1
  312. /// </summary>
  313. public virtual PropertyDescriptor GetOwnProperty(JsValue property)
  314. {
  315. EnsureInitialized();
  316. PropertyDescriptor descriptor = null;
  317. var key = TypeConverter.ToPropertyKey(property);
  318. if (!key.IsSymbol())
  319. {
  320. _properties?.TryGetValue(TypeConverter.ToString(key), out descriptor);
  321. }
  322. else
  323. {
  324. _symbols?.TryGetValue((JsSymbol) key, out descriptor);
  325. }
  326. return descriptor ?? PropertyDescriptor.Undefined;
  327. }
  328. protected internal virtual void SetOwnProperty(JsValue property, PropertyDescriptor desc)
  329. {
  330. EnsureInitialized();
  331. SetProperty(property, desc);
  332. }
  333. /// <summary>
  334. /// http://www.ecma-international.org/ecma-262/5.1/#sec-8.12.2
  335. /// </summary>
  336. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  337. public PropertyDescriptor GetProperty(JsValue property)
  338. {
  339. var prop = GetOwnProperty(property);
  340. if (prop != PropertyDescriptor.Undefined)
  341. {
  342. return prop;
  343. }
  344. return Prototype?.GetProperty(property) ?? PropertyDescriptor.Undefined;
  345. }
  346. public bool TryGetValue(JsValue property, out JsValue value)
  347. {
  348. value = Undefined;
  349. var desc = GetOwnProperty(property);
  350. if (desc != null && desc != PropertyDescriptor.Undefined)
  351. {
  352. if (desc == PropertyDescriptor.Undefined)
  353. {
  354. return false;
  355. }
  356. var descValue = desc.Value;
  357. if (desc.WritableSet && !ReferenceEquals(descValue, null))
  358. {
  359. value = descValue;
  360. return true;
  361. }
  362. var getter = desc.Get ?? Undefined;
  363. if (getter.IsUndefined())
  364. {
  365. value = Undefined;
  366. return false;
  367. }
  368. // if getter is not undefined it must be ICallable
  369. var callable = getter.TryCast<ICallable>();
  370. value = callable.Call(this, Arguments.Empty);
  371. return true;
  372. }
  373. if (ReferenceEquals(Prototype, null))
  374. {
  375. return false;
  376. }
  377. return Prototype.TryGetValue(property, out value);
  378. }
  379. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  380. public bool Set(JsValue p, JsValue v, bool throwOnError)
  381. {
  382. if (!Set(p, v, this) && throwOnError)
  383. {
  384. ExceptionHelper.ThrowTypeError(_engine.Realm);
  385. }
  386. return true;
  387. }
  388. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  389. public bool Set(JsValue property, JsValue value)
  390. {
  391. return Set(property, value, this);
  392. }
  393. /// <summary>
  394. /// https://tc39.es/ecma262/#sec-ordinarysetwithowndescriptor
  395. /// </summary>
  396. public override bool Set(JsValue property, JsValue value, JsValue receiver)
  397. {
  398. var ownDesc = GetOwnProperty(property);
  399. if (ownDesc == PropertyDescriptor.Undefined)
  400. {
  401. var parent = GetPrototypeOf();
  402. if (parent is not null)
  403. {
  404. return parent.Set(property, value, receiver);
  405. }
  406. ownDesc = new PropertyDescriptor(Undefined, PropertyFlag.ConfigurableEnumerableWritable);
  407. }
  408. if (ownDesc.IsDataDescriptor())
  409. {
  410. if (!ownDesc.Writable)
  411. {
  412. return false;
  413. }
  414. if (receiver is not ObjectInstance oi)
  415. {
  416. return false;
  417. }
  418. var existingDescriptor = oi.GetOwnProperty(property);
  419. if (existingDescriptor != PropertyDescriptor.Undefined)
  420. {
  421. if (existingDescriptor.IsAccessorDescriptor())
  422. {
  423. return false;
  424. }
  425. if (!existingDescriptor.Writable)
  426. {
  427. return false;
  428. }
  429. var valueDesc = new PropertyDescriptor(value, PropertyFlag.None);
  430. return oi.DefineOwnProperty(property, valueDesc);
  431. }
  432. else
  433. {
  434. return oi.CreateDataProperty(property, value);
  435. }
  436. }
  437. if (ownDesc.Set is not FunctionInstance setter)
  438. {
  439. return false;
  440. }
  441. _engine.Call(setter, receiver, new[] { value }, expression: null);
  442. return true;
  443. }
  444. /// <summary>
  445. /// Returns a Boolean value indicating whether a
  446. /// [[Put]] operation with PropertyName can be
  447. /// performed.
  448. /// http://www.ecma-international.org/ecma-262/5.1/#sec-8.12.4
  449. /// </summary>
  450. public bool CanPut(JsValue property)
  451. {
  452. var desc = GetOwnProperty(property);
  453. if (desc != PropertyDescriptor.Undefined)
  454. {
  455. if (desc.IsAccessorDescriptor())
  456. {
  457. var set = desc.Set;
  458. if (ReferenceEquals(set, null) || set.IsUndefined())
  459. {
  460. return false;
  461. }
  462. return true;
  463. }
  464. return desc.Writable;
  465. }
  466. if (ReferenceEquals(Prototype, null))
  467. {
  468. return Extensible;
  469. }
  470. var inherited = Prototype.GetProperty(property);
  471. if (inherited == PropertyDescriptor.Undefined)
  472. {
  473. return Extensible;
  474. }
  475. if (inherited.IsAccessorDescriptor())
  476. {
  477. var set = inherited.Set;
  478. if (ReferenceEquals(set, null) || set.IsUndefined())
  479. {
  480. return false;
  481. }
  482. return true;
  483. }
  484. if (!Extensible)
  485. {
  486. return false;
  487. }
  488. return inherited.Writable;
  489. }
  490. /// <summary>
  491. /// https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-hasproperty-p
  492. /// </summary>
  493. public virtual bool HasProperty(JsValue property)
  494. {
  495. var hasOwn = GetOwnProperty(property);
  496. if (hasOwn != PropertyDescriptor.Undefined)
  497. {
  498. return true;
  499. }
  500. var parent = GetPrototypeOf();
  501. if (parent != null)
  502. {
  503. return parent.HasProperty(property);
  504. }
  505. return false;
  506. }
  507. /// <summary>
  508. /// https://tc39.es/ecma262/#sec-deletepropertyorthrow
  509. /// </summary>
  510. public bool DeletePropertyOrThrow(JsValue property)
  511. {
  512. if (!Delete(property))
  513. {
  514. ExceptionHelper.ThrowTypeError(_engine.Realm);
  515. }
  516. return true;
  517. }
  518. /// <summary>
  519. /// Removes the specified named own property
  520. /// from the object. The flag controls failure
  521. /// handling.
  522. /// </summary>
  523. public virtual bool Delete(JsValue property)
  524. {
  525. var desc = GetOwnProperty(property);
  526. if (desc == PropertyDescriptor.Undefined)
  527. {
  528. return true;
  529. }
  530. if (desc.Configurable)
  531. {
  532. RemoveOwnProperty(property);
  533. return true;
  534. }
  535. return false;
  536. }
  537. public bool DefinePropertyOrThrow(JsValue property, PropertyDescriptor desc)
  538. {
  539. if (!DefineOwnProperty(property, desc))
  540. {
  541. ExceptionHelper.ThrowTypeError(_engine.Realm, "Cannot redefine property: " + property);
  542. }
  543. return true;
  544. }
  545. /// <summary>
  546. /// Creates or alters the named own property to
  547. /// have the state described by a Property
  548. /// Descriptor. The flag controls failure handling.
  549. /// </summary>
  550. public virtual bool DefineOwnProperty(JsValue property, PropertyDescriptor desc)
  551. {
  552. var current = GetOwnProperty(property);
  553. var extensible = Extensible;
  554. if (current == desc)
  555. {
  556. return true;
  557. }
  558. return ValidateAndApplyPropertyDescriptor(this, property, extensible, desc, current);
  559. }
  560. /// <summary>
  561. /// https://tc39.es/ecma262/#sec-validateandapplypropertydescriptor
  562. /// </summary>
  563. protected static bool ValidateAndApplyPropertyDescriptor(ObjectInstance o, JsValue property, bool extensible, PropertyDescriptor desc, PropertyDescriptor current)
  564. {
  565. var descValue = desc.Value;
  566. if (current == PropertyDescriptor.Undefined)
  567. {
  568. if (!extensible)
  569. {
  570. return false;
  571. }
  572. if (o is object)
  573. {
  574. if (desc.IsGenericDescriptor() || desc.IsDataDescriptor())
  575. {
  576. PropertyDescriptor propertyDescriptor;
  577. if ((desc._flags & PropertyFlag.ConfigurableEnumerableWritable) == PropertyFlag.ConfigurableEnumerableWritable)
  578. {
  579. propertyDescriptor = new PropertyDescriptor(descValue ?? Undefined, PropertyFlag.ConfigurableEnumerableWritable);
  580. }
  581. else if ((desc._flags & PropertyFlag.ConfigurableEnumerableWritable) == 0)
  582. {
  583. propertyDescriptor = new PropertyDescriptor(descValue ?? Undefined, PropertyFlag.AllForbidden);
  584. }
  585. else
  586. {
  587. propertyDescriptor = new PropertyDescriptor(desc)
  588. {
  589. Value = descValue ?? Undefined
  590. };
  591. }
  592. o.SetOwnProperty(property, propertyDescriptor);
  593. }
  594. else
  595. {
  596. var descriptor = new GetSetPropertyDescriptor(desc.Get, desc.Set, PropertyFlag.None)
  597. {
  598. Enumerable = desc.Enumerable,
  599. Configurable = desc.Configurable
  600. };
  601. o.SetOwnProperty(property, descriptor);
  602. }
  603. }
  604. return true;
  605. }
  606. // Step 3
  607. var currentGet = current.Get;
  608. var currentSet = current.Set;
  609. var currentValue = current.Value;
  610. // 4. If every field in Desc is absent, return true.
  611. if ((current._flags & (PropertyFlag.ConfigurableSet | PropertyFlag.EnumerableSet | PropertyFlag.WritableSet)) == 0 &&
  612. ReferenceEquals(currentGet, null) &&
  613. ReferenceEquals(currentSet, null) &&
  614. ReferenceEquals(currentValue, null))
  615. {
  616. return true;
  617. }
  618. // Step 6
  619. var descGet = desc.Get;
  620. var descSet = desc.Set;
  621. if (
  622. current.Configurable == desc.Configurable && current.ConfigurableSet == desc.ConfigurableSet &&
  623. current.Writable == desc.Writable && current.WritableSet == desc.WritableSet &&
  624. current.Enumerable == desc.Enumerable && current.EnumerableSet == desc.EnumerableSet &&
  625. ((ReferenceEquals(currentGet, null) && ReferenceEquals(descGet, null)) || (!ReferenceEquals(currentGet, null) && !ReferenceEquals(descGet, null) && SameValue(currentGet, descGet))) &&
  626. ((ReferenceEquals(currentSet, null) && ReferenceEquals(descSet, null)) || (!ReferenceEquals(currentSet, null) && !ReferenceEquals(descSet, null) && SameValue(currentSet, descSet))) &&
  627. ((ReferenceEquals(currentValue, null) && ReferenceEquals(descValue, null)) || (!ReferenceEquals(currentValue, null) && !ReferenceEquals(descValue, null) && currentValue == descValue))
  628. )
  629. {
  630. return true;
  631. }
  632. if (!current.Configurable)
  633. {
  634. if (desc.Configurable)
  635. {
  636. return false;
  637. }
  638. if (desc.EnumerableSet && (desc.Enumerable != current.Enumerable))
  639. {
  640. return false;
  641. }
  642. }
  643. if (!desc.IsGenericDescriptor())
  644. {
  645. if (current.IsDataDescriptor() != desc.IsDataDescriptor())
  646. {
  647. if (!current.Configurable)
  648. {
  649. return false;
  650. }
  651. if (o is object)
  652. {
  653. var flags = current.Flags & ~(PropertyFlag.Writable | PropertyFlag.WritableSet | PropertyFlag.CustomJsValue);
  654. if (current.IsDataDescriptor())
  655. {
  656. o.SetOwnProperty(property, current = new GetSetPropertyDescriptor(
  657. get: Undefined,
  658. set: Undefined,
  659. flags
  660. ));
  661. }
  662. else
  663. {
  664. o.SetOwnProperty(property, current = new PropertyDescriptor(
  665. value: Undefined,
  666. flags
  667. ));
  668. }
  669. }
  670. }
  671. else if (current.IsDataDescriptor() && desc.IsDataDescriptor())
  672. {
  673. if (!current.Configurable)
  674. {
  675. if (!current.Writable && desc.Writable)
  676. {
  677. return false;
  678. }
  679. if (!current.Writable)
  680. {
  681. if (!ReferenceEquals(descValue, null) && !SameValue(descValue, currentValue))
  682. {
  683. return false;
  684. }
  685. }
  686. }
  687. }
  688. else if (current.IsAccessorDescriptor() && desc.IsAccessorDescriptor())
  689. {
  690. if (!current.Configurable)
  691. {
  692. if ((!ReferenceEquals(descSet, null) && !SameValue(descSet, currentSet ?? Undefined))
  693. ||
  694. (!ReferenceEquals(descGet, null) && !SameValue(descGet, currentGet ?? Undefined)))
  695. {
  696. return false;
  697. }
  698. }
  699. }
  700. }
  701. if (o is object)
  702. {
  703. if (!ReferenceEquals(descValue, null))
  704. {
  705. current.Value = descValue;
  706. }
  707. if (desc.WritableSet)
  708. {
  709. current.Writable = desc.Writable;
  710. }
  711. if (desc.EnumerableSet)
  712. {
  713. current.Enumerable = desc.Enumerable;
  714. }
  715. if (desc.ConfigurableSet)
  716. {
  717. current.Configurable = desc.Configurable;
  718. }
  719. PropertyDescriptor mutable = null;
  720. if (!ReferenceEquals(descGet, null))
  721. {
  722. mutable = new GetSetPropertyDescriptor(mutable ?? current);
  723. ((GetSetPropertyDescriptor) mutable).SetGet(descGet);
  724. }
  725. if (!ReferenceEquals(descSet, null))
  726. {
  727. mutable = new GetSetPropertyDescriptor(mutable ?? current);
  728. ((GetSetPropertyDescriptor) mutable).SetSet(descSet);
  729. }
  730. if (mutable != null)
  731. {
  732. // replace old with new type that supports get and set
  733. o.FastSetProperty(property, mutable);
  734. }
  735. }
  736. return true;
  737. }
  738. /// <summary>
  739. /// Optimized version of [[Put]] when the property is known to be undeclared already
  740. /// </summary>
  741. public void FastAddProperty(JsValue name, JsValue value, bool writable, bool enumerable, bool configurable)
  742. {
  743. SetOwnProperty(name, new PropertyDescriptor(value, writable, enumerable, configurable));
  744. }
  745. /// <summary>
  746. /// Optimized version of [[Put]] when the property is known to be already declared
  747. /// </summary>
  748. /// <param name="name"></param>
  749. /// <param name="value"></param>
  750. public void FastSetProperty(JsValue name, PropertyDescriptor value)
  751. {
  752. SetOwnProperty(name, value);
  753. }
  754. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  755. protected internal void EnsureInitialized()
  756. {
  757. if (_initialized)
  758. {
  759. return;
  760. }
  761. // we need to set flag eagerly to prevent wrong recursion
  762. _initialized = true;
  763. Initialize();
  764. }
  765. protected virtual void Initialize()
  766. {
  767. }
  768. public override object ToObject()
  769. {
  770. return ToObject(new ObjectTraverseStack(_engine));
  771. }
  772. private object ToObject(ObjectTraverseStack stack)
  773. {
  774. if (this is IObjectWrapper wrapper)
  775. {
  776. return wrapper.Target;
  777. }
  778. stack.Enter(this);
  779. object converted = null;
  780. switch (Class)
  781. {
  782. case ObjectClass.Array:
  783. if (this is ArrayInstance arrayInstance)
  784. {
  785. var result = new object[arrayInstance.Length];
  786. for (uint i = 0; i < result.Length; i++)
  787. {
  788. var value = arrayInstance[i];
  789. object valueToSet = null;
  790. if (!value.IsUndefined())
  791. {
  792. valueToSet = value is ObjectInstance oi
  793. ? oi.ToObject(stack)
  794. : value.ToObject();
  795. }
  796. result[i] = valueToSet;
  797. }
  798. converted = result;
  799. }
  800. break;
  801. case ObjectClass.String:
  802. if (this is StringInstance stringInstance)
  803. {
  804. converted = stringInstance.StringData.ToString();
  805. }
  806. break;
  807. case ObjectClass.Date:
  808. if (this is DateInstance dateInstance)
  809. {
  810. converted = dateInstance.ToDateTime();
  811. }
  812. break;
  813. case ObjectClass.Boolean:
  814. if (this is BooleanInstance booleanInstance)
  815. {
  816. converted = ((JsBoolean) booleanInstance.BooleanData)._value
  817. ? JsBoolean.BoxedTrue
  818. : JsBoolean.BoxedFalse;
  819. }
  820. break;
  821. case ObjectClass.Function:
  822. if (this is FunctionInstance function)
  823. {
  824. converted = new Func<JsValue, JsValue[], JsValue>(
  825. (thisVal, args) => function.Engine.Invoke(function, (object) thisVal, args));
  826. }
  827. break;
  828. case ObjectClass.Number:
  829. if (this is NumberInstance numberInstance)
  830. {
  831. converted = numberInstance.NumberData._value;
  832. }
  833. break;
  834. case ObjectClass.RegExp:
  835. if (this is RegExpInstance regeExpInstance)
  836. {
  837. converted = regeExpInstance.Value;
  838. }
  839. break;
  840. case ObjectClass.Arguments:
  841. case ObjectClass.Object:
  842. IDictionary<string, object> o = new ExpandoObject();
  843. foreach (var p in GetOwnProperties())
  844. {
  845. if (!p.Value.Enumerable)
  846. {
  847. continue;
  848. }
  849. var key = p.Key.ToString();
  850. var propertyValue = Get(p.Key, this);
  851. var value = propertyValue is ObjectInstance oi
  852. ? oi.ToObject(stack)
  853. : propertyValue.ToObject();
  854. o.Add(key, value);
  855. }
  856. converted = o;
  857. break;
  858. default:
  859. converted = this;
  860. break;
  861. }
  862. stack.Exit();
  863. return converted;
  864. }
  865. /// <summary>
  866. /// Handles the generic find of (callback[, thisArg])
  867. /// </summary>
  868. internal virtual bool FindWithCallback(
  869. JsValue[] arguments,
  870. out uint index,
  871. out JsValue value,
  872. bool visitUnassigned,
  873. bool fromEnd = false)
  874. {
  875. long GetLength()
  876. {
  877. var desc = GetProperty(CommonProperties.Length);
  878. var descValue = desc.Value;
  879. double len;
  880. if (desc.IsDataDescriptor() && !ReferenceEquals(descValue, null))
  881. {
  882. len = TypeConverter.ToNumber(descValue);
  883. }
  884. else
  885. {
  886. var getter = desc.Get ?? Undefined;
  887. if (getter.IsUndefined())
  888. {
  889. len = 0;
  890. }
  891. else
  892. {
  893. // if getter is not undefined it must be ICallable
  894. len = TypeConverter.ToNumber(((ICallable) getter).Call(this, Arguments.Empty));
  895. }
  896. }
  897. return (long) System.Math.Max(
  898. 0,
  899. System.Math.Min(len, ArrayOperations.MaxArrayLikeLength));
  900. }
  901. bool TryGetValue(uint idx, out JsValue jsValue)
  902. {
  903. var property = JsString.Create(idx);
  904. var kPresent = HasProperty(property);
  905. jsValue = kPresent ? Get(property, this) : Undefined;
  906. return kPresent;
  907. }
  908. if (GetLength() == 0)
  909. {
  910. index = 0;
  911. value = Undefined;
  912. return false;
  913. }
  914. var callbackfn = arguments.At(0);
  915. var thisArg = arguments.At(1);
  916. var callable = GetCallable(callbackfn);
  917. var args = _engine._jsValueArrayPool.RentArray(3);
  918. args[2] = this;
  919. var length = GetLength();
  920. for (uint k = 0; k < length; k++)
  921. {
  922. if (TryGetValue(k, out var kvalue) || visitUnassigned)
  923. {
  924. args[0] = kvalue;
  925. args[1] = k;
  926. var testResult = callable.Call(thisArg, args);
  927. if (TypeConverter.ToBoolean(testResult))
  928. {
  929. index = k;
  930. value = kvalue;
  931. return true;
  932. }
  933. }
  934. }
  935. _engine._jsValueArrayPool.ReturnArray(args);
  936. index = 0;
  937. value = Undefined;
  938. return false;
  939. }
  940. internal ICallable GetCallable(JsValue source)
  941. {
  942. if (source is ICallable callable)
  943. {
  944. return callable;
  945. }
  946. ExceptionHelper.ThrowTypeError(_engine.Realm, "Argument must be callable");
  947. return null;
  948. }
  949. internal bool IsConcatSpreadable
  950. {
  951. get
  952. {
  953. var spreadable = Get(GlobalSymbolRegistry.IsConcatSpreadable, this);
  954. if (!spreadable.IsUndefined())
  955. {
  956. return TypeConverter.ToBoolean(spreadable);
  957. }
  958. return IsArray();
  959. }
  960. }
  961. public virtual bool IsArrayLike => TryGetValue(CommonProperties.Length, out var lengthValue)
  962. && lengthValue.IsNumber()
  963. && ((JsNumber) lengthValue)._value >= 0;
  964. // safe default
  965. internal virtual bool HasOriginalIterator => false;
  966. internal override bool IsIntegerIndexedArray => false;
  967. public virtual uint Length => (uint) TypeConverter.ToLength(Get(CommonProperties.Length));
  968. public virtual bool PreventExtensions()
  969. {
  970. Extensible = false;
  971. return true;
  972. }
  973. protected internal virtual ObjectInstance GetPrototypeOf()
  974. {
  975. return _prototype;
  976. }
  977. /// <summary>
  978. /// https://tc39.es/ecma262/#sec-ordinarysetprototypeof
  979. /// </summary>
  980. public virtual bool SetPrototypeOf(JsValue value)
  981. {
  982. if (!value.IsObject() && !value.IsNull())
  983. {
  984. ExceptionHelper.ThrowArgumentException();
  985. }
  986. var current = _prototype ?? Null;
  987. if (ReferenceEquals(value, current))
  988. {
  989. return true;
  990. }
  991. if (!Extensible)
  992. {
  993. return false;
  994. }
  995. if (value.IsNull())
  996. {
  997. _prototype = null;
  998. return true;
  999. }
  1000. // validate chain
  1001. var p = value as ObjectInstance;
  1002. bool done = false;
  1003. while (!done)
  1004. {
  1005. if (p is null)
  1006. {
  1007. done = true;
  1008. }
  1009. else if (ReferenceEquals(p, this))
  1010. {
  1011. return false;
  1012. }
  1013. else
  1014. {
  1015. p = p._prototype;
  1016. }
  1017. }
  1018. _prototype = value as ObjectInstance;
  1019. return true;
  1020. }
  1021. /// <summary>
  1022. /// https://tc39.es/ecma262/#sec-setfunctionname
  1023. /// </summary>
  1024. internal void SetFunctionName(JsValue name, string prefix = null)
  1025. {
  1026. if (name is JsSymbol symbol)
  1027. {
  1028. name = symbol._value.IsUndefined()
  1029. ? JsString.Empty
  1030. : new JsString("[" + symbol._value + "]");
  1031. }
  1032. if (!string.IsNullOrWhiteSpace(prefix))
  1033. {
  1034. name = prefix + " " + name;
  1035. }
  1036. DefinePropertyOrThrow(CommonProperties.Name, new PropertyDescriptor(name, PropertyFlag.Configurable));
  1037. }
  1038. /// <summary>
  1039. /// https://tc39.es/ecma262/#sec-createmethodproperty
  1040. /// </summary>
  1041. internal virtual bool CreateMethodProperty(JsValue p, JsValue v)
  1042. {
  1043. var newDesc = new PropertyDescriptor(v, PropertyFlag.NonEnumerable);
  1044. return DefineOwnProperty(p, newDesc);
  1045. }
  1046. /// <summary>
  1047. /// https://tc39.es/ecma262/#sec-createdatapropertyorthrow
  1048. /// </summary>
  1049. internal bool CreateDataProperty(JsValue p, JsValue v)
  1050. {
  1051. var newDesc = new PropertyDescriptor(v, PropertyFlag.ConfigurableEnumerableWritable);
  1052. return DefineOwnProperty(p, newDesc);
  1053. }
  1054. /// <summary>
  1055. /// https://tc39.es/ecma262/#sec-createdataproperty
  1056. /// </summary>
  1057. internal bool CreateDataPropertyOrThrow(JsValue p, JsValue v)
  1058. {
  1059. if (!CreateDataProperty(p, v))
  1060. {
  1061. ExceptionHelper.ThrowTypeError(_engine.Realm);
  1062. }
  1063. return true;
  1064. }
  1065. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1066. internal ICallable GetMethod(JsValue property)
  1067. {
  1068. return GetMethod(_engine.Realm, this, property);
  1069. }
  1070. internal static ICallable GetMethod(Realm realm, JsValue v, JsValue p)
  1071. {
  1072. var jsValue = v.Get(p);
  1073. if (jsValue.IsNullOrUndefined())
  1074. {
  1075. return null;
  1076. }
  1077. var callable = jsValue as ICallable;
  1078. if (callable is null)
  1079. {
  1080. ExceptionHelper.ThrowTypeError(realm, "Value returned for property '" + p + "' of object is not a function");
  1081. }
  1082. return callable;
  1083. }
  1084. internal void CopyDataProperties(
  1085. ObjectInstance target,
  1086. HashSet<JsValue> excludedItems)
  1087. {
  1088. var keys = GetOwnPropertyKeys();
  1089. for (var i = 0; i < keys.Count; i++)
  1090. {
  1091. var key = keys[i];
  1092. if (excludedItems == null || !excludedItems.Contains(key))
  1093. {
  1094. var desc = GetOwnProperty(key);
  1095. if (desc.Enumerable)
  1096. {
  1097. target.CreateDataProperty(key, UnwrapJsValue(desc, this));
  1098. }
  1099. }
  1100. }
  1101. }
  1102. internal ArrayInstance EnumerableOwnPropertyNames(EnumerableOwnPropertyNamesKind kind)
  1103. {
  1104. var ownKeys = GetOwnPropertyKeys(Types.String);
  1105. var array = Engine.Realm.Intrinsics.Array.ArrayCreate((uint) ownKeys.Count);
  1106. uint index = 0;
  1107. for (var i = 0; i < ownKeys.Count; i++)
  1108. {
  1109. var property = ownKeys[i];
  1110. if (!property.IsString())
  1111. {
  1112. continue;
  1113. }
  1114. var desc = GetOwnProperty(property);
  1115. if (desc != PropertyDescriptor.Undefined && desc.Enumerable)
  1116. {
  1117. if (kind == EnumerableOwnPropertyNamesKind.Key)
  1118. {
  1119. array.SetIndexValue(index, property, updateLength: false);
  1120. }
  1121. else
  1122. {
  1123. var value = Get(property);
  1124. if (kind == EnumerableOwnPropertyNamesKind.Value)
  1125. {
  1126. array.SetIndexValue(index, value, updateLength: false);
  1127. }
  1128. else
  1129. {
  1130. var objectInstance = _engine.Realm.Intrinsics.Array.ArrayCreate(2);
  1131. objectInstance.SetIndexValue(0, property, updateLength: false);
  1132. objectInstance.SetIndexValue(1, value, updateLength: false);
  1133. array.SetIndexValue(index, objectInstance, updateLength: false);
  1134. }
  1135. }
  1136. index++;
  1137. }
  1138. }
  1139. array.SetLength(index);
  1140. return array;
  1141. }
  1142. internal enum EnumerableOwnPropertyNamesKind
  1143. {
  1144. Key,
  1145. Value,
  1146. KeyValue
  1147. }
  1148. internal ObjectInstance AssertThisIsObjectInstance(JsValue value, string methodName)
  1149. {
  1150. var instance = value as ObjectInstance;
  1151. if (instance is null)
  1152. {
  1153. ThrowIncompatibleReceiver(value, methodName);
  1154. }
  1155. return instance;
  1156. }
  1157. [MethodImpl(MethodImplOptions.NoInlining)]
  1158. private void ThrowIncompatibleReceiver(JsValue value, string methodName)
  1159. {
  1160. ExceptionHelper.ThrowTypeError(_engine.Realm, $"Method {methodName} called on incompatible receiver {value}");
  1161. }
  1162. public override bool Equals(JsValue obj)
  1163. {
  1164. return Equals(obj as ObjectInstance);
  1165. }
  1166. public bool Equals(ObjectInstance other)
  1167. {
  1168. if (other is null)
  1169. {
  1170. return false;
  1171. }
  1172. if (ReferenceEquals(this, other))
  1173. {
  1174. return true;
  1175. }
  1176. return false;
  1177. }
  1178. public override string ToString()
  1179. {
  1180. return TypeConverter.ToString(this);
  1181. }
  1182. }
  1183. }