StringPrototype.cs 42 KB

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