2
0

ObjectInstance.cs 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425
  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. }
  1224. }