ObjectInstance.cs 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466
  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 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.FastSetProperty(property, mutable);
  731. }
  732. }
  733. return true;
  734. }
  735. /// <summary>
  736. /// Optimized version of [[Put]] when the property is known to be undeclared already
  737. /// </summary>
  738. public void FastAddProperty(JsValue name, JsValue value, bool writable, bool enumerable, bool configurable)
  739. {
  740. SetOwnProperty(name, new PropertyDescriptor(value, writable, enumerable, configurable));
  741. }
  742. /// <summary>
  743. /// Optimized version of [[Put]] when the property is known to be already declared
  744. /// </summary>
  745. /// <param name="name"></param>
  746. /// <param name="value"></param>
  747. public void FastSetProperty(JsValue name, PropertyDescriptor value)
  748. {
  749. SetOwnProperty(name, value);
  750. }
  751. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  752. protected internal void EnsureInitialized()
  753. {
  754. if (_initialized)
  755. {
  756. return;
  757. }
  758. // we need to set flag eagerly to prevent wrong recursion
  759. _initialized = true;
  760. Initialize();
  761. }
  762. protected virtual void Initialize()
  763. {
  764. }
  765. public override object ToObject()
  766. {
  767. return ToObject(new ObjectTraverseStack(_engine));
  768. }
  769. private object ToObject(ObjectTraverseStack stack)
  770. {
  771. if (this is IObjectWrapper wrapper)
  772. {
  773. return wrapper.Target;
  774. }
  775. stack.Enter(this);
  776. object? converted = null;
  777. switch (Class)
  778. {
  779. case ObjectClass.String:
  780. if (this is StringInstance stringInstance)
  781. {
  782. converted = stringInstance.StringData.ToString();
  783. }
  784. break;
  785. case ObjectClass.Date:
  786. if (this is DateInstance dateInstance)
  787. {
  788. converted = dateInstance.ToDateTime();
  789. }
  790. break;
  791. case ObjectClass.Boolean:
  792. if (this is BooleanInstance booleanInstance)
  793. {
  794. converted = ((JsBoolean) booleanInstance.BooleanData)._value
  795. ? JsBoolean.BoxedTrue
  796. : JsBoolean.BoxedFalse;
  797. }
  798. break;
  799. case ObjectClass.Function:
  800. if (this is ICallable function)
  801. {
  802. converted = (Func<JsValue, JsValue[], JsValue>) function.Call;
  803. }
  804. break;
  805. case ObjectClass.Number:
  806. if (this is NumberInstance numberInstance)
  807. {
  808. converted = numberInstance.NumberData._value;
  809. }
  810. break;
  811. case ObjectClass.RegExp:
  812. if (this is RegExpInstance regeExpInstance)
  813. {
  814. converted = regeExpInstance.Value;
  815. }
  816. break;
  817. case ObjectClass.Arguments:
  818. case ObjectClass.Object:
  819. if (this is ArrayInstance arrayInstance)
  820. {
  821. var result = new object?[arrayInstance.Length];
  822. for (uint i = 0; i < result.Length; i++)
  823. {
  824. var value = arrayInstance[i];
  825. object? valueToSet = null;
  826. if (!value.IsUndefined())
  827. {
  828. valueToSet = value is ObjectInstance oi
  829. ? oi.ToObject(stack)
  830. : value.ToObject();
  831. }
  832. result[i] = valueToSet;
  833. }
  834. converted = result;
  835. break;
  836. }
  837. if (this is BigIntInstance bigIntInstance)
  838. {
  839. converted = bigIntInstance.BigIntData._value;
  840. break;
  841. }
  842. var o = _engine.Options.Interop.CreateClrObject(this);
  843. foreach (var p in GetOwnProperties())
  844. {
  845. if (!p.Value.Enumerable)
  846. {
  847. continue;
  848. }
  849. var key = p.Key.ToString();
  850. var propertyValue = Get(p.Key);
  851. var value = propertyValue is ObjectInstance oi
  852. ? oi.ToObject(stack)
  853. : propertyValue.ToObject();
  854. o.Add(key, value);
  855. }
  856. converted = o;
  857. break;
  858. default:
  859. converted = this;
  860. break;
  861. }
  862. stack.Exit();
  863. return converted!;
  864. }
  865. /// <summary>
  866. /// Handles the generic find of (callback[, thisArg])
  867. /// </summary>
  868. internal virtual bool FindWithCallback(
  869. JsValue[] arguments,
  870. out uint index,
  871. out JsValue value,
  872. bool visitUnassigned,
  873. bool fromEnd = false)
  874. {
  875. long GetLength()
  876. {
  877. var descValue = Get(CommonProperties.Length);
  878. var len = TypeConverter.ToNumber(descValue);
  879. return (long) System.Math.Max(
  880. 0,
  881. System.Math.Min(len, ArrayOperations.MaxArrayLikeLength));
  882. }
  883. bool TryGetValue(uint idx, out JsValue jsValue)
  884. {
  885. var property = JsString.Create(idx);
  886. var kPresent = HasProperty(property);
  887. jsValue = kPresent ? Get(property, this) : Undefined;
  888. return kPresent;
  889. }
  890. var length = GetLength();
  891. if (length == 0)
  892. {
  893. index = 0;
  894. value = Undefined;
  895. return false;
  896. }
  897. var callbackfn = arguments.At(0);
  898. var thisArg = arguments.At(1);
  899. var callable = GetCallable(callbackfn);
  900. var args = _engine._jsValueArrayPool.RentArray(3);
  901. args[2] = this;
  902. for (uint k = 0; k < length; k++)
  903. {
  904. if (TryGetValue(k, out var kvalue) || visitUnassigned)
  905. {
  906. args[0] = kvalue;
  907. args[1] = k;
  908. var testResult = callable.Call(thisArg, args);
  909. if (TypeConverter.ToBoolean(testResult))
  910. {
  911. index = k;
  912. value = kvalue;
  913. return true;
  914. }
  915. }
  916. }
  917. _engine._jsValueArrayPool.ReturnArray(args);
  918. index = 0;
  919. value = Undefined;
  920. return false;
  921. }
  922. internal ICallable GetCallable(JsValue source)
  923. {
  924. if (source is ICallable callable)
  925. {
  926. return callable;
  927. }
  928. ExceptionHelper.ThrowTypeError(_engine.Realm, "Argument must be callable");
  929. return null;
  930. }
  931. internal bool IsConcatSpreadable
  932. {
  933. get
  934. {
  935. var spreadable = Get(GlobalSymbolRegistry.IsConcatSpreadable, this);
  936. if (!spreadable.IsUndefined())
  937. {
  938. return TypeConverter.ToBoolean(spreadable);
  939. }
  940. return IsArray();
  941. }
  942. }
  943. public virtual bool IsArrayLike => TryGetValue(CommonProperties.Length, out var lengthValue)
  944. && lengthValue.IsNumber()
  945. && ((JsNumber) lengthValue)._value >= 0;
  946. // safe default
  947. internal virtual bool HasOriginalIterator => false;
  948. internal override bool IsIntegerIndexedArray => false;
  949. public virtual uint Length => (uint) TypeConverter.ToLength(Get(CommonProperties.Length));
  950. public virtual bool PreventExtensions()
  951. {
  952. Extensible = false;
  953. return true;
  954. }
  955. protected internal virtual ObjectInstance? GetPrototypeOf()
  956. {
  957. return _prototype;
  958. }
  959. /// <summary>
  960. /// https://tc39.es/ecma262/#sec-ordinarysetprototypeof
  961. /// </summary>
  962. public virtual bool SetPrototypeOf(JsValue value)
  963. {
  964. if (!value.IsObject() && !value.IsNull())
  965. {
  966. ExceptionHelper.ThrowArgumentException();
  967. }
  968. var current = _prototype ?? Null;
  969. if (ReferenceEquals(value, current))
  970. {
  971. return true;
  972. }
  973. if (!Extensible)
  974. {
  975. return false;
  976. }
  977. if (value.IsNull())
  978. {
  979. _prototype = null;
  980. return true;
  981. }
  982. // validate chain
  983. var p = value as ObjectInstance;
  984. bool done = false;
  985. while (!done)
  986. {
  987. if (p is null)
  988. {
  989. done = true;
  990. }
  991. else if (ReferenceEquals(p, this))
  992. {
  993. return false;
  994. }
  995. else
  996. {
  997. p = p._prototype;
  998. }
  999. }
  1000. _prototype = value as ObjectInstance;
  1001. return true;
  1002. }
  1003. /// <summary>
  1004. /// https://tc39.es/ecma262/#sec-setfunctionname
  1005. /// </summary>
  1006. internal void SetFunctionName(JsValue name, string? prefix = null)
  1007. {
  1008. if (name is JsSymbol symbol)
  1009. {
  1010. name = symbol._value.IsUndefined()
  1011. ? JsString.Empty
  1012. : new JsString("[" + symbol._value + "]");
  1013. }
  1014. if (!string.IsNullOrWhiteSpace(prefix))
  1015. {
  1016. name = prefix + " " + name;
  1017. }
  1018. DefinePropertyOrThrow(CommonProperties.Name, new PropertyDescriptor(name, PropertyFlag.Configurable));
  1019. }
  1020. /// <summary>
  1021. /// https://tc39.es/ecma262/#sec-createmethodproperty
  1022. /// </summary>
  1023. internal virtual bool CreateMethodProperty(JsValue p, JsValue v)
  1024. {
  1025. var newDesc = new PropertyDescriptor(v, PropertyFlag.NonEnumerable);
  1026. return DefineOwnProperty(p, newDesc);
  1027. }
  1028. /// <summary>
  1029. /// https://tc39.es/ecma262/#sec-createdatapropertyorthrow
  1030. /// </summary>
  1031. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1032. internal bool CreateDataProperty(JsValue p, JsValue v)
  1033. {
  1034. return DefineOwnProperty(p, new PropertyDescriptor(v, PropertyFlag.ConfigurableEnumerableWritable));
  1035. }
  1036. /// <summary>
  1037. /// https://tc39.es/ecma262/#sec-createdataproperty
  1038. /// </summary>
  1039. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1040. internal bool CreateDataPropertyOrThrow(JsValue p, JsValue v)
  1041. {
  1042. if (!CreateDataProperty(p, v))
  1043. {
  1044. ExceptionHelper.ThrowTypeError(_engine.Realm);
  1045. }
  1046. return true;
  1047. }
  1048. /// <summary>
  1049. /// https://tc39.es/ecma262/#sec-createnonenumerabledatapropertyorthrow
  1050. /// </summary>
  1051. internal void CreateNonEnumerableDataPropertyOrThrow(JsValue p, JsValue v)
  1052. {
  1053. var newDesc = new PropertyDescriptor(v, true, false, true);
  1054. DefinePropertyOrThrow(p, newDesc);
  1055. }
  1056. /// <summary>
  1057. /// https://tc39.es/ecma262/#sec-ordinaryobjectcreate
  1058. /// </summary>
  1059. internal static ObjectInstance OrdinaryObjectCreate(Engine engine, ObjectInstance? proto)
  1060. {
  1061. var prototype = new ObjectInstance(engine)
  1062. {
  1063. _prototype = proto
  1064. };
  1065. return prototype;
  1066. }
  1067. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1068. internal ICallable? GetMethod(JsValue property)
  1069. {
  1070. return GetMethod(_engine.Realm, this, property);
  1071. }
  1072. internal static ICallable? GetMethod(Realm realm, JsValue v, JsValue p)
  1073. {
  1074. var jsValue = v.Get(p);
  1075. if (jsValue.IsNullOrUndefined())
  1076. {
  1077. return null;
  1078. }
  1079. var callable = jsValue as ICallable;
  1080. if (callable is null)
  1081. {
  1082. ExceptionHelper.ThrowTypeError(realm, "Value returned for property '" + p + "' of object is not a function");
  1083. }
  1084. return callable;
  1085. }
  1086. internal void CopyDataProperties(
  1087. ObjectInstance target,
  1088. HashSet<JsValue>? excludedItems)
  1089. {
  1090. var keys = GetOwnPropertyKeys();
  1091. for (var i = 0; i < keys.Count; i++)
  1092. {
  1093. var key = keys[i];
  1094. if (excludedItems == null || !excludedItems.Contains(key))
  1095. {
  1096. var desc = GetOwnProperty(key);
  1097. if (desc.Enumerable)
  1098. {
  1099. target.CreateDataProperty(key, UnwrapJsValue(desc, this));
  1100. }
  1101. }
  1102. }
  1103. }
  1104. internal ArrayInstance EnumerableOwnPropertyNames(EnumerableOwnPropertyNamesKind kind)
  1105. {
  1106. var ownKeys = GetOwnPropertyKeys(Types.String);
  1107. var array = Engine.Realm.Intrinsics.Array.ArrayCreate((uint) ownKeys.Count);
  1108. uint index = 0;
  1109. for (var i = 0; i < ownKeys.Count; i++)
  1110. {
  1111. var property = ownKeys[i];
  1112. if (!property.IsString())
  1113. {
  1114. continue;
  1115. }
  1116. var desc = GetOwnProperty(property);
  1117. if (desc != PropertyDescriptor.Undefined && desc.Enumerable)
  1118. {
  1119. if (kind == EnumerableOwnPropertyNamesKind.Key)
  1120. {
  1121. array.SetIndexValue(index, property, updateLength: false);
  1122. }
  1123. else
  1124. {
  1125. var value = Get(property);
  1126. if (kind == EnumerableOwnPropertyNamesKind.Value)
  1127. {
  1128. array.SetIndexValue(index, value, updateLength: false);
  1129. }
  1130. else
  1131. {
  1132. var objectInstance = _engine.Realm.Intrinsics.Array.ArrayCreate(2);
  1133. objectInstance.SetIndexValue(0, property, updateLength: false);
  1134. objectInstance.SetIndexValue(1, value, updateLength: false);
  1135. array.SetIndexValue(index, objectInstance, updateLength: false);
  1136. }
  1137. }
  1138. index++;
  1139. }
  1140. }
  1141. array.SetLength(index);
  1142. return array;
  1143. }
  1144. internal enum EnumerableOwnPropertyNamesKind
  1145. {
  1146. Key,
  1147. Value,
  1148. KeyValue
  1149. }
  1150. internal ObjectInstance AssertThisIsObjectInstance(JsValue value, string methodName)
  1151. {
  1152. var instance = value as ObjectInstance;
  1153. if (instance is null)
  1154. {
  1155. ThrowIncompatibleReceiver(value, methodName);
  1156. }
  1157. return instance!;
  1158. }
  1159. [MethodImpl(MethodImplOptions.NoInlining)]
  1160. private void ThrowIncompatibleReceiver(JsValue value, string methodName)
  1161. {
  1162. ExceptionHelper.ThrowTypeError(_engine.Realm, $"Method {methodName} called on incompatible receiver {value}");
  1163. }
  1164. public override bool Equals(JsValue? obj)
  1165. {
  1166. return Equals(obj as ObjectInstance);
  1167. }
  1168. public bool Equals(ObjectInstance? other)
  1169. {
  1170. if (other is null)
  1171. {
  1172. return false;
  1173. }
  1174. if (ReferenceEquals(this, other))
  1175. {
  1176. return true;
  1177. }
  1178. return false;
  1179. }
  1180. public override string ToString()
  1181. {
  1182. return TypeConverter.ToString(this);
  1183. }
  1184. internal virtual ulong GetSmallestIndex(ulong length)
  1185. {
  1186. // there are some evil tests that iterate a lot with unshift..
  1187. if (Properties == null)
  1188. {
  1189. return 0;
  1190. }
  1191. var min = length;
  1192. foreach (var entry in Properties)
  1193. {
  1194. if (ulong.TryParse(entry.Key.ToString(), out var index))
  1195. {
  1196. min = System.Math.Min(index, min);
  1197. }
  1198. }
  1199. if (Prototype?.Properties != null)
  1200. {
  1201. foreach (var entry in Prototype.Properties)
  1202. {
  1203. if (ulong.TryParse(entry.Key.ToString(), out var index))
  1204. {
  1205. min = System.Math.Min(index, min);
  1206. }
  1207. }
  1208. }
  1209. return min;
  1210. }
  1211. /// <summary>
  1212. /// https://tc39.es/ecma262/#sec-setintegritylevel
  1213. /// </summary>
  1214. internal bool SetIntegrityLevel(IntegrityLevel level)
  1215. {
  1216. var status = PreventExtensions();
  1217. if (!status)
  1218. {
  1219. return false;
  1220. }
  1221. var keys = GetOwnPropertyKeys();
  1222. if (level == IntegrityLevel.Sealed)
  1223. {
  1224. for (var i = 0; i < keys.Count; i++)
  1225. {
  1226. var k = keys[i];
  1227. DefinePropertyOrThrow(k, new PropertyDescriptor { Configurable = false });
  1228. }
  1229. }
  1230. else
  1231. {
  1232. for (var i = 0; i < keys.Count; i++)
  1233. {
  1234. var k = keys[i];
  1235. var currentDesc = GetOwnProperty(k);
  1236. if (currentDesc != PropertyDescriptor.Undefined)
  1237. {
  1238. PropertyDescriptor desc;
  1239. if (currentDesc.IsAccessorDescriptor())
  1240. {
  1241. desc = new PropertyDescriptor { Configurable = false };
  1242. }
  1243. else
  1244. {
  1245. desc = new PropertyDescriptor { Configurable = false, Writable = false };
  1246. }
  1247. DefinePropertyOrThrow(k, desc);
  1248. }
  1249. }
  1250. }
  1251. return true;
  1252. }
  1253. internal enum IntegrityLevel
  1254. {
  1255. Sealed,
  1256. Frozen
  1257. }
  1258. }
  1259. }