JsValue.cs 13 KB

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