JsValue.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  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 struct 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 (_type != other._type)
  204. {
  205. return false;
  206. }
  207. switch (_type)
  208. {
  209. case Types.None:
  210. return false;
  211. case Types.Undefined:
  212. return true;
  213. case Types.Null:
  214. return true;
  215. case Types.Boolean:
  216. case Types.Number:
  217. return _double == other._double;
  218. case Types.String:
  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._ObjectConverters)
  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 System.Array;
  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 (value.GetType().IsEnum)
  327. {
  328. return new JsValue((Int32)value);
  329. }
  330. // if no known type could be guessed, wrap it as an ObjectInstance
  331. return new ObjectWrapper(engine, value);
  332. }
  333. /// <summary>
  334. /// Converts a <see cref="JsValue"/> to its underlying CLR value.
  335. /// </summary>
  336. /// <returns>The underlying CLR value of the <see cref="JsValue"/> instance.</returns>
  337. public object ToObject()
  338. {
  339. switch (_type)
  340. {
  341. case Types.None:
  342. case Types.Undefined:
  343. case Types.Null:
  344. return null;
  345. case Types.String:
  346. return _object;
  347. case Types.Boolean:
  348. return _double != 0;
  349. case Types.Number:
  350. return _double;
  351. case Types.Object:
  352. var wrapper = _object as IObjectWrapper;
  353. if (wrapper != null)
  354. {
  355. return wrapper.Target;
  356. }
  357. switch ((_object as ObjectInstance).Class)
  358. {
  359. case "Array":
  360. var arrayInstance = _object as ArrayInstance;
  361. if (arrayInstance != null)
  362. {
  363. var len = TypeConverter.ToInt32(arrayInstance.Get("length"));
  364. var result = new object[len];
  365. for (var k = 0; k < len; k++)
  366. {
  367. var pk = k.ToString();
  368. var kpresent = arrayInstance.HasProperty(pk);
  369. if (kpresent)
  370. {
  371. var kvalue = arrayInstance.Get(pk);
  372. result[k] = kvalue.ToObject();
  373. }
  374. else
  375. {
  376. result[k] = null;
  377. }
  378. }
  379. return result;
  380. }
  381. break;
  382. case "String":
  383. var stringInstance = _object as StringInstance;
  384. if (stringInstance != null)
  385. {
  386. return stringInstance.PrimitiveValue.AsString();
  387. }
  388. break;
  389. case "Date":
  390. var dateInstance = _object as DateInstance;
  391. if (dateInstance != null)
  392. {
  393. return dateInstance.ToDateTime();
  394. }
  395. break;
  396. case "Boolean":
  397. var booleanInstance = _object as BooleanInstance;
  398. if (booleanInstance != null)
  399. {
  400. return booleanInstance.PrimitiveValue.AsBoolean();
  401. }
  402. break;
  403. case "Function":
  404. var function = _object as FunctionInstance;
  405. if (function != null)
  406. {
  407. return (Func<JsValue, JsValue[], JsValue>)function.Call;
  408. }
  409. break;
  410. case "Number":
  411. var numberInstance = _object as NumberInstance;
  412. if (numberInstance != null)
  413. {
  414. return numberInstance.PrimitiveValue.AsNumber();
  415. }
  416. break;
  417. case "RegExp":
  418. var regeExpInstance = _object as RegExpInstance;
  419. if (regeExpInstance != null)
  420. {
  421. return regeExpInstance.Value;
  422. }
  423. break;
  424. case "Object":
  425. #if __IOS__
  426. IDictionary<string, object> o = new Dictionary<string, object>();
  427. #else
  428. IDictionary<string, object> o = new ExpandoObject();
  429. #endif
  430. foreach (var p in (_object as ObjectInstance).GetOwnProperties())
  431. {
  432. if (!p.Value.Enumerable.HasValue || p.Value.Enumerable.Value == false)
  433. {
  434. continue;
  435. }
  436. o.Add(p.Key, (_object as ObjectInstance).Get(p.Key).ToObject());
  437. }
  438. return o;
  439. }
  440. return _object;
  441. default:
  442. throw new ArgumentOutOfRangeException();
  443. }
  444. }
  445. /// <summary>
  446. /// Invoke the current value as function.
  447. /// </summary>
  448. /// <param name="arguments">The arguments of the function call.</param>
  449. /// <returns>The value returned by the function call.</returns>
  450. public JsValue Invoke(params JsValue[] arguments)
  451. {
  452. return Invoke(Undefined, arguments);
  453. }
  454. /// <summary>
  455. /// Invoke the current value as function.
  456. /// </summary>
  457. /// <param name="thisObj">The this value inside the function call.</param>
  458. /// <param name="arguments">The arguments of the function call.</param>
  459. /// <returns>The value returned by the function call.</returns>
  460. public JsValue Invoke(JsValue thisObj, JsValue[] arguments)
  461. {
  462. var callable = TryCast<ICallable>();
  463. if (callable == null)
  464. {
  465. throw new ArgumentException("Can only invoke functions");
  466. }
  467. return callable.Call(thisObj, arguments);
  468. }
  469. public override string ToString()
  470. {
  471. switch (Type)
  472. {
  473. case Types.None:
  474. return "None";
  475. case Types.Undefined:
  476. return "undefined";
  477. case Types.Null:
  478. return "null";
  479. case Types.Boolean:
  480. return _double != 0 ? bool.TrueString : bool.FalseString;
  481. case Types.Number:
  482. return _double.ToString();
  483. case Types.String:
  484. case Types.Object:
  485. return _object.ToString();
  486. default:
  487. return string.Empty;
  488. }
  489. }
  490. public static bool operator ==(JsValue a, JsValue b)
  491. {
  492. return a.Equals(b);
  493. }
  494. public static bool operator !=(JsValue a, JsValue b)
  495. {
  496. return !a.Equals(b);
  497. }
  498. static public implicit operator JsValue(double value)
  499. {
  500. return new JsValue(value);
  501. }
  502. static public implicit operator JsValue(bool value)
  503. {
  504. return new JsValue(value);
  505. }
  506. static public implicit operator JsValue(string value)
  507. {
  508. return new JsValue(value);
  509. }
  510. static public implicit operator JsValue(ObjectInstance value)
  511. {
  512. return new JsValue(value);
  513. }
  514. internal class JsValueDebugView
  515. {
  516. public string Value;
  517. public JsValueDebugView(JsValue value)
  518. {
  519. switch (value.Type)
  520. {
  521. case Types.None:
  522. Value = "None";
  523. break;
  524. case Types.Undefined:
  525. Value = "undefined";
  526. break;
  527. case Types.Null:
  528. Value = "null";
  529. break;
  530. case Types.Boolean:
  531. Value = value.AsBoolean() + " (bool)";
  532. break;
  533. case Types.String:
  534. Value = value.AsString() + " (string)";
  535. break;
  536. case Types.Number:
  537. Value = value.AsNumber() + " (number)";
  538. break;
  539. case Types.Object:
  540. Value = value.AsObject().GetType().Name;
  541. break;
  542. default:
  543. Value = "Unknown";
  544. break;
  545. }
  546. }
  547. }
  548. public override bool Equals(object obj)
  549. {
  550. if (ReferenceEquals(null, obj)) return false;
  551. return obj is JsValue && Equals((JsValue)obj);
  552. }
  553. public override int GetHashCode()
  554. {
  555. unchecked
  556. {
  557. var hashCode = 0;
  558. hashCode = (hashCode * 397) ^ _double.GetHashCode();
  559. hashCode = (hashCode * 397) ^ (_object != null ? _object.GetHashCode() : 0);
  560. hashCode = (hashCode * 397) ^ (int)_type;
  561. return hashCode;
  562. }
  563. }
  564. }
  565. }