ObjectInstance.cs 39 KB

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