StringPrototype.cs 42 KB

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