JsValue.cs 20 KB

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