JsValue.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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;
  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 converters = engine.Options._ObjectConverters;
  176. var convertersCount = converters.Count;
  177. for (var i = 0; i < convertersCount; i++)
  178. {
  179. var converter = converters[i];
  180. if (converter.TryConvert(value, out var result))
  181. {
  182. return result;
  183. }
  184. }
  185. var valueType = value.GetType();
  186. var typeMappers = Engine.TypeMappers;
  187. if (typeMappers.TryGetValue(valueType, out var typeMapper))
  188. {
  189. return typeMapper(engine, value);
  190. }
  191. var type = value as Type;
  192. if (type != null)
  193. {
  194. var typeReference = TypeReference.CreateTypeReference(engine, type);
  195. return typeReference;
  196. }
  197. if (value is System.Array a)
  198. {
  199. // racy, we don't care, worst case we'll catch up later
  200. Interlocked.CompareExchange(ref Engine.TypeMappers, new Dictionary<Type, Func<Engine, object, JsValue>>(typeMappers)
  201. {
  202. [valueType] = Convert
  203. }, typeMappers);
  204. return Convert(engine, a);
  205. }
  206. if (value is Delegate d)
  207. {
  208. return new DelegateWrapper(engine, d);
  209. }
  210. if (value.GetType().IsEnum())
  211. {
  212. return JsNumber.Create((int) value);
  213. }
  214. // if no known type could be guessed, wrap it as an ObjectInstance
  215. return new ObjectWrapper(engine, value);
  216. }
  217. private static JsValue Convert(Engine e, object v)
  218. {
  219. var array = (System.Array) v;
  220. var arrayLength = (uint) array.Length;
  221. var jsArray = new ArrayInstance(e, arrayLength);
  222. jsArray.Prototype = e.Array.PrototypeObject;
  223. jsArray.Extensible = true;
  224. for (uint i = 0; i < arrayLength; ++i)
  225. {
  226. var jsItem = FromObject(e, array.GetValue(i));
  227. jsArray.WriteArrayValue(i, new PropertyDescriptor(jsItem, PropertyFlag.ConfigurableEnumerableWritable));
  228. }
  229. jsArray.SetOwnProperty("length", new PropertyDescriptor(arrayLength, PropertyFlag.OnlyWritable));
  230. return jsArray;
  231. }
  232. /// <summary>
  233. /// Converts a <see cref="JsValue"/> to its underlying CLR value.
  234. /// </summary>
  235. /// <returns>The underlying CLR value of the <see cref="JsValue"/> instance.</returns>
  236. public abstract object ToObject();
  237. /// <summary>
  238. /// Invoke the current value as function.
  239. /// </summary>
  240. /// <param name="arguments">The arguments of the function call.</param>
  241. /// <returns>The value returned by the function call.</returns>
  242. public JsValue Invoke(params JsValue[] arguments)
  243. {
  244. return Invoke(Undefined, arguments);
  245. }
  246. /// <summary>
  247. /// Invoke the current value as function.
  248. /// </summary>
  249. /// <param name="thisObj">The this value inside the function call.</param>
  250. /// <param name="arguments">The arguments of the function call.</param>
  251. /// <returns>The value returned by the function call.</returns>
  252. public JsValue Invoke(JsValue thisObj, JsValue[] arguments)
  253. {
  254. var callable = TryCast<ICallable>();
  255. if (callable == null)
  256. {
  257. throw new ArgumentException("Can only invoke functions");
  258. }
  259. return callable.Call(thisObj, arguments);
  260. }
  261. public static bool ReturnOnAbruptCompletion(ref JsValue argument)
  262. {
  263. if (!argument.IsCompletion())
  264. {
  265. return false;
  266. }
  267. var completion = argument.AsCompletion();
  268. if (completion.IsAbrupt())
  269. {
  270. return true;
  271. }
  272. argument = completion.Value;
  273. return false;
  274. }
  275. public override string ToString()
  276. {
  277. return "None";
  278. }
  279. public static bool operator ==(JsValue a, JsValue b)
  280. {
  281. if ((object)a == null)
  282. {
  283. if ((object)b == null)
  284. {
  285. return true;
  286. }
  287. return false;
  288. }
  289. if ((object)b == null)
  290. {
  291. return false;
  292. }
  293. return a.Equals(b);
  294. }
  295. public static bool operator !=(JsValue a, JsValue b)
  296. {
  297. if ((object)a == null)
  298. {
  299. if ((object)b == null)
  300. {
  301. return false;
  302. }
  303. return true;
  304. }
  305. if ((object)b == null)
  306. {
  307. return true;
  308. }
  309. return !a.Equals(b);
  310. }
  311. static public implicit operator JsValue(char value)
  312. {
  313. return JsString.Create(value);
  314. }
  315. static public implicit operator JsValue(int value)
  316. {
  317. return JsNumber.Create(value);
  318. }
  319. static public implicit operator JsValue(uint value)
  320. {
  321. return JsNumber.Create(value);
  322. }
  323. static public implicit operator JsValue(double value)
  324. {
  325. return JsNumber.Create(value);
  326. }
  327. public static implicit operator JsValue(bool value)
  328. {
  329. return value ? JsBoolean.True : JsBoolean.False;
  330. }
  331. public static implicit operator JsValue(string value)
  332. {
  333. if (value == null)
  334. {
  335. return Null;
  336. }
  337. return JsString.Create(value);
  338. }
  339. public override bool Equals(object obj)
  340. {
  341. if (ReferenceEquals(null, obj))
  342. {
  343. return false;
  344. }
  345. if (ReferenceEquals(this, obj))
  346. {
  347. return true;
  348. }
  349. return obj is JsValue value && Equals(value);
  350. }
  351. public abstract bool Equals(JsValue other);
  352. public override int GetHashCode()
  353. {
  354. return Type.GetHashCode();
  355. }
  356. internal class JsValueDebugView
  357. {
  358. public string Value;
  359. public JsValueDebugView(JsValue value)
  360. {
  361. switch (value.Type)
  362. {
  363. case Types.None:
  364. Value = "None";
  365. break;
  366. case Types.Undefined:
  367. Value = "undefined";
  368. break;
  369. case Types.Null:
  370. Value = "null";
  371. break;
  372. case Types.Boolean:
  373. Value = value.AsBoolean() + " (bool)";
  374. break;
  375. case Types.String:
  376. Value = value.AsString() + " (string)";
  377. break;
  378. case Types.Number:
  379. Value = value.AsNumber() + " (number)";
  380. break;
  381. case Types.Object:
  382. Value = value.AsObject().GetType().Name;
  383. break;
  384. case Types.Symbol:
  385. Value = value.AsSymbol() + " (symbol)";
  386. break;
  387. default:
  388. Value = "Unknown";
  389. break;
  390. }
  391. }
  392. }
  393. }
  394. }