GlobalObject.cs 34 KB

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