ObjectInstance.cs 47 KB

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