StringPrototype.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251
  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. result.Append(thisString.AsSpan(endOfLastMatch));
  600. }
  601. return result.ToString();
  602. }
  603. private JsValue Match(JsValue thisObject, JsValue[] arguments)
  604. {
  605. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  606. var regex = arguments.At(0);
  607. if (regex is ObjectInstance oi)
  608. {
  609. var matcher = GetMethod(_realm, oi, GlobalSymbolRegistry.Match);
  610. if (matcher != null)
  611. {
  612. return matcher.Call(regex, new[] { thisObject });
  613. }
  614. }
  615. var rx = (JsRegExp) _realm.Intrinsics.RegExp.Construct(new[] {regex});
  616. var s = TypeConverter.ToJsString(thisObject);
  617. return _engine.Invoke(rx, GlobalSymbolRegistry.Match, new JsValue[] { s });
  618. }
  619. private JsValue MatchAll(JsValue thisObject, JsValue[] arguments)
  620. {
  621. TypeConverter.CheckObjectCoercible(_engine, thisObject);
  622. var regex = arguments.At(0);
  623. if (!regex.IsNullOrUndefined())
  624. {
  625. if (regex.IsRegExp())
  626. {
  627. var flags = regex.Get(RegExpPrototype.PropertyFlags);
  628. TypeConverter.CheckObjectCoercible(_engine, flags);
  629. if (!TypeConverter.ToString(flags).Contains('g'))
  630. {
  631. ExceptionHelper.ThrowTypeError(_realm);
  632. }
  633. }
  634. var matcher = GetMethod(_realm, (ObjectInstance) regex, GlobalSymbolRegistry.MatchAll);
  635. if (matcher != null)
  636. {
  637. return matcher.Call(regex, new[] { thisObject });
  638. }
  639. }
  640. var s = TypeConverter.ToJsString(thisObject);
  641. var rx = (JsRegExp) _realm.Intrinsics.RegExp.Construct(new[] { regex, "g" });
  642. return _engine.Invoke(rx, GlobalSymbolRegistry.MatchAll, new JsValue[] { s });
  643. }
  644. private JsValue LocaleCompare(JsValue thisObject, JsValue[] arguments)
  645. {
  646. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  647. var s = TypeConverter.ToString(thisObject);
  648. var that = TypeConverter.ToString(arguments.At(0));
  649. var culture = Engine.Options.Culture;
  650. if (arguments.Length > 1 && arguments[1].IsString())
  651. {
  652. culture = CultureInfo.GetCultureInfo(arguments.At(1).AsString());
  653. }
  654. return culture.CompareInfo.Compare(s.Normalize(NormalizationForm.FormKD), that.Normalize(NormalizationForm.FormKD));
  655. }
  656. /// <summary>
  657. /// https://tc39.es/ecma262/#sec-string.prototype.lastindexof
  658. /// </summary>
  659. private JsValue LastIndexOf(JsValue thisObject, JsValue[] arguments)
  660. {
  661. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  662. var jsString = TypeConverter.ToJsString(thisObject);
  663. var searchStr = TypeConverter.ToString(arguments.At(0));
  664. double numPos = double.NaN;
  665. if (arguments.Length > 1 && !arguments[1].IsUndefined())
  666. {
  667. numPos = TypeConverter.ToNumber(arguments[1]);
  668. }
  669. var pos = double.IsNaN(numPos) ? double.PositiveInfinity : TypeConverter.ToInteger(numPos);
  670. var len = jsString.Length;
  671. var start = (int)System.Math.Min(System.Math.Max(pos, 0), len);
  672. var searchLen = searchStr.Length;
  673. if (searchLen > len)
  674. {
  675. return JsNumber.IntegerNegativeOne;
  676. }
  677. var s = jsString.ToString();
  678. var i = start;
  679. bool found;
  680. do
  681. {
  682. found = true;
  683. var j = 0;
  684. while (found && j < searchLen)
  685. {
  686. if (i + searchLen > len || s[i + j] != searchStr[j])
  687. {
  688. found = false;
  689. }
  690. else
  691. {
  692. j++;
  693. }
  694. }
  695. if (!found)
  696. {
  697. i--;
  698. }
  699. } while (!found && i >= 0);
  700. return i;
  701. }
  702. /// <summary>
  703. /// https://tc39.es/ecma262/#sec-string.prototype.indexof
  704. /// </summary>
  705. private JsValue IndexOf(JsValue thisObject, JsValue[] arguments)
  706. {
  707. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  708. var s = TypeConverter.ToJsString(thisObject);
  709. var searchStr = TypeConverter.ToString(arguments.At(0));
  710. double pos = 0;
  711. if (arguments.Length > 1 && !arguments[1].IsUndefined())
  712. {
  713. pos = TypeConverter.ToInteger(arguments[1]);
  714. }
  715. if (pos > s.Length)
  716. {
  717. pos = s.Length;
  718. }
  719. if (pos < 0)
  720. {
  721. pos = 0;
  722. }
  723. return s.IndexOf(searchStr, (int) pos);
  724. }
  725. private JsValue Concat(JsValue thisObject, JsValue[] arguments)
  726. {
  727. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  728. if (thisObject is not JsString jsString)
  729. {
  730. jsString = new JsString.ConcatenatedString(TypeConverter.ToString(thisObject));
  731. }
  732. else
  733. {
  734. jsString = jsString.EnsureCapacity(0);
  735. }
  736. foreach (var argument in arguments)
  737. {
  738. jsString = jsString.Append(argument);
  739. }
  740. return jsString;
  741. }
  742. private JsValue CharCodeAt(JsValue thisObject, JsValue[] arguments)
  743. {
  744. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  745. JsValue pos = arguments.Length > 0 ? arguments[0] : 0;
  746. var s = TypeConverter.ToJsString(thisObject);
  747. var position = (int) TypeConverter.ToInteger(pos);
  748. if (position < 0 || position >= s.Length)
  749. {
  750. return JsNumber.DoubleNaN;
  751. }
  752. return (long) s[position];
  753. }
  754. /// <summary>
  755. /// https://tc39.es/ecma262/#sec-string.prototype.codepointat
  756. /// </summary>
  757. private JsValue CodePointAt(JsValue thisObject, JsValue[] arguments)
  758. {
  759. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  760. JsValue pos = arguments.Length > 0 ? arguments[0] : 0;
  761. var s = TypeConverter.ToString(thisObject);
  762. var position = (int)TypeConverter.ToInteger(pos);
  763. if (position < 0 || position >= s.Length)
  764. {
  765. return Undefined;
  766. }
  767. return CodePointAt(s, position).CodePoint;
  768. }
  769. [StructLayout(LayoutKind.Auto)]
  770. private readonly record struct CodePointResult(int CodePoint, int CodeUnitCount, bool IsUnpairedSurrogate);
  771. private static CodePointResult CodePointAt(string s, int position)
  772. {
  773. var size = s.Length;
  774. var first = s.CharCodeAt(position);
  775. var cp = s.CharCodeAt(position);
  776. var firstIsLeading = char.IsHighSurrogate(first);
  777. var firstIsTrailing = char.IsLowSurrogate(first);
  778. if (!firstIsLeading && !firstIsTrailing)
  779. {
  780. return new CodePointResult(cp, 1, false);
  781. }
  782. if (firstIsTrailing || position + 1 == size)
  783. {
  784. return new CodePointResult(cp, 1, true);
  785. }
  786. var second = s.CharCodeAt(position + 1);
  787. if (!char.IsLowSurrogate(second))
  788. {
  789. return new CodePointResult(cp, 1, true);
  790. }
  791. return new CodePointResult(char.ConvertToUtf32(first, second), 2, false);
  792. }
  793. private JsValue CharAt(JsValue thisObject, JsValue[] arguments)
  794. {
  795. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  796. var s = TypeConverter.ToJsString(thisObject);
  797. var position = TypeConverter.ToInteger(arguments.At(0));
  798. var size = s.Length;
  799. if (position >= size || position < 0)
  800. {
  801. return JsString.Empty;
  802. }
  803. return JsString.Create(s[(int) position]);
  804. }
  805. private JsValue ValueOf(JsValue thisObject, JsValue[] arguments)
  806. {
  807. if (thisObject is StringInstance si)
  808. {
  809. return si.StringData;
  810. }
  811. if (thisObject is JsString)
  812. {
  813. return thisObject;
  814. }
  815. ExceptionHelper.ThrowTypeError(_realm);
  816. return Undefined;
  817. }
  818. /// <summary>
  819. /// https://tc39.es/ecma262/#sec-string.prototype.padstart
  820. /// </summary>
  821. private JsValue PadStart(JsValue thisObject, JsValue[] arguments)
  822. {
  823. return StringPad(thisObject, arguments, true);
  824. }
  825. /// <summary>
  826. /// https://tc39.es/ecma262/#sec-string.prototype.padend
  827. /// </summary>
  828. private JsValue PadEnd(JsValue thisObject, JsValue[] arguments)
  829. {
  830. return StringPad(thisObject, arguments, false);
  831. }
  832. /// <summary>
  833. /// https://tc39.es/ecma262/#sec-stringpad
  834. /// </summary>
  835. private JsValue StringPad(JsValue thisObject, JsValue[] arguments, bool padStart)
  836. {
  837. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  838. var s = TypeConverter.ToJsString(thisObject);
  839. var targetLength = TypeConverter.ToInt32(arguments.At(0));
  840. var padStringValue = arguments.At(1);
  841. var padString = padStringValue.IsUndefined()
  842. ? " "
  843. : TypeConverter.ToString(padStringValue);
  844. if (s.Length > targetLength || padString.Length == 0)
  845. {
  846. return s;
  847. }
  848. targetLength -= s.Length;
  849. if (targetLength > padString.Length)
  850. {
  851. padString = string.Join("", System.Linq.Enumerable.Repeat(padString, (targetLength / padString.Length) + 1));
  852. }
  853. return padStart
  854. ? $"{padString.Substring(0, targetLength)}{s}"
  855. : $"{s}{padString.Substring(0, targetLength)}";
  856. }
  857. /// <summary>
  858. /// https://tc39.es/ecma262/#sec-string.prototype.startswith
  859. /// </summary>
  860. private JsValue StartsWith(JsValue thisObject, JsValue[] arguments)
  861. {
  862. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  863. var s = TypeConverter.ToJsString(thisObject);
  864. var searchString = arguments.At(0);
  865. if (ReferenceEquals(searchString, Null))
  866. {
  867. searchString = "null";
  868. }
  869. else
  870. {
  871. if (searchString.IsRegExp())
  872. {
  873. ExceptionHelper.ThrowTypeError(_realm);
  874. }
  875. }
  876. var searchStr = TypeConverter.ToString(searchString);
  877. var pos = TypeConverter.ToInt32(arguments.At(1));
  878. var len = s.Length;
  879. var start = System.Math.Min(System.Math.Max(pos, 0), len);
  880. return s.StartsWith(searchStr, start);
  881. }
  882. /// <summary>
  883. /// https://tc39.es/ecma262/#sec-string.prototype.endswith
  884. /// </summary>
  885. private JsValue EndsWith(JsValue thisObject, JsValue[] arguments)
  886. {
  887. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  888. var s = TypeConverter.ToJsString(thisObject);
  889. var searchString = arguments.At(0);
  890. if (ReferenceEquals(searchString, Null))
  891. {
  892. searchString = "null";
  893. }
  894. else
  895. {
  896. if (searchString.IsRegExp())
  897. {
  898. ExceptionHelper.ThrowTypeError(_realm);
  899. }
  900. }
  901. var searchStr = TypeConverter.ToString(searchString);
  902. var len = s.Length;
  903. var pos = TypeConverter.ToInt32(arguments.At(1, len));
  904. var end = System.Math.Min(System.Math.Max(pos, 0), len);
  905. return s.EndsWith(searchStr, end);
  906. }
  907. /// <summary>
  908. /// https://tc39.es/ecma262/#sec-string.prototype.includes
  909. /// </summary>
  910. private JsValue Includes(JsValue thisObject, JsValue[] arguments)
  911. {
  912. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  913. var s = TypeConverter.ToJsString(thisObject);
  914. var searchString = arguments.At(0);
  915. if (searchString.IsRegExp())
  916. {
  917. ExceptionHelper.ThrowTypeError(_realm, "First argument to String.prototype.includes must not be a regular expression");
  918. }
  919. var searchStr = TypeConverter.ToString(searchString);
  920. double pos = 0;
  921. if (arguments.Length > 1 && !arguments[1].IsUndefined())
  922. {
  923. pos = TypeConverter.ToInteger(arguments[1]);
  924. }
  925. if (searchStr.Length == 0)
  926. {
  927. return JsBoolean.True;
  928. }
  929. if (pos < 0)
  930. {
  931. pos = 0;
  932. }
  933. return s.IndexOf(searchStr, (int) pos) > -1;
  934. }
  935. private JsValue Normalize(JsValue thisObject, JsValue[] arguments)
  936. {
  937. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  938. var str = TypeConverter.ToString(thisObject);
  939. var param = arguments.At(0);
  940. var form = "NFC";
  941. if (!param.IsUndefined())
  942. {
  943. form = TypeConverter.ToString(param);
  944. }
  945. var nf = NormalizationForm.FormC;
  946. switch (form)
  947. {
  948. case "NFC":
  949. nf = NormalizationForm.FormC;
  950. break;
  951. case "NFD":
  952. nf = NormalizationForm.FormD;
  953. break;
  954. case "NFKC":
  955. nf = NormalizationForm.FormKC;
  956. break;
  957. case "NFKD":
  958. nf = NormalizationForm.FormKD;
  959. break;
  960. default:
  961. ExceptionHelper.ThrowRangeError(
  962. _realm,
  963. "The normalization form should be one of NFC, NFD, NFKC, NFKD.");
  964. break;
  965. }
  966. return str.Normalize(nf);
  967. }
  968. /// <summary>
  969. /// https://tc39.es/ecma262/#sec-string.prototype.repeat
  970. /// </summary>
  971. private JsValue Repeat(JsValue thisObject, JsValue[] arguments)
  972. {
  973. TypeConverter.CheckObjectCoercible(Engine, thisObject);
  974. var s = TypeConverter.ToString(thisObject);
  975. var count = arguments.At(0);
  976. var n = TypeConverter.ToIntegerOrInfinity(count);
  977. if (n < 0 || double.IsPositiveInfinity(n))
  978. {
  979. ExceptionHelper.ThrowRangeError(_realm, "Invalid count value");
  980. }
  981. if (n == 0 || s.Length == 0)
  982. {
  983. return JsString.Empty;
  984. }
  985. if (s.Length == 1)
  986. {
  987. return new string(s[0], (int) n);
  988. }
  989. var sb = new ValueStringBuilder((int) (n * s.Length));
  990. for (var i = 0; i < n; ++i)
  991. {
  992. sb.Append(s);
  993. }
  994. return sb.ToString();
  995. }
  996. private JsValue IsWellFormed(JsValue thisObject, JsValue[] arguments)
  997. {
  998. TypeConverter.CheckObjectCoercible(_engine, thisObject);
  999. var s = TypeConverter.ToString(thisObject);
  1000. return IsStringWellFormedUnicode(s);
  1001. }
  1002. private JsValue ToWellFormed(JsValue thisObject, JsValue[] arguments)
  1003. {
  1004. TypeConverter.CheckObjectCoercible(_engine, thisObject);
  1005. var s = TypeConverter.ToString(thisObject);
  1006. var strLen = s.Length;
  1007. var k = 0;
  1008. var result = new ValueStringBuilder();
  1009. while (k < strLen)
  1010. {
  1011. var cp = CodePointAt(s, k);
  1012. if (cp.IsUnpairedSurrogate)
  1013. {
  1014. // \uFFFD
  1015. result.Append('�');
  1016. }
  1017. else
  1018. {
  1019. result.Append(s.AsSpan(k, cp.CodeUnitCount));
  1020. }
  1021. k += cp.CodeUnitCount;
  1022. }
  1023. return result.ToString();
  1024. }
  1025. private static bool IsStringWellFormedUnicode(string s)
  1026. {
  1027. for (var i = 0; i < s.Length; ++i)
  1028. {
  1029. var isSurrogate = (s.CharCodeAt(i) & 0xF800) == 0xD800;
  1030. if (!isSurrogate)
  1031. {
  1032. continue;
  1033. }
  1034. var isLeadingSurrogate = s.CharCodeAt(i) < 0xDC00;
  1035. if (!isLeadingSurrogate)
  1036. {
  1037. return false; // unpaired trailing surrogate
  1038. }
  1039. var isFollowedByTrailingSurrogate = i + 1 < s.Length && (s.CharCodeAt(i + 1) & 0xFC00) == 0xDC00;
  1040. if (!isFollowedByTrailingSurrogate)
  1041. {
  1042. return false; // unpaired leading surrogate
  1043. }
  1044. ++i;
  1045. }
  1046. return true;
  1047. }
  1048. }