StringPrototype.cs 22 KB

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