ObjectInstance.cs 44 KB

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