ObjectInstance.cs 51 KB

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