StringPrototype.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  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), 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. private JsValue Trim(JsValue thisObj, JsValue[] arguments)
  65. {
  66. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  67. var s = TypeConverter.ToString(thisObj);
  68. return s.Trim();
  69. }
  70. private static JsValue ToLocaleUpperCase(JsValue thisObj, JsValue[] arguments)
  71. {
  72. var s = TypeConverter.ToString(thisObj);
  73. return s.ToUpper();
  74. }
  75. private static JsValue ToUpperCase(JsValue thisObj, JsValue[] arguments)
  76. {
  77. var s = TypeConverter.ToString(thisObj);
  78. return s.ToUpperInvariant();
  79. }
  80. private static JsValue ToLocaleLowerCase(JsValue thisObj, JsValue[] arguments)
  81. {
  82. var s = TypeConverter.ToString(thisObj);
  83. return s.ToLower();
  84. }
  85. private static JsValue ToLowerCase(JsValue thisObj, JsValue[] arguments)
  86. {
  87. var s = TypeConverter.ToString(thisObj);
  88. return s.ToLowerInvariant();
  89. }
  90. private static int ToIntegerSupportInfinity(JsValue numberVal)
  91. {
  92. var doubleVal = TypeConverter.ToInteger(numberVal);
  93. var intVal = (int) doubleVal;
  94. if (double.IsPositiveInfinity(doubleVal))
  95. intVal = int.MaxValue;
  96. else if (double.IsNegativeInfinity(doubleVal))
  97. intVal = int.MinValue;
  98. else
  99. intVal = (int) doubleVal;
  100. return intVal;
  101. }
  102. private JsValue Substring(JsValue thisObj, JsValue[] arguments)
  103. {
  104. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  105. var s = TypeConverter.ToString(thisObj);
  106. var start = TypeConverter.ToNumber(arguments.At(0));
  107. var end = TypeConverter.ToNumber(arguments.At(1));
  108. if (double.IsNaN(start) || start < 0)
  109. {
  110. start = 0;
  111. }
  112. if (double.IsNaN(end) || end < 0)
  113. {
  114. end = 0;
  115. }
  116. var len = s.Length;
  117. var intStart = ToIntegerSupportInfinity(start);
  118. var intEnd = arguments.At(1) == Undefined.Instance ? len : (int)ToIntegerSupportInfinity(end);
  119. var finalStart = System.Math.Min(len, System.Math.Max(intStart, 0));
  120. var finalEnd = System.Math.Min(len, System.Math.Max(intEnd, 0));
  121. // Swap value if finalStart < finalEnd
  122. var from = System.Math.Min(finalStart, finalEnd);
  123. var to = System.Math.Max(finalStart, finalEnd);
  124. return s.Substring(from, to - from);
  125. }
  126. private JsValue Split(JsValue thisObj, JsValue[] arguments)
  127. {
  128. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  129. var s = TypeConverter.ToString(thisObj);
  130. var separator = arguments.At(0);
  131. // Coerce into a number, true will become 1
  132. var l = arguments.At(1);
  133. var a = (ArrayInstance) Engine.Array.Construct(Arguments.Empty);
  134. var limit = l == Undefined.Instance ? UInt32.MaxValue : TypeConverter.ToUint32(l);
  135. var len = s.Length;
  136. if (limit == 0)
  137. {
  138. return a;
  139. }
  140. if (separator == Null.Instance)
  141. {
  142. separator = Null.Text;
  143. }
  144. else if (separator == Undefined.Instance)
  145. {
  146. return (ArrayInstance)Engine.Array.Construct(Arguments.From(s));
  147. }
  148. else
  149. {
  150. if (!separator.IsRegExp())
  151. {
  152. separator = TypeConverter.ToString(separator); // Coerce into a string, for an object call toString()
  153. }
  154. }
  155. var rx = TypeConverter.ToObject(Engine, separator) as RegExpInstance;
  156. const string regExpForMatchingAllCharactere = "(?:)";
  157. if (rx != null &&
  158. rx.Source != regExpForMatchingAllCharactere // We need pattern to be defined -> for s.split(new RegExp)
  159. )
  160. {
  161. var match = rx.Value.Match(s, 0);
  162. if (!match.Success) // No match at all return the string in an array
  163. {
  164. a.DefineOwnProperty("0", new PropertyDescriptor(s, true, true, true), false);
  165. return a;
  166. }
  167. int lastIndex = 0;
  168. int index = 0;
  169. while (match.Success && index < limit)
  170. {
  171. if (match.Length == 0 && (match.Index == 0 || match.Index == len || match.Index == lastIndex))
  172. {
  173. match = match.NextMatch();
  174. continue;
  175. }
  176. // Add the match results to the array.
  177. a.DefineOwnProperty(index++.ToString(), new PropertyDescriptor(s.Substring(lastIndex, match.Index - lastIndex), true, true, true), false);
  178. if (index >= limit)
  179. {
  180. return a;
  181. }
  182. lastIndex = match.Index + match.Length;
  183. for (int i = 1; i < match.Groups.Count; i++)
  184. {
  185. var group = match.Groups[i];
  186. var item = Undefined.Instance;
  187. if (group.Captures.Count > 0)
  188. {
  189. item = match.Groups[i].Value;
  190. }
  191. a.DefineOwnProperty(index++.ToString(), new PropertyDescriptor(item, true, true, true ), false);
  192. if (index >= limit)
  193. {
  194. return a;
  195. }
  196. }
  197. match = match.NextMatch();
  198. if (!match.Success) // Add the last part of the split
  199. {
  200. a.DefineOwnProperty(index++.ToString(), new PropertyDescriptor(s.Substring(lastIndex), true, true, true), false);
  201. }
  202. }
  203. return a;
  204. }
  205. else
  206. {
  207. var segments = new List<string>();
  208. var sep = TypeConverter.ToString(separator);
  209. if (sep == string.Empty || (rx != null && rx.Source == regExpForMatchingAllCharactere)) // for s.split(new RegExp)
  210. {
  211. segments.AddRange(from object c in s select c.ToString());
  212. }
  213. else
  214. {
  215. segments = s.Split(new[] {sep}, StringSplitOptions.None).ToList();
  216. }
  217. for (int i = 0; i < segments.Count && i < limit; i++)
  218. {
  219. a.DefineOwnProperty(i.ToString(), new PropertyDescriptor(segments[i], true, true, true), false);
  220. }
  221. return a;
  222. }
  223. }
  224. private JsValue Slice(JsValue thisObj, JsValue[] arguments)
  225. {
  226. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  227. var s = TypeConverter.ToString(thisObj);
  228. var start = TypeConverter.ToNumber(arguments.At(0));
  229. if (start == double.NegativeInfinity)
  230. {
  231. start = 0;
  232. }
  233. if (start == double.PositiveInfinity)
  234. {
  235. return string.Empty;
  236. }
  237. var end = TypeConverter.ToNumber(arguments.At(1));
  238. if (end == double.PositiveInfinity)
  239. {
  240. end = s.Length;
  241. }
  242. var len = s.Length;
  243. var intStart = (int)TypeConverter.ToInteger(start);
  244. var intEnd = arguments.At(1) == Undefined.Instance ? len : (int)TypeConverter.ToInteger(end);
  245. var from = intStart < 0 ? System.Math.Max(len + intStart, 0) : System.Math.Min(intStart, len);
  246. var to = intEnd < 0 ? System.Math.Max(len + intEnd, 0) : System.Math.Min(intEnd, len);
  247. var span = System.Math.Max(to - from, 0);
  248. return s.Substring(from, span);
  249. }
  250. private JsValue Search(JsValue thisObj, JsValue[] arguments)
  251. {
  252. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  253. var s = TypeConverter.ToString(thisObj);
  254. var regex = arguments.At(0);
  255. if (regex.IsUndefined())
  256. {
  257. regex = string.Empty;
  258. }
  259. else if (regex.IsNull())
  260. {
  261. regex = Null.Text;
  262. }
  263. var rx = TypeConverter.ToObject(Engine, regex) as RegExpInstance ?? (RegExpInstance)Engine.RegExp.Construct(new[] { regex });
  264. var match = rx.Value.Match(s);
  265. if (!match.Success)
  266. {
  267. return -1;
  268. }
  269. return match.Index;
  270. }
  271. private JsValue Replace(JsValue thisObj, JsValue[] arguments)
  272. {
  273. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  274. var thisString = TypeConverter.ToString(thisObj);
  275. var searchValue = arguments.At(0);
  276. var replaceValue = arguments.At(1);
  277. // If the second parameter is not a function we create one
  278. var replaceFunction = replaceValue.TryCast<FunctionInstance>();
  279. if (replaceFunction == null)
  280. {
  281. replaceFunction = new ClrFunctionInstance(Engine, (self, args) =>
  282. {
  283. var replaceString = TypeConverter.ToString(replaceValue);
  284. var matchValue = TypeConverter.ToString(args.At(0));
  285. var matchIndex = (int)TypeConverter.ToInteger(args.At(args.Length - 2));
  286. // Check if the replacement string contains any patterns.
  287. bool replaceTextContainsPattern = replaceString.IndexOf('$') >= 0;
  288. // If there is no pattern, replace the pattern as is.
  289. if (replaceTextContainsPattern == false)
  290. return replaceString;
  291. // Patterns
  292. // $$ Inserts a "$".
  293. // $& Inserts the matched substring.
  294. // $` Inserts the portion of the string that precedes the matched substring.
  295. // $' Inserts the portion of the string that follows the matched substring.
  296. // $n or $nn Where n or nn are decimal digits, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object.
  297. var replacementBuilder = new StringBuilder();
  298. for (int i = 0; i < replaceString.Length; i++)
  299. {
  300. char c = replaceString[i];
  301. if (c == '$' && i < replaceString.Length - 1)
  302. {
  303. c = replaceString[++i];
  304. if (c == '$')
  305. replacementBuilder.Append('$');
  306. else if (c == '&')
  307. replacementBuilder.Append(matchValue);
  308. else if (c == '`')
  309. replacementBuilder.Append(thisString.Substring(0, matchIndex));
  310. else if (c == '\'')
  311. replacementBuilder.Append(thisString.Substring(matchIndex + matchValue.Length));
  312. else if (c >= '0' && c <= '9')
  313. {
  314. int matchNumber1 = c - '0';
  315. // The match number can be one or two digits long.
  316. int matchNumber2 = 0;
  317. if (i < replaceString.Length - 1 && replaceString[i + 1] >= '0' && replaceString[i + 1] <= '9')
  318. matchNumber2 = matchNumber1 * 10 + (replaceString[i + 1] - '0');
  319. // Try the two digit capture first.
  320. if (matchNumber2 > 0 && matchNumber2 < args.Length - 2)
  321. {
  322. // Two digit capture replacement.
  323. replacementBuilder.Append(TypeConverter.ToString(args[matchNumber2]));
  324. i++;
  325. }
  326. else if (matchNumber1 > 0 && matchNumber1 < args.Length - 2)
  327. {
  328. // Single digit capture replacement.
  329. replacementBuilder.Append(TypeConverter.ToString(args[matchNumber1]));
  330. }
  331. else
  332. {
  333. // Capture does not exist.
  334. replacementBuilder.Append('$');
  335. i--;
  336. }
  337. }
  338. else
  339. {
  340. // Unknown replacement pattern.
  341. replacementBuilder.Append('$');
  342. replacementBuilder.Append(c);
  343. }
  344. }
  345. else
  346. replacementBuilder.Append(c);
  347. }
  348. return replacementBuilder.ToString();
  349. });
  350. }
  351. // searchValue is a regular expression
  352. if (searchValue.IsNull())
  353. {
  354. searchValue = new JsValue(Null.Text);
  355. }
  356. if (searchValue.IsUndefined())
  357. {
  358. searchValue = new JsValue(Undefined.Text);
  359. }
  360. var rx = TypeConverter.ToObject(Engine, searchValue) as RegExpInstance;
  361. if (rx != null)
  362. {
  363. // Replace the input string with replaceText, recording the last match found.
  364. string result = rx.Value.Replace(thisString, match =>
  365. {
  366. var args = new List<JsValue>();
  367. //if (match.Groups.Count == 0) args.Add(match.Value);
  368. for (var k = 0; k < match.Groups.Count; k++)
  369. {
  370. var group = match.Groups[k];
  371. if (group.Success)
  372. args.Add(group.Value);
  373. }
  374. args.Add(match.Index);
  375. args.Add(thisString);
  376. var v = TypeConverter.ToString(replaceFunction.Call(Undefined.Instance, args.ToArray()));
  377. return v;
  378. }, rx.Global == true ? -1 : 1);
  379. // Set the deprecated RegExp properties if at least one match was found.
  380. //if (lastMatch != null)
  381. // this.Engine.RegExp.SetDeprecatedProperties(input, lastMatch);
  382. return result;
  383. }
  384. // searchValue is a string
  385. else
  386. {
  387. var substr = TypeConverter.ToString(searchValue);
  388. // Find the first occurrance of substr.
  389. int start = thisString.IndexOf(substr, StringComparison.Ordinal);
  390. if (start == -1)
  391. return thisString;
  392. int end = start + substr.Length;
  393. var args = new List<JsValue>();
  394. args.Add(substr);
  395. args.Add(start);
  396. args.Add(thisString);
  397. var replaceString = TypeConverter.ToString(replaceFunction.Call(Undefined.Instance, args.ToArray()));
  398. // Replace only the first match.
  399. var result = new StringBuilder(thisString.Length + (substr.Length - substr.Length));
  400. result.Append(thisString, 0, start);
  401. result.Append(replaceString);
  402. result.Append(thisString, end, thisString.Length - end);
  403. return result.ToString();
  404. }
  405. }
  406. private JsValue Match(JsValue thisObj, JsValue[] arguments)
  407. {
  408. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  409. var s = TypeConverter.ToString(thisObj);
  410. var regex = arguments.At(0);
  411. var rx = regex.TryCast<RegExpInstance>();
  412. rx = rx ?? (RegExpInstance) Engine.RegExp.Construct(new[] {regex});
  413. var global = rx.Get("global").AsBoolean();
  414. if (!global)
  415. {
  416. return Engine.RegExp.PrototypeObject.Exec(rx, Arguments.From(s));
  417. }
  418. else
  419. {
  420. rx.Put("lastIndex", 0, false);
  421. var a = Engine.Array.Construct(Arguments.Empty);
  422. double previousLastIndex = 0;
  423. var n = 0;
  424. var lastMatch = true;
  425. while (lastMatch)
  426. {
  427. var result = Engine.RegExp.PrototypeObject.Exec(rx, Arguments.From(s)).TryCast<ObjectInstance>();
  428. if (result == null)
  429. {
  430. lastMatch = false;
  431. }
  432. else
  433. {
  434. var thisIndex = rx.Get("lastIndex").AsNumber();
  435. if (thisIndex == previousLastIndex)
  436. {
  437. rx.Put("lastIndex", thisIndex + 1, false);
  438. previousLastIndex = thisIndex;
  439. }
  440. var matchStr = result.Get("0");
  441. a.DefineOwnProperty(TypeConverter.ToString(n), new PropertyDescriptor(matchStr, true, true, true), false);
  442. n++;
  443. }
  444. }
  445. if (n == 0)
  446. {
  447. return Null.Instance;
  448. }
  449. return a;
  450. }
  451. }
  452. private JsValue LocaleCompare(JsValue thisObj, JsValue[] arguments)
  453. {
  454. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  455. var s = TypeConverter.ToString(thisObj);
  456. var that = TypeConverter.ToString(arguments.At(0));
  457. return string.CompareOrdinal(s, that);
  458. }
  459. private JsValue LastIndexOf(JsValue thisObj, JsValue[] arguments)
  460. {
  461. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  462. var s = TypeConverter.ToString(thisObj);
  463. var searchStr = TypeConverter.ToString(arguments.At(0));
  464. double numPos = arguments.At(0) == Undefined.Instance ? double.NaN : TypeConverter.ToNumber(arguments.At(0));
  465. double pos = double.IsNaN(numPos) ? double.PositiveInfinity : TypeConverter.ToInteger(numPos);
  466. var len = s.Length;
  467. var start = System.Math.Min(len, System.Math.Max(pos, 0));
  468. var searchLen = searchStr.Length;
  469. return s.LastIndexOf(searchStr, len - (int) start, StringComparison.Ordinal);
  470. }
  471. private JsValue IndexOf(JsValue thisObj, JsValue[] arguments)
  472. {
  473. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  474. var s = TypeConverter.ToString(thisObj);
  475. var searchStr = TypeConverter.ToString(arguments.At(0));
  476. double pos = 0;
  477. if (arguments.Length > 1 && arguments[1] != Undefined.Instance)
  478. {
  479. pos = TypeConverter.ToInteger(arguments[1]);
  480. }
  481. if (pos >= s.Length)
  482. {
  483. return -1;
  484. }
  485. if (pos < 0)
  486. {
  487. pos = 0;
  488. }
  489. return s.IndexOf(searchStr, (int) pos, StringComparison.Ordinal);
  490. }
  491. private JsValue Concat(JsValue thisObj, JsValue[] arguments)
  492. {
  493. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  494. var s = TypeConverter.ToString(thisObj);
  495. var sb = new StringBuilder(s);
  496. for (int i = 0; i < arguments.Length; i++)
  497. {
  498. sb.Append(TypeConverter.ToString(arguments[i]));
  499. }
  500. return sb.ToString();
  501. }
  502. private JsValue CharCodeAt(JsValue thisObj, JsValue[] arguments)
  503. {
  504. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  505. JsValue pos = arguments.Length > 0 ? arguments[0] : 0;
  506. var s = TypeConverter.ToString(thisObj);
  507. var position = (int)TypeConverter.ToInteger(pos);
  508. if (position < 0 || position >= s.Length)
  509. {
  510. return double.NaN;
  511. }
  512. return s[position];
  513. }
  514. private JsValue CharAt(JsValue thisObj, JsValue[] arguments)
  515. {
  516. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  517. var s = TypeConverter.ToString(thisObj);
  518. var position = TypeConverter.ToInteger(arguments.At(0));
  519. var size = s.Length;
  520. if (position >= size || position < 0)
  521. {
  522. return "";
  523. }
  524. return s[(int) position].ToString();
  525. }
  526. private JsValue ValueOf(JsValue thisObj, JsValue[] arguments)
  527. {
  528. var s = thisObj.TryCast<StringInstance>();
  529. if (s == null)
  530. {
  531. throw new JavaScriptException(Engine.TypeError);
  532. }
  533. return s.PrimitiveValue;
  534. }
  535. }
  536. }