TypeConverter.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Runtime.CompilerServices;
  7. using Esprima.Ast;
  8. using Jint.Native;
  9. using Jint.Native.Number;
  10. using Jint.Native.Object;
  11. using Jint.Native.String;
  12. using Jint.Runtime.References;
  13. using Jint.Native.Symbol;
  14. namespace Jint.Runtime
  15. {
  16. public enum Types
  17. {
  18. None,
  19. Undefined,
  20. Null,
  21. Boolean,
  22. String,
  23. Number,
  24. Object,
  25. Completion,
  26. Symbol
  27. }
  28. public class TypeConverter
  29. {
  30. // how many decimals to check when determining if double is actually an int
  31. private const double DoubleIsIntegerTolerance = double.Epsilon * 100;
  32. private static readonly string[] intToString = new string[1024];
  33. private static readonly string[] charToString = new string[256];
  34. static TypeConverter()
  35. {
  36. for (var i = 0; i < intToString.Length; ++i)
  37. {
  38. intToString[i] = i.ToString();
  39. }
  40. for (var i = 0; i < charToString.Length; ++i)
  41. {
  42. var c = (char) i;
  43. charToString[i] = c.ToString();
  44. }
  45. }
  46. /// <summary>
  47. /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.1
  48. /// </summary>
  49. /// <param name="input"></param>
  50. /// <param name="preferredType"></param>
  51. /// <returns></returns>
  52. public static JsValue ToPrimitive(JsValue input, Types preferredType = Types.None)
  53. {
  54. if (ReferenceEquals(input, Null.Instance) || ReferenceEquals(input, Undefined.Instance))
  55. {
  56. return input;
  57. }
  58. if (input.IsPrimitive())
  59. {
  60. return input;
  61. }
  62. return input.AsObject().DefaultValue(preferredType);
  63. }
  64. /// <summary>
  65. /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.2
  66. /// </summary>
  67. public static bool ToBoolean(JsValue o)
  68. {
  69. var type = o.Type;
  70. if (type == Types.Object)
  71. {
  72. return true;
  73. }
  74. if (type == Types.Boolean)
  75. {
  76. return ((JsBoolean) o)._value;
  77. }
  78. if (ReferenceEquals(o, Undefined.Instance) || ReferenceEquals(o, Null.Instance))
  79. {
  80. return false;
  81. }
  82. if (type == Types.Number)
  83. {
  84. var n = ((JsNumber) o)._value;
  85. if (n.Equals(0) || double.IsNaN(n))
  86. {
  87. return false;
  88. }
  89. return true;
  90. }
  91. if (type == Types.String)
  92. {
  93. return !((JsString) o).IsNullOrEmpty();
  94. }
  95. return true;
  96. }
  97. /// <summary>
  98. /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.3
  99. /// </summary>
  100. /// <param name="o"></param>
  101. /// <returns></returns>
  102. public static double ToNumber(JsValue o)
  103. {
  104. // check number first as this is what is usually expected
  105. var type = o.Type;
  106. if (type == Types.Number)
  107. {
  108. return ((JsNumber) o)._value;
  109. }
  110. if (type == Types.Object)
  111. {
  112. if (o is IPrimitiveInstance p)
  113. {
  114. o = p.PrimitiveValue;
  115. }
  116. }
  117. if (ReferenceEquals(o, Undefined.Instance))
  118. {
  119. return double.NaN;
  120. }
  121. if (ReferenceEquals(o, Null.Instance))
  122. {
  123. return 0;
  124. }
  125. if (type == Types.Boolean)
  126. {
  127. return ((JsBoolean) o)._value ? 1 : 0;
  128. }
  129. if (type == Types.String)
  130. {
  131. return ToNumber(o.AsString());
  132. }
  133. return ToNumber(ToPrimitive(o, Types.Number));
  134. }
  135. private static double ToNumber(string input)
  136. {
  137. // eager checks to save time and trimming
  138. if (string.IsNullOrEmpty(input))
  139. {
  140. return 0;
  141. }
  142. var s = StringPrototype.IsWhiteSpaceEx(input[0]) || StringPrototype.IsWhiteSpaceEx(input[input.Length - 1])
  143. ? StringPrototype.TrimEx(input)
  144. : input;
  145. if (string.IsNullOrEmpty(s))
  146. {
  147. return 0;
  148. }
  149. if ("+Infinity".Equals(s) || "Infinity".Equals(s))
  150. {
  151. return double.PositiveInfinity;
  152. }
  153. if ("-Infinity".Equals(s))
  154. {
  155. return double.NegativeInfinity;
  156. }
  157. // todo: use a common implementation with JavascriptParser
  158. try
  159. {
  160. if (!s.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
  161. {
  162. var start = s[0];
  163. if (start != '+' && start != '-' && start != '.' && !char.IsDigit(start))
  164. {
  165. return double.NaN;
  166. }
  167. double n = Double.Parse(s,
  168. NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign |
  169. NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite |
  170. NumberStyles.AllowExponent, CultureInfo.InvariantCulture);
  171. if (s.StartsWith("-") && n.Equals(0))
  172. {
  173. return -0.0;
  174. }
  175. return n;
  176. }
  177. int i = int.Parse(s.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
  178. return i;
  179. }
  180. catch (OverflowException)
  181. {
  182. return s.StartsWith("-") ? double.NegativeInfinity : double.PositiveInfinity;
  183. }
  184. catch
  185. {
  186. return double.NaN;
  187. }
  188. }
  189. /// <summary>
  190. /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.4
  191. /// </summary>
  192. /// <param name="o"></param>
  193. /// <returns></returns>
  194. public static double ToInteger(JsValue o)
  195. {
  196. var number = ToNumber(o);
  197. if (double.IsNaN(number))
  198. {
  199. return 0;
  200. }
  201. if (number.Equals(0) || double.IsInfinity(number))
  202. {
  203. return number;
  204. }
  205. return (long) number;
  206. }
  207. internal static double ToInteger(string o)
  208. {
  209. var number = ToNumber(o);
  210. if (double.IsNaN(number))
  211. {
  212. return 0;
  213. }
  214. if (number.Equals(0) || double.IsInfinity(number))
  215. {
  216. return number;
  217. }
  218. return (long) number;
  219. }
  220. /// <summary>
  221. /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.5
  222. /// </summary>
  223. /// <param name="o"></param>
  224. /// <returns></returns>
  225. public static int ToInt32(JsValue o)
  226. {
  227. return (int) (uint) ToNumber(o);
  228. }
  229. /// <summary>
  230. /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.6
  231. /// </summary>
  232. /// <param name="o"></param>
  233. /// <returns></returns>
  234. public static uint ToUint32(JsValue o)
  235. {
  236. return (uint) ToNumber(o);
  237. }
  238. /// <summary>
  239. /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.7
  240. /// </summary>
  241. /// <param name="o"></param>
  242. /// <returns></returns>
  243. public static ushort ToUint16(JsValue o)
  244. {
  245. return (ushort) (uint) ToNumber(o);
  246. }
  247. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  248. internal static string ToString(long i)
  249. {
  250. return i >= 0 && i < intToString.Length
  251. ? intToString[i]
  252. : i.ToString();
  253. }
  254. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  255. internal static string ToString(int i)
  256. {
  257. return i >= 0 && i < intToString.Length
  258. ? intToString[i]
  259. : i.ToString();
  260. }
  261. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  262. internal static string ToString(uint i)
  263. {
  264. return i >= 0 && i < intToString.Length
  265. ? intToString[i]
  266. : i.ToString();
  267. }
  268. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  269. internal static string ToString(char c)
  270. {
  271. return c >= 0 && c < charToString.Length
  272. ? charToString[c]
  273. : c.ToString();
  274. }
  275. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  276. internal static string ToString(double d)
  277. {
  278. if (d > long.MinValue && d < long.MaxValue && Math.Abs(d % 1) <= DoubleIsIntegerTolerance)
  279. {
  280. // we are dealing with integer that can be cached
  281. return ToString((long) d);
  282. }
  283. return NumberPrototype.ToNumberString(d);
  284. }
  285. /// <summary>
  286. /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.8
  287. /// </summary>
  288. /// <param name="o"></param>
  289. /// <returns></returns>
  290. public static string ToString(JsValue o)
  291. {
  292. if (o.IsString())
  293. {
  294. return o.AsString();
  295. }
  296. if (o.IsObject())
  297. {
  298. var p = o.AsObject() as IPrimitiveInstance;
  299. if (p != null)
  300. {
  301. o = p.PrimitiveValue;
  302. }
  303. else
  304. {
  305. var s = o.AsInstance<SymbolInstance>();
  306. if (!ReferenceEquals(s, null))
  307. {
  308. // TODO: throw a TypeError
  309. // NB: But it requires an Engine reference
  310. throw new JavaScriptException(new JsString("TypeError"));
  311. }
  312. }
  313. }
  314. if (ReferenceEquals(o, Undefined.Instance))
  315. {
  316. return Undefined.Text;
  317. }
  318. if (ReferenceEquals(o, Null.Instance))
  319. {
  320. return Null.Text;
  321. }
  322. if (o.IsBoolean())
  323. {
  324. return o.AsBoolean() ? "true" : "false";
  325. }
  326. if (o.IsNumber())
  327. {
  328. return ToString(o.AsNumber());
  329. }
  330. if (o.IsSymbol())
  331. {
  332. return o.AsSymbol();
  333. }
  334. return ToString(ToPrimitive(o, Types.String));
  335. }
  336. public static ObjectInstance ToObject(Engine engine, JsValue value)
  337. {
  338. if (value.IsObject())
  339. {
  340. return value.AsObject();
  341. }
  342. if (ReferenceEquals(value, Undefined.Instance))
  343. {
  344. throw new JavaScriptException(engine.TypeError);
  345. }
  346. if (ReferenceEquals(value, Null.Instance))
  347. {
  348. throw new JavaScriptException(engine.TypeError);
  349. }
  350. if (value.IsBoolean())
  351. {
  352. return engine.Boolean.Construct(value.AsBoolean());
  353. }
  354. if (value.IsNumber())
  355. {
  356. return engine.Number.Construct(value.AsNumber());
  357. }
  358. if (value.IsString())
  359. {
  360. return engine.String.Construct(value.AsString());
  361. }
  362. if (value.IsSymbol())
  363. {
  364. return engine.Symbol.Construct(value.AsSymbol());
  365. }
  366. throw new JavaScriptException(engine.TypeError);
  367. }
  368. public static Types GetPrimitiveType(JsValue value)
  369. {
  370. if (value.IsObject())
  371. {
  372. var primitive = value.TryCast<IPrimitiveInstance>();
  373. if (primitive != null)
  374. {
  375. return primitive.Type;
  376. }
  377. return Types.Object;
  378. }
  379. return value.Type;
  380. }
  381. public static void CheckObjectCoercible(
  382. Engine engine,
  383. JsValue o,
  384. MemberExpression expression,
  385. object baseReference)
  386. {
  387. if (!ReferenceEquals(o, Undefined.Instance) && !ReferenceEquals(o, Null.Instance))
  388. {
  389. return;
  390. }
  391. var referenceResolver = engine.Options.ReferenceResolver;
  392. if (referenceResolver != null && referenceResolver.CheckCoercible(o))
  393. {
  394. return;
  395. }
  396. string referencedName;
  397. if (baseReference is Reference reference)
  398. {
  399. referencedName = reference.GetReferencedName();
  400. }
  401. else
  402. {
  403. referencedName = "The value";
  404. }
  405. var message = $"{referencedName} is {o}";
  406. throw new JavaScriptException(engine.TypeError, message)
  407. .SetCallstack(engine, expression.Location);
  408. }
  409. public static void CheckObjectCoercible(Engine engine, JsValue o)
  410. {
  411. if (ReferenceEquals(o, Undefined.Instance) || ReferenceEquals(o, Null.Instance))
  412. {
  413. throw new JavaScriptException(engine.TypeError);
  414. }
  415. }
  416. public static IEnumerable<MethodBase> FindBestMatch(Engine engine, MethodBase[] methods, JsValue[] arguments)
  417. {
  418. methods = methods
  419. .Where(m => m.GetParameters().Length == arguments.Length)
  420. .ToArray();
  421. if (methods.Length == 1 && !methods[0].GetParameters().Any())
  422. {
  423. yield return methods[0];
  424. yield break;
  425. }
  426. var objectArguments = arguments.Select(x => x.ToObject()).ToArray();
  427. foreach (var method in methods)
  428. {
  429. var perfectMatch = true;
  430. var parameters = method.GetParameters();
  431. for (var i = 0; i < arguments.Length; i++)
  432. {
  433. var arg = objectArguments[i];
  434. var paramType = parameters[i].ParameterType;
  435. if (arg == null)
  436. {
  437. if (!TypeIsNullable(paramType))
  438. {
  439. perfectMatch = false;
  440. break;
  441. }
  442. }
  443. else if (arg.GetType() != paramType)
  444. {
  445. perfectMatch = false;
  446. break;
  447. }
  448. }
  449. if (perfectMatch)
  450. {
  451. yield return method;
  452. yield break;
  453. }
  454. }
  455. foreach (var method in methods)
  456. {
  457. yield return method;
  458. }
  459. }
  460. public static bool TypeIsNullable(Type type)
  461. {
  462. return !type.IsValueType() || Nullable.GetUnderlyingType(type) != null;
  463. }
  464. }
  465. }