StringPrototype.cs 23 KB

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