StringPrototype.cs 28 KB

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