2
0

ObjectInstance.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353
  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 object ToObject()
  759. {
  760. return ToObject(new ObjectTraverseStack(_engine));
  761. }
  762. private object ToObject(ObjectTraverseStack stack)
  763. {
  764. if (this is IObjectWrapper wrapper)
  765. {
  766. return wrapper.Target;
  767. }
  768. stack.Enter(this);
  769. object converted = null;
  770. switch (Class)
  771. {
  772. case ObjectClass.Array:
  773. if (this is ArrayInstance arrayInstance)
  774. {
  775. var result = new object[arrayInstance.Length];
  776. for (uint i = 0; i < result.Length; i++)
  777. {
  778. var value = arrayInstance[i];
  779. object valueToSet = null;
  780. if (!value.IsUndefined())
  781. {
  782. valueToSet = value is ObjectInstance oi
  783. ? oi.ToObject(stack)
  784. : value.ToObject();
  785. }
  786. result[i] = valueToSet;
  787. }
  788. converted = result;
  789. }
  790. break;
  791. case ObjectClass.String:
  792. if (this is StringInstance stringInstance)
  793. {
  794. converted = stringInstance.PrimitiveValue.ToString();
  795. }
  796. break;
  797. case ObjectClass.Date:
  798. if (this is DateInstance dateInstance)
  799. {
  800. converted = dateInstance.ToDateTime();
  801. }
  802. break;
  803. case ObjectClass.Boolean:
  804. if (this is BooleanInstance booleanInstance)
  805. {
  806. converted = ((JsBoolean) booleanInstance.PrimitiveValue)._value
  807. ? JsBoolean.BoxedTrue
  808. : JsBoolean.BoxedFalse;
  809. }
  810. break;
  811. case ObjectClass.Function:
  812. if (this is FunctionInstance function)
  813. {
  814. converted = (Func<JsValue, JsValue[], JsValue>) function.Call;
  815. }
  816. break;
  817. case ObjectClass.Number:
  818. if (this is NumberInstance numberInstance)
  819. {
  820. converted = numberInstance.NumberData._value;
  821. }
  822. break;
  823. case ObjectClass.RegExp:
  824. if (this is RegExpInstance regeExpInstance)
  825. {
  826. converted = regeExpInstance.Value;
  827. }
  828. break;
  829. case ObjectClass.Arguments:
  830. case ObjectClass.Object:
  831. IDictionary<string, object> o = new ExpandoObject();
  832. foreach (var p in GetOwnProperties())
  833. {
  834. if (!p.Value.Enumerable)
  835. {
  836. continue;
  837. }
  838. var key = p.Key.ToString();
  839. var propertyValue = Get(p.Key, this);
  840. var value = propertyValue is ObjectInstance oi
  841. ? oi.ToObject(stack)
  842. : propertyValue.ToObject();
  843. o.Add(key, value);
  844. }
  845. converted = o;
  846. break;
  847. default:
  848. converted = this;
  849. break;
  850. }
  851. stack.Exit();
  852. return converted;
  853. }
  854. /// <summary>
  855. /// Handles the generic find of (callback[, thisArg])
  856. /// </summary>
  857. internal virtual bool FindWithCallback(
  858. JsValue[] arguments,
  859. out uint index,
  860. out JsValue value,
  861. bool visitUnassigned)
  862. {
  863. long GetLength()
  864. {
  865. var desc = GetProperty(CommonProperties.Length);
  866. var descValue = desc.Value;
  867. double len;
  868. if (desc.IsDataDescriptor() && !ReferenceEquals(descValue, null))
  869. {
  870. len = TypeConverter.ToNumber(descValue);
  871. }
  872. else
  873. {
  874. var getter = desc.Get ?? Undefined;
  875. if (getter.IsUndefined())
  876. {
  877. len = 0;
  878. }
  879. else
  880. {
  881. // if getter is not undefined it must be ICallable
  882. len = TypeConverter.ToNumber(((ICallable) getter).Call(this, Arguments.Empty));
  883. }
  884. }
  885. return (long) System.Math.Max(
  886. 0,
  887. System.Math.Min(len, ArrayOperations.MaxArrayLikeLength));
  888. }
  889. bool TryGetValue(uint idx, out JsValue jsValue)
  890. {
  891. var property = JsString.Create(idx);
  892. var kPresent = HasProperty(property);
  893. jsValue = kPresent ? Get(property, this) : Undefined;
  894. return kPresent;
  895. }
  896. if (GetLength() == 0)
  897. {
  898. index = 0;
  899. value = Undefined;
  900. return false;
  901. }
  902. var callbackfn = arguments.At(0);
  903. var thisArg = arguments.At(1);
  904. var callable = GetCallable(callbackfn);
  905. var args = _engine._jsValueArrayPool.RentArray(3);
  906. args[2] = this;
  907. var length = GetLength();
  908. for (uint k = 0; k < length; k++)
  909. {
  910. if (TryGetValue(k, out var kvalue) || visitUnassigned)
  911. {
  912. args[0] = kvalue;
  913. args[1] = k;
  914. var testResult = callable.Call(thisArg, args);
  915. if (TypeConverter.ToBoolean(testResult))
  916. {
  917. index = k;
  918. value = kvalue;
  919. return true;
  920. }
  921. }
  922. }
  923. _engine._jsValueArrayPool.ReturnArray(args);
  924. index = 0;
  925. value = Undefined;
  926. return false;
  927. }
  928. protected ICallable GetCallable(JsValue source)
  929. {
  930. if (source is ICallable callable)
  931. {
  932. return callable;
  933. }
  934. ExceptionHelper.ThrowTypeError(_engine.Realm, "Argument must be callable");
  935. return null;
  936. }
  937. internal bool IsConcatSpreadable
  938. {
  939. get
  940. {
  941. var spreadable = Get(GlobalSymbolRegistry.IsConcatSpreadable, this);
  942. if (!spreadable.IsUndefined())
  943. {
  944. return TypeConverter.ToBoolean(spreadable);
  945. }
  946. return IsArray();
  947. }
  948. }
  949. public virtual bool IsArrayLike => TryGetValue(CommonProperties.Length, out var lengthValue)
  950. && lengthValue.IsNumber()
  951. && ((JsNumber) lengthValue)._value >= 0;
  952. // safe default
  953. internal virtual bool HasOriginalIterator => false;
  954. internal override bool IsIntegerIndexedArray => false;
  955. public virtual uint Length => (uint) TypeConverter.ToLength(Get(CommonProperties.Length));
  956. public virtual JsValue PreventExtensions()
  957. {
  958. Extensible = false;
  959. return JsBoolean.True;
  960. }
  961. protected internal virtual ObjectInstance GetPrototypeOf()
  962. {
  963. return _prototype;
  964. }
  965. /// <summary>
  966. /// https://tc39.es/ecma262/#sec-ordinarysetprototypeof
  967. /// </summary>
  968. public virtual bool SetPrototypeOf(JsValue value)
  969. {
  970. if (!value.IsObject() && !value.IsNull())
  971. {
  972. ExceptionHelper.ThrowArgumentException();
  973. }
  974. var current = _prototype ?? Null;
  975. if (ReferenceEquals(value, current))
  976. {
  977. return true;
  978. }
  979. if (!Extensible)
  980. {
  981. return false;
  982. }
  983. if (value.IsNull())
  984. {
  985. _prototype = null;
  986. return true;
  987. }
  988. // validate chain
  989. var p = value as ObjectInstance;
  990. bool done = false;
  991. while (!done)
  992. {
  993. if (p is null)
  994. {
  995. done = true;
  996. }
  997. else if (ReferenceEquals(p, this))
  998. {
  999. return false;
  1000. }
  1001. else
  1002. {
  1003. p = p._prototype;
  1004. }
  1005. }
  1006. _prototype = value as ObjectInstance;
  1007. return true;
  1008. }
  1009. /// <summary>
  1010. /// https://tc39.es/ecma262/#sec-createmethodproperty
  1011. /// </summary>
  1012. internal virtual bool CreateMethodProperty(JsValue p, JsValue v)
  1013. {
  1014. var newDesc = new PropertyDescriptor(v, PropertyFlag.NonEnumerable);
  1015. return DefineOwnProperty(p, newDesc);
  1016. }
  1017. /// <summary>
  1018. /// https://tc39.es/ecma262/#sec-createdatapropertyorthrow
  1019. /// </summary>
  1020. internal bool CreateDataProperty(JsValue p, JsValue v)
  1021. {
  1022. var newDesc = new PropertyDescriptor(v, PropertyFlag.ConfigurableEnumerableWritable);
  1023. return DefineOwnProperty(p, newDesc);
  1024. }
  1025. /// <summary>
  1026. /// https://tc39.es/ecma262/#sec-createdataproperty
  1027. /// </summary>
  1028. internal bool CreateDataPropertyOrThrow(JsValue p, JsValue v)
  1029. {
  1030. if (!CreateDataProperty(p, v))
  1031. {
  1032. ExceptionHelper.ThrowTypeError(_engine.Realm);
  1033. }
  1034. return true;
  1035. }
  1036. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1037. internal ICallable GetMethod(JsValue property)
  1038. {
  1039. return GetMethod(_engine.Realm, this, property);
  1040. }
  1041. internal static ICallable GetMethod(Realm realm, JsValue v, JsValue p)
  1042. {
  1043. var jsValue = v.Get(p);
  1044. if (jsValue.IsNullOrUndefined())
  1045. {
  1046. return null;
  1047. }
  1048. var callable = jsValue as ICallable;
  1049. if (callable is null)
  1050. {
  1051. ExceptionHelper.ThrowTypeError(realm, "Value returned for property '" + p + "' of object is not a function");
  1052. }
  1053. return callable;
  1054. }
  1055. internal void CopyDataProperties(
  1056. ObjectInstance target,
  1057. HashSet<JsValue> excludedItems)
  1058. {
  1059. var keys = GetOwnPropertyKeys();
  1060. for (var i = 0; i < keys.Count; i++)
  1061. {
  1062. var key = keys[i];
  1063. if (excludedItems == null || !excludedItems.Contains(key))
  1064. {
  1065. var desc = GetOwnProperty(key);
  1066. if (desc.Enumerable)
  1067. {
  1068. target.CreateDataProperty(key, UnwrapJsValue(desc, this));
  1069. }
  1070. }
  1071. }
  1072. }
  1073. internal ArrayInstance EnumerableOwnPropertyNames(EnumerableOwnPropertyNamesKind kind)
  1074. {
  1075. var ownKeys = GetOwnPropertyKeys(Types.String);
  1076. var array = Engine.Realm.Intrinsics.Array.ConstructFast((uint) ownKeys.Count);
  1077. uint index = 0;
  1078. for (var i = 0; i < ownKeys.Count; i++)
  1079. {
  1080. var property = ownKeys[i];
  1081. if (!property.IsString())
  1082. {
  1083. continue;
  1084. }
  1085. var desc = GetOwnProperty(property);
  1086. if (desc != PropertyDescriptor.Undefined && desc.Enumerable)
  1087. {
  1088. if (kind == EnumerableOwnPropertyNamesKind.Key)
  1089. {
  1090. array.SetIndexValue(index, property, updateLength: false);
  1091. }
  1092. else
  1093. {
  1094. var value = Get(property);
  1095. if (kind == EnumerableOwnPropertyNamesKind.Value)
  1096. {
  1097. array.SetIndexValue(index, value, updateLength: false);
  1098. }
  1099. else
  1100. {
  1101. var objectInstance = _engine.Realm.Intrinsics.Array.ConstructFast(2);
  1102. objectInstance.SetIndexValue(0, property, updateLength: false);
  1103. objectInstance.SetIndexValue(1, value, updateLength: false);
  1104. array.SetIndexValue(index, objectInstance, updateLength: false);
  1105. }
  1106. }
  1107. index++;
  1108. }
  1109. }
  1110. array.SetLength(index);
  1111. return array;
  1112. }
  1113. internal enum EnumerableOwnPropertyNamesKind
  1114. {
  1115. Key,
  1116. Value,
  1117. KeyValue
  1118. }
  1119. internal ObjectInstance AssertThisIsObjectInstance(JsValue value, string methodName)
  1120. {
  1121. var instance = value as ObjectInstance;
  1122. if (instance is null)
  1123. {
  1124. ThrowIncompatibleReceiver(value, methodName);
  1125. }
  1126. return instance;
  1127. }
  1128. [MethodImpl(MethodImplOptions.NoInlining)]
  1129. private void ThrowIncompatibleReceiver(JsValue value, string methodName)
  1130. {
  1131. ExceptionHelper.ThrowTypeError(_engine.Realm, $"Method {methodName} called on incompatible receiver {value}");
  1132. }
  1133. public override bool Equals(JsValue obj)
  1134. {
  1135. if (ReferenceEquals(null, obj))
  1136. {
  1137. return false;
  1138. }
  1139. if (!(obj is ObjectInstance s))
  1140. {
  1141. return false;
  1142. }
  1143. return Equals(s);
  1144. }
  1145. public bool Equals(ObjectInstance other)
  1146. {
  1147. if (ReferenceEquals(null, other))
  1148. {
  1149. return false;
  1150. }
  1151. if (ReferenceEquals(this, other))
  1152. {
  1153. return true;
  1154. }
  1155. return false;
  1156. }
  1157. public override string ToString()
  1158. {
  1159. return TypeConverter.ToString(this);
  1160. }
  1161. }
  1162. }