GlobalObject.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. using System.Globalization;
  2. using System.Linq;
  3. using System.Runtime.CompilerServices;
  4. using System.Text;
  5. using Esprima;
  6. using Jint.Native.Object;
  7. using Jint.Native.String;
  8. using Jint.Runtime;
  9. using Jint.Runtime.Descriptors;
  10. namespace Jint.Native.Global
  11. {
  12. public sealed partial class GlobalObject : ObjectInstance
  13. {
  14. private readonly Realm _realm;
  15. private readonly StringBuilder _stringBuilder = new();
  16. internal GlobalObject(
  17. Engine engine,
  18. Realm realm) : base(engine, ObjectClass.Object, InternalTypes.Object | InternalTypes.PlainObject)
  19. {
  20. _realm = realm;
  21. }
  22. private JsValue ToStringString(JsValue thisObject, JsValue[] arguments)
  23. {
  24. return _realm.Intrinsics.Object.PrototypeObject.ToObjectString(thisObject, Arguments.Empty);
  25. }
  26. /// <summary>
  27. /// https://tc39.es/ecma262/#sec-parseint-string-radix
  28. /// </summary>
  29. public static JsValue ParseInt(JsValue thisObject, JsValue[] arguments)
  30. {
  31. var inputString = TypeConverter.ToString(arguments.At(0));
  32. var trimmed = StringPrototype.TrimEx(inputString);
  33. var s = trimmed.AsSpan();
  34. var radix = arguments.Length > 1 ? TypeConverter.ToInt32(arguments[1]) : 0;
  35. var hexStart = s.Length > 1 && trimmed.StartsWith("0x", StringComparison.OrdinalIgnoreCase);
  36. var stripPrefix = true;
  37. if (radix == 0)
  38. {
  39. radix = hexStart ? 16 : 10;
  40. }
  41. else if (radix < 2 || radix > 36)
  42. {
  43. return JsNumber.DoubleNaN;
  44. }
  45. else if (radix != 16)
  46. {
  47. stripPrefix = false;
  48. }
  49. // check fast case
  50. if (radix == 10 && int.TryParse(trimmed, out var number))
  51. {
  52. return JsNumber.Create(number);
  53. }
  54. var sign = 1;
  55. if (s.Length > 0)
  56. {
  57. var c = s[0];
  58. if (c == '-')
  59. {
  60. sign = -1;
  61. }
  62. if (c is '-' or '+')
  63. {
  64. s = s.Slice(1);
  65. }
  66. }
  67. if (stripPrefix && hexStart)
  68. {
  69. s = s.Slice(2);
  70. }
  71. if (s.Length == 0)
  72. {
  73. return double.NaN;
  74. }
  75. var hasResult = false;
  76. double result = 0;
  77. double pow = 1;
  78. for (var i = s.Length - 1; i >= 0; i--)
  79. {
  80. var digit = s[i];
  81. var index = digit switch
  82. {
  83. >= '0' and <= '9' => digit - '0',
  84. >= 'a' and <= 'z' => digit - 'a' + 10,
  85. >= 'A' and <= 'Z' => digit - 'A' + 10,
  86. _ => -1
  87. };
  88. if (index == -1 || index >= radix)
  89. {
  90. // reset
  91. hasResult = false;
  92. result = 0;
  93. pow = 1;
  94. continue;
  95. }
  96. hasResult = true;
  97. result += index * pow;
  98. pow *= radix;
  99. }
  100. return hasResult ? JsNumber.Create(sign * result) : JsNumber.DoubleNaN;
  101. }
  102. /// <summary>
  103. /// https://tc39.es/ecma262/#sec-parsefloat-string
  104. /// </summary>
  105. public static JsValue ParseFloat(JsValue thisObject, JsValue[] arguments)
  106. {
  107. var inputString = TypeConverter.ToString(arguments.At(0));
  108. var trimmedString = StringPrototype.TrimStartEx(inputString);
  109. if (string.IsNullOrWhiteSpace(trimmedString))
  110. {
  111. return JsNumber.DoubleNaN;
  112. }
  113. // start of string processing
  114. var i = 0;
  115. // check known string constants
  116. if (!char.IsDigit(trimmedString[0]))
  117. {
  118. if (trimmedString[0] == '-')
  119. {
  120. i++;
  121. if (trimmedString.Length > 1 && trimmedString[1] == 'I' && trimmedString.StartsWith("-Infinity"))
  122. {
  123. return JsNumber.DoubleNegativeInfinity;
  124. }
  125. }
  126. if (trimmedString[0] == '+')
  127. {
  128. i++;
  129. if (trimmedString.Length > 1 && trimmedString[1] == 'I' && trimmedString.StartsWith("+Infinity"))
  130. {
  131. return JsNumber.DoublePositiveInfinity;
  132. }
  133. }
  134. if (trimmedString.StartsWith("Infinity"))
  135. {
  136. return JsNumber.DoublePositiveInfinity;
  137. }
  138. if (trimmedString.StartsWith("NaN"))
  139. {
  140. return JsNumber.DoubleNaN;
  141. }
  142. }
  143. // find the starting part of string that is still acceptable JS number
  144. var dotFound = false;
  145. var exponentFound = false;
  146. while (i < trimmedString.Length)
  147. {
  148. var c = trimmedString[i];
  149. if (Character.IsDecimalDigit(c))
  150. {
  151. i++;
  152. continue;
  153. }
  154. if (c == '.')
  155. {
  156. if (dotFound)
  157. {
  158. // does not look right
  159. break;
  160. }
  161. i++;
  162. dotFound = true;
  163. continue;
  164. }
  165. if (c is 'e' or 'E')
  166. {
  167. if (exponentFound)
  168. {
  169. // does not look right
  170. break;
  171. }
  172. i++;
  173. exponentFound = true;
  174. continue;
  175. }
  176. if (c is '+' or '-' && trimmedString[i - 1] is 'e' or 'E')
  177. {
  178. // ok
  179. i++;
  180. continue;
  181. }
  182. break;
  183. }
  184. while (exponentFound && i > 0 && !Character.IsDecimalDigit(trimmedString[i - 1]))
  185. {
  186. // we are missing required exponent number part info
  187. i--;
  188. }
  189. // we should now have proper input part
  190. #if SUPPORTS_SPAN_PARSE
  191. var substring = trimmedString.AsSpan(0, i);
  192. #else
  193. var substring = trimmedString.Substring(0, i);
  194. #endif
  195. const NumberStyles Styles = NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent | NumberStyles.AllowLeadingSign;
  196. if (double.TryParse(substring, Styles, CultureInfo.InvariantCulture, out var d))
  197. {
  198. return d;
  199. }
  200. return JsNumber.DoubleNaN;
  201. }
  202. /// <summary>
  203. /// http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.2.4
  204. /// </summary>
  205. public static JsValue IsNaN(JsValue thisObject, JsValue[] arguments)
  206. {
  207. var value = arguments.At(0);
  208. if (ReferenceEquals(value, JsNumber.DoubleNaN))
  209. {
  210. return true;
  211. }
  212. var x = TypeConverter.ToNumber(value);
  213. return double.IsNaN(x);
  214. }
  215. /// <summary>
  216. /// http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.2.5
  217. /// </summary>
  218. public static JsValue IsFinite(JsValue thisObject, JsValue[] arguments)
  219. {
  220. if (arguments.Length != 1)
  221. {
  222. return false;
  223. }
  224. var n = TypeConverter.ToNumber(arguments.At(0));
  225. if (double.IsNaN(n) || double.IsInfinity(n))
  226. {
  227. return false;
  228. }
  229. return true;
  230. }
  231. private static readonly HashSet<char> UriReserved = new HashSet<char>
  232. {
  233. ';', '/', '?', ':', '@', '&', '=', '+', '$', ','
  234. };
  235. private static readonly HashSet<char> UriUnescaped = new HashSet<char>
  236. {
  237. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
  238. 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
  239. 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_', '.', '!',
  240. '~', '*', '\'', '(', ')'
  241. };
  242. private static readonly HashSet<char> UnescapedUriSet = new HashSet<char>(UriReserved.Concat(UriUnescaped).Concat(new[] { '#' }));
  243. private static readonly HashSet<char> ReservedUriSet = new HashSet<char>(UriReserved.Concat(new[] { '#' }));
  244. private const string HexaMap = "0123456789ABCDEF";
  245. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  246. private static bool IsValidHexaChar(char c) => Uri.IsHexDigit(c);
  247. /// <summary>
  248. /// http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3.2
  249. /// </summary>
  250. /// <param name="thisObject"></param>
  251. /// <param name="arguments"></param>
  252. /// <returns></returns>
  253. public JsValue EncodeUri(JsValue thisObject, JsValue[] arguments)
  254. {
  255. var uriString = TypeConverter.ToString(arguments.At(0));
  256. return Encode(uriString, UnescapedUriSet);
  257. }
  258. /// <summary>
  259. /// http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3.4
  260. /// </summary>
  261. /// <param name="thisObject"></param>
  262. /// <param name="arguments"></param>
  263. /// <returns></returns>
  264. public JsValue EncodeUriComponent(JsValue thisObject, JsValue[] arguments)
  265. {
  266. var uriString = TypeConverter.ToString(arguments.At(0));
  267. return Encode(uriString, UriUnescaped);
  268. }
  269. private string Encode(string uriString, HashSet<char> unescapedUriSet)
  270. {
  271. var strLen = uriString.Length;
  272. _stringBuilder.EnsureCapacity(uriString.Length);
  273. _stringBuilder.Clear();
  274. for (var k = 0; k < strLen; k++)
  275. {
  276. var c = uriString[k];
  277. if (unescapedUriSet != null && unescapedUriSet.Contains(c))
  278. {
  279. _stringBuilder.Append(c);
  280. }
  281. else
  282. {
  283. if (c >= 0xDC00 && c <= 0xDBFF)
  284. {
  285. ExceptionHelper.ThrowUriError(_realm);
  286. }
  287. int v;
  288. if (c < 0xD800 || c > 0xDBFF)
  289. {
  290. v = c;
  291. }
  292. else
  293. {
  294. k++;
  295. if (k == strLen)
  296. {
  297. ExceptionHelper.ThrowUriError(_realm);
  298. }
  299. var kChar = (int)uriString[k];
  300. if (kChar < 0xDC00 || kChar > 0xDFFF)
  301. {
  302. ExceptionHelper.ThrowUriError(_realm);
  303. }
  304. v = (c - 0xD800) * 0x400 + (kChar - 0xDC00) + 0x10000;
  305. }
  306. byte[] octets = System.Array.Empty<byte>();
  307. if (v >= 0 && v <= 0x007F)
  308. {
  309. // 00000000 0zzzzzzz -> 0zzzzzzz
  310. octets = new[] { (byte)v };
  311. }
  312. else if (v <= 0x07FF)
  313. {
  314. // 00000yyy yyzzzzzz -> 110yyyyy ; 10zzzzzz
  315. octets = new[]
  316. {
  317. (byte)(0xC0 | (v >> 6)),
  318. (byte)(0x80 | (v & 0x3F))
  319. };
  320. }
  321. else if (v <= 0xD7FF)
  322. {
  323. // xxxxyyyy yyzzzzzz -> 1110xxxx; 10yyyyyy; 10zzzzzz
  324. octets = new[]
  325. {
  326. (byte)(0xE0 | (v >> 12)),
  327. (byte)(0x80 | ((v >> 6) & 0x3F)),
  328. (byte)(0x80 | (v & 0x3F))
  329. };
  330. }
  331. else if (v <= 0xDFFF)
  332. {
  333. ExceptionHelper.ThrowUriError(_realm);
  334. }
  335. else if (v <= 0xFFFF)
  336. {
  337. octets = new[]
  338. {
  339. (byte) (0xE0 | (v >> 12)),
  340. (byte) (0x80 | ((v >> 6) & 0x3F)),
  341. (byte) (0x80 | (v & 0x3F))
  342. };
  343. }
  344. else
  345. {
  346. octets = new[]
  347. {
  348. (byte) (0xF0 | (v >> 18)),
  349. (byte) (0x80 | (v >> 12 & 0x3F)),
  350. (byte) (0x80 | (v >> 6 & 0x3F)),
  351. (byte) (0x80 | (v >> 0 & 0x3F))
  352. };
  353. }
  354. foreach (var octet in octets)
  355. {
  356. var x1 = HexaMap[octet / 16];
  357. var x2 = HexaMap[octet % 16];
  358. _stringBuilder.Append('%').Append(x1).Append(x2);
  359. }
  360. }
  361. }
  362. return _stringBuilder.ToString();
  363. }
  364. public JsValue DecodeUri(JsValue thisObject, JsValue[] arguments)
  365. {
  366. var uriString = TypeConverter.ToString(arguments.At(0));
  367. return Decode(uriString, ReservedUriSet);
  368. }
  369. public JsValue DecodeUriComponent(JsValue thisObject, JsValue[] arguments)
  370. {
  371. var componentString = TypeConverter.ToString(arguments.At(0));
  372. return Decode(componentString, null);
  373. }
  374. private string Decode(string uriString, HashSet<char>? reservedSet)
  375. {
  376. var strLen = uriString.Length;
  377. _stringBuilder.EnsureCapacity(strLen);
  378. _stringBuilder.Clear();
  379. var octets = System.Array.Empty<byte>();
  380. for (var k = 0; k < strLen; k++)
  381. {
  382. var C = uriString[k];
  383. if (C != '%')
  384. {
  385. _stringBuilder.Append(C);
  386. }
  387. else
  388. {
  389. var start = k;
  390. if (k + 2 >= strLen)
  391. {
  392. ExceptionHelper.ThrowUriError(_realm);
  393. }
  394. if (!IsValidHexaChar(uriString[k + 1]) || !IsValidHexaChar(uriString[k + 2]))
  395. {
  396. ExceptionHelper.ThrowUriError(_realm);
  397. }
  398. var B = Convert.ToByte(uriString[k + 1].ToString() + uriString[k + 2], 16);
  399. k += 2;
  400. if ((B & 0x80) == 0)
  401. {
  402. C = (char)B;
  403. if (reservedSet == null || !reservedSet.Contains(C))
  404. {
  405. _stringBuilder.Append(C);
  406. }
  407. else
  408. {
  409. _stringBuilder.Append(uriString, start, k - start + 1);
  410. }
  411. }
  412. else
  413. {
  414. var n = 0;
  415. for (; ((B << n) & 0x80) != 0; n++) ;
  416. if (n == 1 || n > 4)
  417. {
  418. ExceptionHelper.ThrowUriError(_realm);
  419. }
  420. octets = octets.Length == n
  421. ? octets
  422. : new byte[n];
  423. octets[0] = B;
  424. if (k + (3 * (n - 1)) >= strLen)
  425. {
  426. ExceptionHelper.ThrowUriError(_realm);
  427. }
  428. for (var j = 1; j < n; j++)
  429. {
  430. k++;
  431. if (uriString[k] != '%')
  432. {
  433. ExceptionHelper.ThrowUriError(_realm);
  434. }
  435. if (!IsValidHexaChar(uriString[k + 1]) || !IsValidHexaChar(uriString[k + 2]))
  436. {
  437. ExceptionHelper.ThrowUriError(_realm);
  438. }
  439. B = Convert.ToByte(uriString[k + 1].ToString() + uriString[k + 2], 16);
  440. // B & 11000000 != 10000000
  441. if ((B & 0xC0) != 0x80)
  442. {
  443. ExceptionHelper.ThrowUriError(_realm);
  444. }
  445. k += 2;
  446. octets[j] = B;
  447. }
  448. _stringBuilder.Append(Encoding.UTF8.GetString(octets, 0, octets.Length));
  449. }
  450. }
  451. }
  452. return _stringBuilder.ToString();
  453. }
  454. /// <summary>
  455. /// http://www.ecma-international.org/ecma-262/5.1/#sec-B.2.1
  456. /// </summary>
  457. public JsValue Escape(JsValue thisObject, JsValue[] arguments)
  458. {
  459. const string whiteList = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*_ + -./";
  460. var uriString = TypeConverter.ToString(arguments.At(0));
  461. var strLen = uriString.Length;
  462. _stringBuilder.EnsureCapacity(strLen);
  463. _stringBuilder.Clear();
  464. for (var k = 0; k < strLen; k++)
  465. {
  466. var c = uriString[k];
  467. if (whiteList.IndexOf(c) != -1)
  468. {
  469. _stringBuilder.Append(c);
  470. }
  471. else if (c < 256)
  472. {
  473. _stringBuilder.Append($"%{((int) c):X2}");
  474. }
  475. else
  476. {
  477. _stringBuilder.Append($"%u{((int) c):X4}");
  478. }
  479. }
  480. return _stringBuilder.ToString();
  481. }
  482. /// <summary>
  483. /// http://www.ecma-international.org/ecma-262/5.1/#sec-B.2.2
  484. /// </summary>
  485. public JsValue Unescape(JsValue thisObject, JsValue[] arguments)
  486. {
  487. var uriString = TypeConverter.ToString(arguments.At(0));
  488. var strLen = uriString.Length;
  489. _stringBuilder.EnsureCapacity(strLen);
  490. _stringBuilder.Clear();
  491. for (var k = 0; k < strLen; k++)
  492. {
  493. var c = uriString[k];
  494. if (c == '%')
  495. {
  496. if (k <= strLen - 6
  497. && uriString[k + 1] == 'u'
  498. && uriString.Skip(k + 2).Take(4).All(IsValidHexaChar))
  499. {
  500. c = (char)int.Parse(
  501. string.Join(string.Empty, uriString.Skip(k + 2).Take(4)),
  502. NumberStyles.AllowHexSpecifier);
  503. k += 5;
  504. }
  505. else if (k <= strLen - 3
  506. && uriString.Skip(k + 1).Take(2).All(IsValidHexaChar))
  507. {
  508. c = (char)int.Parse(
  509. string.Join(string.Empty, uriString.Skip(k + 1).Take(2)),
  510. NumberStyles.AllowHexSpecifier);
  511. k += 2;
  512. }
  513. }
  514. _stringBuilder.Append(c);
  515. }
  516. return _stringBuilder.ToString();
  517. }
  518. // optimized versions with string parameter and without virtual dispatch for global environment usage
  519. internal bool HasProperty(Key property)
  520. {
  521. return GetOwnProperty(property) != PropertyDescriptor.Undefined;
  522. }
  523. internal PropertyDescriptor GetProperty(Key property) => GetOwnProperty(property);
  524. internal bool DefinePropertyOrThrow(Key property, PropertyDescriptor desc)
  525. {
  526. if (!DefineOwnProperty(property, desc))
  527. {
  528. ExceptionHelper.ThrowTypeError(_realm);
  529. }
  530. return true;
  531. }
  532. internal bool DefineOwnProperty(Key property, PropertyDescriptor desc)
  533. {
  534. var current = GetOwnProperty(property);
  535. if (current == desc)
  536. {
  537. return true;
  538. }
  539. // check fast path
  540. if ((current._flags & PropertyFlag.MutableBinding) != 0)
  541. {
  542. current._value = desc.Value;
  543. return true;
  544. }
  545. return ValidateAndApplyPropertyDescriptor(this, new JsString(property), true, desc, current);
  546. }
  547. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  548. internal PropertyDescriptor GetOwnProperty(Key property)
  549. {
  550. Properties!.TryGetValue(property, out var descriptor);
  551. return descriptor ?? PropertyDescriptor.Undefined;
  552. }
  553. internal bool SetFromMutableBinding(Key property, JsValue value, bool strict)
  554. {
  555. // here we are called only from global environment record context
  556. // we can take some shortcuts to be faster
  557. if (!_properties!.TryGetValue(property, out var existingDescriptor))
  558. {
  559. if (strict)
  560. {
  561. ExceptionHelper.ThrowReferenceNameError(_realm, property.Name);
  562. }
  563. _properties[property] = new PropertyDescriptor(value, PropertyFlag.ConfigurableEnumerableWritable | PropertyFlag.MutableBinding);
  564. return true;
  565. }
  566. if (existingDescriptor.IsDataDescriptor())
  567. {
  568. if (!existingDescriptor.Writable || existingDescriptor.IsAccessorDescriptor())
  569. {
  570. return false;
  571. }
  572. // check fast path
  573. if ((existingDescriptor._flags & PropertyFlag.MutableBinding) != 0)
  574. {
  575. existingDescriptor._value = value;
  576. return true;
  577. }
  578. // slow path
  579. return DefineOwnProperty(property, new PropertyDescriptor(value, PropertyFlag.None));
  580. }
  581. if (existingDescriptor.Set is not ICallable setter)
  582. {
  583. return false;
  584. }
  585. setter.Call(this, new[] {value});
  586. return true;
  587. }
  588. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  589. internal void SetOwnProperty(Key property, PropertyDescriptor desc)
  590. {
  591. SetProperty(property, desc);
  592. }
  593. }
  594. }