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