JsValue.cs 18 KB

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