ObjectInstance.cs 44 KB

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