ObjectInstance.cs 56 KB

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