ObjectInstance.cs 53 KB

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