ObjectInstance.cs 57 KB

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