StringPrototype.cs 40 KB

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