ObjectInstance.cs 42 KB

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