ObjectInstance.cs 47 KB

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