ObjectInstance.cs 39 KB

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