ObjectInstance.cs 42 KB

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