2
0

JsValue.cs 20 KB

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