ObjectInstance.cs 44 KB

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