2
0

GlobalObject.cs 33 KB

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