StringPrototype.cs 41 KB

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