ObjectInstance.cs 41 KB

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