ObjectInstance.cs 52 KB

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