JsValue.cs 20 KB

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