JsValue.cs 19 KB

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