ObjectInstance.cs 52 KB

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