JsValue.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. using System.Diagnostics;
  2. using System.Diagnostics.Contracts;
  3. using System.Numerics;
  4. using System.Runtime.CompilerServices;
  5. using Jint.Native.Generator;
  6. using Jint.Native.Iterator;
  7. using Jint.Native.Number;
  8. using Jint.Native.Object;
  9. using Jint.Native.Symbol;
  10. using Jint.Runtime;
  11. namespace Jint.Native
  12. {
  13. [DebuggerTypeProxy(typeof(JsValueDebugView))]
  14. public abstract class JsValue : IEquatable<JsValue>
  15. {
  16. public static readonly JsValue Undefined = new JsUndefined();
  17. public static readonly JsValue Null = new JsNull();
  18. internal readonly InternalTypes _type;
  19. protected JsValue(Types type)
  20. {
  21. _type = (InternalTypes) type;
  22. }
  23. internal JsValue(InternalTypes type)
  24. {
  25. _type = type;
  26. }
  27. [Pure]
  28. public virtual bool IsArray() => false;
  29. internal virtual bool IsIntegerIndexedArray => false;
  30. internal virtual bool IsConstructor => false;
  31. [Pure]
  32. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  33. internal IteratorInstance GetIterator(Realm realm, GeneratorKind hint = GeneratorKind.Sync, ICallable method = null)
  34. {
  35. if (!TryGetIterator(realm, out var iterator, hint, method))
  36. {
  37. ExceptionHelper.ThrowTypeError(realm, "The value is not iterable");
  38. }
  39. return iterator;
  40. }
  41. [Pure]
  42. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  43. internal bool TryGetIterator(Realm realm, out IteratorInstance iterator, GeneratorKind hint = GeneratorKind.Sync, ICallable method = null)
  44. {
  45. var obj = TypeConverter.ToObject(realm, this);
  46. if (method is null)
  47. {
  48. if (hint == GeneratorKind.Async)
  49. {
  50. method = obj.GetMethod(GlobalSymbolRegistry.AsyncIterator);
  51. if (method is null)
  52. {
  53. var syncMethod = obj.GetMethod(GlobalSymbolRegistry.Iterator);
  54. var syncIteratorRecord = obj.GetIterator(realm, GeneratorKind.Sync, syncMethod);
  55. // TODO async CreateAsyncFromSyncIterator(syncIteratorRecord);
  56. ExceptionHelper.ThrowNotImplementedException("async");
  57. }
  58. }
  59. else
  60. {
  61. method = obj.GetMethod(GlobalSymbolRegistry.Iterator);
  62. }
  63. }
  64. if (method is null)
  65. {
  66. iterator = null;
  67. return false;
  68. }
  69. var iteratorResult = method.Call(obj, Arguments.Empty) as ObjectInstance;
  70. if (iteratorResult is null)
  71. {
  72. ExceptionHelper.ThrowTypeError(realm, "Result of the Symbol.iterator method is not an object");
  73. }
  74. if (iteratorResult is IteratorInstance i)
  75. {
  76. iterator = i;
  77. }
  78. else
  79. {
  80. iterator = new IteratorInstance.ObjectIterator(iteratorResult);
  81. }
  82. return true;
  83. }
  84. public Types Type
  85. {
  86. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  87. get => _type == InternalTypes.Integer
  88. ? Types.Number
  89. : (Types) (_type & ~InternalTypes.InternalFlags);
  90. }
  91. /// <summary>
  92. /// Creates a valid <see cref="JsValue"/> instance from any <see cref="Object"/> instance
  93. /// </summary>
  94. public static JsValue FromObject(Engine engine, object value)
  95. {
  96. if (value is null)
  97. {
  98. return Null;
  99. }
  100. if (value is JsValue jsValue)
  101. {
  102. return jsValue;
  103. }
  104. if (engine._objectConverters != null)
  105. {
  106. foreach (var converter in engine._objectConverters)
  107. {
  108. if (converter.TryConvert(engine, value, out var result))
  109. {
  110. return result;
  111. }
  112. }
  113. }
  114. if (DefaultObjectConverter.TryConvert(engine, value, out var defaultConversion))
  115. {
  116. return defaultConversion;
  117. }
  118. return null;
  119. }
  120. /// <summary>
  121. /// Converts a <see cref="JsValue"/> to its underlying CLR value.
  122. /// </summary>
  123. /// <returns>The underlying CLR value of the <see cref="JsValue"/> instance.</returns>
  124. public abstract object ToObject();
  125. /// <summary>
  126. /// Invoke the current value as function.
  127. /// </summary>
  128. /// <param name="engine">The engine handling the invoke.</param>
  129. /// <param name="arguments">The arguments of the function call.</param>
  130. /// <returns>The value returned by the function call.</returns>
  131. [Obsolete("Should use Engine.Invoke when direct invoking is needed.")]
  132. public JsValue Invoke(Engine engine, params JsValue[] arguments)
  133. {
  134. return engine.Invoke(this, arguments);
  135. }
  136. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  137. public JsValue Get(JsValue property)
  138. {
  139. return Get(property, this);
  140. }
  141. /// <summary>
  142. /// https://tc39.es/ecma262/#sec-get-o-p
  143. /// </summary>
  144. public virtual JsValue Get(JsValue property, JsValue receiver)
  145. {
  146. return Undefined;
  147. }
  148. /// <summary>
  149. /// https://tc39.es/ecma262/#sec-set-o-p-v-throw
  150. /// </summary>
  151. public virtual bool Set(JsValue property, JsValue value, JsValue receiver)
  152. {
  153. ExceptionHelper.ThrowNotSupportedException();
  154. return false;
  155. }
  156. /// <summary>
  157. /// https://tc39.es/ecma262/#sec-instanceofoperator
  158. /// </summary>
  159. internal bool InstanceofOperator(JsValue target)
  160. {
  161. var oi = target as ObjectInstance;
  162. if (oi is null)
  163. {
  164. ExceptionHelper.ThrowTypeErrorNoEngine("not an object");
  165. }
  166. var instOfHandler = oi.GetMethod(GlobalSymbolRegistry.HasInstance);
  167. if (instOfHandler is not null)
  168. {
  169. return TypeConverter.ToBoolean(instOfHandler.Call(target, new[] {this}));
  170. }
  171. if (!target.IsCallable)
  172. {
  173. ExceptionHelper.ThrowTypeErrorNoEngine("not callable");
  174. }
  175. return target.OrdinaryHasInstance(this);
  176. }
  177. public override string ToString()
  178. {
  179. return "None";
  180. }
  181. public static bool operator ==(JsValue a, JsValue b)
  182. {
  183. if (a is null)
  184. {
  185. return b is null;
  186. }
  187. return b is not null && a.Equals(b);
  188. }
  189. public static bool operator !=(JsValue a, JsValue b)
  190. {
  191. return !(a == b);
  192. }
  193. public static implicit operator JsValue(char value)
  194. {
  195. return JsString.Create(value);
  196. }
  197. public static implicit operator JsValue(int value)
  198. {
  199. return JsNumber.Create(value);
  200. }
  201. public static implicit operator JsValue(uint value)
  202. {
  203. return JsNumber.Create(value);
  204. }
  205. public static implicit operator JsValue(double value)
  206. {
  207. return JsNumber.Create(value);
  208. }
  209. public static implicit operator JsValue(long value)
  210. {
  211. return JsNumber.Create(value);
  212. }
  213. public static implicit operator JsValue(ulong value)
  214. {
  215. return JsNumber.Create(value);
  216. }
  217. public static implicit operator JsValue(BigInteger value)
  218. {
  219. return JsBigInt.Create(value);
  220. }
  221. public static implicit operator JsValue(bool value)
  222. {
  223. return value ? JsBoolean.True : JsBoolean.False;
  224. }
  225. [DebuggerStepThrough]
  226. public static implicit operator JsValue(string value)
  227. {
  228. if (value == null)
  229. {
  230. return Null;
  231. }
  232. return JsString.Create(value);
  233. }
  234. /// <summary>
  235. /// https://tc39.es/ecma262/#sec-islooselyequal
  236. /// </summary>
  237. public virtual bool IsLooselyEqual(JsValue value)
  238. {
  239. if (ReferenceEquals(this, value))
  240. {
  241. return true;
  242. }
  243. // TODO move to type specific IsLooselyEqual
  244. var x = this;
  245. var y = value;
  246. if (x.IsNumber() && y.IsString())
  247. {
  248. return x.IsLooselyEqual(TypeConverter.ToNumber(y));
  249. }
  250. if (x.IsString() && y.IsNumber())
  251. {
  252. return y.IsLooselyEqual(TypeConverter.ToNumber(x));
  253. }
  254. if (x.IsBoolean())
  255. {
  256. return y.IsLooselyEqual(TypeConverter.ToNumber(x));
  257. }
  258. if (y.IsBoolean())
  259. {
  260. return x.IsLooselyEqual(TypeConverter.ToNumber(y));
  261. }
  262. if (y.IsObject() && (x._type & InternalTypes.Primitive) != 0)
  263. {
  264. return x.IsLooselyEqual(TypeConverter.ToPrimitive(y));
  265. }
  266. if (x.IsObject() && (y._type & InternalTypes.Primitive) != 0)
  267. {
  268. return y.IsLooselyEqual(TypeConverter.ToPrimitive(x));
  269. }
  270. return false;
  271. }
  272. /// <summary>
  273. /// Strict equality.
  274. /// </summary>
  275. public override bool Equals(object obj)
  276. {
  277. return Equals(obj as JsValue);
  278. }
  279. /// <summary>
  280. /// Strict equality.
  281. /// </summary>
  282. public virtual bool Equals(JsValue other)
  283. {
  284. return ReferenceEquals(this, other);
  285. }
  286. public override int GetHashCode()
  287. {
  288. return _type.GetHashCode();
  289. }
  290. internal sealed class JsValueDebugView
  291. {
  292. public string Value;
  293. public JsValueDebugView(JsValue value)
  294. {
  295. switch (value.Type)
  296. {
  297. case Types.None:
  298. Value = "None";
  299. break;
  300. case Types.Undefined:
  301. Value = "undefined";
  302. break;
  303. case Types.Null:
  304. Value = "null";
  305. break;
  306. case Types.Boolean:
  307. Value = ((JsBoolean) value)._value + " (bool)";
  308. break;
  309. case Types.String:
  310. Value = value.ToString() + " (string)";
  311. break;
  312. case Types.Number:
  313. Value = ((JsNumber) value)._value + " (number)";
  314. break;
  315. case Types.BigInt:
  316. Value = ((JsBigInt) value)._value + " (bigint)";
  317. break;
  318. case Types.Object:
  319. Value = value.AsObject().GetType().Name;
  320. break;
  321. case Types.Symbol:
  322. var jsValue = ((JsSymbol) value)._value;
  323. Value = (jsValue.IsUndefined() ? "" : jsValue.ToString()) + " (symbol)";
  324. break;
  325. default:
  326. Value = "Unknown";
  327. break;
  328. }
  329. }
  330. }
  331. /// <summary>
  332. /// Some values need to be cloned in order to be assigned, like ConcatenatedString.
  333. /// </summary>
  334. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  335. internal JsValue Clone()
  336. {
  337. // concatenated string and arguments currently may require cloning
  338. return (_type & InternalTypes.RequiresCloning) == 0
  339. ? this
  340. : DoClone();
  341. }
  342. internal virtual JsValue DoClone()
  343. {
  344. return this;
  345. }
  346. internal virtual bool IsCallable => this is ICallable;
  347. /// <summary>
  348. /// https://tc39.es/ecma262/#sec-ordinaryhasinstance
  349. /// </summary>
  350. internal virtual bool OrdinaryHasInstance(JsValue v)
  351. {
  352. if (!IsCallable)
  353. {
  354. return false;
  355. }
  356. if (v is not ObjectInstance o)
  357. {
  358. return false;
  359. }
  360. var p = Get(CommonProperties.Prototype);
  361. if (p is not ObjectInstance)
  362. {
  363. ExceptionHelper.ThrowTypeError(o.Engine.Realm, $"Function has non-object prototype '{TypeConverter.ToString(p)}' in instanceof check");
  364. }
  365. while (true)
  366. {
  367. o = o.Prototype;
  368. if (o is null)
  369. {
  370. return false;
  371. }
  372. if (SameValue(p, o))
  373. {
  374. return true;
  375. }
  376. }
  377. }
  378. internal static bool SameValue(JsValue x, JsValue y)
  379. {
  380. var typea = x.Type;
  381. var typeb = y.Type;
  382. if (typea != typeb)
  383. {
  384. return false;
  385. }
  386. switch (typea)
  387. {
  388. case Types.Number:
  389. if (x._type == y._type && x._type == InternalTypes.Integer)
  390. {
  391. return x.AsInteger() == y.AsInteger();
  392. }
  393. var nx = TypeConverter.ToNumber(x);
  394. var ny = TypeConverter.ToNumber(y);
  395. if (double.IsNaN(nx) && double.IsNaN(ny))
  396. {
  397. return true;
  398. }
  399. if (nx == ny)
  400. {
  401. if (nx == 0)
  402. {
  403. // +0 !== -0
  404. return NumberInstance.IsNegativeZero(nx) == NumberInstance.IsNegativeZero(ny);
  405. }
  406. return true;
  407. }
  408. return false;
  409. case Types.String:
  410. return TypeConverter.ToString(x) == TypeConverter.ToString(y);
  411. case Types.Boolean:
  412. return TypeConverter.ToBoolean(x) == TypeConverter.ToBoolean(y);
  413. case Types.Undefined:
  414. case Types.Null:
  415. return true;
  416. case Types.Symbol:
  417. return x == y;
  418. default:
  419. return ReferenceEquals(x, y);
  420. }
  421. }
  422. internal static IConstructor AssertConstructor(Engine engine, JsValue c)
  423. {
  424. if (!c.IsConstructor)
  425. {
  426. ExceptionHelper.ThrowTypeError(engine.Realm, c + " is not a constructor");
  427. }
  428. return (IConstructor) c;
  429. }
  430. }
  431. }