ObjectInstance.cs 46 KB

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