StringPrototype.cs 24 KB

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