StringPrototype.cs 43 KB

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