2
0

JsValue.cs 15 KB

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