ObjectInstance.cs 45 KB

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