StringPrototype.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.CompilerServices;
  5. using System.Text;
  6. using Jint.Native.Array;
  7. using Jint.Native.Function;
  8. using Jint.Native.Object;
  9. using Jint.Native.RegExp;
  10. using Jint.Runtime;
  11. using Jint.Runtime.Descriptors.Specialized;
  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 StringBuilder _stringBuilder;
  21. private List<string> _splitSegmentList;
  22. private JsValue[] _callArray3;
  23. private string[] _splitArray1;
  24. private StringPrototype(Engine engine)
  25. : base(engine)
  26. {
  27. }
  28. public static StringPrototype CreatePrototypeObject(Engine engine, StringConstructor stringConstructor)
  29. {
  30. var obj = new StringPrototype(engine);
  31. obj.Prototype = engine.Object.PrototypeObject;
  32. obj.PrimitiveValue = "";
  33. obj.Extensible = true;
  34. obj.SetOwnProperty("length", new AllForbiddenPropertyDescriptor(0));
  35. obj.SetOwnProperty("constructor", new NonEnumerablePropertyDescriptor(stringConstructor));
  36. return obj;
  37. }
  38. public void Configure()
  39. {
  40. FastAddProperty("toString", new ClrFunctionInstance(Engine, ToStringString), true, false, true);
  41. FastAddProperty("valueOf", new ClrFunctionInstance(Engine, ValueOf), true, false, true);
  42. FastAddProperty("charAt", new ClrFunctionInstance(Engine, CharAt, 1), true, false, true);
  43. FastAddProperty("charCodeAt", new ClrFunctionInstance(Engine, CharCodeAt, 1), true, false, true);
  44. FastAddProperty("concat", new ClrFunctionInstance(Engine, Concat, 1), true, false, true);
  45. FastAddProperty("indexOf", new ClrFunctionInstance(Engine, IndexOf, 1), true, false, true);
  46. FastAddProperty("startsWith", new ClrFunctionInstance(Engine, StartsWith, 1), true, false, true);
  47. FastAddProperty("lastIndexOf", new ClrFunctionInstance(Engine, LastIndexOf, 1), true, false, true);
  48. FastAddProperty("localeCompare", new ClrFunctionInstance(Engine, LocaleCompare, 1), true, false, true);
  49. FastAddProperty("match", new ClrFunctionInstance(Engine, Match, 1), true, false, true);
  50. FastAddProperty("replace", new ClrFunctionInstance(Engine, Replace, 2), true, false, true);
  51. FastAddProperty("search", new ClrFunctionInstance(Engine, Search, 1), true, false, true);
  52. FastAddProperty("slice", new ClrFunctionInstance(Engine, Slice, 2), true, false, true);
  53. FastAddProperty("split", new ClrFunctionInstance(Engine, Split, 2), true, false, true);
  54. FastAddProperty("substr", new ClrFunctionInstance(Engine, Substr, 2), true, false, true);
  55. FastAddProperty("substring", new ClrFunctionInstance(Engine, Substring, 2), true, false, true);
  56. FastAddProperty("toLowerCase", new ClrFunctionInstance(Engine, ToLowerCase), true, false, true);
  57. FastAddProperty("toLocaleLowerCase", new ClrFunctionInstance(Engine, ToLocaleLowerCase), true, false, true);
  58. FastAddProperty("toUpperCase", new ClrFunctionInstance(Engine, ToUpperCase), true, false, true);
  59. FastAddProperty("toLocaleUpperCase", new ClrFunctionInstance(Engine, ToLocaleUpperCase), true, false, true);
  60. FastAddProperty("trim", new ClrFunctionInstance(Engine, Trim), true, false, true);
  61. FastAddProperty("padStart", new ClrFunctionInstance(Engine, PadStart), true, false, true);
  62. FastAddProperty("padEnd", new ClrFunctionInstance(Engine, PadEnd), true, false, true);
  63. }
  64. private StringBuilder GetStringBuilder(int capacity)
  65. {
  66. if (_stringBuilder == null)
  67. {
  68. _stringBuilder = new StringBuilder(capacity);
  69. }
  70. else
  71. {
  72. _stringBuilder.EnsureCapacity(capacity);
  73. }
  74. return _stringBuilder;
  75. }
  76. private JsValue ToStringString(JsValue thisObj, JsValue[] arguments)
  77. {
  78. var s = TypeConverter.ToObject(Engine, thisObj) as StringInstance;
  79. if (s == null)
  80. {
  81. throw new JavaScriptException(Engine.TypeError);
  82. }
  83. return s.PrimitiveValue;
  84. }
  85. // http://msdn.microsoft.com/en-us/library/system.char.iswhitespace(v=vs.110).aspx
  86. // http://en.wikipedia.org/wiki/Byte_order_mark
  87. const char BOM_CHAR = '\uFEFF';
  88. const char MONGOLIAN_VOWEL_SEPARATOR = '\u180E';
  89. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  90. private static bool IsWhiteSpaceEx(char c)
  91. {
  92. return
  93. char.IsWhiteSpace(c) ||
  94. c == BOM_CHAR ||
  95. // In .NET 4.6 this was removed from WS based on Unicode 6.3 changes
  96. c == MONGOLIAN_VOWEL_SEPARATOR;
  97. }
  98. public static string TrimEndEx(string s)
  99. {
  100. if (s.Length == 0)
  101. return string.Empty;
  102. if (!IsWhiteSpaceEx(s[s.Length - 1]))
  103. return s;
  104. var i = s.Length - 1;
  105. while (i >= 0)
  106. {
  107. if (IsWhiteSpaceEx(s[i]))
  108. i--;
  109. else
  110. break;
  111. }
  112. if (i >= 0)
  113. return s.Substring(0, i + 1);
  114. else
  115. return string.Empty;
  116. }
  117. public static string TrimStartEx(string s)
  118. {
  119. if (s.Length == 0)
  120. return string.Empty;
  121. if (!IsWhiteSpaceEx(s[0]))
  122. return s;
  123. var i = 0;
  124. while (i < s.Length)
  125. {
  126. if (IsWhiteSpaceEx(s[i]))
  127. i++;
  128. else
  129. break;
  130. }
  131. if (i >= s.Length)
  132. return string.Empty;
  133. else
  134. return s.Substring(i);
  135. }
  136. public static string TrimEx(string s)
  137. {
  138. return TrimEndEx(TrimStartEx(s));
  139. }
  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 static JsValue ToLocaleUpperCase(JsValue thisObj, JsValue[] arguments)
  147. {
  148. var s = TypeConverter.ToString(thisObj);
  149. return s.ToUpper();
  150. }
  151. private static JsValue ToUpperCase(JsValue thisObj, JsValue[] arguments)
  152. {
  153. var s = TypeConverter.ToString(thisObj);
  154. return s.ToUpperInvariant();
  155. }
  156. private static JsValue ToLocaleLowerCase(JsValue thisObj, JsValue[] arguments)
  157. {
  158. var s = TypeConverter.ToString(thisObj);
  159. return s.ToLower();
  160. }
  161. private static JsValue ToLowerCase(JsValue thisObj, JsValue[] arguments)
  162. {
  163. var s = TypeConverter.ToString(thisObj);
  164. return s.ToLowerInvariant();
  165. }
  166. private static int ToIntegerSupportInfinity(JsValue numberVal)
  167. {
  168. var doubleVal = TypeConverter.ToInteger(numberVal);
  169. int intVal;
  170. if (double.IsPositiveInfinity(doubleVal))
  171. intVal = int.MaxValue;
  172. else if (double.IsNegativeInfinity(doubleVal))
  173. intVal = int.MinValue;
  174. else
  175. intVal = (int) doubleVal;
  176. return intVal;
  177. }
  178. private JsValue Substring(JsValue thisObj, JsValue[] arguments)
  179. {
  180. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  181. var s = TypeConverter.ToString(thisObj);
  182. var start = TypeConverter.ToNumber(arguments.At(0));
  183. var end = TypeConverter.ToNumber(arguments.At(1));
  184. if (double.IsNaN(start) || start < 0)
  185. {
  186. start = 0;
  187. }
  188. if (double.IsNaN(end) || end < 0)
  189. {
  190. end = 0;
  191. }
  192. var len = s.Length;
  193. var intStart = ToIntegerSupportInfinity(start);
  194. var intEnd = ReferenceEquals(arguments.At(1), Undefined) ? len : ToIntegerSupportInfinity(end);
  195. var finalStart = System.Math.Min(len, System.Math.Max(intStart, 0));
  196. var finalEnd = System.Math.Min(len, System.Math.Max(intEnd, 0));
  197. // Swap value if finalStart < finalEnd
  198. var from = System.Math.Min(finalStart, finalEnd);
  199. var to = System.Math.Max(finalStart, finalEnd);
  200. var length = to - from;
  201. if (length == 0)
  202. {
  203. return string.Empty;
  204. }
  205. if (length == 1)
  206. {
  207. return TypeConverter.ToString(s[from]);
  208. }
  209. return s.Substring(from, length);
  210. }
  211. private JsValue Substr(JsValue thisObj, JsValue[] arguments)
  212. {
  213. var s = TypeConverter.ToString(thisObj);
  214. var start = TypeConverter.ToInteger(arguments.At(0));
  215. var length = arguments.At(1) == JsValue.Undefined
  216. ? double.PositiveInfinity
  217. : TypeConverter.ToInteger(arguments.At(1));
  218. start = start >= 0 ? start : System.Math.Max(s.Length + start, 0);
  219. length = System.Math.Min(System.Math.Max(length, 0), s.Length - start);
  220. if (length <= 0)
  221. {
  222. return "";
  223. }
  224. var startIndex = TypeConverter.ToInt32(start);
  225. var l = TypeConverter.ToInt32(length);
  226. if (l == 1)
  227. {
  228. return TypeConverter.ToString(s[startIndex]);
  229. }
  230. return s.Substring(startIndex, l);
  231. }
  232. private JsValue Split(JsValue thisObj, JsValue[] arguments)
  233. {
  234. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  235. var s = TypeConverter.ToString(thisObj);
  236. var separator = arguments.At(0);
  237. // Coerce into a number, true will become 1
  238. var l = arguments.At(1);
  239. var limit = ReferenceEquals(l, Undefined) ? uint.MaxValue : TypeConverter.ToUint32(l);
  240. var len = s.Length;
  241. if (limit == 0)
  242. {
  243. return Engine.Array.Construct(Arguments.Empty);
  244. }
  245. if (ReferenceEquals(separator, Null))
  246. {
  247. separator = Native.Null.Text;
  248. }
  249. else if (ReferenceEquals(separator, Undefined))
  250. {
  251. return (ArrayInstance)Engine.Array.Construct(Arguments.From(s));
  252. }
  253. else
  254. {
  255. if (!separator.IsRegExp())
  256. {
  257. separator = TypeConverter.ToString(separator); // Coerce into a string, for an object call toString()
  258. }
  259. }
  260. var rx = TypeConverter.ToObject(Engine, separator) as RegExpInstance;
  261. const string regExpForMatchingAllCharactere = "(?:)";
  262. if (rx != null &&
  263. rx.Source != regExpForMatchingAllCharactere // We need pattern to be defined -> for s.split(new RegExp)
  264. )
  265. {
  266. var a = (ArrayInstance) Engine.Array.Construct(Arguments.Empty);
  267. var match = rx.Value.Match(s, 0);
  268. if (!match.Success) // No match at all return the string in an array
  269. {
  270. a.SetIndexValue(0, s, throwOnError: false);
  271. return a;
  272. }
  273. int lastIndex = 0;
  274. uint index = 0;
  275. while (match.Success && index < limit)
  276. {
  277. if (match.Length == 0 && (match.Index == 0 || match.Index == len || match.Index == lastIndex))
  278. {
  279. match = match.NextMatch();
  280. continue;
  281. }
  282. // Add the match results to the array.
  283. a.SetIndexValue(index++, s.Substring(lastIndex, match.Index - lastIndex), throwOnError: false);
  284. if (index >= limit)
  285. {
  286. return a;
  287. }
  288. lastIndex = match.Index + match.Length;
  289. for (int i = 1; i < match.Groups.Count; i++)
  290. {
  291. var group = match.Groups[i];
  292. var item = Undefined;
  293. if (group.Captures.Count > 0)
  294. {
  295. item = match.Groups[i].Value;
  296. }
  297. a.SetIndexValue(index++, item, throwOnError: false);
  298. if (index >= limit)
  299. {
  300. return a;
  301. }
  302. }
  303. match = match.NextMatch();
  304. if (!match.Success) // Add the last part of the split
  305. {
  306. a.SetIndexValue(index++, s.Substring(lastIndex), throwOnError: false);
  307. }
  308. }
  309. return a;
  310. }
  311. else
  312. {
  313. var segments = _splitSegmentList = _splitSegmentList ?? new List<string>();
  314. segments.Clear();
  315. var sep = TypeConverter.ToString(separator);
  316. if (sep == string.Empty || (rx != null && rx.Source == regExpForMatchingAllCharactere)) // for s.split(new RegExp)
  317. {
  318. if (s.Length > segments.Capacity)
  319. {
  320. segments.Capacity = s.Length;
  321. }
  322. foreach (var c in s)
  323. {
  324. segments.Add(TypeConverter.ToString(c));
  325. }
  326. }
  327. else
  328. {
  329. var array = _splitArray1 = _splitArray1 ?? new string[1];
  330. array[0] = sep;
  331. segments.AddRange(s.Split(array, StringSplitOptions.None));
  332. }
  333. var a = Engine.Array.Construct(Arguments.Empty, (uint) segments.Count);
  334. for (int i = 0; i < segments.Count && i < limit; i++)
  335. {
  336. a.SetIndexValue((uint) i, segments[i], throwOnError: false);
  337. }
  338. return a;
  339. }
  340. }
  341. private JsValue Slice(JsValue thisObj, JsValue[] arguments)
  342. {
  343. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  344. var start = TypeConverter.ToNumber(arguments.At(0));
  345. if (double.NegativeInfinity.Equals(start))
  346. {
  347. start = 0;
  348. }
  349. if (double.PositiveInfinity.Equals(start))
  350. {
  351. return string.Empty;
  352. }
  353. var s = TypeConverter.ToString(thisObj);
  354. var end = TypeConverter.ToNumber(arguments.At(1));
  355. if (double.PositiveInfinity.Equals(end))
  356. {
  357. end = s.Length;
  358. }
  359. var len = s.Length;
  360. var intStart = (int)TypeConverter.ToInteger(start);
  361. var intEnd = ReferenceEquals(arguments.At(1), Undefined) ? len : (int)TypeConverter.ToInteger(end);
  362. var from = intStart < 0 ? System.Math.Max(len + intStart, 0) : System.Math.Min(intStart, len);
  363. var to = intEnd < 0 ? System.Math.Max(len + intEnd, 0) : System.Math.Min(intEnd, len);
  364. var span = System.Math.Max(to - from, 0);
  365. if (span == 0)
  366. {
  367. return string.Empty;
  368. }
  369. if (span == 1)
  370. {
  371. return TypeConverter.ToString(s[from]);
  372. }
  373. return s.Substring(from, span);
  374. }
  375. private JsValue Search(JsValue thisObj, JsValue[] arguments)
  376. {
  377. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  378. var s = TypeConverter.ToString(thisObj);
  379. var regex = arguments.At(0);
  380. if (regex.IsUndefined())
  381. {
  382. regex = string.Empty;
  383. }
  384. else if (regex.IsNull())
  385. {
  386. regex = Native.Null.Text;
  387. }
  388. var rx = TypeConverter.ToObject(Engine, regex) as RegExpInstance ?? (RegExpInstance)Engine.RegExp.Construct(new[] { regex });
  389. var match = rx.Value.Match(s);
  390. if (!match.Success)
  391. {
  392. return -1;
  393. }
  394. return match.Index;
  395. }
  396. private JsValue Replace(JsValue thisObj, JsValue[] arguments)
  397. {
  398. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  399. var thisString = TypeConverter.ToString(thisObj);
  400. var searchValue = arguments.At(0);
  401. var replaceValue = arguments.At(1);
  402. // If the second parameter is not a function we create one
  403. var replaceFunction = replaceValue.TryCast<FunctionInstance>();
  404. if (replaceFunction == null)
  405. {
  406. replaceFunction = new ClrFunctionInstance(Engine, (self, args) =>
  407. {
  408. var replaceString = TypeConverter.ToString(replaceValue);
  409. var matchValue = TypeConverter.ToString(args.At(0));
  410. var matchIndex = (int)TypeConverter.ToInteger(args.At(args.Length - 2));
  411. // Check if the replacement string contains any patterns.
  412. bool replaceTextContainsPattern = replaceString.IndexOf('$') >= 0;
  413. // If there is no pattern, replace the pattern as is.
  414. if (replaceTextContainsPattern == false)
  415. return replaceString;
  416. // Patterns
  417. // $$ Inserts a "$".
  418. // $& Inserts the matched substring.
  419. // $` Inserts the portion of the string that precedes the matched substring.
  420. // $' Inserts the portion of the string that follows the matched substring.
  421. // $n or $nn Where n or nn are decimal digits, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object.
  422. var replacementBuilder = GetStringBuilder(0);
  423. replacementBuilder.Clear();
  424. for (int i = 0; i < replaceString.Length; i++)
  425. {
  426. char c = replaceString[i];
  427. if (c == '$' && i < replaceString.Length - 1)
  428. {
  429. c = replaceString[++i];
  430. if (c == '$')
  431. replacementBuilder.Append('$');
  432. else if (c == '&')
  433. replacementBuilder.Append(matchValue);
  434. else if (c == '`')
  435. replacementBuilder.Append(thisString.Substring(0, matchIndex));
  436. else if (c == '\'')
  437. replacementBuilder.Append(thisString.Substring(matchIndex + matchValue.Length));
  438. else if (c >= '0' && c <= '9')
  439. {
  440. int matchNumber1 = c - '0';
  441. // The match number can be one or two digits long.
  442. int matchNumber2 = 0;
  443. if (i < replaceString.Length - 1 && replaceString[i + 1] >= '0' && replaceString[i + 1] <= '9')
  444. matchNumber2 = matchNumber1 * 10 + (replaceString[i + 1] - '0');
  445. // Try the two digit capture first.
  446. if (matchNumber2 > 0 && matchNumber2 < args.Length - 2)
  447. {
  448. // Two digit capture replacement.
  449. replacementBuilder.Append(TypeConverter.ToString(args[matchNumber2]));
  450. i++;
  451. }
  452. else if (matchNumber1 > 0 && matchNumber1 < args.Length - 2)
  453. {
  454. // Single digit capture replacement.
  455. replacementBuilder.Append(TypeConverter.ToString(args[matchNumber1]));
  456. }
  457. else
  458. {
  459. // Capture does not exist.
  460. replacementBuilder.Append('$');
  461. i--;
  462. }
  463. }
  464. else
  465. {
  466. // Unknown replacement pattern.
  467. replacementBuilder.Append('$');
  468. replacementBuilder.Append(c);
  469. }
  470. }
  471. else
  472. replacementBuilder.Append(c);
  473. }
  474. return replacementBuilder.ToString();
  475. });
  476. }
  477. // searchValue is a regular expression
  478. if (searchValue.IsNull())
  479. {
  480. searchValue = Native.Null.Text;
  481. }
  482. if (searchValue.IsUndefined())
  483. {
  484. searchValue = Native.Undefined.Text;
  485. }
  486. var rx = TypeConverter.ToObject(Engine, searchValue) as RegExpInstance;
  487. if (rx != null)
  488. {
  489. // Replace the input string with replaceText, recording the last match found.
  490. string result = rx.Value.Replace(thisString, match =>
  491. {
  492. var args = new JsValue[match.Groups.Count + 2];
  493. for (var k = 0; k < match.Groups.Count; k++)
  494. {
  495. var group = match.Groups[k];
  496. args[k] = @group.Value;
  497. }
  498. args[match.Groups.Count] = match.Index;
  499. args[match.Groups.Count + 1] = thisString;
  500. var v = TypeConverter.ToString(replaceFunction.Call(Undefined, args));
  501. return v;
  502. }, rx.Global == true ? -1 : 1);
  503. // Set the deprecated RegExp properties if at least one match was found.
  504. //if (lastMatch != null)
  505. // this.Engine.RegExp.SetDeprecatedProperties(input, lastMatch);
  506. return result;
  507. }
  508. // searchValue is a string
  509. else
  510. {
  511. var substr = TypeConverter.ToString(searchValue);
  512. // Find the first occurrance of substr.
  513. int start = thisString.IndexOf(substr, StringComparison.Ordinal);
  514. if (start == -1)
  515. return thisString;
  516. int end = start + substr.Length;
  517. var args = _callArray3 = _callArray3 ?? new JsValue[3];
  518. args[0] = substr;
  519. args[1] = start;
  520. args[2] = thisString;
  521. var replaceString = TypeConverter.ToString(replaceFunction.Call(Undefined, args));
  522. // Replace only the first match.
  523. var result = GetStringBuilder(thisString.Length + (substr.Length - substr.Length));
  524. result.Clear();
  525. result.Append(thisString, 0, start);
  526. result.Append(replaceString);
  527. result.Append(thisString, end, thisString.Length - end);
  528. return result.ToString();
  529. }
  530. }
  531. private JsValue Match(JsValue thisObj, JsValue[] arguments)
  532. {
  533. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  534. var s = TypeConverter.ToString(thisObj);
  535. var regex = arguments.At(0);
  536. var rx = regex.TryCast<RegExpInstance>();
  537. rx = rx ?? (RegExpInstance) Engine.RegExp.Construct(new[] {regex});
  538. var global = rx.Get("global").AsBoolean();
  539. if (!global)
  540. {
  541. return Engine.RegExp.PrototypeObject.Exec(rx, Arguments.From(s));
  542. }
  543. else
  544. {
  545. rx.Put("lastIndex", 0, false);
  546. var a = (ArrayInstance) Engine.Array.Construct(Arguments.Empty);
  547. double previousLastIndex = 0;
  548. uint n = 0;
  549. var lastMatch = true;
  550. while (lastMatch)
  551. {
  552. var result = Engine.RegExp.PrototypeObject.Exec(rx, Arguments.From(s)).TryCast<ObjectInstance>();
  553. if (result == null)
  554. {
  555. lastMatch = false;
  556. }
  557. else
  558. {
  559. var thisIndex = rx.Get("lastIndex").AsNumber();
  560. if (thisIndex == previousLastIndex)
  561. {
  562. rx.Put("lastIndex", thisIndex + 1, false);
  563. previousLastIndex = thisIndex;
  564. }
  565. var matchStr = result.Get("0");
  566. a.SetIndexValue(n, matchStr, throwOnError: false);
  567. n++;
  568. }
  569. }
  570. if (n == 0)
  571. {
  572. return Null;
  573. }
  574. return a;
  575. }
  576. }
  577. private JsValue LocaleCompare(JsValue thisObj, JsValue[] arguments)
  578. {
  579. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  580. var s = TypeConverter.ToString(thisObj);
  581. var that = TypeConverter.ToString(arguments.At(0));
  582. return string.CompareOrdinal(s, that);
  583. }
  584. private JsValue LastIndexOf(JsValue thisObj, JsValue[] arguments)
  585. {
  586. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  587. var s = TypeConverter.ToString(thisObj);
  588. var searchStr = TypeConverter.ToString(arguments.At(0));
  589. double numPos = double.NaN;
  590. if (arguments.Length > 1 && arguments[1] != Undefined)
  591. {
  592. numPos = TypeConverter.ToNumber(arguments[1]);
  593. }
  594. var pos = double.IsNaN(numPos) ? double.PositiveInfinity : TypeConverter.ToInteger(numPos);
  595. var len = s.Length;
  596. var start = (int)System.Math.Min(System.Math.Max(pos, 0), len);
  597. var searchLen = searchStr.Length;
  598. var i = start;
  599. bool found;
  600. do
  601. {
  602. found = true;
  603. var j = 0;
  604. while (found && j < searchLen)
  605. {
  606. if ((i + searchLen > len) || (s[i + j] != searchStr[j]))
  607. {
  608. found = false;
  609. }
  610. else
  611. {
  612. j++;
  613. }
  614. }
  615. if (!found)
  616. {
  617. i--;
  618. }
  619. } while (!found && i >= 0);
  620. return i;
  621. }
  622. private JsValue IndexOf(JsValue thisObj, JsValue[] arguments)
  623. {
  624. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  625. var s = TypeConverter.ToString(thisObj);
  626. var searchStr = TypeConverter.ToString(arguments.At(0));
  627. double pos = 0;
  628. if (arguments.Length > 1 && arguments[1] != Undefined)
  629. {
  630. pos = TypeConverter.ToInteger(arguments[1]);
  631. }
  632. if (pos >= s.Length)
  633. {
  634. return -1;
  635. }
  636. if (pos < 0)
  637. {
  638. pos = 0;
  639. }
  640. return s.IndexOf(searchStr, (int) pos, StringComparison.Ordinal);
  641. }
  642. private JsValue Concat(JsValue thisObj, JsValue[] arguments)
  643. {
  644. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  645. // try to hint capacity if possible
  646. int capacity = 0;
  647. for (int i = 0; i < arguments.Length; ++i)
  648. {
  649. if (arguments[i].Type == Types.String)
  650. {
  651. capacity += arguments[i].AsString().Length;
  652. }
  653. }
  654. var value = TypeConverter.ToString(thisObj);
  655. capacity += value.Length;
  656. if (!(thisObj is JsString jsString))
  657. {
  658. jsString = new JsString.ConcatenatedString(value, capacity);
  659. }
  660. else
  661. {
  662. jsString = jsString.EnsureCapacity(capacity);
  663. }
  664. for (int i = 0; i < arguments.Length; i++)
  665. {
  666. jsString = jsString.Append(arguments[i]);
  667. }
  668. return jsString;
  669. }
  670. private JsValue CharCodeAt(JsValue thisObj, JsValue[] arguments)
  671. {
  672. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  673. JsValue pos = arguments.Length > 0 ? arguments[0] : 0;
  674. var s = TypeConverter.ToString(thisObj);
  675. var position = (int)TypeConverter.ToInteger(pos);
  676. if (position < 0 || position >= s.Length)
  677. {
  678. return double.NaN;
  679. }
  680. return (double) s[position];
  681. }
  682. private JsValue CharAt(JsValue thisObj, JsValue[] arguments)
  683. {
  684. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  685. var s = TypeConverter.ToString(thisObj);
  686. var position = TypeConverter.ToInteger(arguments.At(0));
  687. var size = s.Length;
  688. if (position >= size || position < 0)
  689. {
  690. return "";
  691. }
  692. return TypeConverter.ToString(s[(int) position]);
  693. }
  694. private JsValue ValueOf(JsValue thisObj, JsValue[] arguments)
  695. {
  696. var s = thisObj.TryCast<StringInstance>();
  697. if (s == null)
  698. {
  699. throw new JavaScriptException(Engine.TypeError);
  700. }
  701. return s.PrimitiveValue;
  702. }
  703. /// <summary>
  704. /// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
  705. /// </summary>
  706. /// <param name="thisObj">The original string object</param>
  707. /// <param name="arguments">
  708. /// argument[0] is the target length of the output string
  709. /// argument[1] is the string to pad with
  710. /// </param>
  711. /// <returns></returns>
  712. private JsValue PadStart(JsValue thisObj, JsValue[] arguments)
  713. {
  714. return Pad(thisObj, arguments, true);
  715. }
  716. /// <summary>
  717. /// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd
  718. /// </summary>
  719. /// <param name="thisObj">The original string object</param>
  720. /// <param name="arguments">
  721. /// argument[0] is the target length of the output string
  722. /// argument[1] is the string to pad with
  723. /// </param>
  724. /// <returns></returns>
  725. private JsValue PadEnd(JsValue thisObj, JsValue[] arguments)
  726. {
  727. return Pad(thisObj, arguments, false);
  728. }
  729. private JsValue Pad(JsValue thisObj, JsValue[] arguments, bool padStart)
  730. {
  731. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  732. var targetLength = TypeConverter.ToInt32(arguments.At(0));
  733. var padString = TypeConverter.ToString(arguments.At(1, " "));
  734. var s = TypeConverter.ToString(thisObj);
  735. if (s.Length > targetLength)
  736. {
  737. return s;
  738. }
  739. targetLength = targetLength - s.Length;
  740. if (targetLength > padString.Length)
  741. {
  742. padString = string.Join("", Enumerable.Repeat(padString, (targetLength / padString.Length) + 1));
  743. }
  744. return padStart ? $"{padString.Substring(0, targetLength)}{s}" : $"{s}{padString.Substring(0, targetLength)}";
  745. }
  746. /// <summary>
  747. /// https://www.ecma-international.org/ecma-262/6.0/#sec-string.prototype.startswith
  748. /// </summary>
  749. /// <param name="thisObj"></param>
  750. /// <param name="arguments"></param>
  751. /// <returns></returns>
  752. private JsValue StartsWith(JsValue thisObj, JsValue[] arguments)
  753. {
  754. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  755. var s = TypeConverter.ToString(thisObj);
  756. var searchString = arguments.At(0);
  757. if (ReferenceEquals(searchString, Null))
  758. {
  759. searchString = Native.Null.Text;
  760. }
  761. else
  762. {
  763. if (searchString.IsRegExp())
  764. {
  765. throw new JavaScriptException(Engine.TypeError);
  766. }
  767. }
  768. var searchStr = TypeConverter.ToString(searchString);
  769. var pos = TypeConverter.ToInt32(arguments.At(1));
  770. var len = s.Length;
  771. var start = System.Math.Min(System.Math.Max(pos, 0), len);
  772. var searchLength = searchStr.Length;
  773. if (searchLength + start > len)
  774. {
  775. return false;
  776. }
  777. for (var i = 0; i < searchLength; i++)
  778. {
  779. if (s[start + i] != searchStr[i])
  780. {
  781. return false;
  782. }
  783. }
  784. return true;
  785. }
  786. }
  787. }