ObjectInstance.cs 42 KB

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