ObjectInstance.cs 45 KB

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