JsValue.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Diagnostics.Contracts;
  5. using System.Dynamic;
  6. using System.Reflection;
  7. using System.Threading;
  8. using Jint.Native.Array;
  9. using Jint.Native.Boolean;
  10. using Jint.Native.Date;
  11. using Jint.Native.Function;
  12. using Jint.Native.Number;
  13. using Jint.Native.Object;
  14. using Jint.Native.RegExp;
  15. using Jint.Native.String;
  16. using Jint.Runtime;
  17. using Jint.Runtime.Interop;
  18. namespace Jint.Native
  19. {
  20. [DebuggerTypeProxy(typeof(JsValueDebugView))]
  21. public class JsValue : IEquatable<JsValue>
  22. {
  23. public readonly static JsValue Undefined = new JsValue(Types.Undefined);
  24. public readonly static JsValue Null = new JsValue(Types.Null);
  25. public readonly static JsValue False = new JsValue(false);
  26. public readonly static JsValue True = new JsValue(true);
  27. public JsValue(bool value)
  28. {
  29. _double = value ? 1.0 : 0.0;
  30. _object = null;
  31. _type = Types.Boolean;
  32. }
  33. public JsValue(double value)
  34. {
  35. _object = null;
  36. _type = Types.Number;
  37. _double = value;
  38. }
  39. public JsValue(string value)
  40. {
  41. _double = double.NaN;
  42. _object = value;
  43. _type = Types.String;
  44. }
  45. public JsValue(ObjectInstance value)
  46. {
  47. _double = double.NaN;
  48. _type = Types.Object;
  49. _object = value;
  50. }
  51. private JsValue(Types type)
  52. {
  53. _double = double.NaN;
  54. _object = null;
  55. _type = type;
  56. }
  57. private readonly double _double;
  58. private readonly object _object;
  59. private readonly Types _type;
  60. [Pure]
  61. public bool IsPrimitive()
  62. {
  63. return _type != Types.Object && _type != Types.None;
  64. }
  65. [Pure]
  66. public bool IsUndefined()
  67. {
  68. return _type == Types.Undefined;
  69. }
  70. [Pure]
  71. public bool IsArray()
  72. {
  73. return IsObject() && AsObject() is ArrayInstance;
  74. }
  75. [Pure]
  76. public bool IsDate()
  77. {
  78. return IsObject() && AsObject() is DateInstance;
  79. }
  80. [Pure]
  81. public bool IsRegExp()
  82. {
  83. return IsObject() && AsObject() is RegExpInstance;
  84. }
  85. [Pure]
  86. public bool IsObject()
  87. {
  88. return _type == Types.Object;
  89. }
  90. [Pure]
  91. public bool IsString()
  92. {
  93. return _type == Types.String;
  94. }
  95. [Pure]
  96. public bool IsNumber()
  97. {
  98. return _type == Types.Number;
  99. }
  100. [Pure]
  101. public bool IsBoolean()
  102. {
  103. return _type == Types.Boolean;
  104. }
  105. [Pure]
  106. public bool IsNull()
  107. {
  108. return _type == Types.Null;
  109. }
  110. [Pure]
  111. public ObjectInstance AsObject()
  112. {
  113. if (_type != Types.Object)
  114. {
  115. throw new ArgumentException("The value is not an object");
  116. }
  117. return _object as ObjectInstance;
  118. }
  119. [Pure]
  120. public ArrayInstance AsArray()
  121. {
  122. if (!IsArray())
  123. {
  124. throw new ArgumentException("The value is not an array");
  125. }
  126. return _object as ArrayInstance;
  127. }
  128. [Pure]
  129. public DateInstance AsDate()
  130. {
  131. if (!IsDate())
  132. {
  133. throw new ArgumentException("The value is not a date");
  134. }
  135. return _object as DateInstance;
  136. }
  137. [Pure]
  138. public RegExpInstance AsRegExp()
  139. {
  140. if (!IsRegExp())
  141. {
  142. throw new ArgumentException("The value is not a date");
  143. }
  144. return _object as RegExpInstance;
  145. }
  146. [Pure]
  147. public T TryCast<T>(Action<JsValue> fail = null) where T : class
  148. {
  149. if (IsObject())
  150. {
  151. var o = AsObject();
  152. var t = o as T;
  153. if (t != null)
  154. {
  155. return t;
  156. }
  157. }
  158. if (fail != null)
  159. {
  160. fail(this);
  161. }
  162. return null;
  163. }
  164. public bool Is<T>()
  165. {
  166. return IsObject() && AsObject() is T;
  167. }
  168. public T As<T>() where T : ObjectInstance
  169. {
  170. return _object as T;
  171. }
  172. [Pure]
  173. public bool AsBoolean()
  174. {
  175. if (_type != Types.Boolean)
  176. {
  177. throw new ArgumentException("The value is not a boolean");
  178. }
  179. return _double != 0;
  180. }
  181. [Pure]
  182. public string AsString()
  183. {
  184. if (_type != Types.String)
  185. {
  186. throw new ArgumentException("The value is not a string");
  187. }
  188. if (_object == null)
  189. {
  190. throw new ArgumentException("The value is not defined");
  191. }
  192. return _object as string;
  193. }
  194. [Pure]
  195. public double AsNumber()
  196. {
  197. if (_type != Types.Number)
  198. {
  199. throw new ArgumentException("The value is not a number");
  200. }
  201. return _double;
  202. }
  203. public bool Equals(JsValue other)
  204. {
  205. if (other == null)
  206. {
  207. return false;
  208. }
  209. if(ReferenceEquals(this, other))
  210. {
  211. return true;
  212. }
  213. if (_type != other._type)
  214. {
  215. return false;
  216. }
  217. switch (_type)
  218. {
  219. case Types.None:
  220. return false;
  221. case Types.Undefined:
  222. return true;
  223. case Types.Null:
  224. return true;
  225. case Types.Boolean:
  226. case Types.Number:
  227. return _double == other._double;
  228. case Types.String:
  229. case Types.Object:
  230. return _object == other._object;
  231. default:
  232. throw new ArgumentOutOfRangeException();
  233. }
  234. }
  235. public Types Type
  236. {
  237. get { return _type; }
  238. }
  239. /// <summary>
  240. /// Creates a valid <see cref="JsValue"/> instance from any <see cref="Object"/> instance
  241. /// </summary>
  242. /// <param name="engine"></param>
  243. /// <param name="value"></param>
  244. /// <returns></returns>
  245. public static JsValue FromObject(Engine engine, object value)
  246. {
  247. if (value == null)
  248. {
  249. return Null;
  250. }
  251. foreach (var converter in engine.Options._ObjectConverters)
  252. {
  253. JsValue result;
  254. if (converter.TryConvert(value, out result))
  255. {
  256. return result;
  257. }
  258. }
  259. var valueType = value.GetType();
  260. var typeMappers = Engine.TypeMappers;
  261. Func<Engine, object, JsValue> typeMapper;
  262. if (typeMappers.TryGetValue(valueType, out typeMapper))
  263. {
  264. return typeMapper(engine, value);
  265. }
  266. // if an ObjectInstance is passed directly, use it as is
  267. var instance = value as ObjectInstance;
  268. if (instance != null)
  269. {
  270. // Learn conversion.
  271. // Learn conversion, racy, worst case we'll try again later
  272. Interlocked.CompareExchange(ref Engine.TypeMappers, new Dictionary<Type, Func<Engine, object, JsValue>>(typeMappers)
  273. {
  274. [valueType] = (Engine e, object v) => new JsValue((ObjectInstance)v)
  275. }, typeMappers);
  276. return new JsValue(instance);
  277. }
  278. var type = value as Type;
  279. if(type != null)
  280. {
  281. var typeReference = TypeReference.CreateTypeReference(engine, type);
  282. return new JsValue(typeReference);
  283. }
  284. var a = value as System.Array;
  285. if (a != null)
  286. {
  287. Func<Engine, object, JsValue> convert = (Engine e, object v) =>
  288. {
  289. var array = (System.Array)v;
  290. var jsArray = engine.Array.Construct(Arguments.Empty);
  291. foreach (var item in array)
  292. {
  293. var jsItem = JsValue.FromObject(engine, item);
  294. engine.Array.PrototypeObject.Push(jsArray, Arguments.From(jsItem));
  295. }
  296. return jsArray;
  297. };
  298. // racy, we don't care, worst case we'll catch up later
  299. Interlocked.CompareExchange(ref Engine.TypeMappers, new Dictionary<Type, Func<Engine, object, JsValue>>(typeMappers)
  300. {
  301. [valueType] = convert
  302. }, typeMappers);
  303. return convert(engine, a);
  304. }
  305. var d = value as Delegate;
  306. if (d != null)
  307. {
  308. return new DelegateWrapper(engine, d);
  309. }
  310. if (value.GetType().IsEnum())
  311. {
  312. return new JsValue((Int32)value);
  313. }
  314. // if no known type could be guessed, wrap it as an ObjectInstance
  315. return new ObjectWrapper(engine, value);
  316. }
  317. /// <summary>
  318. /// Converts a <see cref="JsValue"/> to its underlying CLR value.
  319. /// </summary>
  320. /// <returns>The underlying CLR value of the <see cref="JsValue"/> instance.</returns>
  321. public object ToObject()
  322. {
  323. switch (_type)
  324. {
  325. case Types.None:
  326. case Types.Undefined:
  327. case Types.Null:
  328. return null;
  329. case Types.String:
  330. return _object;
  331. case Types.Boolean:
  332. return _double != 0;
  333. case Types.Number:
  334. return _double;
  335. case Types.Object:
  336. var wrapper = _object as IObjectWrapper;
  337. if (wrapper != null)
  338. {
  339. return wrapper.Target;
  340. }
  341. switch ((_object as ObjectInstance).Class)
  342. {
  343. case "Array":
  344. var arrayInstance = _object as ArrayInstance;
  345. if (arrayInstance != null)
  346. {
  347. var len = TypeConverter.ToInt32(arrayInstance.Get("length"));
  348. var result = new object[len];
  349. for (var k = 0; k < len; k++)
  350. {
  351. var pk = k.ToString();
  352. var kpresent = arrayInstance.HasProperty(pk);
  353. if (kpresent)
  354. {
  355. var kvalue = arrayInstance.Get(pk);
  356. result[k] = kvalue.ToObject();
  357. }
  358. else
  359. {
  360. result[k] = null;
  361. }
  362. }
  363. return result;
  364. }
  365. break;
  366. case "String":
  367. var stringInstance = _object as StringInstance;
  368. if (stringInstance != null)
  369. {
  370. return stringInstance.PrimitiveValue.AsString();
  371. }
  372. break;
  373. case "Date":
  374. var dateInstance = _object as DateInstance;
  375. if (dateInstance != null)
  376. {
  377. return dateInstance.ToDateTime();
  378. }
  379. break;
  380. case "Boolean":
  381. var booleanInstance = _object as BooleanInstance;
  382. if (booleanInstance != null)
  383. {
  384. return booleanInstance.PrimitiveValue.AsBoolean();
  385. }
  386. break;
  387. case "Function":
  388. var function = _object as FunctionInstance;
  389. if (function != null)
  390. {
  391. return (Func<JsValue, JsValue[], JsValue>)function.Call;
  392. }
  393. break;
  394. case "Number":
  395. var numberInstance = _object as NumberInstance;
  396. if (numberInstance != null)
  397. {
  398. return numberInstance.PrimitiveValue.AsNumber();
  399. }
  400. break;
  401. case "RegExp":
  402. var regeExpInstance = _object as RegExpInstance;
  403. if (regeExpInstance != null)
  404. {
  405. return regeExpInstance.Value;
  406. }
  407. break;
  408. case "Arguments":
  409. case "Object":
  410. #if __IOS__
  411. IDictionary<string, object> o = new Dictionary<string, object>();
  412. #else
  413. IDictionary<string, object> o = new ExpandoObject();
  414. #endif
  415. foreach (var p in (_object as ObjectInstance).GetOwnProperties())
  416. {
  417. if (!p.Value.Enumerable.HasValue || p.Value.Enumerable.Value == false)
  418. {
  419. continue;
  420. }
  421. o.Add(p.Key, (_object as ObjectInstance).Get(p.Key).ToObject());
  422. }
  423. return o;
  424. }
  425. return _object;
  426. default:
  427. throw new ArgumentOutOfRangeException();
  428. }
  429. }
  430. /// <summary>
  431. /// Invoke the current value as function.
  432. /// </summary>
  433. /// <param name="arguments">The arguments of the function call.</param>
  434. /// <returns>The value returned by the function call.</returns>
  435. public JsValue Invoke(params JsValue[] arguments)
  436. {
  437. return Invoke(Undefined, arguments);
  438. }
  439. /// <summary>
  440. /// Invoke the current value as function.
  441. /// </summary>
  442. /// <param name="thisObj">The this value inside the function call.</param>
  443. /// <param name="arguments">The arguments of the function call.</param>
  444. /// <returns>The value returned by the function call.</returns>
  445. public JsValue Invoke(JsValue thisObj, JsValue[] arguments)
  446. {
  447. var callable = TryCast<ICallable>();
  448. if (callable == null)
  449. {
  450. throw new ArgumentException("Can only invoke functions");
  451. }
  452. return callable.Call(thisObj, arguments);
  453. }
  454. public override string ToString()
  455. {
  456. switch (Type)
  457. {
  458. case Types.None:
  459. return "None";
  460. case Types.Undefined:
  461. return "undefined";
  462. case Types.Null:
  463. return "null";
  464. case Types.Boolean:
  465. return _double != 0 ? bool.TrueString : bool.FalseString;
  466. case Types.Number:
  467. return _double.ToString();
  468. case Types.String:
  469. case Types.Object:
  470. return _object.ToString();
  471. default:
  472. return string.Empty;
  473. }
  474. }
  475. public static bool operator ==(JsValue a, JsValue b)
  476. {
  477. if ((object)a == null)
  478. {
  479. if ((object)b == null)
  480. {
  481. return true;
  482. }
  483. return false;
  484. }
  485. return a.Equals(b);
  486. }
  487. public static bool operator !=(JsValue a, JsValue b)
  488. {
  489. if ((object)a == null)
  490. {
  491. if ((object)b == null)
  492. {
  493. return false;
  494. }
  495. return true;
  496. }
  497. return !a.Equals(b);
  498. }
  499. static public implicit operator JsValue(double value)
  500. {
  501. return new JsValue(value);
  502. }
  503. static public implicit operator JsValue(bool value)
  504. {
  505. return new JsValue(value);
  506. }
  507. static public implicit operator JsValue(string value)
  508. {
  509. return new JsValue(value);
  510. }
  511. static public implicit operator JsValue(ObjectInstance value)
  512. {
  513. return new JsValue(value);
  514. }
  515. internal class JsValueDebugView
  516. {
  517. public string Value;
  518. public JsValueDebugView(JsValue value)
  519. {
  520. switch (value.Type)
  521. {
  522. case Types.None:
  523. Value = "None";
  524. break;
  525. case Types.Undefined:
  526. Value = "undefined";
  527. break;
  528. case Types.Null:
  529. Value = "null";
  530. break;
  531. case Types.Boolean:
  532. Value = value.AsBoolean() + " (bool)";
  533. break;
  534. case Types.String:
  535. Value = value.AsString() + " (string)";
  536. break;
  537. case Types.Number:
  538. Value = value.AsNumber() + " (number)";
  539. break;
  540. case Types.Object:
  541. Value = value.AsObject().GetType().Name;
  542. break;
  543. default:
  544. Value = "Unknown";
  545. break;
  546. }
  547. }
  548. }
  549. public override bool Equals(object obj)
  550. {
  551. if (ReferenceEquals(null, obj)) return false;
  552. return obj is JsValue && Equals((JsValue)obj);
  553. }
  554. public override int GetHashCode()
  555. {
  556. unchecked
  557. {
  558. var hashCode = 0;
  559. hashCode = (hashCode * 397) ^ _double.GetHashCode();
  560. hashCode = (hashCode * 397) ^ (_object != null ? _object.GetHashCode() : 0);
  561. hashCode = (hashCode * 397) ^ (int)_type;
  562. return hashCode;
  563. }
  564. }
  565. }
  566. }