StringPrototype.cs 43 KB

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