ObjectInstance.cs 44 KB

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