TypeConverter.cs 15 KB

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