@@ -37,10 +37,11 @@ public PeepholeReplaceKnownMethodsTest() {
3737 super (
3838 MINIMAL_EXTERNS
3939 + lines (
40- // NOTE: these are defined as variadic to avoid wrong-argument-count warnings in
41- // NTI,
40+ // NOTE: these are defined as variadic to avoid wrong-argument-count warnings,
4241 // which enables testing that the pass does not touch calls with wrong argument
4342 // count.
43+ "/** @type {function(this: string, ...*): string} */ String.prototype.replaceAll;" ,
44+ "/** @type {function(this: string, ...*): string} */ String.prototype.replace;" ,
4445 "/** @type {function(this: string, ...*): string} */ String.prototype.substring;" ,
4546 "/** @type {function(this: string, ...*): string} */ String.prototype.substr;" ,
4647 "/** @type {function(this: string, ...*): string} */ String.prototype.slice;" ,
@@ -205,6 +206,41 @@ public void testFoldStringSubstr() {
205206 foldSame ("x = `abc ${xyz} def`.substr(0,2)" );
206207 }
207208
209+ @ Test
210+ public void testFoldStringReplace () {
211+ // TODO(johnlenz): support folding this case
212+ foldSame ("x = 'acaca'.replace('c','x')" );
213+
214+ // not a literal
215+ foldSame ("x.replace('x','c')" );
216+
217+ foldSame ("'Xyz'.replace('Xyz', '$$')" ); // would fold to '$'
218+ foldSame ("'PreXyzPost'.replace('Xyz', '$&')" ); // would fold to 'PreXyzPost'
219+ foldSame ("'PreXyzPost'.replace('Xyz', '$`')" ); // would fold to 'PrePrePost'
220+ foldSame ("'PreXyzPost'.replace('Xyz', '$\\ '')" ); // would fold to 'PrePostPost'
221+ foldSame ("'PreXyzPostXyz'.replace('Xyz', '$\\ '')" ); // would fold to 'PrePostXyzPost'
222+ foldSame ("'123'.replace('2', '$`')" ); // would fold to '113'
223+ }
224+
225+ @ Test
226+ public void testFoldStringReplaceAll () {
227+ fold ("x = 'abcde'.replaceAll('bcd','c')" , "x = 'ace'" );
228+ fold ("x = 'abcde'.replaceAll('c','xxx')" , "x = 'abxxxde'" );
229+ fold ("x = 'abcde'.replaceAll('xxx','c')" , "x = 'abcde'" );
230+
231+ fold ("x = 'c_c_c'.replaceAll('c','x')" , "x = 'x_x_x'" );
232+
233+ // not a literal
234+ foldSame ("x.replaceAll('x','c')" );
235+
236+ foldSame ("'Xyz'.replaceAll('Xyz', '$$')" ); // would fold to '$'
237+ foldSame ("'PreXyzPost'.replaceAll('Xyz', '$&')" ); // would fold to 'PreXyzPost'
238+ foldSame ("'PreXyzPost'.replaceAll('Xyz', '$`')" ); // would fold to 'PrePrePost'
239+ foldSame ("'PreXyzPost'.replaceAll('Xyz', '$\\ '')" ); // would fold to 'PrePostPost'
240+ foldSame ("'PreXyzPostXyz'.replaceAll('Xyz', '$\\ '')" ); // would fold to 'PrePostXyzPost'
241+ foldSame ("'123'.replaceAll('2', '$`')" ); // would fold to '113'
242+ }
243+
208244 @ Test
209245 public void testFoldStringSubstring () {
210246 fold ("x = 'abcde'.substring(0,2)" , "x = 'ab'" );
0 commit comments