2
0

JsValue.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. using System;
  2. using System.Diagnostics;
  3. using System.Diagnostics.Contracts;
  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. public virtual bool HasOwnProperty(JsValue property) => false;
  137. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  138. public JsValue Get(JsValue property)
  139. {
  140. return Get(property, this);
  141. }
  142. /// <summary>
  143. /// http://www.ecma-international.org/ecma-262/5.1/#sec-8.12.3
  144. /// </summary>
  145. public virtual JsValue Get(JsValue property, JsValue receiver)
  146. {
  147. return Undefined;
  148. }
  149. /// <summary>
  150. /// https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-set-p-v-receiver
  151. /// </summary>
  152. public virtual bool Set(JsValue property, JsValue value, JsValue receiver)
  153. {
  154. ExceptionHelper.ThrowNotSupportedException();
  155. return false;
  156. }
  157. /// <summary>
  158. /// https://tc39.es/ecma262/#sec-instanceofoperator
  159. /// </summary>
  160. internal bool InstanceofOperator(JsValue target)
  161. {
  162. var oi = target as ObjectInstance;
  163. if (oi is null)
  164. {
  165. ExceptionHelper.ThrowTypeErrorNoEngine("not an object");
  166. }
  167. var instOfHandler = oi.GetMethod(GlobalSymbolRegistry.HasInstance);
  168. if (instOfHandler is not null)
  169. {
  170. return TypeConverter.ToBoolean(instOfHandler.Call(target, new[] {this}));
  171. }
  172. if (!target.IsCallable)
  173. {
  174. ExceptionHelper.ThrowTypeErrorNoEngine("not callable");
  175. }
  176. return target.OrdinaryHasInstance(this);
  177. }
  178. public override string ToString()
  179. {
  180. return "None";
  181. }
  182. public static bool operator ==(JsValue a, JsValue b)
  183. {
  184. if ((object) a == null)
  185. {
  186. return (object) b == null;
  187. }
  188. return (object) b != null && a.Equals(b);
  189. }
  190. public static bool operator !=(JsValue a, JsValue b)
  191. {
  192. if ((object) a == null)
  193. {
  194. if ((object) b == null)
  195. {
  196. return false;
  197. }
  198. return true;
  199. }
  200. if ((object) b == null)
  201. {
  202. return true;
  203. }
  204. return !a.Equals(b);
  205. }
  206. public static implicit operator JsValue(char value)
  207. {
  208. return JsString.Create(value);
  209. }
  210. public static implicit operator JsValue(int value)
  211. {
  212. return JsNumber.Create(value);
  213. }
  214. public static implicit operator JsValue(uint value)
  215. {
  216. return JsNumber.Create(value);
  217. }
  218. public static implicit operator JsValue(double value)
  219. {
  220. return JsNumber.Create(value);
  221. }
  222. public static implicit operator JsValue(long value)
  223. {
  224. return JsNumber.Create(value);
  225. }
  226. public static implicit operator JsValue(ulong value)
  227. {
  228. return JsNumber.Create(value);
  229. }
  230. public static implicit operator JsValue(bool value)
  231. {
  232. return value ? JsBoolean.True : JsBoolean.False;
  233. }
  234. [DebuggerStepThrough]
  235. public static implicit operator JsValue(string value)
  236. {
  237. if (value == null)
  238. {
  239. return Null;
  240. }
  241. return JsString.Create(value);
  242. }
  243. public override bool Equals(object obj)
  244. {
  245. if (ReferenceEquals(null, obj))
  246. {
  247. return false;
  248. }
  249. if (ReferenceEquals(this, obj))
  250. {
  251. return true;
  252. }
  253. return obj is JsValue value && Equals(value);
  254. }
  255. public abstract bool Equals(JsValue other);
  256. public override int GetHashCode()
  257. {
  258. return _type.GetHashCode();
  259. }
  260. internal sealed class JsValueDebugView
  261. {
  262. public string Value;
  263. public JsValueDebugView(JsValue value)
  264. {
  265. switch (value.Type)
  266. {
  267. case Types.None:
  268. Value = "None";
  269. break;
  270. case Types.Undefined:
  271. Value = "undefined";
  272. break;
  273. case Types.Null:
  274. Value = "null";
  275. break;
  276. case Types.Boolean:
  277. Value = ((JsBoolean) value)._value + " (bool)";
  278. break;
  279. case Types.String:
  280. Value = value.ToString() + " (string)";
  281. break;
  282. case Types.Number:
  283. Value = ((JsNumber) value)._value + " (number)";
  284. break;
  285. case Types.Object:
  286. Value = value.AsObject().GetType().Name;
  287. break;
  288. case Types.Symbol:
  289. var jsValue = ((JsSymbol) value)._value;
  290. Value = (jsValue.IsUndefined() ? "" : jsValue.ToString()) + " (symbol)";
  291. break;
  292. default:
  293. Value = "Unknown";
  294. break;
  295. }
  296. }
  297. }
  298. /// <summary>
  299. /// Some values need to be cloned in order to be assigned, like ConcatenatedString.
  300. /// </summary>
  301. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  302. internal JsValue Clone()
  303. {
  304. // concatenated string and arguments currently may require cloning
  305. return (_type & InternalTypes.RequiresCloning) == 0
  306. ? this
  307. : DoClone();
  308. }
  309. internal virtual JsValue DoClone()
  310. {
  311. return this;
  312. }
  313. internal virtual bool IsCallable => this is ICallable;
  314. /// <summary>
  315. /// https://tc39.es/ecma262/#sec-ordinaryhasinstance
  316. /// </summary>
  317. internal virtual bool OrdinaryHasInstance(JsValue v)
  318. {
  319. if (!IsCallable)
  320. {
  321. return false;
  322. }
  323. if (v is not ObjectInstance o)
  324. {
  325. return false;
  326. }
  327. var p = Get(CommonProperties.Prototype);
  328. if (p is not ObjectInstance)
  329. {
  330. ExceptionHelper.ThrowTypeError(o.Engine.Realm, $"Function has non-object prototype '{TypeConverter.ToString(p)}' in instanceof check");
  331. }
  332. while (true)
  333. {
  334. o = o.Prototype;
  335. if (o is null)
  336. {
  337. return false;
  338. }
  339. if (SameValue(p, o))
  340. {
  341. return true;
  342. }
  343. }
  344. }
  345. internal static bool SameValue(JsValue x, JsValue y)
  346. {
  347. var typea = x.Type;
  348. var typeb = y.Type;
  349. if (typea != typeb)
  350. {
  351. return false;
  352. }
  353. switch (typea)
  354. {
  355. case Types.Number:
  356. if (x._type == y._type && x._type == InternalTypes.Integer)
  357. {
  358. return x.AsInteger() == y.AsInteger();
  359. }
  360. var nx = TypeConverter.ToNumber(x);
  361. var ny = TypeConverter.ToNumber(y);
  362. if (double.IsNaN(nx) && double.IsNaN(ny))
  363. {
  364. return true;
  365. }
  366. if (nx == ny)
  367. {
  368. if (nx == 0)
  369. {
  370. // +0 !== -0
  371. return NumberInstance.IsNegativeZero(nx) == NumberInstance.IsNegativeZero(ny);
  372. }
  373. return true;
  374. }
  375. return false;
  376. case Types.String:
  377. return TypeConverter.ToString(x) == TypeConverter.ToString(y);
  378. case Types.Boolean:
  379. return TypeConverter.ToBoolean(x) == TypeConverter.ToBoolean(y);
  380. case Types.Undefined:
  381. case Types.Null:
  382. return true;
  383. case Types.Symbol:
  384. return x == y;
  385. default:
  386. return ReferenceEquals(x, y);
  387. }
  388. }
  389. internal static IConstructor AssertConstructor(Engine engine, JsValue c)
  390. {
  391. var constructor = c as IConstructor;
  392. if (constructor is null)
  393. {
  394. ExceptionHelper.ThrowTypeError(engine.Realm, c + " is not a constructor");
  395. }
  396. return constructor;
  397. }
  398. }
  399. }