StringPrototype.cs 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160
  1. using System;
  2. using System.Linq;
  3. using System.Runtime.CompilerServices;
  4. using System.Text;
  5. using Jint.Collections;
  6. using Jint.Native.Array;
  7. using Jint.Native.Function;
  8. using Jint.Native.Object;
  9. using Jint.Native.RegExp;
  10. using Jint.Native.Symbol;
  11. using Jint.Pooling;
  12. using Jint.Runtime;
  13. using Jint.Runtime.Descriptors;
  14. using Jint.Runtime.Interop;
  15. namespace Jint.Native.String
  16. {
  17. /// <summary>
  18. /// http://www.ecma-international.org/ecma-262/5.1/#sec-15.5.4
  19. /// </summary>
  20. public sealed class StringPrototype : StringInstance
  21. {
  22. private StringConstructor _stringConstructor;
  23. private StringPrototype(Engine engine)
  24. : base(engine)
  25. {
  26. }
  27. public static StringPrototype CreatePrototypeObject(Engine engine, StringConstructor stringConstructor)
  28. {
  29. var obj = new StringPrototype(engine)
  30. {
  31. Prototype = engine.Object.PrototypeObject,
  32. PrimitiveValue = JsString.Empty,
  33. Extensible = true,
  34. _length = PropertyDescriptor.AllForbiddenDescriptor.NumberZero,
  35. _stringConstructor = stringConstructor,
  36. };
  37. return obj;
  38. }
  39. protected override void Initialize()
  40. {
  41. _properties = new StringDictionarySlim<PropertyDescriptor>(40)
  42. {
  43. ["constructor"] = new PropertyDescriptor(_stringConstructor, PropertyFlag.NonEnumerable),
  44. ["toString"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "toString", ToStringString, 0, PropertyFlag.Configurable), true, false, true),
  45. ["valueOf"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "valueOf", ValueOf, 0, PropertyFlag.Configurable), true, false, true),
  46. ["charAt"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "charAt", CharAt, 1, PropertyFlag.Configurable), true, false, true),
  47. ["charCodeAt"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "charCodeAt", CharCodeAt, 1, PropertyFlag.Configurable), true, false, true),
  48. ["codePointAt"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "codePointAt", CodePointAt, 1, PropertyFlag.Configurable), true, false, true),
  49. ["concat"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "concat", Concat, 1, PropertyFlag.Configurable), true, false, true),
  50. ["indexOf"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "indexOf", IndexOf, 1, PropertyFlag.Configurable), true, false, true),
  51. ["endsWith"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "endsWith", EndsWith, 1, PropertyFlag.Configurable), true, false, true),
  52. ["startsWith"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "startsWith", StartsWith, 1, PropertyFlag.Configurable), true, false, true),
  53. ["lastIndexOf"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "lastIndexOf", LastIndexOf, 1, PropertyFlag.Configurable), true, false, true),
  54. ["localeCompare"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "localeCompare", LocaleCompare, 1, PropertyFlag.Configurable), true, false, true),
  55. ["match"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "match", Match, 1, PropertyFlag.Configurable), true, false, true),
  56. ["replace"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "replace", Replace, 2, PropertyFlag.Configurable), true, false, true),
  57. ["search"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "search", Search, 1, PropertyFlag.Configurable), true, false, true),
  58. ["slice"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "slice", Slice, 2, PropertyFlag.Configurable), true, false, true),
  59. ["split"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "split", Split, 2, PropertyFlag.Configurable), true, false, true),
  60. ["substr"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "substr", Substr, 2), true, false, true),
  61. ["substring"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "substring", Substring, 2, PropertyFlag.Configurable), true, false, true),
  62. ["toLowerCase"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "toLowerCase", ToLowerCase, 0, PropertyFlag.Configurable), true, false, true),
  63. ["toLocaleLowerCase"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "toLocaleLowerCase", ToLocaleLowerCase, 0, PropertyFlag.Configurable), true, false, true),
  64. ["toUpperCase"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "toUpperCase", ToUpperCase, 0, PropertyFlag.Configurable), true, false, true),
  65. ["toLocaleUpperCase"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "toLocaleUpperCase", ToLocaleUpperCase, 0, PropertyFlag.Configurable), true, false, true),
  66. ["trim"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "trim", Trim, 0, PropertyFlag.Configurable), true, false, true),
  67. ["trimStart"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "trimStart", TrimStart, 0, PropertyFlag.Configurable), true, false, true),
  68. ["trimEnd"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "trimEnd", TrimEnd, 0, PropertyFlag.Configurable), true, false, true),
  69. ["padStart"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "padStart", PadStart, 1, PropertyFlag.Configurable), true, false, true),
  70. ["padEnd"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "padEnd", PadEnd, 1, PropertyFlag.Configurable), true, false, true),
  71. ["includes"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "includes", Includes, 1, PropertyFlag.Configurable), true, false, true),
  72. ["normalize"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "normalize", Normalize, 0, PropertyFlag.Configurable), true, false, true),
  73. ["repeat"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "repeat", Repeat, 1, PropertyFlag.Configurable), true, false, true),
  74. [GlobalSymbolRegistry.Iterator._value] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "[Symbol.iterator]", Iterator, 0, PropertyFlag.Configurable), true, false, true)
  75. };
  76. }
  77. private ObjectInstance Iterator(JsValue thisObj, JsValue[] arguments)
  78. {
  79. TypeConverter.CheckObjectCoercible(_engine, thisObj);
  80. var str = TypeConverter.ToString(thisObj);
  81. return _engine.Iterator.Construct(str);
  82. }
  83. private JsValue ToStringString(JsValue thisObj, JsValue[] arguments)
  84. {
  85. var s = TypeConverter.ToObject(Engine, thisObj) as StringInstance;
  86. if (ReferenceEquals(s, null))
  87. {
  88. ExceptionHelper.ThrowTypeError(Engine);
  89. }
  90. return s.PrimitiveValue;
  91. }
  92. // http://msdn.microsoft.com/en-us/library/system.char.iswhitespace(v=vs.110).aspx
  93. // http://en.wikipedia.org/wiki/Byte_order_mark
  94. const char BOM_CHAR = '\uFEFF';
  95. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  96. internal static bool IsWhiteSpaceEx(char c)
  97. {
  98. return char.IsWhiteSpace(c) || c == BOM_CHAR;
  99. }
  100. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  101. public static string TrimEndEx(string s)
  102. {
  103. if (s.Length == 0)
  104. return string.Empty;
  105. if (!IsWhiteSpaceEx(s[s.Length - 1]))
  106. return s;
  107. return TrimEnd(s);
  108. }
  109. private static string TrimEnd(string s)
  110. {
  111. var i = s.Length - 1;
  112. while (i >= 0)
  113. {
  114. if (IsWhiteSpaceEx(s[i]))
  115. i--;
  116. else
  117. break;
  118. }
  119. return i >= 0 ? s.Substring(0, i + 1) : string.Empty;
  120. }
  121. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  122. public static string TrimStartEx(string s)
  123. {
  124. if (s.Length == 0)
  125. return string.Empty;
  126. if (!IsWhiteSpaceEx(s[0]))
  127. return s;
  128. return TrimStart(s);
  129. }
  130. private static string TrimStart(string s)
  131. {
  132. var i = 0;
  133. while (i < s.Length)
  134. {
  135. if (IsWhiteSpaceEx(s[i]))
  136. i++;
  137. else
  138. break;
  139. }
  140. return i >= s.Length ? string.Empty : s.Substring(i);
  141. }
  142. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  143. public static string TrimEx(string s)
  144. {
  145. return TrimEndEx(TrimStartEx(s));
  146. }
  147. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  148. private JsValue Trim(JsValue thisObj, JsValue[] arguments)
  149. {
  150. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  151. var s = TypeConverter.ToString(thisObj);
  152. return TrimEx(s);
  153. }
  154. private JsValue TrimStart(JsValue thisObj, JsValue[] arguments)
  155. {
  156. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  157. var s = TypeConverter.ToString(thisObj);
  158. return TrimStartEx(s);
  159. }
  160. private JsValue TrimEnd(JsValue thisObj, JsValue[] arguments)
  161. {
  162. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  163. var s = TypeConverter.ToString(thisObj);
  164. return TrimEndEx(s);
  165. }
  166. private JsValue ToLocaleUpperCase(JsValue thisObj, JsValue[] arguments)
  167. {
  168. TypeConverter.CheckObjectCoercible(_engine, thisObj);
  169. var s = TypeConverter.ToString(thisObj);
  170. return s.ToUpper();
  171. }
  172. private JsValue ToUpperCase(JsValue thisObj, JsValue[] arguments)
  173. {
  174. TypeConverter.CheckObjectCoercible(_engine, thisObj);
  175. var s = TypeConverter.ToString(thisObj);
  176. return s.ToUpperInvariant();
  177. }
  178. private JsValue ToLocaleLowerCase(JsValue thisObj, JsValue[] arguments)
  179. {
  180. TypeConverter.CheckObjectCoercible(_engine, thisObj);
  181. var s = TypeConverter.ToString(thisObj);
  182. return s.ToLower();
  183. }
  184. private JsValue ToLowerCase(JsValue thisObj, JsValue[] arguments)
  185. {
  186. TypeConverter.CheckObjectCoercible(_engine, thisObj);
  187. var s = TypeConverter.ToString(thisObj);
  188. return s.ToLowerInvariant();
  189. }
  190. private static int ToIntegerSupportInfinity(JsValue numberVal)
  191. {
  192. return numberVal._type == InternalTypes.Integer
  193. ? numberVal.AsInteger()
  194. : ToIntegerSupportInfinityUnlikely(numberVal);
  195. }
  196. [MethodImpl(MethodImplOptions.NoInlining)]
  197. private static int ToIntegerSupportInfinityUnlikely(JsValue numberVal)
  198. {
  199. var doubleVal = TypeConverter.ToInteger(numberVal);
  200. int intVal;
  201. if (double.IsPositiveInfinity(doubleVal))
  202. intVal = int.MaxValue;
  203. else if (double.IsNegativeInfinity(doubleVal))
  204. intVal = int.MinValue;
  205. else
  206. intVal = (int) doubleVal;
  207. return intVal;
  208. }
  209. private JsValue Substring(JsValue thisObj, JsValue[] arguments)
  210. {
  211. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  212. var s = TypeConverter.ToString(thisObj);
  213. var start = TypeConverter.ToNumber(arguments.At(0));
  214. var end = TypeConverter.ToNumber(arguments.At(1));
  215. if (double.IsNaN(start) || start < 0)
  216. {
  217. start = 0;
  218. }
  219. if (double.IsNaN(end) || end < 0)
  220. {
  221. end = 0;
  222. }
  223. var len = s.Length;
  224. var intStart = ToIntegerSupportInfinity(start);
  225. var intEnd = arguments.At(1).IsUndefined() ? len : ToIntegerSupportInfinity(end);
  226. var finalStart = System.Math.Min(len, System.Math.Max(intStart, 0));
  227. var finalEnd = System.Math.Min(len, System.Math.Max(intEnd, 0));
  228. // Swap value if finalStart < finalEnd
  229. var from = System.Math.Min(finalStart, finalEnd);
  230. var to = System.Math.Max(finalStart, finalEnd);
  231. var length = to - from;
  232. if (length == 0)
  233. {
  234. return string.Empty;
  235. }
  236. if (length == 1)
  237. {
  238. return TypeConverter.ToString(s[from]);
  239. }
  240. return s.Substring(from, length);
  241. }
  242. private JsValue Substr(JsValue thisObj, JsValue[] arguments)
  243. {
  244. var s = TypeConverter.ToString(thisObj);
  245. var start = TypeConverter.ToInteger(arguments.At(0));
  246. var length = arguments.At(1).IsUndefined()
  247. ? double.PositiveInfinity
  248. : TypeConverter.ToInteger(arguments.At(1));
  249. start = start >= 0 ? start : System.Math.Max(s.Length + start, 0);
  250. length = System.Math.Min(System.Math.Max(length, 0), s.Length - start);
  251. if (length <= 0)
  252. {
  253. return "";
  254. }
  255. var startIndex = TypeConverter.ToInt32(start);
  256. var l = TypeConverter.ToInt32(length);
  257. if (l == 1)
  258. {
  259. return TypeConverter.ToString(s[startIndex]);
  260. }
  261. return s.Substring(startIndex, l);
  262. }
  263. private JsValue Split(JsValue thisObj, JsValue[] arguments)
  264. {
  265. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  266. var s = TypeConverter.ToString(thisObj);
  267. var separator = arguments.At(0);
  268. // Coerce into a number, true will become 1
  269. var l = arguments.At(1);
  270. var limit = l.IsUndefined() ? uint.MaxValue : TypeConverter.ToUint32(l);
  271. var len = s.Length;
  272. if (limit == 0)
  273. {
  274. return Engine.Array.Construct(Arguments.Empty);
  275. }
  276. if (separator.IsNull())
  277. {
  278. separator = Native.Null.Text;
  279. }
  280. else if (separator.IsUndefined())
  281. {
  282. var jsValues = _engine._jsValueArrayPool.RentArray(1);
  283. jsValues[0] = s;
  284. var arrayInstance = (ArrayInstance)Engine.Array.Construct(jsValues);
  285. _engine._jsValueArrayPool.ReturnArray(jsValues);
  286. return arrayInstance;
  287. }
  288. else
  289. {
  290. if (!separator.IsRegExp())
  291. {
  292. separator = TypeConverter.ToString(separator); // Coerce into a string, for an object call toString()
  293. }
  294. }
  295. var rx = TypeConverter.ToObject(Engine, separator) as RegExpInstance;
  296. const string regExpForMatchingAllCharactere = "(?:)";
  297. if (!ReferenceEquals(rx, null) &&
  298. rx.Source != regExpForMatchingAllCharactere // We need pattern to be defined -> for s.split(new RegExp)
  299. )
  300. {
  301. var a = (ArrayInstance) Engine.Array.Construct(Arguments.Empty);
  302. var match = rx.Value.Match(s, 0);
  303. if (!match.Success) // No match at all return the string in an array
  304. {
  305. a.SetIndexValue(0, s, updateLength: true);
  306. return a;
  307. }
  308. int lastIndex = 0;
  309. uint index = 0;
  310. while (match.Success && index < limit)
  311. {
  312. if (match.Length == 0 && (match.Index == 0 || match.Index == len || match.Index == lastIndex))
  313. {
  314. match = match.NextMatch();
  315. continue;
  316. }
  317. // Add the match results to the array.
  318. a.SetIndexValue(index++, s.Substring(lastIndex, match.Index - lastIndex), updateLength: true);
  319. if (index >= limit)
  320. {
  321. return a;
  322. }
  323. lastIndex = match.Index + match.Length;
  324. for (int i = 1; i < match.Groups.Count; i++)
  325. {
  326. var group = match.Groups[i];
  327. var item = Undefined;
  328. if (group.Captures.Count > 0)
  329. {
  330. item = match.Groups[i].Value;
  331. }
  332. a.SetIndexValue(index++, item, updateLength: true);
  333. if (index >= limit)
  334. {
  335. return a;
  336. }
  337. }
  338. match = match.NextMatch();
  339. if (!match.Success) // Add the last part of the split
  340. {
  341. a.SetIndexValue(index++, s.Substring(lastIndex), updateLength: true);
  342. }
  343. }
  344. return a;
  345. }
  346. else
  347. {
  348. var segments = StringExecutionContext.Current.SplitSegmentList;
  349. segments.Clear();
  350. var sep = TypeConverter.ToString(separator);
  351. if (sep == string.Empty || (!ReferenceEquals(rx, null) && rx.Source == regExpForMatchingAllCharactere)) // for s.split(new RegExp)
  352. {
  353. if (s.Length > segments.Capacity)
  354. {
  355. segments.Capacity = s.Length;
  356. }
  357. for (var i = 0; i < s.Length; i++)
  358. {
  359. segments.Add(TypeConverter.ToString(s[i]));
  360. }
  361. }
  362. else
  363. {
  364. var array = StringExecutionContext.Current.SplitArray1;
  365. array[0] = sep;
  366. segments.AddRange(s.Split(array, StringSplitOptions.None));
  367. }
  368. var length = (uint) System.Math.Min(segments.Count, limit);
  369. var a = Engine.Array.ConstructFast(length);
  370. for (int i = 0; i < length; i++)
  371. {
  372. a.SetIndexValue((uint) i, segments[i], updateLength: false);
  373. }
  374. a.SetLength(length);
  375. return a;
  376. }
  377. }
  378. private JsValue Slice(JsValue thisObj, JsValue[] arguments)
  379. {
  380. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  381. var start = TypeConverter.ToNumber(arguments.At(0));
  382. if (double.IsNegativeInfinity(start))
  383. {
  384. start = 0;
  385. }
  386. if (double.IsPositiveInfinity(start))
  387. {
  388. return string.Empty;
  389. }
  390. var s = TypeConverter.ToString(thisObj);
  391. var end = TypeConverter.ToNumber(arguments.At(1));
  392. if (double.IsPositiveInfinity(end))
  393. {
  394. end = s.Length;
  395. }
  396. var len = s.Length;
  397. var intStart = (int) start;
  398. var intEnd = arguments.At(1).IsUndefined() ? len : (int) TypeConverter.ToInteger(end);
  399. var from = intStart < 0 ? System.Math.Max(len + intStart, 0) : System.Math.Min(intStart, len);
  400. var to = intEnd < 0 ? System.Math.Max(len + intEnd, 0) : System.Math.Min(intEnd, len);
  401. var span = System.Math.Max(to - from, 0);
  402. if (span == 0)
  403. {
  404. return string.Empty;
  405. }
  406. if (span == 1)
  407. {
  408. return TypeConverter.ToString(s[from]);
  409. }
  410. return s.Substring(from, span);
  411. }
  412. private JsValue Search(JsValue thisObj, JsValue[] arguments)
  413. {
  414. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  415. var s = TypeConverter.ToString(thisObj);
  416. var regex = arguments.At(0);
  417. if (regex.IsUndefined())
  418. {
  419. regex = string.Empty;
  420. }
  421. else if (regex.IsNull())
  422. {
  423. regex = Native.Null.Text;
  424. }
  425. var rx = TypeConverter.ToObject(Engine, regex) as RegExpInstance ?? (RegExpInstance)Engine.RegExp.Construct(new[] { regex });
  426. var match = rx.Value.Match(s);
  427. if (!match.Success)
  428. {
  429. return -1;
  430. }
  431. return match.Index;
  432. }
  433. private JsValue Replace(JsValue thisObj, JsValue[] arguments)
  434. {
  435. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  436. var thisString = TypeConverter.ToString(thisObj);
  437. var searchValue = arguments.At(0);
  438. var replaceValue = arguments.At(1);
  439. // If the second parameter is not a function we create one
  440. var replaceFunction = replaceValue.TryCast<FunctionInstance>();
  441. if (ReferenceEquals(replaceFunction, null))
  442. {
  443. replaceFunction = new ClrFunctionInstance(Engine, "anonymous", (self, args) =>
  444. {
  445. var replaceString = TypeConverter.ToString(replaceValue);
  446. var matchValue = TypeConverter.ToString(args.At(0));
  447. var matchIndex = (int)TypeConverter.ToInteger(args.At(args.Length - 2));
  448. // Check if the replacement string contains any patterns.
  449. bool replaceTextContainsPattern = replaceString.IndexOf('$') >= 0;
  450. // If there is no pattern, replace the pattern as is.
  451. if (replaceTextContainsPattern == false)
  452. return replaceString;
  453. // Patterns
  454. // $$ Inserts a "$".
  455. // $& Inserts the matched substring.
  456. // $` Inserts the portion of the string that precedes the matched substring.
  457. // $' Inserts the portion of the string that follows the matched substring.
  458. // $n or $nn Where n or nn are decimal digits, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object.
  459. using (var replacementBuilder = StringBuilderPool.Rent())
  460. {
  461. for (int i = 0; i < replaceString.Length; i++)
  462. {
  463. char c = replaceString[i];
  464. if (c == '$' && i < replaceString.Length - 1)
  465. {
  466. c = replaceString[++i];
  467. if (c == '$')
  468. replacementBuilder.Builder.Append('$');
  469. else if (c == '&')
  470. replacementBuilder.Builder.Append(matchValue);
  471. else if (c == '`')
  472. replacementBuilder.Builder.Append(thisString.Substring(0, matchIndex));
  473. else if (c == '\'')
  474. replacementBuilder.Builder.Append(thisString.Substring(matchIndex + matchValue.Length));
  475. else if (c >= '0' && c <= '9')
  476. {
  477. int matchNumber1 = c - '0';
  478. // The match number can be one or two digits long.
  479. int matchNumber2 = 0;
  480. if (i < replaceString.Length - 1 && replaceString[i + 1] >= '0' && replaceString[i + 1] <= '9')
  481. matchNumber2 = matchNumber1 * 10 + (replaceString[i + 1] - '0');
  482. // Try the two digit capture first.
  483. if (matchNumber2 > 0 && matchNumber2 < args.Length - 2)
  484. {
  485. // Two digit capture replacement.
  486. replacementBuilder.Builder.Append(TypeConverter.ToString(args[matchNumber2]));
  487. i++;
  488. }
  489. else if (matchNumber1 > 0 && matchNumber1 < args.Length - 2)
  490. {
  491. // Single digit capture replacement.
  492. replacementBuilder.Builder.Append(TypeConverter.ToString(args[matchNumber1]));
  493. }
  494. else
  495. {
  496. // Capture does not exist.
  497. replacementBuilder.Builder.Append('$');
  498. i--;
  499. }
  500. }
  501. else
  502. {
  503. // Unknown replacement pattern.
  504. replacementBuilder.Builder.Append('$');
  505. replacementBuilder.Builder.Append(c);
  506. }
  507. }
  508. else
  509. replacementBuilder.Builder.Append(c);
  510. }
  511. return replacementBuilder.ToString();
  512. }
  513. });
  514. }
  515. // searchValue is a regular expression
  516. if (searchValue.IsNull())
  517. {
  518. searchValue = Native.Null.Text;
  519. }
  520. if (searchValue.IsUndefined())
  521. {
  522. searchValue = Native.Undefined.Text;
  523. }
  524. var rx = TypeConverter.ToObject(Engine, searchValue) as RegExpInstance;
  525. if (!ReferenceEquals(rx, null))
  526. {
  527. // Replace the input string with replaceText, recording the last match found.
  528. string result = rx.Value.Replace(thisString, match =>
  529. {
  530. var args = new JsValue[match.Groups.Count + 2];
  531. for (var k = 0; k < match.Groups.Count; k++)
  532. {
  533. var group = match.Groups[k];
  534. args[k] = @group.Value;
  535. }
  536. args[match.Groups.Count] = match.Index;
  537. args[match.Groups.Count + 1] = thisString;
  538. var v = TypeConverter.ToString(replaceFunction.Call(Undefined, args));
  539. return v;
  540. }, rx.Global == true ? -1 : 1);
  541. // Set the deprecated RegExp properties if at least one match was found.
  542. //if (lastMatch != null)
  543. // this.Engine.RegExp.SetDeprecatedProperties(input, lastMatch);
  544. return result;
  545. }
  546. // searchValue is a string
  547. else
  548. {
  549. var substr = TypeConverter.ToString(searchValue);
  550. // Find the first occurrance of substr.
  551. int start = thisString.IndexOf(substr, StringComparison.Ordinal);
  552. if (start == -1)
  553. return thisString;
  554. int end = start + substr.Length;
  555. var args = _engine._jsValueArrayPool.RentArray(3);
  556. args[0] = substr;
  557. args[1] = start;
  558. args[2] = thisString;
  559. var replaceString = TypeConverter.ToString(replaceFunction.Call(Undefined, args));
  560. _engine._jsValueArrayPool.ReturnArray(args);
  561. // Replace only the first match.
  562. using (var result = StringBuilderPool.Rent())
  563. {
  564. result.Builder.EnsureCapacity(thisString.Length + (substr.Length - substr.Length));
  565. result.Builder.Append(thisString, 0, start);
  566. result.Builder.Append(replaceString);
  567. result.Builder.Append(thisString, end, thisString.Length - end);
  568. return result.ToString();
  569. }
  570. }
  571. }
  572. private JsValue Match(JsValue thisObj, JsValue[] arguments)
  573. {
  574. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  575. var s = TypeConverter.ToString(thisObj);
  576. var regex = arguments.At(0);
  577. var rx = regex.TryCast<RegExpInstance>();
  578. rx = rx ?? (RegExpInstance) Engine.RegExp.Construct(new[] {regex});
  579. var global = ((JsBoolean) rx.Get("global"))._value;
  580. if (!global)
  581. {
  582. return Engine.RegExp.PrototypeObject.Exec(rx, Arguments.From(s));
  583. }
  584. else
  585. {
  586. rx.Put("lastIndex", 0, false);
  587. var a = (ArrayInstance) Engine.Array.Construct(Arguments.Empty);
  588. int previousLastIndex = 0;
  589. uint n = 0;
  590. var lastMatch = true;
  591. while (lastMatch)
  592. {
  593. var result = Engine.RegExp.PrototypeObject.Exec(rx, Arguments.From(s)).TryCast<ObjectInstance>();
  594. if (ReferenceEquals(result, null))
  595. {
  596. lastMatch = false;
  597. }
  598. else
  599. {
  600. var thisIndex = (int) ((JsNumber) rx.Get("lastIndex"))._value;
  601. if (thisIndex == previousLastIndex)
  602. {
  603. rx.Put("lastIndex", thisIndex + 1, false);
  604. previousLastIndex = thisIndex + 1;
  605. }
  606. var matchStr = result.Get("0");
  607. a.SetIndexValue(n, matchStr, updateLength: false);
  608. n++;
  609. }
  610. }
  611. if (n == 0)
  612. {
  613. return Null;
  614. }
  615. a.SetLength(n);
  616. return a;
  617. }
  618. }
  619. private JsValue LocaleCompare(JsValue thisObj, JsValue[] arguments)
  620. {
  621. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  622. var s = TypeConverter.ToString(thisObj);
  623. var that = TypeConverter.ToString(arguments.At(0));
  624. return string.CompareOrdinal(s, that);
  625. }
  626. private JsValue LastIndexOf(JsValue thisObj, JsValue[] arguments)
  627. {
  628. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  629. var s = TypeConverter.ToString(thisObj);
  630. var searchStr = TypeConverter.ToString(arguments.At(0));
  631. double numPos = double.NaN;
  632. if (arguments.Length > 1 && !arguments[1].IsUndefined())
  633. {
  634. numPos = TypeConverter.ToNumber(arguments[1]);
  635. }
  636. var pos = double.IsNaN(numPos) ? double.PositiveInfinity : TypeConverter.ToInteger(numPos);
  637. var len = s.Length;
  638. var start = (int)System.Math.Min(System.Math.Max(pos, 0), len);
  639. var searchLen = searchStr.Length;
  640. var i = start;
  641. bool found;
  642. do
  643. {
  644. found = true;
  645. var j = 0;
  646. while (found && j < searchLen)
  647. {
  648. if ((i + searchLen > len) || (s[i + j] != searchStr[j]))
  649. {
  650. found = false;
  651. }
  652. else
  653. {
  654. j++;
  655. }
  656. }
  657. if (!found)
  658. {
  659. i--;
  660. }
  661. } while (!found && i >= 0);
  662. return i;
  663. }
  664. private JsValue IndexOf(JsValue thisObj, JsValue[] arguments)
  665. {
  666. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  667. var s = TypeConverter.ToString(thisObj);
  668. var searchStr = TypeConverter.ToString(arguments.At(0));
  669. double pos = 0;
  670. if (arguments.Length > 1 && !arguments[1].IsUndefined())
  671. {
  672. pos = TypeConverter.ToInteger(arguments[1]);
  673. }
  674. if (pos >= s.Length)
  675. {
  676. return -1;
  677. }
  678. if (pos < 0)
  679. {
  680. pos = 0;
  681. }
  682. return s.IndexOf(searchStr, (int) pos, StringComparison.Ordinal);
  683. }
  684. private JsValue Concat(JsValue thisObj, JsValue[] arguments)
  685. {
  686. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  687. // try to hint capacity if possible
  688. int capacity = 0;
  689. for (int i = 0; i < arguments.Length; ++i)
  690. {
  691. if (arguments[i].Type == Types.String)
  692. {
  693. capacity += arguments[i].AsStringWithoutTypeCheck().Length;
  694. }
  695. }
  696. var value = TypeConverter.ToString(thisObj);
  697. capacity += value.Length;
  698. if (!(thisObj is JsString jsString))
  699. {
  700. jsString = new JsString.ConcatenatedString(value, capacity);
  701. }
  702. else
  703. {
  704. jsString = jsString.EnsureCapacity(capacity);
  705. }
  706. for (int i = 0; i < arguments.Length; i++)
  707. {
  708. jsString = jsString.Append(arguments[i]);
  709. }
  710. return jsString;
  711. }
  712. private JsValue CharCodeAt(JsValue thisObj, JsValue[] arguments)
  713. {
  714. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  715. JsValue pos = arguments.Length > 0 ? arguments[0] : 0;
  716. var s = TypeConverter.ToString(thisObj);
  717. var position = (int)TypeConverter.ToInteger(pos);
  718. if (position < 0 || position >= s.Length)
  719. {
  720. return JsNumber.DoubleNaN;
  721. }
  722. return (long) s[position];
  723. }
  724. private JsValue CodePointAt(JsValue thisObj, JsValue[] arguments)
  725. {
  726. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  727. JsValue pos = arguments.Length > 0 ? arguments[0] : 0;
  728. var s = TypeConverter.ToString(thisObj);
  729. var position = (int)TypeConverter.ToInteger(pos);
  730. if (position < 0 || position >= s.Length)
  731. {
  732. return Undefined;
  733. }
  734. var first = (long) s[position];
  735. if (first >= 0xD800 && first <= 0xDBFF && s.Length > position + 1)
  736. {
  737. long second = s[position + 1];
  738. if (second >= 0xDC00 && second <= 0xDFFF)
  739. {
  740. return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
  741. }
  742. }
  743. return first;
  744. }
  745. private JsValue CharAt(JsValue thisObj, JsValue[] arguments)
  746. {
  747. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  748. var s = TypeConverter.ToString(thisObj);
  749. var position = TypeConverter.ToInteger(arguments.At(0));
  750. var size = s.Length;
  751. if (position >= size || position < 0)
  752. {
  753. return "";
  754. }
  755. return TypeConverter.ToString(s[(int) position]);
  756. }
  757. private JsValue ValueOf(JsValue thisObj, JsValue[] arguments)
  758. {
  759. if (thisObj is StringInstance si)
  760. {
  761. return si.PrimitiveValue;
  762. }
  763. if (thisObj is JsString)
  764. {
  765. return thisObj;
  766. }
  767. return ExceptionHelper.ThrowTypeError<JsValue>(Engine);
  768. }
  769. /// <summary>
  770. /// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
  771. /// </summary>
  772. /// <param name="thisObj">The original string object</param>
  773. /// <param name="arguments">
  774. /// argument[0] is the target length of the output string
  775. /// argument[1] is the string to pad with
  776. /// </param>
  777. /// <returns></returns>
  778. private JsValue PadStart(JsValue thisObj, JsValue[] arguments)
  779. {
  780. return Pad(thisObj, arguments, true);
  781. }
  782. /// <summary>
  783. /// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd
  784. /// </summary>
  785. /// <param name="thisObj">The original string object</param>
  786. /// <param name="arguments">
  787. /// argument[0] is the target length of the output string
  788. /// argument[1] is the string to pad with
  789. /// </param>
  790. /// <returns></returns>
  791. private JsValue PadEnd(JsValue thisObj, JsValue[] arguments)
  792. {
  793. return Pad(thisObj, arguments, false);
  794. }
  795. private JsValue Pad(JsValue thisObj, JsValue[] arguments, bool padStart)
  796. {
  797. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  798. var targetLength = TypeConverter.ToInt32(arguments.At(0));
  799. var padStringValue = arguments.At(1);
  800. var padString = padStringValue.IsUndefined()
  801. ? " "
  802. : TypeConverter.ToString(padStringValue);
  803. var s = TypeConverter.ToString(thisObj);
  804. if (s.Length > targetLength || padString.Length == 0)
  805. {
  806. return s;
  807. }
  808. targetLength = targetLength - s.Length;
  809. if (targetLength > padString.Length)
  810. {
  811. padString = string.Join("", Enumerable.Repeat(padString, (targetLength / padString.Length) + 1));
  812. }
  813. return padStart
  814. ? $"{padString.Substring(0, targetLength)}{s}"
  815. : $"{s}{padString.Substring(0, targetLength)}";
  816. }
  817. /// <summary>
  818. /// https://www.ecma-international.org/ecma-262/6.0/#sec-string.prototype.startswith
  819. /// </summary>
  820. private JsValue StartsWith(JsValue thisObj, JsValue[] arguments)
  821. {
  822. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  823. var s = TypeConverter.ToString(thisObj);
  824. var searchString = arguments.At(0);
  825. if (ReferenceEquals(searchString, Null))
  826. {
  827. searchString = Native.Null.Text;
  828. }
  829. else
  830. {
  831. if (searchString.IsRegExp())
  832. {
  833. ExceptionHelper.ThrowTypeError(Engine);
  834. }
  835. }
  836. var searchStr = TypeConverter.ToString(searchString);
  837. var pos = TypeConverter.ToInt32(arguments.At(1));
  838. var len = s.Length;
  839. var start = System.Math.Min(System.Math.Max(pos, 0), len);
  840. var searchLength = searchStr.Length;
  841. if (searchLength + start > len)
  842. {
  843. return false;
  844. }
  845. for (var i = 0; i < searchLength; i++)
  846. {
  847. if (s[start + i] != searchStr[i])
  848. {
  849. return false;
  850. }
  851. }
  852. return true;
  853. }
  854. /// <summary>
  855. /// https://www.ecma-international.org/ecma-262/6.0/#sec-string.prototype.endswith
  856. /// </summary>
  857. private JsValue EndsWith(JsValue thisObj, JsValue[] arguments)
  858. {
  859. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  860. var s = TypeConverter.ToString(thisObj);
  861. var searchString = arguments.At(0);
  862. if (ReferenceEquals(searchString, Null))
  863. {
  864. searchString = Native.Null.Text;
  865. }
  866. else
  867. {
  868. if (searchString.IsRegExp())
  869. {
  870. ExceptionHelper.ThrowTypeError(Engine);
  871. }
  872. }
  873. var searchStr = TypeConverter.ToString(searchString);
  874. var len = s.Length;
  875. var pos = TypeConverter.ToInt32(arguments.At(1, len));
  876. var end = System.Math.Min(System.Math.Max(pos, 0), len);
  877. var searchLength = searchStr.Length;
  878. var start = end - searchLength;
  879. if (start < 0)
  880. {
  881. return false;
  882. }
  883. for (var i = 0; i < searchLength; i++)
  884. {
  885. if (s[start + i] != searchStr[i])
  886. {
  887. return false;
  888. }
  889. }
  890. return true;
  891. }
  892. private JsValue Includes(JsValue thisObj, JsValue[] arguments)
  893. {
  894. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  895. var s1 = TypeConverter.ToString(thisObj);
  896. var searchString = arguments.At(0);
  897. if (searchString.IsRegExp())
  898. {
  899. return ExceptionHelper.ThrowTypeError<JsValue>(_engine, "First argument to String.prototype.includes must not be a regular expression");
  900. }
  901. var searchStr = TypeConverter.ToString(searchString);
  902. double pos = 0;
  903. if (arguments.Length > 1 && !arguments[1].IsUndefined())
  904. {
  905. pos = TypeConverter.ToInteger(arguments[1]);
  906. }
  907. if (searchStr.Length == 0)
  908. {
  909. return true;
  910. }
  911. if (pos >= s1.Length)
  912. {
  913. return false;
  914. }
  915. if (pos < 0)
  916. {
  917. pos = 0;
  918. }
  919. return s1.IndexOf(searchStr, (int) pos, StringComparison.Ordinal) > -1;
  920. }
  921. private JsValue Normalize(JsValue thisObj, JsValue[] arguments)
  922. {
  923. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  924. var str = TypeConverter.ToString(thisObj);
  925. var param = arguments.At(0);
  926. var form = "NFC";
  927. if (!param.IsUndefined())
  928. {
  929. form = TypeConverter.ToString(param);
  930. }
  931. var nf = NormalizationForm.FormC;
  932. switch (form)
  933. {
  934. case "NFC":
  935. nf = NormalizationForm.FormC;
  936. break;
  937. case "NFD":
  938. nf = NormalizationForm.FormD;
  939. break;
  940. case "NFKC":
  941. nf = NormalizationForm.FormKC;
  942. break;
  943. case "NFKD":
  944. nf = NormalizationForm.FormKD;
  945. break;
  946. default:
  947. ExceptionHelper.ThrowRangeError(
  948. _engine,
  949. "The normalization form should be one of NFC, NFD, NFKC, NFKD.");
  950. break;
  951. }
  952. return str.Normalize(nf);
  953. }
  954. private JsValue Repeat(JsValue thisObj, JsValue[] arguments)
  955. {
  956. TypeConverter.CheckObjectCoercible(Engine, thisObj);
  957. var str = TypeConverter.ToString(thisObj);
  958. var n = (int) TypeConverter.ToInteger(arguments.At(0));
  959. if (n < 0)
  960. {
  961. return ExceptionHelper.ThrowRangeError<JsValue>(_engine, "Invalid count value");
  962. }
  963. if (n == 0 || str.Length == 0)
  964. {
  965. return JsString.Empty;
  966. }
  967. if (str.Length == 1)
  968. {
  969. return new string(str[0], n);
  970. }
  971. using (var sb = StringBuilderPool.Rent())
  972. {
  973. sb.Builder.EnsureCapacity(n * str.Length);
  974. for (var i = 0; i < n; ++i)
  975. {
  976. sb.Builder.Append(str);
  977. }
  978. return sb.ToString();
  979. }
  980. }
  981. }
  982. }