StringPrototype.cs 29 KB

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