StringPrototype.cs 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255
  1. #pragma warning disable CA1859 // Use concrete types when possible for improved performance -- most of prototype methods return JsValue
  2. using System.Globalization;
  3. using System.Runtime.CompilerServices;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. using Jint.Collections;
  7. using Jint.Native.Json;
  8. using Jint.Native.Object;
  9. using Jint.Native.RegExp;
  10. using Jint.Native.Symbol;
  11. using Jint.Runtime;
  12. using Jint.Runtime.Descriptors;
  13. using Jint.Runtime.Descriptors.Specialized;
  14. using Jint.Runtime.Interop;
  15. namespace Jint.Native.String;
  16. /// <summary>
  17. /// https://tc39.es/ecma262/#sec-properties-of-the-string-prototype-object
  18. /// </summary>
  19. internal sealed class StringPrototype : StringInstance
  20. {
  21. private readonly Realm _realm;
  22. private readonly StringConstructor _constructor;
  23. internal ClrFunction? _originalIteratorFunction;
  24. internal StringPrototype(
  25. Engine engine,
  26. Realm realm,
  27. StringConstructor constructor,
  28. ObjectPrototype objectPrototype)
  29. : base(engine, JsString.Empty)
  30. {
  31. _prototype = objectPrototype;
  32. _length = PropertyDescriptor.AllForbiddenDescriptor.NumberZero;
  33. _realm = realm;
  34. _constructor = constructor;
  35. }
  36. protected override void Initialize()
  37. {
  38. const PropertyFlag lengthFlags = PropertyFlag.Configurable;
  39. const PropertyFlag propertyFlags = lengthFlags | PropertyFlag.Writable;
  40. var trimStart = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "trimStart", prototype.TrimStart, 0, lengthFlags), propertyFlags);
  41. var trimEnd = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "trimEnd", prototype.TrimEnd, 0, lengthFlags), propertyFlags);
  42. var properties = new PropertyDictionary(37, checkExistingKeys: false)
  43. {
  44. ["constructor"] = new PropertyDescriptor(_constructor, PropertyFlag.NonEnumerable),
  45. ["toString"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "toString", prototype.ToStringString, 0, lengthFlags), propertyFlags),
  46. ["valueOf"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "valueOf", prototype.ValueOf, 0, lengthFlags), propertyFlags),
  47. ["charAt"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "charAt", prototype.CharAt, 1, lengthFlags), propertyFlags),
  48. ["charCodeAt"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "charCodeAt", prototype.CharCodeAt, 1, lengthFlags), propertyFlags),
  49. ["codePointAt"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "codePointAt", prototype.CodePointAt, 1, lengthFlags), propertyFlags),
  50. ["concat"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "concat", prototype.Concat, 1, lengthFlags), propertyFlags),
  51. ["indexOf"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "indexOf", prototype.IndexOf, 1, lengthFlags), propertyFlags),
  52. ["endsWith"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "endsWith", prototype.EndsWith, 1, lengthFlags), propertyFlags),
  53. ["startsWith"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "startsWith", prototype.StartsWith, 1, lengthFlags), propertyFlags),
  54. ["lastIndexOf"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "lastIndexOf", prototype.LastIndexOf, 1, lengthFlags), propertyFlags),
  55. ["localeCompare"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "localeCompare", prototype.LocaleCompare, 1, lengthFlags), propertyFlags),
  56. ["match"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "match", prototype.Match, 1, lengthFlags), propertyFlags),
  57. ["matchAll"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "matchAll", prototype.MatchAll, 1, lengthFlags), propertyFlags),
  58. ["replace"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "replace", prototype.Replace, 2, lengthFlags), propertyFlags),
  59. ["replaceAll"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "replaceAll", prototype.ReplaceAll, 2, lengthFlags), propertyFlags),
  60. ["search"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "search", prototype.Search, 1, lengthFlags), propertyFlags),
  61. ["slice"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "slice", prototype.Slice, 2, lengthFlags), propertyFlags),
  62. ["split"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "split", prototype.Split, 2, lengthFlags), propertyFlags),
  63. ["substr"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "substr", Substr, 2), propertyFlags),
  64. ["substring"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "substring", prototype.Substring, 2, lengthFlags), propertyFlags),
  65. ["toLowerCase"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "toLowerCase", prototype.ToLowerCase, 0, lengthFlags), propertyFlags),
  66. ["toLocaleLowerCase"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "toLocaleLowerCase", prototype.ToLocaleLowerCase, 0, lengthFlags), propertyFlags),
  67. ["toUpperCase"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "toUpperCase", prototype.ToUpperCase, 0, lengthFlags), propertyFlags),
  68. ["toLocaleUpperCase"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "toLocaleUpperCase", prototype.ToLocaleUpperCase, 0, lengthFlags), propertyFlags),
  69. ["trim"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "trim", prototype.Trim, 0, lengthFlags), propertyFlags),
  70. ["trimStart"] = trimStart,
  71. ["trimEnd"] = trimEnd,
  72. ["trimLeft"] = trimStart,
  73. ["trimRight"] = trimEnd,
  74. ["padStart"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "padStart", prototype.PadStart, 1, lengthFlags), propertyFlags),
  75. ["padEnd"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "padEnd", prototype.PadEnd, 1, lengthFlags), propertyFlags),
  76. ["includes"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "includes", prototype.Includes, 1, lengthFlags), propertyFlags),
  77. ["normalize"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "normalize", prototype.Normalize, 0, lengthFlags), propertyFlags),
  78. ["repeat"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "repeat", prototype.Repeat, 1, lengthFlags), propertyFlags),
  79. ["at"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "at", prototype.At, 1, lengthFlags), propertyFlags),
  80. ["isWellFormed"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "isWellFormed", prototype.IsWellFormed, 0, lengthFlags), propertyFlags),
  81. ["toWellFormed"] = new LazyPropertyDescriptor<StringPrototype>(this, static prototype => new ClrFunction(prototype._engine, "toWellFormed", prototype.ToWellFormed, 0, lengthFlags), propertyFlags),
  82. };
  83. SetProperties(properties);
  84. _originalIteratorFunction = new ClrFunction(_engine, "[Symbol.iterator]", Iterator, 0, lengthFlags);
  85. var symbols = new SymbolDictionary(1)
  86. {
  87. [GlobalSymbolRegistry.Iterator] = new PropertyDescriptor(_originalIteratorFunction, propertyFlags)
  88. };
  89. SetSymbols(symbols);
  90. }
  91. internal override bool HasOriginalIterator => ReferenceEquals(Get(GlobalSymbolRegistry.Iterator), _originalIteratorFunction);
  92. private ObjectInstance Iterator(JsValue thisObject, JsValue[] arguments)
  93. {
  94. TypeConverter.CheckObjectCoercible(_engine, thisObject);
  95. var str = TypeConverter.ToString(thisObject);
  96. return _realm.Intrinsics.StringIteratorPrototype.Construct(str);
  97. }
  98. private JsValue ToStringString(JsValue thisObject, JsValue[] arguments)
  99. {
  100. if (thisObject.IsString())
  101. {
  102. return thisObject;
  103. }
  104. var s = TypeConverter.ToObject(_realm, thisObject) as StringInstance;
  105. if (s is null)
  106. {
  107. ExceptionHelper.ThrowTypeError(_realm);
  108. }
  109. return s.StringData;
  110. }
  111. // http://msdn.microsoft.com/en-us/library/system.char.iswhitespace(v=vs.110).aspx
  112. // http://en.wikipedia.org/wiki/Byte_order_mark
  113. const char BOM_CHAR = '\uFEFF';
  114. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  115. private static bool IsWhiteSpaceEx(char c)
  116. {
  117. return char.IsWhiteSpace(c) || c == BOM_CHAR;
  118. }
  119. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  120. private static string TrimEndEx(string s)
  121. {
  122. if (s.Length == 0)
  123. return string.Empty;
  124. if (!IsWhiteSpaceEx(s[s.Length - 1]))
  125. return s;
  126. return TrimEnd(s);
  127. }
  128. private static string TrimEnd(string s)
  129. {
  130. var i = s.Length - 1;
  131. while (i >= 0)
  132. {
  133. if (IsWhiteSpaceEx(s[i]))
  134. i--;
  135. else
  136. break;
  137. }
  138. return i >= 0 ? s.Substring(0, i + 1) : string.Empty;
  139. }
  140. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  141. internal static string TrimStartEx(string s)
  142. {
  143. if (s.Length == 0)
  144. return string.Empty;
  145. if (!IsWhiteSpaceEx(s[0]))
  146. return s;
  147. return TrimStart(s);
  148. }
  149. private static string TrimStart(string s)
  150. {
  151. var i = 0;
  152. while (i < s.Length)
  153. {
  154. if (IsWhiteSpaceEx(s[i]))
  155. i++;
  156. else
  157. break;
  158. }
  159. return i >= s.Length ? string.Empty : s.Substring(i);
  160. }
  161. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  162. internal static string TrimEx(string s)
  163. {
  164. return TrimEndEx(TrimStartEx(s));
  165. }
  166. /// <summary>
  167. /// https://tc39.es/ecma262/#sec-string.prototype.trim
  168. /// </summary>
  169. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  170. private JsValue Trim(JsValue thisObject, JsValue[] arguments)
  171. {
  172. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  173. var s = TypeConverter.ToJsString(thisObject);
  174. if (s.Length == 0 || (!IsWhiteSpaceEx(s[0]) && !IsWhiteSpaceEx(s[s.Length - 1])))
  175. {
  176. return s;
  177. }
  178. return TrimEx(s.ToString());
  179. }
  180. /// <summary>
  181. /// https://tc39.es/ecma262/#sec-string.prototype.trimstart
  182. /// </summary>
  183. private JsValue TrimStart(JsValue thisObject, JsValue[] arguments)
  184. {
  185. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  186. var s = TypeConverter.ToJsString(thisObject);
  187. if (s.Length == 0 || !IsWhiteSpaceEx(s[0]))
  188. {
  189. return s;
  190. }
  191. return TrimStartEx(s.ToString());
  192. }
  193. /// <summary>
  194. /// https://tc39.es/ecma262/#sec-string.prototype.trimend
  195. /// </summary>
  196. private JsValue TrimEnd(JsValue thisObject, JsValue[] arguments)
  197. {
  198. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  199. var s = TypeConverter.ToJsString(thisObject);
  200. if (s.Length == 0 || !IsWhiteSpaceEx(s[s.Length - 1]))
  201. {
  202. return s;
  203. }
  204. return TrimEndEx(s.ToString());
  205. }
  206. private JsValue ToLocaleUpperCase(JsValue thisObject, JsValue[] arguments)
  207. {
  208. TypeConverter.CheckObjectCoercible(_engine, thisObject);
  209. var s = TypeConverter.ToString(thisObject);
  210. var culture = CultureInfo.InvariantCulture;
  211. if (arguments.Length > 0 && arguments[0].IsString())
  212. {
  213. try
  214. {
  215. var cultureArgument = arguments[0].ToString();
  216. culture = CultureInfo.GetCultureInfo(cultureArgument);
  217. }
  218. catch (CultureNotFoundException)
  219. {
  220. ExceptionHelper.ThrowRangeError(_realm, "Incorrect culture information provided");
  221. }
  222. }
  223. if (string.Equals("lt", culture.Name, StringComparison.OrdinalIgnoreCase))
  224. {
  225. s = StringInlHelper.LithuanianStringProcessor(s);
  226. #if NET462
  227. // Code specific to .NET Framework 4.6.2.
  228. // For no good reason this verison does not upper case these characters correctly.
  229. return new JsString(s.ToUpper(culture)
  230. .Replace("ϳ", "Ϳ")
  231. .Replace("ʝ", "Ʝ"));
  232. #endif
  233. }
  234. return new JsString(s.ToUpper(culture));
  235. }
  236. private JsValue ToUpperCase(JsValue thisObject, JsValue[] arguments)
  237. {
  238. TypeConverter.CheckObjectCoercible(_engine, thisObject);
  239. var s = TypeConverter.ToString(thisObject);
  240. return new JsString(s.ToUpperInvariant());
  241. }
  242. private JsValue ToLocaleLowerCase(JsValue thisObject, JsValue[] arguments)
  243. {
  244. TypeConverter.CheckObjectCoercible(_engine, thisObject);
  245. var s = TypeConverter.ToString(thisObject);
  246. return new JsString(s.ToLower(CultureInfo.InvariantCulture));
  247. }
  248. private JsValue ToLowerCase(JsValue thisObject, JsValue[] arguments)
  249. {
  250. TypeConverter.CheckObjectCoercible(_engine, thisObject);
  251. var s = TypeConverter.ToString(thisObject);
  252. return s.ToLowerInvariant();
  253. }
  254. private static int ToIntegerSupportInfinity(JsValue numberVal)
  255. {
  256. return numberVal._type == InternalTypes.Integer
  257. ? numberVal.AsInteger()
  258. : ToIntegerSupportInfinityUnlikely(numberVal);
  259. }
  260. [MethodImpl(MethodImplOptions.NoInlining)]
  261. private static int ToIntegerSupportInfinityUnlikely(JsValue numberVal)
  262. {
  263. var doubleVal = TypeConverter.ToInteger(numberVal);
  264. int intVal;
  265. if (double.IsPositiveInfinity(doubleVal))
  266. intVal = int.MaxValue;
  267. else if (double.IsNegativeInfinity(doubleVal))
  268. intVal = int.MinValue;
  269. else
  270. intVal = (int) doubleVal;
  271. return intVal;
  272. }
  273. private JsValue Substring(JsValue thisObject, JsValue[] arguments)
  274. {
  275. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  276. var s = TypeConverter.ToString(thisObject);
  277. var start = TypeConverter.ToNumber(arguments.At(0));
  278. var end = TypeConverter.ToNumber(arguments.At(1));
  279. if (double.IsNaN(start) || start < 0)
  280. {
  281. start = 0;
  282. }
  283. if (double.IsNaN(end) || end < 0)
  284. {
  285. end = 0;
  286. }
  287. var len = s.Length;
  288. var intStart = ToIntegerSupportInfinity(start);
  289. var intEnd = arguments.At(1).IsUndefined() ? len : ToIntegerSupportInfinity(end);
  290. var finalStart = System.Math.Min(len, System.Math.Max(intStart, 0));
  291. var finalEnd = System.Math.Min(len, System.Math.Max(intEnd, 0));
  292. // Swap value if finalStart < finalEnd
  293. var from = System.Math.Min(finalStart, finalEnd);
  294. var to = System.Math.Max(finalStart, finalEnd);
  295. var length = to - from;
  296. if (length == 0)
  297. {
  298. return JsString.Empty;
  299. }
  300. if (length == 1)
  301. {
  302. return JsString.Create(s[from]);
  303. }
  304. return new JsString(s.Substring(from, length));
  305. }
  306. private static JsValue Substr(JsValue thisObject, JsValue[] arguments)
  307. {
  308. var s = TypeConverter.ToString(thisObject);
  309. var start = TypeConverter.ToInteger(arguments.At(0));
  310. var length = arguments.At(1).IsUndefined()
  311. ? double.PositiveInfinity
  312. : TypeConverter.ToInteger(arguments.At(1));
  313. start = start >= 0 ? start : System.Math.Max(s.Length + start, 0);
  314. length = System.Math.Min(System.Math.Max(length, 0), s.Length - start);
  315. if (length <= 0)
  316. {
  317. return JsString.Empty;
  318. }
  319. var startIndex = TypeConverter.ToInt32(start);
  320. var l = TypeConverter.ToInt32(length);
  321. if (l == 1)
  322. {
  323. return TypeConverter.ToString(s[startIndex]);
  324. }
  325. return s.Substring(startIndex, l);
  326. }
  327. /// <summary>
  328. /// https://tc39.es/ecma262/#sec-string.prototype.split
  329. /// </summary>
  330. private JsValue Split(JsValue thisObject, JsValue[] arguments)
  331. {
  332. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  333. var separator = arguments.At(0);
  334. var limit = arguments.At(1);
  335. // fast path for empty regexp
  336. if (separator is JsRegExp R && string.Equals(R.Source, JsRegExp.regExpForMatchingAllCharacters, StringComparison.Ordinal))
  337. {
  338. separator = JsString.Empty;
  339. }
  340. if (separator is ObjectInstance oi)
  341. {
  342. var splitter = GetMethod(_realm, oi, GlobalSymbolRegistry.Split);
  343. if (splitter != null)
  344. {
  345. return splitter.Call(separator, new[] { thisObject, limit });
  346. }
  347. }
  348. var s = TypeConverter.ToString(thisObject);
  349. // Coerce into a number, true will become 1
  350. var lim = limit.IsUndefined() ? uint.MaxValue : TypeConverter.ToUint32(limit);
  351. if (separator.IsNull())
  352. {
  353. separator = "null";
  354. }
  355. else if (!separator.IsUndefined())
  356. {
  357. if (!separator.IsRegExp())
  358. {
  359. separator = TypeConverter.ToJsString(separator); // Coerce into a string, for an object call toString()
  360. }
  361. }
  362. if (lim == 0)
  363. {
  364. return _realm.Intrinsics.Array.ArrayCreate(0);
  365. }
  366. if (separator.IsUndefined())
  367. {
  368. var arrayInstance = _realm.Intrinsics.Array.ArrayCreate(1);
  369. arrayInstance.SetIndexValue(0, s, updateLength: false);
  370. return arrayInstance;
  371. }
  372. return SplitWithStringSeparator(_realm, separator, s, lim);
  373. }
  374. internal static JsValue SplitWithStringSeparator(Realm realm, JsValue separator, string s, uint lim)
  375. {
  376. var segments = StringExecutionContext.Current.SplitSegmentList;
  377. segments.Clear();
  378. var sep = TypeConverter.ToString(separator);
  379. if (sep == string.Empty)
  380. {
  381. if (s.Length > segments.Capacity)
  382. {
  383. segments.Capacity = s.Length;
  384. }
  385. for (var i = 0; i < s.Length; i++)
  386. {
  387. segments.Add(TypeConverter.ToString(s[i]));
  388. }
  389. }
  390. else
  391. {
  392. var array = StringExecutionContext.Current.SplitArray1;
  393. array[0] = sep;
  394. segments.AddRange(s.Split(array, StringSplitOptions.None));
  395. }
  396. var length = (uint) System.Math.Min(segments.Count, lim);
  397. var a = realm.Intrinsics.Array.ArrayCreate(length);
  398. for (int i = 0; i < length; i++)
  399. {
  400. a.SetIndexValue((uint) i, segments[i], updateLength: false);
  401. }
  402. a.SetLength(length);
  403. return a;
  404. }
  405. /// <summary>
  406. /// https://tc39.es/proposal-relative-indexing-method/#sec-string-prototype-additions
  407. /// </summary>
  408. private JsValue At(JsValue thisObject, JsValue[] arguments)
  409. {
  410. TypeConverter.CheckObjectCoercible(_engine, thisObject);
  411. var start = arguments.At(0);
  412. var o = thisObject.ToString();
  413. long len = o.Length;
  414. var relativeIndex = TypeConverter.ToInteger(start);
  415. int k;
  416. if (relativeIndex < 0)
  417. {
  418. k = (int) (len + relativeIndex);
  419. }
  420. else
  421. {
  422. k = (int) relativeIndex;
  423. }
  424. if (k < 0 || k >= len)
  425. {
  426. return Undefined;
  427. }
  428. return o[k];
  429. }
  430. private JsValue Slice(JsValue thisObject, JsValue[] arguments)
  431. {
  432. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  433. var start = TypeConverter.ToNumber(arguments.At(0));
  434. if (double.IsNegativeInfinity(start))
  435. {
  436. start = 0;
  437. }
  438. if (double.IsPositiveInfinity(start))
  439. {
  440. return JsString.Empty;
  441. }
  442. var s = TypeConverter.ToJsString(thisObject);
  443. var end = TypeConverter.ToNumber(arguments.At(1));
  444. if (double.IsPositiveInfinity(end))
  445. {
  446. end = s.Length;
  447. }
  448. var len = s.Length;
  449. var intStart = (int) start;
  450. var intEnd = arguments.At(1).IsUndefined() ? len : (int) TypeConverter.ToInteger(end);
  451. var from = intStart < 0 ? System.Math.Max(len + intStart, 0) : System.Math.Min(intStart, len);
  452. var to = intEnd < 0 ? System.Math.Max(len + intEnd, 0) : System.Math.Min(intEnd, len);
  453. var span = System.Math.Max(to - from, 0);
  454. if (span == 0)
  455. {
  456. return JsString.Empty;
  457. }
  458. if (span == 1)
  459. {
  460. return JsString.Create(s[from]);
  461. }
  462. return s.Substring(from, span);
  463. }
  464. private JsValue Search(JsValue thisObject, JsValue[] arguments)
  465. {
  466. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  467. var regex = arguments.At(0);
  468. if (regex is ObjectInstance oi)
  469. {
  470. var searcher = GetMethod(_realm, oi, GlobalSymbolRegistry.Search);
  471. if (searcher != null)
  472. {
  473. return searcher.Call(regex, new[] { thisObject });
  474. }
  475. }
  476. var rx = (JsRegExp) _realm.Intrinsics.RegExp.Construct(new[] {regex});
  477. var s = TypeConverter.ToJsString(thisObject);
  478. return _engine.Invoke(rx, GlobalSymbolRegistry.Search, new JsValue[] { s });
  479. }
  480. /// <summary>
  481. /// https://tc39.es/ecma262/#sec-string.prototype.replace
  482. /// </summary>
  483. private JsValue Replace(JsValue thisObject, JsValue[] arguments)
  484. {
  485. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  486. var searchValue = arguments.At(0);
  487. var replaceValue = arguments.At(1);
  488. if (!searchValue.IsNullOrUndefined())
  489. {
  490. var replacer = GetMethod(_realm, searchValue, GlobalSymbolRegistry.Replace);
  491. if (replacer != null)
  492. {
  493. return replacer.Call(searchValue, thisObject, replaceValue);
  494. }
  495. }
  496. var thisString = TypeConverter.ToJsString(thisObject);
  497. var searchString = TypeConverter.ToString(searchValue);
  498. var functionalReplace = replaceValue is ICallable;
  499. if (!functionalReplace)
  500. {
  501. replaceValue = TypeConverter.ToJsString(replaceValue);
  502. }
  503. var position = thisString.IndexOf(searchString);
  504. if (position < 0)
  505. {
  506. return thisString;
  507. }
  508. string replStr;
  509. if (functionalReplace)
  510. {
  511. var replValue = ((ICallable) replaceValue).Call(Undefined, searchString, position, thisString);
  512. replStr = TypeConverter.ToString(replValue);
  513. }
  514. else
  515. {
  516. var captures = System.Array.Empty<string>();
  517. replStr = RegExpPrototype.GetSubstitution(searchString, thisString.ToString(), position, captures, Undefined, TypeConverter.ToString(replaceValue));
  518. }
  519. var tailPos = position + searchString.Length;
  520. var newString = thisString.Substring(0, position) + replStr + thisString.Substring(tailPos);
  521. return newString;
  522. }
  523. /// <summary>
  524. /// https://tc39.es/ecma262/#sec-string.prototype.replaceall
  525. /// </summary>
  526. private JsValue ReplaceAll(JsValue thisObject, JsValue[] arguments)
  527. {
  528. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  529. var searchValue = arguments.At(0);
  530. var replaceValue = arguments.At(1);
  531. if (!searchValue.IsNullOrUndefined())
  532. {
  533. if (searchValue.IsRegExp())
  534. {
  535. var flags = searchValue.Get(RegExpPrototype.PropertyFlags);
  536. TypeConverter.CheckObjectCoercible(_engine, flags);
  537. if (!TypeConverter.ToString(flags).Contains('g'))
  538. {
  539. ExceptionHelper.ThrowTypeError(_realm, "String.prototype.replaceAll called with a non-global RegExp argument");
  540. }
  541. }
  542. var replacer = GetMethod(_realm, searchValue, GlobalSymbolRegistry.Replace);
  543. if (replacer != null)
  544. {
  545. return replacer.Call(searchValue, thisObject, replaceValue);
  546. }
  547. }
  548. var thisString = TypeConverter.ToString(thisObject);
  549. var searchString = TypeConverter.ToString(searchValue);
  550. var functionalReplace = replaceValue is ICallable;
  551. if (!functionalReplace)
  552. {
  553. replaceValue = TypeConverter.ToJsString(replaceValue);
  554. // check fast case
  555. var newValue = replaceValue.ToString();
  556. if (!newValue.Contains('$') && searchString.Length > 0)
  557. {
  558. // just plain old string replace
  559. return thisString.Replace(searchString, newValue);
  560. }
  561. }
  562. // https://tc39.es/ecma262/#sec-stringindexof
  563. static int StringIndexOf(string s, string search, int fromIndex)
  564. {
  565. if (search.Length == 0 && fromIndex <= s.Length)
  566. {
  567. return fromIndex;
  568. }
  569. return fromIndex < s.Length
  570. ? s.IndexOf(search, fromIndex, StringComparison.Ordinal)
  571. : -1;
  572. }
  573. var searchLength = searchString.Length;
  574. var advanceBy = System.Math.Max(1, searchLength);
  575. var endOfLastMatch = 0;
  576. using var result = new ValueStringBuilder();
  577. var position = StringIndexOf(thisString, searchString, 0);
  578. while (position != -1)
  579. {
  580. string replacement;
  581. var preserved = thisString.Substring(endOfLastMatch, position - endOfLastMatch);
  582. if (functionalReplace)
  583. {
  584. var replValue = ((ICallable) replaceValue).Call(Undefined, searchString, position, thisString);
  585. replacement = TypeConverter.ToString(replValue);
  586. }
  587. else
  588. {
  589. var captures = System.Array.Empty<string>();
  590. replacement = RegExpPrototype.GetSubstitution(searchString, thisString, position, captures, Undefined, TypeConverter.ToString(replaceValue));
  591. }
  592. result.Append(preserved);
  593. result.Append(replacement);
  594. endOfLastMatch = position + searchLength;
  595. position = StringIndexOf(thisString, searchString, position + advanceBy);
  596. }
  597. if (endOfLastMatch < thisString.Length)
  598. {
  599. #if NETFRAMEWORK
  600. result.Append(thisString.AsSpan(endOfLastMatch));
  601. #else
  602. result.Append(thisString[endOfLastMatch..]);
  603. #endif
  604. }
  605. return result.ToString();
  606. }
  607. private JsValue Match(JsValue thisObject, JsValue[] arguments)
  608. {
  609. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  610. var regex = arguments.At(0);
  611. if (regex is ObjectInstance oi)
  612. {
  613. var matcher = GetMethod(_realm, oi, GlobalSymbolRegistry.Match);
  614. if (matcher != null)
  615. {
  616. return matcher.Call(regex, new[] { thisObject });
  617. }
  618. }
  619. var rx = (JsRegExp) _realm.Intrinsics.RegExp.Construct(new[] {regex});
  620. var s = TypeConverter.ToJsString(thisObject);
  621. return _engine.Invoke(rx, GlobalSymbolRegistry.Match, new JsValue[] { s });
  622. }
  623. private JsValue MatchAll(JsValue thisObject, JsValue[] arguments)
  624. {
  625. TypeConverter.CheckObjectCoercible(_engine, thisObject);
  626. var regex = arguments.At(0);
  627. if (!regex.IsNullOrUndefined())
  628. {
  629. if (regex.IsRegExp())
  630. {
  631. var flags = regex.Get(RegExpPrototype.PropertyFlags);
  632. TypeConverter.CheckObjectCoercible(_engine, flags);
  633. if (!TypeConverter.ToString(flags).Contains('g'))
  634. {
  635. ExceptionHelper.ThrowTypeError(_realm);
  636. }
  637. }
  638. var matcher = GetMethod(_realm, (ObjectInstance) regex, GlobalSymbolRegistry.MatchAll);
  639. if (matcher != null)
  640. {
  641. return matcher.Call(regex, new[] { thisObject });
  642. }
  643. }
  644. var s = TypeConverter.ToJsString(thisObject);
  645. var rx = (JsRegExp) _realm.Intrinsics.RegExp.Construct(new[] { regex, "g" });
  646. return _engine.Invoke(rx, GlobalSymbolRegistry.MatchAll, new JsValue[] { s });
  647. }
  648. private JsValue LocaleCompare(JsValue thisObject, JsValue[] arguments)
  649. {
  650. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  651. var s = TypeConverter.ToString(thisObject);
  652. var that = TypeConverter.ToString(arguments.At(0));
  653. var culture = Engine.Options.Culture;
  654. if (arguments.Length > 1 && arguments[1].IsString())
  655. {
  656. culture = CultureInfo.GetCultureInfo(arguments.At(1).AsString());
  657. }
  658. return culture.CompareInfo.Compare(s.Normalize(NormalizationForm.FormKD), that.Normalize(NormalizationForm.FormKD));
  659. }
  660. /// <summary>
  661. /// https://tc39.es/ecma262/#sec-string.prototype.lastindexof
  662. /// </summary>
  663. private JsValue LastIndexOf(JsValue thisObject, JsValue[] arguments)
  664. {
  665. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  666. var jsString = TypeConverter.ToJsString(thisObject);
  667. var searchStr = TypeConverter.ToString(arguments.At(0));
  668. double numPos = double.NaN;
  669. if (arguments.Length > 1 && !arguments[1].IsUndefined())
  670. {
  671. numPos = TypeConverter.ToNumber(arguments[1]);
  672. }
  673. var pos = double.IsNaN(numPos) ? double.PositiveInfinity : TypeConverter.ToInteger(numPos);
  674. var len = jsString.Length;
  675. var start = (int)System.Math.Min(System.Math.Max(pos, 0), len);
  676. var searchLen = searchStr.Length;
  677. if (searchLen > len)
  678. {
  679. return JsNumber.IntegerNegativeOne;
  680. }
  681. var s = jsString.ToString();
  682. var i = start;
  683. bool found;
  684. do
  685. {
  686. found = true;
  687. var j = 0;
  688. while (found && j < searchLen)
  689. {
  690. if (i + searchLen > len || s[i + j] != searchStr[j])
  691. {
  692. found = false;
  693. }
  694. else
  695. {
  696. j++;
  697. }
  698. }
  699. if (!found)
  700. {
  701. i--;
  702. }
  703. } while (!found && i >= 0);
  704. return i;
  705. }
  706. /// <summary>
  707. /// https://tc39.es/ecma262/#sec-string.prototype.indexof
  708. /// </summary>
  709. private JsValue IndexOf(JsValue thisObject, JsValue[] arguments)
  710. {
  711. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  712. var s = TypeConverter.ToJsString(thisObject);
  713. var searchStr = TypeConverter.ToString(arguments.At(0));
  714. double pos = 0;
  715. if (arguments.Length > 1 && !arguments[1].IsUndefined())
  716. {
  717. pos = TypeConverter.ToInteger(arguments[1]);
  718. }
  719. if (pos > s.Length)
  720. {
  721. pos = s.Length;
  722. }
  723. if (pos < 0)
  724. {
  725. pos = 0;
  726. }
  727. return s.IndexOf(searchStr, (int) pos);
  728. }
  729. private JsValue Concat(JsValue thisObject, JsValue[] arguments)
  730. {
  731. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  732. if (thisObject is not JsString jsString)
  733. {
  734. jsString = new JsString.ConcatenatedString(TypeConverter.ToString(thisObject));
  735. }
  736. else
  737. {
  738. jsString = jsString.EnsureCapacity(0);
  739. }
  740. foreach (var argument in arguments)
  741. {
  742. jsString = jsString.Append(argument);
  743. }
  744. return jsString;
  745. }
  746. private JsValue CharCodeAt(JsValue thisObject, JsValue[] arguments)
  747. {
  748. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  749. JsValue pos = arguments.Length > 0 ? arguments[0] : 0;
  750. var s = TypeConverter.ToJsString(thisObject);
  751. var position = (int) TypeConverter.ToInteger(pos);
  752. if (position < 0 || position >= s.Length)
  753. {
  754. return JsNumber.DoubleNaN;
  755. }
  756. return (long) s[position];
  757. }
  758. /// <summary>
  759. /// https://tc39.es/ecma262/#sec-string.prototype.codepointat
  760. /// </summary>
  761. private JsValue CodePointAt(JsValue thisObject, JsValue[] arguments)
  762. {
  763. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  764. JsValue pos = arguments.Length > 0 ? arguments[0] : 0;
  765. var s = TypeConverter.ToString(thisObject);
  766. var position = (int)TypeConverter.ToInteger(pos);
  767. if (position < 0 || position >= s.Length)
  768. {
  769. return Undefined;
  770. }
  771. return CodePointAt(s, position).CodePoint;
  772. }
  773. [StructLayout(LayoutKind.Auto)]
  774. private readonly record struct CodePointResult(int CodePoint, int CodeUnitCount, bool IsUnpairedSurrogate);
  775. private static CodePointResult CodePointAt(string s, int position)
  776. {
  777. var size = s.Length;
  778. var first = s.CharCodeAt(position);
  779. var cp = s.CharCodeAt(position);
  780. var firstIsLeading = char.IsHighSurrogate(first);
  781. var firstIsTrailing = char.IsLowSurrogate(first);
  782. if (!firstIsLeading && !firstIsTrailing)
  783. {
  784. return new CodePointResult(cp, 1, false);
  785. }
  786. if (firstIsTrailing || position + 1 == size)
  787. {
  788. return new CodePointResult(cp, 1, true);
  789. }
  790. var second = s.CharCodeAt(position + 1);
  791. if (!char.IsLowSurrogate(second))
  792. {
  793. return new CodePointResult(cp, 1, true);
  794. }
  795. return new CodePointResult(char.ConvertToUtf32(first, second), 2, false);
  796. }
  797. private JsValue CharAt(JsValue thisObject, JsValue[] arguments)
  798. {
  799. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  800. var s = TypeConverter.ToJsString(thisObject);
  801. var position = TypeConverter.ToInteger(arguments.At(0));
  802. var size = s.Length;
  803. if (position >= size || position < 0)
  804. {
  805. return JsString.Empty;
  806. }
  807. return JsString.Create(s[(int) position]);
  808. }
  809. private JsValue ValueOf(JsValue thisObject, JsValue[] arguments)
  810. {
  811. if (thisObject is StringInstance si)
  812. {
  813. return si.StringData;
  814. }
  815. if (thisObject is JsString)
  816. {
  817. return thisObject;
  818. }
  819. ExceptionHelper.ThrowTypeError(_realm);
  820. return Undefined;
  821. }
  822. /// <summary>
  823. /// https://tc39.es/ecma262/#sec-string.prototype.padstart
  824. /// </summary>
  825. private JsValue PadStart(JsValue thisObject, JsValue[] arguments)
  826. {
  827. return StringPad(thisObject, arguments, true);
  828. }
  829. /// <summary>
  830. /// https://tc39.es/ecma262/#sec-string.prototype.padend
  831. /// </summary>
  832. private JsValue PadEnd(JsValue thisObject, JsValue[] arguments)
  833. {
  834. return StringPad(thisObject, arguments, false);
  835. }
  836. /// <summary>
  837. /// https://tc39.es/ecma262/#sec-stringpad
  838. /// </summary>
  839. private JsValue StringPad(JsValue thisObject, JsValue[] arguments, bool padStart)
  840. {
  841. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  842. var s = TypeConverter.ToJsString(thisObject);
  843. var targetLength = TypeConverter.ToInt32(arguments.At(0));
  844. var padStringValue = arguments.At(1);
  845. var padString = padStringValue.IsUndefined()
  846. ? " "
  847. : TypeConverter.ToString(padStringValue);
  848. if (s.Length > targetLength || padString.Length == 0)
  849. {
  850. return s;
  851. }
  852. targetLength -= s.Length;
  853. if (targetLength > padString.Length)
  854. {
  855. padString = string.Join("", System.Linq.Enumerable.Repeat(padString, (targetLength / padString.Length) + 1));
  856. }
  857. return padStart
  858. ? $"{padString.Substring(0, targetLength)}{s}"
  859. : $"{s}{padString.Substring(0, targetLength)}";
  860. }
  861. /// <summary>
  862. /// https://tc39.es/ecma262/#sec-string.prototype.startswith
  863. /// </summary>
  864. private JsValue StartsWith(JsValue thisObject, JsValue[] arguments)
  865. {
  866. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  867. var s = TypeConverter.ToJsString(thisObject);
  868. var searchString = arguments.At(0);
  869. if (ReferenceEquals(searchString, Null))
  870. {
  871. searchString = "null";
  872. }
  873. else
  874. {
  875. if (searchString.IsRegExp())
  876. {
  877. ExceptionHelper.ThrowTypeError(_realm);
  878. }
  879. }
  880. var searchStr = TypeConverter.ToString(searchString);
  881. var pos = TypeConverter.ToInt32(arguments.At(1));
  882. var len = s.Length;
  883. var start = System.Math.Min(System.Math.Max(pos, 0), len);
  884. return s.StartsWith(searchStr, start);
  885. }
  886. /// <summary>
  887. /// https://tc39.es/ecma262/#sec-string.prototype.endswith
  888. /// </summary>
  889. private JsValue EndsWith(JsValue thisObject, JsValue[] arguments)
  890. {
  891. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  892. var s = TypeConverter.ToJsString(thisObject);
  893. var searchString = arguments.At(0);
  894. if (ReferenceEquals(searchString, Null))
  895. {
  896. searchString = "null";
  897. }
  898. else
  899. {
  900. if (searchString.IsRegExp())
  901. {
  902. ExceptionHelper.ThrowTypeError(_realm);
  903. }
  904. }
  905. var searchStr = TypeConverter.ToString(searchString);
  906. var len = s.Length;
  907. var pos = TypeConverter.ToInt32(arguments.At(1, len));
  908. var end = System.Math.Min(System.Math.Max(pos, 0), len);
  909. return s.EndsWith(searchStr, end);
  910. }
  911. /// <summary>
  912. /// https://tc39.es/ecma262/#sec-string.prototype.includes
  913. /// </summary>
  914. private JsValue Includes(JsValue thisObject, JsValue[] arguments)
  915. {
  916. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  917. var s = TypeConverter.ToJsString(thisObject);
  918. var searchString = arguments.At(0);
  919. if (searchString.IsRegExp())
  920. {
  921. ExceptionHelper.ThrowTypeError(_realm, "First argument to String.prototype.includes must not be a regular expression");
  922. }
  923. var searchStr = TypeConverter.ToString(searchString);
  924. double pos = 0;
  925. if (arguments.Length > 1 && !arguments[1].IsUndefined())
  926. {
  927. pos = TypeConverter.ToInteger(arguments[1]);
  928. }
  929. if (searchStr.Length == 0)
  930. {
  931. return JsBoolean.True;
  932. }
  933. if (pos < 0)
  934. {
  935. pos = 0;
  936. }
  937. return s.IndexOf(searchStr, (int) pos) > -1;
  938. }
  939. private JsValue Normalize(JsValue thisObject, JsValue[] arguments)
  940. {
  941. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  942. var str = TypeConverter.ToString(thisObject);
  943. var param = arguments.At(0);
  944. var form = "NFC";
  945. if (!param.IsUndefined())
  946. {
  947. form = TypeConverter.ToString(param);
  948. }
  949. var nf = NormalizationForm.FormC;
  950. switch (form)
  951. {
  952. case "NFC":
  953. nf = NormalizationForm.FormC;
  954. break;
  955. case "NFD":
  956. nf = NormalizationForm.FormD;
  957. break;
  958. case "NFKC":
  959. nf = NormalizationForm.FormKC;
  960. break;
  961. case "NFKD":
  962. nf = NormalizationForm.FormKD;
  963. break;
  964. default:
  965. ExceptionHelper.ThrowRangeError(
  966. _realm,
  967. "The normalization form should be one of NFC, NFD, NFKC, NFKD.");
  968. break;
  969. }
  970. return str.Normalize(nf);
  971. }
  972. /// <summary>
  973. /// https://tc39.es/ecma262/#sec-string.prototype.repeat
  974. /// </summary>
  975. private JsValue Repeat(JsValue thisObject, JsValue[] arguments)
  976. {
  977. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  978. var s = TypeConverter.ToString(thisObject);
  979. var count = arguments.At(0);
  980. var n = TypeConverter.ToIntegerOrInfinity(count);
  981. if (n < 0 || double.IsPositiveInfinity(n))
  982. {
  983. ExceptionHelper.ThrowRangeError(_realm, "Invalid count value");
  984. }
  985. if (n == 0 || s.Length == 0)
  986. {
  987. return JsString.Empty;
  988. }
  989. if (s.Length == 1)
  990. {
  991. return new string(s[0], (int) n);
  992. }
  993. var sb = new ValueStringBuilder((int) (n * s.Length));
  994. for (var i = 0; i < n; ++i)
  995. {
  996. sb.Append(s);
  997. }
  998. return sb.ToString();
  999. }
  1000. private JsValue IsWellFormed(JsValue thisObject, JsValue[] arguments)
  1001. {
  1002. TypeConverter.CheckObjectCoercible(_engine, thisObject);
  1003. var s = TypeConverter.ToString(thisObject);
  1004. return IsStringWellFormedUnicode(s);
  1005. }
  1006. private JsValue ToWellFormed(JsValue thisObject, JsValue[] arguments)
  1007. {
  1008. TypeConverter.CheckObjectCoercible(_engine, thisObject);
  1009. var s = TypeConverter.ToString(thisObject);
  1010. var strLen = s.Length;
  1011. var k = 0;
  1012. var result = new ValueStringBuilder();
  1013. while (k < strLen)
  1014. {
  1015. var cp = CodePointAt(s, k);
  1016. if (cp.IsUnpairedSurrogate)
  1017. {
  1018. // \uFFFD
  1019. result.Append('�');
  1020. }
  1021. else
  1022. {
  1023. result.Append(s.AsSpan(k, cp.CodeUnitCount));
  1024. }
  1025. k += cp.CodeUnitCount;
  1026. }
  1027. return result.ToString();
  1028. }
  1029. private static bool IsStringWellFormedUnicode(string s)
  1030. {
  1031. for (var i = 0; i < s.Length; ++i)
  1032. {
  1033. var isSurrogate = (s.CharCodeAt(i) & 0xF800) == 0xD800;
  1034. if (!isSurrogate)
  1035. {
  1036. continue;
  1037. }
  1038. var isLeadingSurrogate = s.CharCodeAt(i) < 0xDC00;
  1039. if (!isLeadingSurrogate)
  1040. {
  1041. return false; // unpaired trailing surrogate
  1042. }
  1043. var isFollowedByTrailingSurrogate = i + 1 < s.Length && (s.CharCodeAt(i + 1) & 0xFC00) == 0xDC00;
  1044. if (!isFollowedByTrailingSurrogate)
  1045. {
  1046. return false; // unpaired leading surrogate
  1047. }
  1048. ++i;
  1049. }
  1050. return true;
  1051. }
  1052. }