ObjectInstance.cs 52 KB

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