ObjectInstance.cs 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410
  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. /// <summary>
  391. /// https://tc39.es/ecma262/#sec-ordinarysetwithowndescriptor
  392. /// </summary>
  393. public override bool Set(JsValue property, JsValue value, JsValue receiver)
  394. {
  395. var ownDesc = GetOwnProperty(property);
  396. if (ownDesc == PropertyDescriptor.Undefined)
  397. {
  398. var parent = GetPrototypeOf();
  399. if (parent is not null)
  400. {
  401. return parent.Set(property, value, receiver);
  402. }
  403. ownDesc = new PropertyDescriptor(Undefined, PropertyFlag.ConfigurableEnumerableWritable);
  404. }
  405. if (ownDesc.IsDataDescriptor())
  406. {
  407. if (!ownDesc.Writable)
  408. {
  409. return false;
  410. }
  411. if (receiver is not ObjectInstance oi)
  412. {
  413. return false;
  414. }
  415. var existingDescriptor = oi.GetOwnProperty(property);
  416. if (existingDescriptor != PropertyDescriptor.Undefined)
  417. {
  418. if (existingDescriptor.IsAccessorDescriptor())
  419. {
  420. return false;
  421. }
  422. if (!existingDescriptor.Writable)
  423. {
  424. return false;
  425. }
  426. var valueDesc = new PropertyDescriptor(value, PropertyFlag.None);
  427. return oi.DefineOwnProperty(property, valueDesc);
  428. }
  429. else
  430. {
  431. return oi.CreateDataProperty(property, value);
  432. }
  433. }
  434. if (ownDesc.Set is not FunctionInstance setter)
  435. {
  436. return false;
  437. }
  438. _engine.Call(setter, receiver, new[] { value }, expression: null);
  439. return true;
  440. }
  441. /// <summary>
  442. /// Returns a Boolean value indicating whether a
  443. /// [[Put]] operation with PropertyName can be
  444. /// performed.
  445. /// http://www.ecma-international.org/ecma-262/5.1/#sec-8.12.4
  446. /// </summary>
  447. public bool CanPut(JsValue property)
  448. {
  449. var desc = GetOwnProperty(property);
  450. if (desc != PropertyDescriptor.Undefined)
  451. {
  452. if (desc.IsAccessorDescriptor())
  453. {
  454. var set = desc.Set;
  455. if (ReferenceEquals(set, null) || set.IsUndefined())
  456. {
  457. return false;
  458. }
  459. return true;
  460. }
  461. return desc.Writable;
  462. }
  463. if (ReferenceEquals(Prototype, null))
  464. {
  465. return Extensible;
  466. }
  467. var inherited = Prototype.GetProperty(property);
  468. if (inherited == PropertyDescriptor.Undefined)
  469. {
  470. return Extensible;
  471. }
  472. if (inherited.IsAccessorDescriptor())
  473. {
  474. var set = inherited.Set;
  475. if (ReferenceEquals(set, null) || set.IsUndefined())
  476. {
  477. return false;
  478. }
  479. return true;
  480. }
  481. if (!Extensible)
  482. {
  483. return false;
  484. }
  485. return inherited.Writable;
  486. }
  487. /// <summary>
  488. /// https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-hasproperty-p
  489. /// </summary>
  490. public virtual bool HasProperty(JsValue property)
  491. {
  492. var hasOwn = GetOwnProperty(property);
  493. if (hasOwn != PropertyDescriptor.Undefined)
  494. {
  495. return true;
  496. }
  497. var parent = GetPrototypeOf();
  498. if (parent != null)
  499. {
  500. return parent.HasProperty(property);
  501. }
  502. return false;
  503. }
  504. /// <summary>
  505. /// https://tc39.es/ecma262/#sec-deletepropertyorthrow
  506. /// </summary>
  507. public bool DeletePropertyOrThrow(JsValue property)
  508. {
  509. if (!Delete(property))
  510. {
  511. ExceptionHelper.ThrowTypeError(_engine.Realm);
  512. }
  513. return true;
  514. }
  515. /// <summary>
  516. /// Removes the specified named own property
  517. /// from the object. The flag controls failure
  518. /// handling.
  519. /// </summary>
  520. public virtual bool Delete(JsValue property)
  521. {
  522. var desc = GetOwnProperty(property);
  523. if (desc == PropertyDescriptor.Undefined)
  524. {
  525. return true;
  526. }
  527. if (desc.Configurable)
  528. {
  529. RemoveOwnProperty(property);
  530. return true;
  531. }
  532. return false;
  533. }
  534. public bool DefinePropertyOrThrow(JsValue property, PropertyDescriptor desc)
  535. {
  536. if (!DefineOwnProperty(property, desc))
  537. {
  538. ExceptionHelper.ThrowTypeError(_engine.Realm, "Cannot redefine property: " + property);
  539. }
  540. return true;
  541. }
  542. /// <summary>
  543. /// Creates or alters the named own property to have the state described by a PropertyDescriptor.
  544. /// </summary>
  545. public virtual bool DefineOwnProperty(JsValue property, PropertyDescriptor desc)
  546. {
  547. var current = GetOwnProperty(property);
  548. if (current == desc)
  549. {
  550. return true;
  551. }
  552. return ValidateAndApplyPropertyDescriptor(this, property, Extensible, desc, current);
  553. }
  554. /// <summary>
  555. /// https://tc39.es/ecma262/#sec-validateandapplypropertydescriptor
  556. /// </summary>
  557. protected static bool ValidateAndApplyPropertyDescriptor(ObjectInstance? o, JsValue property, bool extensible, PropertyDescriptor desc, PropertyDescriptor current)
  558. {
  559. var descValue = desc.Value;
  560. if (current == PropertyDescriptor.Undefined)
  561. {
  562. if (!extensible)
  563. {
  564. return false;
  565. }
  566. if (o is not null)
  567. {
  568. if (desc.IsGenericDescriptor() || desc.IsDataDescriptor())
  569. {
  570. PropertyDescriptor propertyDescriptor;
  571. if ((desc._flags & PropertyFlag.ConfigurableEnumerableWritable) == PropertyFlag.ConfigurableEnumerableWritable)
  572. {
  573. propertyDescriptor = new PropertyDescriptor(descValue ?? Undefined, PropertyFlag.ConfigurableEnumerableWritable);
  574. }
  575. else if ((desc._flags & PropertyFlag.ConfigurableEnumerableWritable) == 0)
  576. {
  577. propertyDescriptor = new PropertyDescriptor(descValue ?? Undefined, PropertyFlag.AllForbidden);
  578. }
  579. else
  580. {
  581. propertyDescriptor = new PropertyDescriptor(desc)
  582. {
  583. Value = descValue ?? Undefined
  584. };
  585. }
  586. o.SetOwnProperty(property, propertyDescriptor);
  587. }
  588. else
  589. {
  590. var descriptor = new GetSetPropertyDescriptor(desc.Get, desc.Set, PropertyFlag.None)
  591. {
  592. Enumerable = desc.Enumerable,
  593. Configurable = desc.Configurable
  594. };
  595. o.SetOwnProperty(property, descriptor);
  596. }
  597. }
  598. return true;
  599. }
  600. // Step 3
  601. var currentGet = current.Get;
  602. var currentSet = current.Set;
  603. var currentValue = current.Value;
  604. // 4. If every field in Desc is absent, return true.
  605. if ((current._flags & (PropertyFlag.ConfigurableSet | PropertyFlag.EnumerableSet | PropertyFlag.WritableSet)) == 0 &&
  606. ReferenceEquals(currentGet, null) &&
  607. ReferenceEquals(currentSet, null) &&
  608. ReferenceEquals(currentValue, null))
  609. {
  610. return true;
  611. }
  612. // Step 6
  613. var descGet = desc.Get;
  614. var descSet = desc.Set;
  615. if (
  616. current.Configurable == desc.Configurable && current.ConfigurableSet == desc.ConfigurableSet &&
  617. current.Writable == desc.Writable && current.WritableSet == desc.WritableSet &&
  618. current.Enumerable == desc.Enumerable && current.EnumerableSet == desc.EnumerableSet &&
  619. ((ReferenceEquals(currentGet, null) && ReferenceEquals(descGet, null)) || (!ReferenceEquals(currentGet, null) && !ReferenceEquals(descGet, null) && SameValue(currentGet, descGet))) &&
  620. ((ReferenceEquals(currentSet, null) && ReferenceEquals(descSet, null)) || (!ReferenceEquals(currentSet, null) && !ReferenceEquals(descSet, null) && SameValue(currentSet, descSet))) &&
  621. ((ReferenceEquals(currentValue, null) && ReferenceEquals(descValue, null)) || (!ReferenceEquals(currentValue, null) && !ReferenceEquals(descValue, null) && currentValue == descValue))
  622. )
  623. {
  624. return true;
  625. }
  626. if (!current.Configurable)
  627. {
  628. if (desc.Configurable)
  629. {
  630. return false;
  631. }
  632. if (desc.EnumerableSet && (desc.Enumerable != current.Enumerable))
  633. {
  634. return false;
  635. }
  636. }
  637. if (!desc.IsGenericDescriptor())
  638. {
  639. if (current.IsDataDescriptor() != desc.IsDataDescriptor())
  640. {
  641. if (!current.Configurable)
  642. {
  643. return false;
  644. }
  645. if (o is not null)
  646. {
  647. var flags = current.Flags & ~(PropertyFlag.Writable | PropertyFlag.WritableSet | PropertyFlag.CustomJsValue);
  648. if (current.IsDataDescriptor())
  649. {
  650. o.SetOwnProperty(property, current = new GetSetPropertyDescriptor(
  651. get: Undefined,
  652. set: Undefined,
  653. flags
  654. ));
  655. }
  656. else
  657. {
  658. o.SetOwnProperty(property, current = new PropertyDescriptor(
  659. value: Undefined,
  660. flags
  661. ));
  662. }
  663. }
  664. }
  665. else if (current.IsDataDescriptor() && desc.IsDataDescriptor())
  666. {
  667. if (!current.Configurable)
  668. {
  669. if (!current.Writable && desc.Writable)
  670. {
  671. return false;
  672. }
  673. if (!current.Writable)
  674. {
  675. if (!ReferenceEquals(descValue, null) && !SameValue(descValue, currentValue!))
  676. {
  677. return false;
  678. }
  679. }
  680. }
  681. }
  682. else if (current.IsAccessorDescriptor() && desc.IsAccessorDescriptor())
  683. {
  684. if (!current.Configurable)
  685. {
  686. if ((!ReferenceEquals(descSet, null) && !SameValue(descSet, currentSet ?? Undefined))
  687. ||
  688. (!ReferenceEquals(descGet, null) && !SameValue(descGet, currentGet ?? Undefined)))
  689. {
  690. return false;
  691. }
  692. }
  693. }
  694. }
  695. if (o is not null)
  696. {
  697. if (!ReferenceEquals(descValue, null))
  698. {
  699. current.Value = descValue;
  700. }
  701. if (desc.WritableSet)
  702. {
  703. current.Writable = desc.Writable;
  704. }
  705. if (desc.EnumerableSet)
  706. {
  707. current.Enumerable = desc.Enumerable;
  708. }
  709. if (desc.ConfigurableSet)
  710. {
  711. current.Configurable = desc.Configurable;
  712. }
  713. PropertyDescriptor? mutable = null;
  714. if (!ReferenceEquals(descGet, null))
  715. {
  716. mutable = new GetSetPropertyDescriptor(mutable ?? current);
  717. ((GetSetPropertyDescriptor) mutable).SetGet(descGet);
  718. }
  719. if (!ReferenceEquals(descSet, null))
  720. {
  721. mutable = new GetSetPropertyDescriptor(mutable ?? current);
  722. ((GetSetPropertyDescriptor) mutable).SetSet(descSet);
  723. }
  724. if (mutable != null)
  725. {
  726. // replace old with new type that supports get and set
  727. o.FastSetProperty(property, mutable);
  728. }
  729. }
  730. return true;
  731. }
  732. /// <summary>
  733. /// Optimized version of [[Put]] when the property is known to be undeclared already
  734. /// </summary>
  735. public void FastAddProperty(JsValue name, JsValue value, bool writable, bool enumerable, bool configurable)
  736. {
  737. SetOwnProperty(name, new PropertyDescriptor(value, writable, enumerable, configurable));
  738. }
  739. /// <summary>
  740. /// Optimized version of [[Put]] when the property is known to be already declared
  741. /// </summary>
  742. /// <param name="name"></param>
  743. /// <param name="value"></param>
  744. public void FastSetProperty(JsValue name, PropertyDescriptor value)
  745. {
  746. SetOwnProperty(name, value);
  747. }
  748. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  749. protected internal void EnsureInitialized()
  750. {
  751. if (_initialized)
  752. {
  753. return;
  754. }
  755. // we need to set flag eagerly to prevent wrong recursion
  756. _initialized = true;
  757. Initialize();
  758. }
  759. protected virtual void Initialize()
  760. {
  761. }
  762. public override object ToObject()
  763. {
  764. return ToObject(new ObjectTraverseStack(_engine));
  765. }
  766. private object ToObject(ObjectTraverseStack stack)
  767. {
  768. if (this is IObjectWrapper wrapper)
  769. {
  770. return wrapper.Target;
  771. }
  772. stack.Enter(this);
  773. object? converted = null;
  774. switch (Class)
  775. {
  776. case ObjectClass.String:
  777. if (this is StringInstance stringInstance)
  778. {
  779. converted = stringInstance.StringData.ToString();
  780. }
  781. break;
  782. case ObjectClass.Date:
  783. if (this is DateInstance dateInstance)
  784. {
  785. converted = dateInstance.ToDateTime();
  786. }
  787. break;
  788. case ObjectClass.Boolean:
  789. if (this is BooleanInstance booleanInstance)
  790. {
  791. converted = ((JsBoolean) booleanInstance.BooleanData)._value
  792. ? JsBoolean.BoxedTrue
  793. : JsBoolean.BoxedFalse;
  794. }
  795. break;
  796. case ObjectClass.Function:
  797. if (this is ICallable function)
  798. {
  799. converted = (Func<JsValue, JsValue[], JsValue>) function.Call;
  800. }
  801. break;
  802. case ObjectClass.Number:
  803. if (this is NumberInstance numberInstance)
  804. {
  805. converted = numberInstance.NumberData._value;
  806. }
  807. break;
  808. case ObjectClass.RegExp:
  809. if (this is RegExpInstance regeExpInstance)
  810. {
  811. converted = regeExpInstance.Value;
  812. }
  813. break;
  814. case ObjectClass.Arguments:
  815. case ObjectClass.Object:
  816. if (this is ArrayInstance arrayInstance)
  817. {
  818. var result = new object?[arrayInstance.Length];
  819. for (uint i = 0; i < result.Length; i++)
  820. {
  821. var value = arrayInstance[i];
  822. object? valueToSet = null;
  823. if (!value.IsUndefined())
  824. {
  825. valueToSet = value is ObjectInstance oi
  826. ? oi.ToObject(stack)
  827. : value.ToObject();
  828. }
  829. result[i] = valueToSet;
  830. }
  831. converted = result;
  832. break;
  833. }
  834. var o = _engine.Options.Interop.CreateClrObject(this);
  835. foreach (var p in GetOwnProperties())
  836. {
  837. if (!p.Value.Enumerable)
  838. {
  839. continue;
  840. }
  841. var key = p.Key.ToString();
  842. var propertyValue = Get(p.Key);
  843. var value = propertyValue is ObjectInstance oi
  844. ? oi.ToObject(stack)
  845. : propertyValue.ToObject();
  846. o.Add(key, value);
  847. }
  848. converted = o;
  849. break;
  850. default:
  851. converted = this;
  852. break;
  853. }
  854. stack.Exit();
  855. return converted!;
  856. }
  857. /// <summary>
  858. /// Handles the generic find of (callback[, thisArg])
  859. /// </summary>
  860. internal virtual bool FindWithCallback(
  861. JsValue[] arguments,
  862. out uint index,
  863. out JsValue value,
  864. bool visitUnassigned,
  865. bool fromEnd = false)
  866. {
  867. long GetLength()
  868. {
  869. var desc = GetProperty(CommonProperties.Length);
  870. var descValue = desc.Value;
  871. double len;
  872. if (desc.IsDataDescriptor() && !ReferenceEquals(descValue, null))
  873. {
  874. len = TypeConverter.ToNumber(descValue);
  875. }
  876. else
  877. {
  878. var getter = desc.Get ?? Undefined;
  879. if (getter.IsUndefined())
  880. {
  881. len = 0;
  882. }
  883. else
  884. {
  885. // if getter is not undefined it must be ICallable
  886. len = TypeConverter.ToNumber(((ICallable) getter).Call(this, Arguments.Empty));
  887. }
  888. }
  889. return (long) System.Math.Max(
  890. 0,
  891. System.Math.Min(len, ArrayOperations.MaxArrayLikeLength));
  892. }
  893. bool TryGetValue(uint idx, out JsValue jsValue)
  894. {
  895. var property = JsString.Create(idx);
  896. var kPresent = HasProperty(property);
  897. jsValue = kPresent ? Get(property, this) : Undefined;
  898. return kPresent;
  899. }
  900. if (GetLength() == 0)
  901. {
  902. index = 0;
  903. value = Undefined;
  904. return false;
  905. }
  906. var callbackfn = arguments.At(0);
  907. var thisArg = arguments.At(1);
  908. var callable = GetCallable(callbackfn);
  909. var args = _engine._jsValueArrayPool.RentArray(3);
  910. args[2] = this;
  911. var length = GetLength();
  912. for (uint k = 0; k < length; k++)
  913. {
  914. if (TryGetValue(k, out var kvalue) || visitUnassigned)
  915. {
  916. args[0] = kvalue;
  917. args[1] = k;
  918. var testResult = callable.Call(thisArg, args);
  919. if (TypeConverter.ToBoolean(testResult))
  920. {
  921. index = k;
  922. value = kvalue;
  923. return true;
  924. }
  925. }
  926. }
  927. _engine._jsValueArrayPool.ReturnArray(args);
  928. index = 0;
  929. value = Undefined;
  930. return false;
  931. }
  932. internal ICallable GetCallable(JsValue source)
  933. {
  934. if (source is ICallable callable)
  935. {
  936. return callable;
  937. }
  938. ExceptionHelper.ThrowTypeError(_engine.Realm, "Argument must be callable");
  939. return null;
  940. }
  941. internal bool IsConcatSpreadable
  942. {
  943. get
  944. {
  945. var spreadable = Get(GlobalSymbolRegistry.IsConcatSpreadable, this);
  946. if (!spreadable.IsUndefined())
  947. {
  948. return TypeConverter.ToBoolean(spreadable);
  949. }
  950. return IsArray();
  951. }
  952. }
  953. public virtual bool IsArrayLike => TryGetValue(CommonProperties.Length, out var lengthValue)
  954. && lengthValue.IsNumber()
  955. && ((JsNumber) lengthValue)._value >= 0;
  956. // safe default
  957. internal virtual bool HasOriginalIterator => false;
  958. internal override bool IsIntegerIndexedArray => false;
  959. public virtual uint Length => (uint) TypeConverter.ToLength(Get(CommonProperties.Length));
  960. public virtual bool PreventExtensions()
  961. {
  962. Extensible = false;
  963. return true;
  964. }
  965. protected internal virtual ObjectInstance? GetPrototypeOf()
  966. {
  967. return _prototype;
  968. }
  969. /// <summary>
  970. /// https://tc39.es/ecma262/#sec-ordinarysetprototypeof
  971. /// </summary>
  972. public virtual bool SetPrototypeOf(JsValue value)
  973. {
  974. if (!value.IsObject() && !value.IsNull())
  975. {
  976. ExceptionHelper.ThrowArgumentException();
  977. }
  978. var current = _prototype ?? Null;
  979. if (ReferenceEquals(value, current))
  980. {
  981. return true;
  982. }
  983. if (!Extensible)
  984. {
  985. return false;
  986. }
  987. if (value.IsNull())
  988. {
  989. _prototype = null;
  990. return true;
  991. }
  992. // validate chain
  993. var p = value as ObjectInstance;
  994. bool done = false;
  995. while (!done)
  996. {
  997. if (p is null)
  998. {
  999. done = true;
  1000. }
  1001. else if (ReferenceEquals(p, this))
  1002. {
  1003. return false;
  1004. }
  1005. else
  1006. {
  1007. p = p._prototype;
  1008. }
  1009. }
  1010. _prototype = value as ObjectInstance;
  1011. return true;
  1012. }
  1013. /// <summary>
  1014. /// https://tc39.es/ecma262/#sec-setfunctionname
  1015. /// </summary>
  1016. internal void SetFunctionName(JsValue name, string? prefix = null)
  1017. {
  1018. if (name is JsSymbol symbol)
  1019. {
  1020. name = symbol._value.IsUndefined()
  1021. ? JsString.Empty
  1022. : new JsString("[" + symbol._value + "]");
  1023. }
  1024. if (!string.IsNullOrWhiteSpace(prefix))
  1025. {
  1026. name = prefix + " " + name;
  1027. }
  1028. DefinePropertyOrThrow(CommonProperties.Name, new PropertyDescriptor(name, PropertyFlag.Configurable));
  1029. }
  1030. /// <summary>
  1031. /// https://tc39.es/ecma262/#sec-createmethodproperty
  1032. /// </summary>
  1033. internal virtual bool CreateMethodProperty(JsValue p, JsValue v)
  1034. {
  1035. var newDesc = new PropertyDescriptor(v, PropertyFlag.NonEnumerable);
  1036. return DefineOwnProperty(p, newDesc);
  1037. }
  1038. /// <summary>
  1039. /// https://tc39.es/ecma262/#sec-createdatapropertyorthrow
  1040. /// </summary>
  1041. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1042. internal bool CreateDataProperty(JsValue p, JsValue v)
  1043. {
  1044. return DefineOwnProperty(p, new PropertyDescriptor(v, PropertyFlag.ConfigurableEnumerableWritable));
  1045. }
  1046. /// <summary>
  1047. /// https://tc39.es/ecma262/#sec-createdataproperty
  1048. /// </summary>
  1049. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1050. internal bool CreateDataPropertyOrThrow(JsValue p, JsValue v)
  1051. {
  1052. if (!CreateDataProperty(p, v))
  1053. {
  1054. ExceptionHelper.ThrowTypeError(_engine.Realm);
  1055. }
  1056. return true;
  1057. }
  1058. /// <summary>
  1059. /// https://tc39.es/ecma262/#sec-createnonenumerabledatapropertyorthrow
  1060. /// </summary>
  1061. internal void CreateNonEnumerableDataPropertyOrThrow(JsValue p, JsValue v)
  1062. {
  1063. var newDesc = new PropertyDescriptor(v, true, false, true);
  1064. DefinePropertyOrThrow(p, newDesc);
  1065. }
  1066. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1067. internal ICallable? GetMethod(JsValue property)
  1068. {
  1069. return GetMethod(_engine.Realm, this, property);
  1070. }
  1071. internal static ICallable? GetMethod(Realm realm, JsValue v, JsValue p)
  1072. {
  1073. var jsValue = v.Get(p);
  1074. if (jsValue.IsNullOrUndefined())
  1075. {
  1076. return null;
  1077. }
  1078. var callable = jsValue as ICallable;
  1079. if (callable is null)
  1080. {
  1081. ExceptionHelper.ThrowTypeError(realm, "Value returned for property '" + p + "' of object is not a function");
  1082. }
  1083. return callable;
  1084. }
  1085. internal void CopyDataProperties(
  1086. ObjectInstance target,
  1087. HashSet<JsValue>? excludedItems)
  1088. {
  1089. var keys = GetOwnPropertyKeys();
  1090. for (var i = 0; i < keys.Count; i++)
  1091. {
  1092. var key = keys[i];
  1093. if (excludedItems == null || !excludedItems.Contains(key))
  1094. {
  1095. var desc = GetOwnProperty(key);
  1096. if (desc.Enumerable)
  1097. {
  1098. target.CreateDataProperty(key, UnwrapJsValue(desc, this));
  1099. }
  1100. }
  1101. }
  1102. }
  1103. internal ArrayInstance EnumerableOwnPropertyNames(EnumerableOwnPropertyNamesKind kind)
  1104. {
  1105. var ownKeys = GetOwnPropertyKeys(Types.String);
  1106. var array = Engine.Realm.Intrinsics.Array.ArrayCreate((uint) ownKeys.Count);
  1107. uint index = 0;
  1108. for (var i = 0; i < ownKeys.Count; i++)
  1109. {
  1110. var property = ownKeys[i];
  1111. if (!property.IsString())
  1112. {
  1113. continue;
  1114. }
  1115. var desc = GetOwnProperty(property);
  1116. if (desc != PropertyDescriptor.Undefined && desc.Enumerable)
  1117. {
  1118. if (kind == EnumerableOwnPropertyNamesKind.Key)
  1119. {
  1120. array.SetIndexValue(index, property, updateLength: false);
  1121. }
  1122. else
  1123. {
  1124. var value = Get(property);
  1125. if (kind == EnumerableOwnPropertyNamesKind.Value)
  1126. {
  1127. array.SetIndexValue(index, value, updateLength: false);
  1128. }
  1129. else
  1130. {
  1131. var objectInstance = _engine.Realm.Intrinsics.Array.ArrayCreate(2);
  1132. objectInstance.SetIndexValue(0, property, updateLength: false);
  1133. objectInstance.SetIndexValue(1, value, updateLength: false);
  1134. array.SetIndexValue(index, objectInstance, updateLength: false);
  1135. }
  1136. }
  1137. index++;
  1138. }
  1139. }
  1140. array.SetLength(index);
  1141. return array;
  1142. }
  1143. internal enum EnumerableOwnPropertyNamesKind
  1144. {
  1145. Key,
  1146. Value,
  1147. KeyValue
  1148. }
  1149. internal ObjectInstance AssertThisIsObjectInstance(JsValue value, string methodName)
  1150. {
  1151. var instance = value as ObjectInstance;
  1152. if (instance is null)
  1153. {
  1154. ThrowIncompatibleReceiver(value, methodName);
  1155. }
  1156. return instance!;
  1157. }
  1158. [MethodImpl(MethodImplOptions.NoInlining)]
  1159. private void ThrowIncompatibleReceiver(JsValue value, string methodName)
  1160. {
  1161. ExceptionHelper.ThrowTypeError(_engine.Realm, $"Method {methodName} called on incompatible receiver {value}");
  1162. }
  1163. public override bool Equals(JsValue? obj)
  1164. {
  1165. return Equals(obj as ObjectInstance);
  1166. }
  1167. public bool Equals(ObjectInstance? other)
  1168. {
  1169. if (other is null)
  1170. {
  1171. return false;
  1172. }
  1173. if (ReferenceEquals(this, other))
  1174. {
  1175. return true;
  1176. }
  1177. return false;
  1178. }
  1179. public override string ToString()
  1180. {
  1181. return TypeConverter.ToString(this);
  1182. }
  1183. internal virtual ulong GetSmallestIndex(ulong length)
  1184. {
  1185. // there are some evil tests that iterate a lot with unshift..
  1186. if (Properties == null)
  1187. {
  1188. return 0;
  1189. }
  1190. var min = length;
  1191. foreach (var entry in Properties)
  1192. {
  1193. if (ulong.TryParse(entry.Key.ToString(), out var index))
  1194. {
  1195. min = System.Math.Min(index, min);
  1196. }
  1197. }
  1198. if (Prototype?.Properties != null)
  1199. {
  1200. foreach (var entry in Prototype.Properties)
  1201. {
  1202. if (ulong.TryParse(entry.Key.ToString(), out var index))
  1203. {
  1204. min = System.Math.Min(index, min);
  1205. }
  1206. }
  1207. }
  1208. return min;
  1209. }
  1210. }
  1211. }