JsValue.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Diagnostics.Contracts;
  5. using System.Threading;
  6. using Jint.Native.Array;
  7. using Jint.Native.Date;
  8. using Jint.Native.Object;
  9. using Jint.Native.RegExp;
  10. using Jint.Runtime;
  11. using Jint.Runtime.Descriptors.Specialized;
  12. using Jint.Runtime.Interop;
  13. namespace Jint.Native
  14. {
  15. [DebuggerTypeProxy(typeof(JsValueDebugView))]
  16. public abstract class JsValue : IEquatable<JsValue>
  17. {
  18. public static readonly JsValue Undefined = new JsUndefined();
  19. public static readonly JsValue Null = new JsNull();
  20. [Pure]
  21. public bool IsPrimitive()
  22. {
  23. return Type != Types.Object && Type != Types.None;
  24. }
  25. [Pure]
  26. public bool IsUndefined()
  27. {
  28. return Type == Types.Undefined;
  29. }
  30. [Pure]
  31. public virtual bool IsArray()
  32. {
  33. return false;
  34. }
  35. [Pure]
  36. public virtual bool IsDate()
  37. {
  38. return false;
  39. }
  40. [Pure]
  41. public virtual bool IsRegExp()
  42. {
  43. return false;
  44. }
  45. [Pure]
  46. public bool IsObject()
  47. {
  48. return Type == Types.Object;
  49. }
  50. [Pure]
  51. public bool IsString()
  52. {
  53. return Type == Types.String;
  54. }
  55. [Pure]
  56. public bool IsNumber()
  57. {
  58. return Type == Types.Number;
  59. }
  60. [Pure]
  61. public bool IsBoolean()
  62. {
  63. return Type == Types.Boolean;
  64. }
  65. [Pure]
  66. public bool IsNull()
  67. {
  68. return Type == Types.Null;
  69. }
  70. [Pure]
  71. public bool IsCompletion()
  72. {
  73. return Type == Types.Completion;
  74. }
  75. [Pure]
  76. public bool IsSymbol()
  77. {
  78. return Type == Types.Symbol;
  79. }
  80. [Pure]
  81. public virtual ObjectInstance AsObject()
  82. {
  83. throw new ArgumentException("The value is not an object");
  84. }
  85. [Pure]
  86. public virtual TInstance AsInstance<TInstance>() where TInstance : class
  87. {
  88. throw new ArgumentException("The value is not an object");
  89. }
  90. [Pure]
  91. public virtual ArrayInstance AsArray()
  92. {
  93. throw new ArgumentException("The value is not an array");
  94. }
  95. [Pure]
  96. public virtual DateInstance AsDate()
  97. {
  98. throw new ArgumentException("The value is not a date");
  99. }
  100. [Pure]
  101. public virtual RegExpInstance AsRegExp()
  102. {
  103. throw new ArgumentException("The value is not a date");
  104. }
  105. [Pure]
  106. public virtual Completion AsCompletion()
  107. {
  108. if (Type != Types.Completion)
  109. {
  110. throw new ArgumentException("The value is not a completion record");
  111. }
  112. // TODO not implemented
  113. return null;
  114. }
  115. [Pure]
  116. public T TryCast<T>(Action<JsValue> fail = null) where T : class
  117. {
  118. if (IsObject())
  119. {
  120. var o = AsObject();
  121. var t = o as T;
  122. if (t != null)
  123. {
  124. return t;
  125. }
  126. }
  127. fail?.Invoke(this);
  128. return null;
  129. }
  130. public virtual bool Is<T>()
  131. {
  132. return false;
  133. }
  134. public virtual T As<T>() where T : ObjectInstance
  135. {
  136. return null;
  137. }
  138. [Pure]
  139. public virtual bool AsBoolean()
  140. {
  141. throw new ArgumentException("The value is not a boolean");
  142. }
  143. [Pure]
  144. public virtual string AsString()
  145. {
  146. throw new ArgumentException("The value is not a string");
  147. }
  148. [Pure]
  149. public virtual string AsSymbol()
  150. {
  151. throw new ArgumentException("The value is not a symbol");
  152. }
  153. [Pure]
  154. public virtual double AsNumber()
  155. {
  156. throw new ArgumentException("The value is not a number");
  157. }
  158. public abstract Types Type { get; }
  159. /// <summary>
  160. /// Creates a valid <see cref="JsValue"/> instance from any <see cref="Object"/> instance
  161. /// </summary>
  162. /// <param name="engine"></param>
  163. /// <param name="value"></param>
  164. /// <returns></returns>
  165. public static JsValue FromObject(Engine engine, object value)
  166. {
  167. if (value == null)
  168. {
  169. return Null;
  170. }
  171. if (value is JsValue jsValue)
  172. {
  173. return jsValue;
  174. }
  175. var objectConvertersCount = engine.Options._ObjectConverters.Count;
  176. for (var i = 0; i < objectConvertersCount; i++)
  177. {
  178. var converter = engine.Options._ObjectConverters[i];
  179. if (converter.TryConvert(value, out var result))
  180. {
  181. return result;
  182. }
  183. }
  184. var valueType = value.GetType();
  185. var typeMappers = Engine.TypeMappers;
  186. if (typeMappers.TryGetValue(valueType, out var typeMapper))
  187. {
  188. return typeMapper(engine, value);
  189. }
  190. var type = value as Type;
  191. if (type != null)
  192. {
  193. var typeReference = TypeReference.CreateTypeReference(engine, type);
  194. return typeReference;
  195. }
  196. if (value is System.Array a)
  197. {
  198. JsValue Convert(Engine e, object v)
  199. {
  200. var array = (System.Array) v;
  201. var arrayLength = (uint) array.Length;
  202. var jsArray = new ArrayInstance(e, arrayLength);
  203. jsArray.Prototype = e.Array.PrototypeObject;
  204. jsArray.Extensible = true;
  205. for (uint i = 0; i < arrayLength; ++i)
  206. {
  207. var jsItem = FromObject(e, array.GetValue(i));
  208. jsArray.WriteArrayValue(i, new ConfigurableEnumerableWritablePropertyDescriptor(jsItem));
  209. }
  210. jsArray.SetOwnProperty("length", new WritablePropertyDescriptor(arrayLength));
  211. return jsArray;
  212. }
  213. // racy, we don't care, worst case we'll catch up later
  214. Interlocked.CompareExchange(ref Engine.TypeMappers, new Dictionary<Type, Func<Engine, object, JsValue>>(typeMappers)
  215. {
  216. [valueType] = Convert
  217. }, typeMappers);
  218. return Convert(engine, a);
  219. }
  220. if (value is Delegate d)
  221. {
  222. return new DelegateWrapper(engine, d);
  223. }
  224. if (value.GetType().IsEnum())
  225. {
  226. return JsNumber.Create((int) value);
  227. }
  228. // if no known type could be guessed, wrap it as an ObjectInstance
  229. return new ObjectWrapper(engine, value);
  230. }
  231. /// <summary>
  232. /// Converts a <see cref="JsValue"/> to its underlying CLR value.
  233. /// </summary>
  234. /// <returns>The underlying CLR value of the <see cref="JsValue"/> instance.</returns>
  235. public abstract object ToObject();
  236. /// <summary>
  237. /// Invoke the current value as function.
  238. /// </summary>
  239. /// <param name="arguments">The arguments of the function call.</param>
  240. /// <returns>The value returned by the function call.</returns>
  241. public JsValue Invoke(params JsValue[] arguments)
  242. {
  243. return Invoke(Undefined, arguments);
  244. }
  245. /// <summary>
  246. /// Invoke the current value as function.
  247. /// </summary>
  248. /// <param name="thisObj">The this value inside the function call.</param>
  249. /// <param name="arguments">The arguments of the function call.</param>
  250. /// <returns>The value returned by the function call.</returns>
  251. public JsValue Invoke(JsValue thisObj, JsValue[] arguments)
  252. {
  253. var callable = TryCast<ICallable>();
  254. if (callable == null)
  255. {
  256. throw new ArgumentException("Can only invoke functions");
  257. }
  258. return callable.Call(thisObj, arguments);
  259. }
  260. public static bool ReturnOnAbruptCompletion(ref JsValue argument)
  261. {
  262. if (!argument.IsCompletion())
  263. {
  264. return false;
  265. }
  266. var completion = argument.AsCompletion();
  267. if (completion.IsAbrupt())
  268. {
  269. return true;
  270. }
  271. argument = completion.Value;
  272. return false;
  273. }
  274. public override string ToString()
  275. {
  276. return "None";
  277. }
  278. public static bool operator ==(JsValue a, JsValue b)
  279. {
  280. if ((object)a == null)
  281. {
  282. if ((object)b == null)
  283. {
  284. return true;
  285. }
  286. return false;
  287. }
  288. if ((object)b == null)
  289. {
  290. return false;
  291. }
  292. return a.Equals(b);
  293. }
  294. public static bool operator !=(JsValue a, JsValue b)
  295. {
  296. if ((object)a == null)
  297. {
  298. if ((object)b == null)
  299. {
  300. return false;
  301. }
  302. return true;
  303. }
  304. if ((object)b == null)
  305. {
  306. return true;
  307. }
  308. return !a.Equals(b);
  309. }
  310. static public implicit operator JsValue(char value)
  311. {
  312. return JsString.Create(value);
  313. }
  314. static public implicit operator JsValue(int value)
  315. {
  316. return JsNumber.Create(value);
  317. }
  318. static public implicit operator JsValue(uint value)
  319. {
  320. return JsNumber.Create(value);
  321. }
  322. static public implicit operator JsValue(double value)
  323. {
  324. return JsNumber.Create(value);
  325. }
  326. public static implicit operator JsValue(bool value)
  327. {
  328. return value ? JsBoolean.True : JsBoolean.False;
  329. }
  330. public static implicit operator JsValue(string value)
  331. {
  332. if (value == null)
  333. {
  334. return Null;
  335. }
  336. return JsString.Create(value);
  337. }
  338. public override bool Equals(object obj)
  339. {
  340. if (ReferenceEquals(null, obj))
  341. {
  342. return false;
  343. }
  344. if (ReferenceEquals(this, obj))
  345. {
  346. return true;
  347. }
  348. return obj is JsValue value && Equals(value);
  349. }
  350. public abstract bool Equals(JsValue other);
  351. public override int GetHashCode()
  352. {
  353. return Type.GetHashCode();
  354. }
  355. internal class JsValueDebugView
  356. {
  357. public string Value;
  358. public JsValueDebugView(JsValue value)
  359. {
  360. switch (value.Type)
  361. {
  362. case Types.None:
  363. Value = "None";
  364. break;
  365. case Types.Undefined:
  366. Value = "undefined";
  367. break;
  368. case Types.Null:
  369. Value = "null";
  370. break;
  371. case Types.Boolean:
  372. Value = value.AsBoolean() + " (bool)";
  373. break;
  374. case Types.String:
  375. Value = value.AsString() + " (string)";
  376. break;
  377. case Types.Number:
  378. Value = value.AsNumber() + " (number)";
  379. break;
  380. case Types.Object:
  381. Value = value.AsObject().GetType().Name;
  382. break;
  383. case Types.Symbol:
  384. Value = value.AsSymbol() + " (symbol)";
  385. break;
  386. default:
  387. Value = "Unknown";
  388. break;
  389. }
  390. }
  391. }
  392. }
  393. }