ObjectInstance.cs 44 KB

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