JsValue.cs 24 KB

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