JsValue.cs 19 KB

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