ObjectInstance.cs 41 KB

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