JsValue.cs 16 KB

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