JsValue.cs 13 KB

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