JsValue.cs 14 KB

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