GlobalObject.cs 33 KB

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