StringPrototype.cs 31 KB

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