StringPrototype.cs 30 KB

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