JsValue.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Diagnostics.Contracts;
  5. using System.Runtime.CompilerServices;
  6. using System.Threading;
  7. using Jint.Native.Array;
  8. using Jint.Native.Date;
  9. using Jint.Native.Iterator;
  10. using Jint.Native.Number;
  11. using Jint.Native.Object;
  12. using Jint.Native.Promise;
  13. using Jint.Native.RegExp;
  14. using Jint.Native.Symbol;
  15. using Jint.Runtime;
  16. using Jint.Runtime.Descriptors;
  17. using Jint.Runtime.Interop;
  18. namespace Jint.Native
  19. {
  20. [DebuggerTypeProxy(typeof(JsValueDebugView))]
  21. public abstract class JsValue : IEquatable<JsValue>
  22. {
  23. public static readonly JsValue Undefined = new JsUndefined();
  24. public static readonly JsValue Null = new JsNull();
  25. internal readonly InternalTypes _type;
  26. protected JsValue(Types type)
  27. {
  28. _type = (InternalTypes) type;
  29. }
  30. internal JsValue(InternalTypes type)
  31. {
  32. _type = type;
  33. }
  34. [Pure]
  35. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  36. public bool IsPrimitive()
  37. {
  38. return (_type & (InternalTypes.Primitive | InternalTypes.Undefined | InternalTypes.Null)) != 0;
  39. }
  40. [Pure]
  41. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  42. public bool IsUndefined()
  43. {
  44. return _type == InternalTypes.Undefined;
  45. }
  46. [Pure]
  47. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  48. internal bool IsNullOrUndefined()
  49. {
  50. return _type < InternalTypes.Boolean;
  51. }
  52. [Pure]
  53. public virtual bool IsArray()
  54. {
  55. return this is ArrayInstance;
  56. }
  57. [Pure]
  58. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  59. public bool IsDate()
  60. {
  61. return this is DateInstance;
  62. }
  63. [Pure]
  64. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  65. public bool IsPromise()
  66. {
  67. return this is PromiseInstance;
  68. }
  69. [Pure]
  70. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  71. public bool IsRegExp()
  72. {
  73. if (!(this is ObjectInstance oi))
  74. {
  75. return false;
  76. }
  77. var matcher = oi.Get(GlobalSymbolRegistry.Match);
  78. if (!matcher.IsUndefined())
  79. {
  80. return TypeConverter.ToBoolean(matcher);
  81. }
  82. return this is RegExpInstance;
  83. }
  84. [Pure]
  85. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  86. public bool IsObject()
  87. {
  88. return (_type & InternalTypes.Object) != 0;
  89. }
  90. [Pure]
  91. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  92. public bool IsString()
  93. {
  94. return (_type & InternalTypes.String) != 0;
  95. }
  96. [Pure]
  97. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  98. public bool IsNumber()
  99. {
  100. return (_type & (InternalTypes.Number | InternalTypes.Integer)) != 0;
  101. }
  102. [Pure]
  103. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  104. internal bool IsInteger()
  105. {
  106. return _type == InternalTypes.Integer;
  107. }
  108. [Pure]
  109. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  110. public bool IsBoolean()
  111. {
  112. return _type == InternalTypes.Boolean;
  113. }
  114. [Pure]
  115. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  116. public bool IsNull()
  117. {
  118. return _type == InternalTypes.Null;
  119. }
  120. internal virtual bool IsIntegerIndexedArray => false;
  121. [Pure]
  122. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  123. public bool IsSymbol()
  124. {
  125. return _type == InternalTypes.Symbol;
  126. }
  127. [Pure]
  128. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  129. public ObjectInstance AsObject()
  130. {
  131. if (!IsObject())
  132. {
  133. ExceptionHelper.ThrowArgumentException("The value is not an object");
  134. }
  135. return this as ObjectInstance;
  136. }
  137. [Pure]
  138. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  139. public TInstance AsInstance<TInstance>() where TInstance : class
  140. {
  141. if (!IsObject())
  142. {
  143. ExceptionHelper.ThrowArgumentException("The value is not an object");
  144. }
  145. return this as TInstance;
  146. }
  147. [Pure]
  148. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  149. public ArrayInstance AsArray()
  150. {
  151. if (!IsArray())
  152. {
  153. ExceptionHelper.ThrowArgumentException("The value is not an array");
  154. }
  155. return this as ArrayInstance;
  156. }
  157. [Pure]
  158. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  159. internal IIterator GetIterator(Engine engine)
  160. {
  161. if (!TryGetIterator(engine, out var iterator))
  162. {
  163. return ExceptionHelper.ThrowTypeError<IIterator>(engine, "The value is not iterable");
  164. }
  165. return iterator;
  166. }
  167. [Pure]
  168. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  169. internal bool TryGetIterator(Engine engine, out IIterator iterator)
  170. {
  171. var objectInstance = TypeConverter.ToObject(engine, this);
  172. if (!objectInstance.TryGetValue(GlobalSymbolRegistry.Iterator, out var value)
  173. || !(value is ICallable callable))
  174. {
  175. iterator = null;
  176. return false;
  177. }
  178. var obj = callable.Call(this, Arguments.Empty) as ObjectInstance
  179. ?? ExceptionHelper.ThrowTypeError<ObjectInstance>(engine,
  180. "Result of the Symbol.iterator method is not an object");
  181. if (obj is IIterator i)
  182. {
  183. iterator = i;
  184. }
  185. else
  186. {
  187. iterator = new IteratorInstance.ObjectIterator(obj);
  188. }
  189. return true;
  190. }
  191. [Pure]
  192. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  193. public DateInstance AsDate()
  194. {
  195. if (!IsDate())
  196. {
  197. ExceptionHelper.ThrowArgumentException("The value is not a date");
  198. }
  199. return this as DateInstance;
  200. }
  201. [Pure]
  202. public RegExpInstance AsRegExp()
  203. {
  204. if (!IsRegExp())
  205. {
  206. ExceptionHelper.ThrowArgumentException("The value is not a regex");
  207. }
  208. return this as RegExpInstance;
  209. }
  210. [Pure]
  211. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  212. public T TryCast<T>() where T : class
  213. {
  214. return this as T;
  215. }
  216. [Pure]
  217. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  218. public T TryCast<T>(Action<JsValue> fail) where T : class
  219. {
  220. if (this is T o)
  221. {
  222. return o;
  223. }
  224. fail.Invoke(this);
  225. return null;
  226. }
  227. [Pure]
  228. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  229. public T As<T>() where T : ObjectInstance
  230. {
  231. if (IsObject())
  232. {
  233. return this as T;
  234. }
  235. return null;
  236. }
  237. public Types Type
  238. {
  239. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  240. get => _type == InternalTypes.Integer
  241. ? Types.Number
  242. : (Types) (_type & ~InternalTypes.InternalFlags);
  243. }
  244. internal virtual bool IsConstructor => false;
  245. /// <summary>
  246. /// Creates a valid <see cref="JsValue"/> instance from any <see cref="Object"/> instance
  247. /// </summary>
  248. public static JsValue FromObject(Engine engine, object value)
  249. {
  250. if (value == null)
  251. {
  252. return Null;
  253. }
  254. if (value is JsValue jsValue)
  255. {
  256. return jsValue;
  257. }
  258. var converters = engine.Options._ObjectConverters;
  259. var convertersCount = converters.Count;
  260. for (var i = 0; i < convertersCount; i++)
  261. {
  262. var converter = converters[i];
  263. if (converter.TryConvert(engine, value, out var result))
  264. {
  265. return result;
  266. }
  267. }
  268. var valueType = value.GetType();
  269. var typeMappers = Engine.TypeMappers;
  270. if (typeMappers.TryGetValue(valueType, out var typeMapper))
  271. {
  272. return typeMapper(engine, value);
  273. }
  274. if (value is System.Array a)
  275. {
  276. // racy, we don't care, worst case we'll catch up later
  277. Interlocked.CompareExchange(ref Engine.TypeMappers,
  278. new Dictionary<Type, Func<Engine, object, JsValue>>(typeMappers)
  279. {
  280. [valueType] = Convert
  281. }, typeMappers);
  282. return Convert(engine, a);
  283. }
  284. if (value is Delegate d)
  285. {
  286. return new DelegateWrapper(engine, d);
  287. }
  288. Type t = value.GetType();
  289. if (t.IsEnum)
  290. {
  291. Type ut = Enum.GetUnderlyingType(t);
  292. if (ut == typeof(ulong))
  293. return JsNumber.Create(System.Convert.ToDouble(value));
  294. if (ut == typeof(uint) || ut == typeof(long))
  295. return JsNumber.Create(System.Convert.ToInt64(value));
  296. return JsNumber.Create(System.Convert.ToInt32(value));
  297. }
  298. // if no known type could be guessed, wrap it as an ObjectInstance
  299. var h = engine.Options._WrapObjectHandler;
  300. var o = h?.Invoke(engine, value) ?? new ObjectWrapper(engine, value);
  301. return o;
  302. }
  303. private static JsValue Convert(Engine e, object v)
  304. {
  305. var array = (System.Array) v;
  306. var arrayLength = (uint) array.Length;
  307. var jsArray = new ArrayInstance(e, arrayLength);
  308. jsArray._prototype = e.Array.PrototypeObject;
  309. for (uint i = 0; i < arrayLength; ++i)
  310. {
  311. var jsItem = FromObject(e, array.GetValue(i));
  312. jsArray.WriteArrayValue(i, new PropertyDescriptor(jsItem, PropertyFlag.ConfigurableEnumerableWritable));
  313. }
  314. jsArray.SetOwnProperty(CommonProperties.Length,
  315. new PropertyDescriptor(arrayLength, PropertyFlag.OnlyWritable));
  316. return jsArray;
  317. }
  318. /// <summary>
  319. /// Converts a <see cref="JsValue"/> to its underlying CLR value.
  320. /// </summary>
  321. /// <returns>The underlying CLR value of the <see cref="JsValue"/> instance.</returns>
  322. public abstract object ToObject();
  323. /// <summary>
  324. /// Invoke the current value as function.
  325. /// </summary>
  326. /// <param name="arguments">The arguments of the function call.</param>
  327. /// <returns>The value returned by the function call.</returns>
  328. public JsValue Invoke(params JsValue[] arguments)
  329. {
  330. var callable = this as ICallable ??
  331. ExceptionHelper.ThrowTypeErrorNoEngine<ICallable>("Can only invoke functions");
  332. return callable.Call(Undefined, arguments);
  333. }
  334. public virtual bool HasOwnProperty(JsValue property) => false;
  335. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  336. public JsValue Get(JsValue property)
  337. {
  338. return Get(property, this);
  339. }
  340. /// <summary>
  341. /// http://www.ecma-international.org/ecma-262/5.1/#sec-8.12.3
  342. /// </summary>
  343. public virtual JsValue Get(JsValue property, JsValue receiver)
  344. {
  345. return Undefined;
  346. }
  347. /// <summary>
  348. /// https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-set-p-v-receiver
  349. /// </summary>
  350. public virtual bool Set(JsValue property, JsValue value, JsValue receiver)
  351. {
  352. return ExceptionHelper.ThrowNotSupportedException<bool>();
  353. }
  354. /// <summary>
  355. /// https://tc39.es/ecma262/#sec-instanceofoperator
  356. /// </summary>
  357. internal bool InstanceofOperator(JsValue target)
  358. {
  359. if (target is not ObjectInstance oi)
  360. {
  361. return ExceptionHelper.ThrowTypeErrorNoEngine<bool>("not an object");
  362. }
  363. var instOfHandler = oi.GetMethod(GlobalSymbolRegistry.HasInstance);
  364. if (instOfHandler is not null)
  365. {
  366. return TypeConverter.ToBoolean(instOfHandler.Call(target, new[] {this}));
  367. }
  368. if (!target.IsCallable)
  369. {
  370. return ExceptionHelper.ThrowTypeErrorNoEngine<bool>("not callable");
  371. }
  372. return target.OrdinaryHasInstance(this);
  373. }
  374. public override string ToString()
  375. {
  376. return "None";
  377. }
  378. public static bool operator ==(JsValue a, JsValue b)
  379. {
  380. if ((object) a == null)
  381. {
  382. return (object) b == null;
  383. }
  384. return (object) b != null && a.Equals(b);
  385. }
  386. public static bool operator !=(JsValue a, JsValue b)
  387. {
  388. if ((object) a == null)
  389. {
  390. if ((object) b == null)
  391. {
  392. return false;
  393. }
  394. return true;
  395. }
  396. if ((object) b == null)
  397. {
  398. return true;
  399. }
  400. return !a.Equals(b);
  401. }
  402. public static implicit operator JsValue(char value)
  403. {
  404. return JsString.Create(value);
  405. }
  406. public static implicit operator JsValue(int value)
  407. {
  408. return JsNumber.Create(value);
  409. }
  410. public static implicit operator JsValue(uint value)
  411. {
  412. return JsNumber.Create(value);
  413. }
  414. public static implicit operator JsValue(double value)
  415. {
  416. return JsNumber.Create(value);
  417. }
  418. public static implicit operator JsValue(long value)
  419. {
  420. return JsNumber.Create(value);
  421. }
  422. public static implicit operator JsValue(ulong value)
  423. {
  424. return JsNumber.Create(value);
  425. }
  426. public static implicit operator JsValue(bool value)
  427. {
  428. return value ? JsBoolean.True : JsBoolean.False;
  429. }
  430. [DebuggerStepThrough]
  431. public static implicit operator JsValue(string value)
  432. {
  433. if (value == null)
  434. {
  435. return Null;
  436. }
  437. return JsString.Create(value);
  438. }
  439. public override bool Equals(object obj)
  440. {
  441. if (ReferenceEquals(null, obj))
  442. {
  443. return false;
  444. }
  445. if (ReferenceEquals(this, obj))
  446. {
  447. return true;
  448. }
  449. return obj is JsValue value && Equals(value);
  450. }
  451. public abstract bool Equals(JsValue other);
  452. public override int GetHashCode()
  453. {
  454. return _type.GetHashCode();
  455. }
  456. internal class JsValueDebugView
  457. {
  458. public string Value;
  459. public JsValueDebugView(JsValue value)
  460. {
  461. switch (value.Type)
  462. {
  463. case Types.None:
  464. Value = "None";
  465. break;
  466. case Types.Undefined:
  467. Value = "undefined";
  468. break;
  469. case Types.Null:
  470. Value = "null";
  471. break;
  472. case Types.Boolean:
  473. Value = ((JsBoolean) value)._value + " (bool)";
  474. break;
  475. case Types.String:
  476. Value = value.ToString() + " (string)";
  477. break;
  478. case Types.Number:
  479. Value = ((JsNumber) value)._value + " (number)";
  480. break;
  481. case Types.Object:
  482. Value = value.AsObject().GetType().Name;
  483. break;
  484. case Types.Symbol:
  485. var jsValue = ((JsSymbol) value)._value;
  486. Value = (jsValue.IsUndefined() ? "" : jsValue.ToString()) + " (symbol)";
  487. break;
  488. default:
  489. Value = "Unknown";
  490. break;
  491. }
  492. }
  493. }
  494. /// <summary>
  495. /// Some values need to be cloned in order to be assigned, like ConcatenatedString.
  496. /// </summary>
  497. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  498. internal JsValue Clone()
  499. {
  500. // concatenated string and arguments currently may require cloning
  501. return (_type & InternalTypes.RequiresCloning) == 0
  502. ? this
  503. : DoClone();
  504. }
  505. internal virtual JsValue DoClone()
  506. {
  507. return this;
  508. }
  509. internal virtual bool IsCallable => this is ICallable;
  510. /// <summary>
  511. /// https://tc39.es/ecma262/#sec-ordinaryhasinstance
  512. /// </summary>
  513. internal virtual bool OrdinaryHasInstance(JsValue v)
  514. {
  515. if (!IsCallable)
  516. {
  517. return false;
  518. }
  519. if (v is not ObjectInstance o)
  520. {
  521. return false;
  522. }
  523. var p = Get(CommonProperties.Prototype);
  524. if (p is not ObjectInstance)
  525. {
  526. ExceptionHelper.ThrowTypeError(o.Engine,
  527. $"Function has non-object prototype '{TypeConverter.ToString(p)}' in instanceof check");
  528. }
  529. while (true)
  530. {
  531. o = o.Prototype;
  532. if (o is null)
  533. {
  534. return false;
  535. }
  536. if (SameValue(p, o))
  537. {
  538. return true;
  539. }
  540. }
  541. }
  542. internal static bool SameValue(JsValue x, JsValue y)
  543. {
  544. var typea = x.Type;
  545. var typeb = y.Type;
  546. if (typea != typeb)
  547. {
  548. return false;
  549. }
  550. switch (typea)
  551. {
  552. case Types.Number:
  553. if (x._type == y._type && x._type == InternalTypes.Integer)
  554. {
  555. return x.AsInteger() == y.AsInteger();
  556. }
  557. var nx = TypeConverter.ToNumber(x);
  558. var ny = TypeConverter.ToNumber(y);
  559. if (double.IsNaN(nx) && double.IsNaN(ny))
  560. {
  561. return true;
  562. }
  563. if (nx == ny)
  564. {
  565. if (nx == 0)
  566. {
  567. // +0 !== -0
  568. return NumberInstance.IsNegativeZero(nx) == NumberInstance.IsNegativeZero(ny);
  569. }
  570. return true;
  571. }
  572. return false;
  573. case Types.String:
  574. return TypeConverter.ToString(x) == TypeConverter.ToString(y);
  575. case Types.Boolean:
  576. return TypeConverter.ToBoolean(x) == TypeConverter.ToBoolean(y);
  577. case Types.Undefined:
  578. case Types.Null:
  579. return true;
  580. case Types.Symbol:
  581. return x == y;
  582. default:
  583. return ReferenceEquals(x, y);
  584. }
  585. }
  586. internal static IConstructor AssertConstructor(Engine engine, JsValue c)
  587. {
  588. if (!(c is IConstructor constructor))
  589. {
  590. return ExceptionHelper.ThrowTypeError<IConstructor>(engine, c + " is not a constructor");
  591. }
  592. return constructor;
  593. }
  594. }
  595. }