ObjectInstance.cs 43 KB

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