ObjectInstance.cs 43 KB

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