StringPrototype.cs 41 KB

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