JsValue.cs 21 KB

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