JsValue.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  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.CompilerServices;
  18. using System.Runtime.InteropServices;
  19. namespace Jint.Native
  20. {
  21. [StructLayout(LayoutKind.Explicit)]
  22. [DebuggerTypeProxy(typeof(JsValueDebugView))]
  23. public struct JsValue : IEquatable<JsValue>
  24. {
  25. public static JsValue Undefined = new JsValue(Types.Undefined);
  26. public static JsValue Null = new JsValue(Types.Null);
  27. public static JsValue False = new JsValue(false);
  28. public static JsValue True = new JsValue(true);
  29. public JsValue(bool value)
  30. {
  31. _double = double.NaN;
  32. _object = null;
  33. _string = null;
  34. _type = Types.Boolean;
  35. _bool = value; //Set value last because of 'FieldOffset' constraints
  36. }
  37. public JsValue(double value)
  38. {
  39. _bool = false;
  40. _object = null;
  41. _string = null;
  42. _type = Types.Number;
  43. _double = value;
  44. }
  45. public JsValue(string value)
  46. {
  47. _bool = false;
  48. _double = double.NaN;
  49. _object = null;
  50. _type = Types.String;
  51. _string = value;
  52. }
  53. public JsValue(ObjectInstance value)
  54. {
  55. _bool = false;
  56. _double = double.NaN;
  57. _string = null;
  58. _type = Types.Object;
  59. _object = value;
  60. }
  61. private JsValue(Types type)
  62. {
  63. _bool = false;
  64. _double = double.NaN;
  65. _object = null;
  66. _string = null;
  67. _type = type;
  68. }
  69. [FieldOffset(0)]
  70. private readonly bool _bool;
  71. [FieldOffset(0)]
  72. private readonly double _double;
  73. [FieldOffset(0)]
  74. private readonly ObjectInstance _object;
  75. [FieldOffset(0)]
  76. private readonly string _string;
  77. [FieldOffset(8)]
  78. private readonly Types _type;
  79. [Pure]
  80. public bool IsPrimitive()
  81. {
  82. return _type != Types.Object && _type != Types.None;
  83. }
  84. [Pure]
  85. public bool IsUndefined()
  86. {
  87. return _type == Types.Undefined;
  88. }
  89. [Pure]
  90. public bool IsArray()
  91. {
  92. return IsObject() && AsObject() is ArrayInstance;
  93. }
  94. [Pure]
  95. public bool IsRegExp()
  96. {
  97. return IsObject() && AsObject() is RegExpInstance;
  98. }
  99. [Pure]
  100. public bool IsObject()
  101. {
  102. return _type == Types.Object;
  103. }
  104. [Pure]
  105. public bool IsString()
  106. {
  107. return _type == Types.String;
  108. }
  109. [Pure]
  110. public bool IsNumber()
  111. {
  112. return _type == Types.Number;
  113. }
  114. [Pure]
  115. public bool IsBoolean()
  116. {
  117. return _type == Types.Boolean;
  118. }
  119. [Pure]
  120. public bool IsNull()
  121. {
  122. return _type == Types.Null;
  123. }
  124. [Pure]
  125. public ObjectInstance AsObject()
  126. {
  127. if (_type != Types.Object)
  128. {
  129. throw new ArgumentException("The value is not an object");
  130. }
  131. return _object;
  132. }
  133. [Pure]
  134. public ArrayInstance AsArray()
  135. {
  136. if (!IsArray())
  137. {
  138. throw new ArgumentException("The value is not an array");
  139. }
  140. return AsObject() as ArrayInstance;
  141. }
  142. [Pure]
  143. public T TryCast<T>(Action<JsValue> fail = null) where T: class
  144. {
  145. if (IsObject())
  146. {
  147. var o = AsObject();
  148. var t = o as T;
  149. if (t != null)
  150. {
  151. return t;
  152. }
  153. }
  154. if (fail != null)
  155. {
  156. fail(this);
  157. }
  158. return null;
  159. }
  160. public bool Is<T>()
  161. {
  162. return IsObject() && AsObject() is T;
  163. }
  164. public T As<T>() where T : ObjectInstance
  165. {
  166. return _object as T;
  167. }
  168. [Pure]
  169. public bool AsBoolean()
  170. {
  171. if (_type != Types.Boolean)
  172. {
  173. throw new ArgumentException("The value is not a boolean");
  174. }
  175. return _bool;
  176. }
  177. [Pure]
  178. public string AsString()
  179. {
  180. if (_type != Types.String)
  181. {
  182. throw new ArgumentException("The value is not a string");
  183. }
  184. if (_string == null)
  185. {
  186. throw new ArgumentException("The value is not defined");
  187. }
  188. return _string;
  189. }
  190. [Pure]
  191. public double AsNumber()
  192. {
  193. if (_type != Types.Number)
  194. {
  195. throw new ArgumentException("The value is not a number");
  196. }
  197. return _double;
  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 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.Boolean:
  346. return _bool;
  347. case Types.String:
  348. return _string;
  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.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.Properties)
  431. {
  432. if (!p.Value.Enumerable.HasValue || p.Value.Enumerable.Value == false)
  433. {
  434. continue;
  435. }
  436. o.Add(p.Key, _object.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 _bool.ToString();
  481. case Types.String:
  482. return _string;
  483. case Types.Number:
  484. return _double.ToString();
  485. case Types.Object:
  486. return _object.ToString();
  487. default:
  488. return string.Empty;
  489. }
  490. }
  491. public static bool operator ==(JsValue a, JsValue b)
  492. {
  493. return a.Equals(b);
  494. }
  495. public static bool operator !=(JsValue a, JsValue b)
  496. {
  497. return !a.Equals(b);
  498. }
  499. static public implicit operator JsValue(double value)
  500. {
  501. return new JsValue(value);
  502. }
  503. static public implicit operator JsValue(bool value)
  504. {
  505. return new JsValue(value);
  506. }
  507. static public implicit operator JsValue(string value)
  508. {
  509. return new JsValue(value);
  510. }
  511. static public implicit operator JsValue(ObjectInstance value)
  512. {
  513. return new JsValue(value);
  514. }
  515. internal class JsValueDebugView
  516. {
  517. public string Value;
  518. public JsValueDebugView(JsValue value)
  519. {
  520. switch (value.Type)
  521. {
  522. case Types.None:
  523. Value = "None";
  524. break;
  525. case Types.Undefined:
  526. Value = "undefined";
  527. break;
  528. case Types.Null:
  529. Value = "null";
  530. break;
  531. case Types.Boolean:
  532. Value = value.AsBoolean() + " (bool)";
  533. break;
  534. case Types.String:
  535. Value = value.AsString() + " (string)";
  536. break;
  537. case Types.Number:
  538. Value = value.AsNumber() + " (number)";
  539. break;
  540. case Types.Object:
  541. Value = value.AsObject().GetType().Name;
  542. break;
  543. default:
  544. Value = "Unknown";
  545. break;
  546. }
  547. }
  548. }
  549. public override bool Equals(object obj)
  550. {
  551. if (ReferenceEquals(null, obj)) return false;
  552. return obj is JsValue && Equals((JsValue)obj);
  553. }
  554. public override int GetHashCode()
  555. {
  556. unchecked
  557. {
  558. var hashCode = _bool.GetHashCode();
  559. hashCode = (hashCode * 397) ^ _double.GetHashCode();
  560. hashCode = (hashCode * 397) ^ (_object != null ? _object.GetHashCode() : 0);
  561. hashCode = (hashCode * 397) ^ (_string != null ? _string.GetHashCode() : 0);
  562. hashCode = (hashCode * 397) ^ (int)_type;
  563. return hashCode;
  564. }
  565. }
  566. }
  567. }