GlobalObject.cs 21 KB

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