]> git.lizzy.rs Git - rust.git/blob - crates/ide_ssr/src/tests.rs
Merge #11872
[rust.git] / crates / ide_ssr / src / tests.rs
1 use crate::{MatchFinder, SsrRule};
2 use expect_test::{expect, Expect};
3 use ide_db::base_db::{salsa::Durability, FileId, FilePosition, FileRange, SourceDatabaseExt};
4 use rustc_hash::FxHashSet;
5 use std::sync::Arc;
6 use test_utils::RangeOrOffset;
7
8 fn parse_error_text(query: &str) -> String {
9     format!("{}", query.parse::<SsrRule>().unwrap_err())
10 }
11
12 #[test]
13 fn parser_empty_query() {
14     assert_eq!(parse_error_text(""), "Parse error: Cannot find delimiter `==>>`");
15 }
16
17 #[test]
18 fn parser_no_delimiter() {
19     assert_eq!(parse_error_text("foo()"), "Parse error: Cannot find delimiter `==>>`");
20 }
21
22 #[test]
23 fn parser_two_delimiters() {
24     assert_eq!(
25         parse_error_text("foo() ==>> a ==>> b "),
26         "Parse error: More than one delimiter found"
27     );
28 }
29
30 #[test]
31 fn parser_repeated_name() {
32     assert_eq!(
33         parse_error_text("foo($a, $a) ==>>"),
34         "Parse error: Placeholder `$a` repeats more than once"
35     );
36 }
37
38 #[test]
39 fn parser_invalid_pattern() {
40     assert_eq!(
41         parse_error_text(" ==>> ()"),
42         "Parse error: Not a valid Rust expression, type, item, path or pattern"
43     );
44 }
45
46 #[test]
47 fn parser_invalid_template() {
48     assert_eq!(
49         parse_error_text("() ==>> )"),
50         "Parse error: Not a valid Rust expression, type, item, path or pattern"
51     );
52 }
53
54 #[test]
55 fn parser_undefined_placeholder_in_replacement() {
56     assert_eq!(
57         parse_error_text("42 ==>> $a"),
58         "Parse error: Replacement contains undefined placeholders: $a"
59     );
60 }
61
62 /// `code` may optionally contain a cursor marker `$0`. If it doesn't, then the position will be
63 /// the start of the file. If there's a second cursor marker, then we'll return a single range.
64 pub(crate) fn single_file(code: &str) -> (ide_db::RootDatabase, FilePosition, Vec<FileRange>) {
65     use ide_db::base_db::fixture::WithFixture;
66     use ide_db::symbol_index::SymbolsDatabase;
67     let (mut db, file_id, range_or_offset) = if code.contains(test_utils::CURSOR_MARKER) {
68         ide_db::RootDatabase::with_range_or_offset(code)
69     } else {
70         let (db, file_id) = ide_db::RootDatabase::with_single_file(code);
71         (db, file_id, RangeOrOffset::Offset(0.into()))
72     };
73     let selections;
74     let position;
75     match range_or_offset {
76         RangeOrOffset::Range(range) => {
77             position = FilePosition { file_id, offset: range.start() };
78             selections = vec![FileRange { file_id, range }];
79         }
80         RangeOrOffset::Offset(offset) => {
81             position = FilePosition { file_id, offset };
82             selections = vec![];
83         }
84     }
85     let mut local_roots = FxHashSet::default();
86     local_roots.insert(ide_db::base_db::fixture::WORKSPACE);
87     db.set_local_roots_with_durability(Arc::new(local_roots), Durability::HIGH);
88     (db, position, selections)
89 }
90
91 fn assert_ssr_transform(rule: &str, input: &str, expected: Expect) {
92     assert_ssr_transforms(&[rule], input, expected);
93 }
94
95 fn assert_ssr_transforms(rules: &[&str], input: &str, expected: Expect) {
96     let (db, position, selections) = single_file(input);
97     let mut match_finder = MatchFinder::in_context(&db, position, selections).unwrap();
98     for rule in rules {
99         let rule: SsrRule = rule.parse().unwrap();
100         match_finder.add_rule(rule).unwrap();
101     }
102     let edits = match_finder.edits();
103     if edits.is_empty() {
104         panic!("No edits were made");
105     }
106     // Note, db.file_text is not necessarily the same as `input`, since fixture parsing alters
107     // stuff.
108     let mut actual = db.file_text(position.file_id).to_string();
109     edits[&position.file_id].apply(&mut actual);
110     expected.assert_eq(&actual);
111 }
112
113 fn print_match_debug_info(match_finder: &MatchFinder, file_id: FileId, snippet: &str) {
114     let debug_info = match_finder.debug_where_text_equal(file_id, snippet);
115     println!(
116         "Match debug info: {} nodes had text exactly equal to '{}'",
117         debug_info.len(),
118         snippet
119     );
120     for (index, d) in debug_info.iter().enumerate() {
121         println!("Node #{}\n{:#?}\n", index, d);
122     }
123 }
124
125 fn assert_matches(pattern: &str, code: &str, expected: &[&str]) {
126     let (db, position, selections) = single_file(code);
127     let mut match_finder = MatchFinder::in_context(&db, position, selections).unwrap();
128     match_finder.add_search_pattern(pattern.parse().unwrap()).unwrap();
129     let matched_strings: Vec<String> =
130         match_finder.matches().flattened().matches.iter().map(|m| m.matched_text()).collect();
131     if matched_strings != expected && !expected.is_empty() {
132         print_match_debug_info(&match_finder, position.file_id, expected[0]);
133     }
134     assert_eq!(matched_strings, expected);
135 }
136
137 fn assert_no_match(pattern: &str, code: &str) {
138     let (db, position, selections) = single_file(code);
139     let mut match_finder = MatchFinder::in_context(&db, position, selections).unwrap();
140     match_finder.add_search_pattern(pattern.parse().unwrap()).unwrap();
141     let matches = match_finder.matches().flattened().matches;
142     if !matches.is_empty() {
143         print_match_debug_info(&match_finder, position.file_id, &matches[0].matched_text());
144         panic!("Got {} matches when we expected none: {:#?}", matches.len(), matches);
145     }
146 }
147
148 fn assert_match_failure_reason(pattern: &str, code: &str, snippet: &str, expected_reason: &str) {
149     let (db, position, selections) = single_file(code);
150     let mut match_finder = MatchFinder::in_context(&db, position, selections).unwrap();
151     match_finder.add_search_pattern(pattern.parse().unwrap()).unwrap();
152     let mut reasons = Vec::new();
153     for d in match_finder.debug_where_text_equal(position.file_id, snippet) {
154         if let Some(reason) = d.match_failure_reason() {
155             reasons.push(reason.to_owned());
156         }
157     }
158     assert_eq!(reasons, vec![expected_reason]);
159 }
160
161 #[test]
162 fn ssr_let_stmt_in_macro_match() {
163     assert_matches(
164         "let a = 0",
165         r#"
166             macro_rules! m1 { ($a:stmt) => {$a}; }
167             fn f() {m1!{ let a = 0 };}"#,
168         // FIXME: Whitespace is not part of the matched block
169         &["leta=0"],
170     );
171 }
172
173 #[test]
174 fn ssr_let_stmt_in_fn_match() {
175     assert_matches("let $a = 10;", "fn main() { let x = 10; x }", &["let x = 10;"]);
176     assert_matches("let $a = $b;", "fn main() { let x = 10; x }", &["let x = 10;"]);
177 }
178
179 #[test]
180 fn ssr_block_expr_match() {
181     assert_matches("{ let $a = $b; }", "fn main() { let x = 10; }", &["{ let x = 10; }"]);
182     assert_matches("{ let $a = $b; $c }", "fn main() { let x = 10; x }", &["{ let x = 10; x }"]);
183 }
184
185 #[test]
186 fn ssr_let_stmt_replace() {
187     // Pattern and template with trailing semicolon
188     assert_ssr_transform(
189         "let $a = $b; ==>> let $a = 11;",
190         "fn main() { let x = 10; x }",
191         expect![["fn main() { let x = 11; x }"]],
192     );
193 }
194
195 #[test]
196 fn ssr_let_stmt_replace_expr() {
197     // Trailing semicolon should be dropped from the new expression
198     assert_ssr_transform(
199         "let $a = $b; ==>> $b",
200         "fn main() { let x = 10; }",
201         expect![["fn main() { 10 }"]],
202     );
203 }
204
205 #[test]
206 fn ssr_blockexpr_replace_stmt_with_stmt() {
207     assert_ssr_transform(
208         "if $a() {$b;} ==>> $b;",
209         "{
210     if foo() {
211         bar();
212     }
213     Ok(())
214 }",
215         expect![[r#"{
216     bar();
217     Ok(())
218 }"#]],
219     );
220 }
221
222 #[test]
223 fn ssr_blockexpr_match_trailing_expr() {
224     assert_matches(
225         "if $a() {$b;}",
226         "{
227     if foo() {
228         bar();
229     }
230 }",
231         &["if foo() {
232         bar();
233     }"],
234     );
235 }
236
237 #[test]
238 fn ssr_blockexpr_replace_trailing_expr_with_stmt() {
239     assert_ssr_transform(
240         "if $a() {$b;} ==>> $b;",
241         "{
242     if foo() {
243         bar();
244     }
245 }",
246         expect![["{
247     bar();
248 }"]],
249     );
250 }
251
252 #[test]
253 fn ssr_function_to_method() {
254     assert_ssr_transform(
255         "my_function($a, $b) ==>> ($a).my_method($b)",
256         "fn my_function() {} fn main() { loop { my_function( other_func(x, y), z + w) } }",
257         expect![["fn my_function() {} fn main() { loop { (other_func(x, y)).my_method(z + w) } }"]],
258     )
259 }
260
261 #[test]
262 fn ssr_nested_function() {
263     assert_ssr_transform(
264         "foo($a, $b, $c) ==>> bar($c, baz($a, $b))",
265         r#"
266             //- /lib.rs crate:foo
267             fn foo() {}
268             fn bar() {}
269             fn baz() {}
270             fn main { foo  (x + value.method(b), x+y-z, true && false) }
271             "#,
272         expect![[r#"
273             fn foo() {}
274             fn bar() {}
275             fn baz() {}
276             fn main { bar(true && false, baz(x + value.method(b), x+y-z)) }
277         "#]],
278     )
279 }
280
281 #[test]
282 fn ssr_expected_spacing() {
283     assert_ssr_transform(
284         "foo($x) + bar() ==>> bar($x)",
285         "fn foo() {} fn bar() {} fn main() { foo(5) + bar() }",
286         expect![["fn foo() {} fn bar() {} fn main() { bar(5) }"]],
287     );
288 }
289
290 #[test]
291 fn ssr_with_extra_space() {
292     assert_ssr_transform(
293         "foo($x  ) +    bar() ==>> bar($x)",
294         "fn foo() {} fn bar() {} fn main() { foo(  5 )  +bar(   ) }",
295         expect![["fn foo() {} fn bar() {} fn main() { bar(5) }"]],
296     );
297 }
298
299 #[test]
300 fn ssr_keeps_nested_comment() {
301     assert_ssr_transform(
302         "foo($x) ==>> bar($x)",
303         "fn foo() {} fn bar() {} fn main() { foo(other(5 /* using 5 */)) }",
304         expect![["fn foo() {} fn bar() {} fn main() { bar(other(5 /* using 5 */)) }"]],
305     )
306 }
307
308 #[test]
309 fn ssr_keeps_comment() {
310     assert_ssr_transform(
311         "foo($x) ==>> bar($x)",
312         "fn foo() {} fn bar() {} fn main() { foo(5 /* using 5 */) }",
313         expect![["fn foo() {} fn bar() {} fn main() { bar(5)/* using 5 */ }"]],
314     )
315 }
316
317 #[test]
318 fn ssr_struct_lit() {
319     assert_ssr_transform(
320         "Foo{a: $a, b: $b} ==>> Foo::new($a, $b)",
321         r#"
322             struct Foo() {}
323             impl Foo { fn new() {} }
324             fn main() { Foo{b:2, a:1} }
325             "#,
326         expect![[r#"
327             struct Foo() {}
328             impl Foo { fn new() {} }
329             fn main() { Foo::new(1, 2) }
330         "#]],
331     )
332 }
333
334 #[test]
335 fn ssr_struct_def() {
336     assert_ssr_transform(
337         "struct Foo { $f: $t } ==>> struct Foo($t);",
338         r#"struct Foo { field: i32 }"#,
339         expect![[r#"struct Foo(i32);"#]],
340     )
341 }
342
343 #[test]
344 fn ignores_whitespace() {
345     assert_matches("1+2", "fn f() -> i32 {1  +  2}", &["1  +  2"]);
346     assert_matches("1 + 2", "fn f() -> i32 {1+2}", &["1+2"]);
347 }
348
349 #[test]
350 fn no_match() {
351     assert_no_match("1 + 3", "fn f() -> i32 {1  +  2}");
352 }
353
354 #[test]
355 fn match_fn_definition() {
356     assert_matches("fn $a($b: $t) {$c}", "fn f(a: i32) {bar()}", &["fn f(a: i32) {bar()}"]);
357 }
358
359 #[test]
360 fn match_struct_definition() {
361     let code = r#"
362         struct Option<T> {}
363         struct Bar {}
364         struct Foo {name: Option<String>}"#;
365     assert_matches("struct $n {$f: Option<String>}", code, &["struct Foo {name: Option<String>}"]);
366 }
367
368 #[test]
369 fn match_expr() {
370     let code = r#"
371         fn foo() {}
372         fn f() -> i32 {foo(40 + 2, 42)}"#;
373     assert_matches("foo($a, $b)", code, &["foo(40 + 2, 42)"]);
374     assert_no_match("foo($a, $b, $c)", code);
375     assert_no_match("foo($a)", code);
376 }
377
378 #[test]
379 fn match_nested_method_calls() {
380     assert_matches(
381         "$a.z().z().z()",
382         "fn f() {h().i().j().z().z().z().d().e()}",
383         &["h().i().j().z().z().z()"],
384     );
385 }
386
387 // Make sure that our node matching semantics don't differ within macro calls.
388 #[test]
389 fn match_nested_method_calls_with_macro_call() {
390     assert_matches(
391         "$a.z().z().z()",
392         r#"
393             macro_rules! m1 { ($a:expr) => {$a}; }
394             fn f() {m1!(h().i().j().z().z().z().d().e())}"#,
395         &["h().i().j().z().z().z()"],
396     );
397 }
398
399 #[test]
400 fn match_complex_expr() {
401     let code = r#"
402         fn foo() {} fn bar() {}
403         fn f() -> i32 {foo(bar(40, 2), 42)}"#;
404     assert_matches("foo($a, $b)", code, &["foo(bar(40, 2), 42)"]);
405     assert_no_match("foo($a, $b, $c)", code);
406     assert_no_match("foo($a)", code);
407     assert_matches("bar($a, $b)", code, &["bar(40, 2)"]);
408 }
409
410 // Trailing commas in the code should be ignored.
411 #[test]
412 fn match_with_trailing_commas() {
413     // Code has comma, pattern doesn't.
414     assert_matches("foo($a, $b)", "fn foo() {} fn f() {foo(1, 2,);}", &["foo(1, 2,)"]);
415     assert_matches("Foo{$a, $b}", "struct Foo {} fn f() {Foo{1, 2,};}", &["Foo{1, 2,}"]);
416
417     // Pattern has comma, code doesn't.
418     assert_matches("foo($a, $b,)", "fn foo() {} fn f() {foo(1, 2);}", &["foo(1, 2)"]);
419     assert_matches("Foo{$a, $b,}", "struct Foo {} fn f() {Foo{1, 2};}", &["Foo{1, 2}"]);
420 }
421
422 #[test]
423 fn match_type() {
424     assert_matches("i32", "fn f() -> i32 {1  +  2}", &["i32"]);
425     assert_matches(
426         "Option<$a>",
427         "struct Option<T> {} fn f() -> Option<i32> {42}",
428         &["Option<i32>"],
429     );
430     assert_no_match(
431         "Option<$a>",
432         "struct Option<T> {} struct Result<T, E> {} fn f() -> Result<i32, ()> {42}",
433     );
434 }
435
436 #[test]
437 fn match_struct_instantiation() {
438     let code = r#"
439         struct Foo {bar: i32, baz: i32}
440         fn f() {Foo {bar: 1, baz: 2}}"#;
441     assert_matches("Foo {bar: 1, baz: 2}", code, &["Foo {bar: 1, baz: 2}"]);
442     // Now with placeholders for all parts of the struct.
443     assert_matches("Foo {$a: $b, $c: $d}", code, &["Foo {bar: 1, baz: 2}"]);
444     assert_matches("Foo {}", "struct Foo {} fn f() {Foo {}}", &["Foo {}"]);
445 }
446
447 #[test]
448 fn match_path() {
449     let code = r#"
450         mod foo {
451             pub fn bar() {}
452         }
453         fn f() {foo::bar(42)}"#;
454     assert_matches("foo::bar", code, &["foo::bar"]);
455     assert_matches("$a::bar", code, &["foo::bar"]);
456     assert_matches("foo::$b", code, &["foo::bar"]);
457 }
458
459 #[test]
460 fn match_pattern() {
461     assert_matches("Some($a)", "struct Some(); fn f() {if let Some(x) = foo() {}}", &["Some(x)"]);
462 }
463
464 // If our pattern has a full path, e.g. a::b::c() and the code has c(), but c resolves to
465 // a::b::c, then we should match.
466 #[test]
467 fn match_fully_qualified_fn_path() {
468     let code = r#"
469         mod a {
470             pub mod b {
471                 pub fn c(_: i32) {}
472             }
473         }
474         use a::b::c;
475         fn f1() {
476             c(42);
477         }
478         "#;
479     assert_matches("a::b::c($a)", code, &["c(42)"]);
480 }
481
482 #[test]
483 fn match_resolved_type_name() {
484     let code = r#"
485         mod m1 {
486             pub mod m2 {
487                 pub trait Foo<T> {}
488             }
489         }
490         mod m3 {
491             trait Foo<T> {}
492             fn f1(f: Option<&dyn Foo<bool>>) {}
493         }
494         mod m4 {
495             use crate::m1::m2::Foo;
496             fn f1(f: Option<&dyn Foo<i32>>) {}
497         }
498         "#;
499     assert_matches("m1::m2::Foo<$t>", code, &["Foo<i32>"]);
500 }
501
502 #[test]
503 fn type_arguments_within_path() {
504     cov_mark::check!(type_arguments_within_path);
505     let code = r#"
506         mod foo {
507             pub struct Bar<T> {t: T}
508             impl<T> Bar<T> {
509                 pub fn baz() {}
510             }
511         }
512         fn f1() {foo::Bar::<i32>::baz();}
513         "#;
514     assert_no_match("foo::Bar::<i64>::baz()", code);
515     assert_matches("foo::Bar::<i32>::baz()", code, &["foo::Bar::<i32>::baz()"]);
516 }
517
518 #[test]
519 fn literal_constraint() {
520     cov_mark::check!(literal_constraint);
521     let code = r#"
522         enum Option<T> { Some(T), None }
523         use Option::Some;
524         fn f1() {
525             let x1 = Some(42);
526             let x2 = Some("foo");
527             let x3 = Some(x1);
528             let x4 = Some(40 + 2);
529             let x5 = Some(true);
530         }
531         "#;
532     assert_matches("Some(${a:kind(literal)})", code, &["Some(42)", "Some(\"foo\")", "Some(true)"]);
533     assert_matches("Some(${a:not(kind(literal))})", code, &["Some(x1)", "Some(40 + 2)"]);
534 }
535
536 #[test]
537 fn match_reordered_struct_instantiation() {
538     assert_matches(
539         "Foo {aa: 1, b: 2, ccc: 3}",
540         "struct Foo {} fn f() {Foo {b: 2, ccc: 3, aa: 1}}",
541         &["Foo {b: 2, ccc: 3, aa: 1}"],
542     );
543     assert_no_match("Foo {a: 1}", "struct Foo {} fn f() {Foo {b: 1}}");
544     assert_no_match("Foo {a: 1}", "struct Foo {} fn f() {Foo {a: 2}}");
545     assert_no_match("Foo {a: 1, b: 2}", "struct Foo {} fn f() {Foo {a: 1}}");
546     assert_no_match("Foo {a: 1, b: 2}", "struct Foo {} fn f() {Foo {b: 2}}");
547     assert_no_match("Foo {a: 1, }", "struct Foo {} fn f() {Foo {a: 1, b: 2}}");
548     assert_no_match("Foo {a: 1, z: 9}", "struct Foo {} fn f() {Foo {a: 1}}");
549 }
550
551 #[test]
552 fn match_macro_invocation() {
553     assert_matches(
554         "foo!($a)",
555         "macro_rules! foo {() => {}} fn() {foo(foo!(foo()))}",
556         &["foo!(foo())"],
557     );
558     assert_matches(
559         "foo!(41, $a, 43)",
560         "macro_rules! foo {() => {}} fn() {foo!(41, 42, 43)}",
561         &["foo!(41, 42, 43)"],
562     );
563     assert_no_match("foo!(50, $a, 43)", "macro_rules! foo {() => {}} fn() {foo!(41, 42, 43}");
564     assert_no_match("foo!(41, $a, 50)", "macro_rules! foo {() => {}} fn() {foo!(41, 42, 43}");
565     assert_matches(
566         "foo!($a())",
567         "macro_rules! foo {() => {}} fn() {foo!(bar())}",
568         &["foo!(bar())"],
569     );
570 }
571
572 // When matching within a macro expansion, we only allow matches of nodes that originated from
573 // the macro call, not from the macro definition.
574 #[test]
575 fn no_match_expression_from_macro() {
576     assert_no_match(
577         "$a.clone()",
578         r#"
579             macro_rules! m1 {
580                 () => {42.clone()}
581             }
582             fn f1() {m1!()}
583             "#,
584     );
585 }
586
587 // We definitely don't want to allow matching of an expression that part originates from the
588 // macro call `42` and part from the macro definition `.clone()`.
589 #[test]
590 fn no_match_split_expression() {
591     assert_no_match(
592         "$a.clone()",
593         r#"
594             macro_rules! m1 {
595                 ($x:expr) => {$x.clone()}
596             }
597             fn f1() {m1!(42)}
598             "#,
599     );
600 }
601
602 #[test]
603 fn replace_function_call() {
604     // This test also makes sure that we ignore empty-ranges.
605     assert_ssr_transform(
606         "foo() ==>> bar()",
607         "fn foo() {$0$0} fn bar() {} fn f1() {foo(); foo();}",
608         expect![["fn foo() {} fn bar() {} fn f1() {bar(); bar();}"]],
609     );
610 }
611
612 #[test]
613 fn replace_function_call_with_placeholders() {
614     assert_ssr_transform(
615         "foo($a, $b) ==>> bar($b, $a)",
616         "fn foo() {} fn bar() {} fn f1() {foo(5, 42)}",
617         expect![["fn foo() {} fn bar() {} fn f1() {bar(42, 5)}"]],
618     );
619 }
620
621 #[test]
622 fn replace_nested_function_calls() {
623     assert_ssr_transform(
624         "foo($a) ==>> bar($a)",
625         "fn foo() {} fn bar() {} fn f1() {foo(foo(42))}",
626         expect![["fn foo() {} fn bar() {} fn f1() {bar(bar(42))}"]],
627     );
628 }
629
630 #[test]
631 fn replace_associated_function_call() {
632     assert_ssr_transform(
633         "Foo::new() ==>> Bar::new()",
634         r#"
635             struct Foo {}
636             impl Foo { fn new() {} }
637             struct Bar {}
638             impl Bar { fn new() {} }
639             fn f1() {Foo::new();}
640             "#,
641         expect![[r#"
642             struct Foo {}
643             impl Foo { fn new() {} }
644             struct Bar {}
645             impl Bar { fn new() {} }
646             fn f1() {Bar::new();}
647         "#]],
648     );
649 }
650
651 #[test]
652 fn replace_associated_trait_default_function_call() {
653     cov_mark::check!(replace_associated_trait_default_function_call);
654     assert_ssr_transform(
655         "Bar2::foo() ==>> Bar2::foo2()",
656         r#"
657             trait Foo { fn foo() {} }
658             pub struct Bar {}
659             impl Foo for Bar {}
660             pub struct Bar2 {}
661             impl Foo for Bar2 {}
662             impl Bar2 { fn foo2() {} }
663             fn main() {
664                 Bar::foo();
665                 Bar2::foo();
666             }
667         "#,
668         expect![[r#"
669             trait Foo { fn foo() {} }
670             pub struct Bar {}
671             impl Foo for Bar {}
672             pub struct Bar2 {}
673             impl Foo for Bar2 {}
674             impl Bar2 { fn foo2() {} }
675             fn main() {
676                 Bar::foo();
677                 Bar2::foo2();
678             }
679         "#]],
680     );
681 }
682
683 #[test]
684 fn replace_associated_trait_constant() {
685     cov_mark::check!(replace_associated_trait_constant);
686     assert_ssr_transform(
687         "Bar2::VALUE ==>> Bar2::VALUE_2222",
688         r#"
689             trait Foo { const VALUE: i32; const VALUE_2222: i32; }
690             pub struct Bar {}
691             impl Foo for Bar { const VALUE: i32 = 1;  const VALUE_2222: i32 = 2; }
692             pub struct Bar2 {}
693             impl Foo for Bar2 { const VALUE: i32 = 1;  const VALUE_2222: i32 = 2; }
694             impl Bar2 { fn foo2() {} }
695             fn main() {
696                 Bar::VALUE;
697                 Bar2::VALUE;
698             }
699             "#,
700         expect![[r#"
701             trait Foo { const VALUE: i32; const VALUE_2222: i32; }
702             pub struct Bar {}
703             impl Foo for Bar { const VALUE: i32 = 1;  const VALUE_2222: i32 = 2; }
704             pub struct Bar2 {}
705             impl Foo for Bar2 { const VALUE: i32 = 1;  const VALUE_2222: i32 = 2; }
706             impl Bar2 { fn foo2() {} }
707             fn main() {
708                 Bar::VALUE;
709                 Bar2::VALUE_2222;
710             }
711         "#]],
712     );
713 }
714
715 #[test]
716 fn replace_path_in_different_contexts() {
717     // Note the $0 inside module a::b which marks the point where the rule is interpreted. We
718     // replace foo with bar, but both need different path qualifiers in different contexts. In f4,
719     // foo is unqualified because of a use statement, however the replacement needs to be fully
720     // qualified.
721     assert_ssr_transform(
722         "c::foo() ==>> c::bar()",
723         r#"
724             mod a {
725                 pub mod b {$0
726                     pub mod c {
727                         pub fn foo() {}
728                         pub fn bar() {}
729                         fn f1() { foo() }
730                     }
731                     fn f2() { c::foo() }
732                 }
733                 fn f3() { b::c::foo() }
734             }
735             use a::b::c::foo;
736             fn f4() { foo() }
737             "#,
738         expect![[r#"
739             mod a {
740                 pub mod b {
741                     pub mod c {
742                         pub fn foo() {}
743                         pub fn bar() {}
744                         fn f1() { bar() }
745                     }
746                     fn f2() { c::bar() }
747                 }
748                 fn f3() { b::c::bar() }
749             }
750             use a::b::c::foo;
751             fn f4() { a::b::c::bar() }
752             "#]],
753     );
754 }
755
756 #[test]
757 fn replace_associated_function_with_generics() {
758     assert_ssr_transform(
759         "c::Foo::<$a>::new() ==>> d::Bar::<$a>::default()",
760         r#"
761             mod c {
762                 pub struct Foo<T> {v: T}
763                 impl<T> Foo<T> { pub fn new() {} }
764                 fn f1() {
765                     Foo::<i32>::new();
766                 }
767             }
768             mod d {
769                 pub struct Bar<T> {v: T}
770                 impl<T> Bar<T> { pub fn default() {} }
771                 fn f1() {
772                     super::c::Foo::<i32>::new();
773                 }
774             }
775             "#,
776         expect![[r#"
777             mod c {
778                 pub struct Foo<T> {v: T}
779                 impl<T> Foo<T> { pub fn new() {} }
780                 fn f1() {
781                     crate::d::Bar::<i32>::default();
782                 }
783             }
784             mod d {
785                 pub struct Bar<T> {v: T}
786                 impl<T> Bar<T> { pub fn default() {} }
787                 fn f1() {
788                     Bar::<i32>::default();
789                 }
790             }
791             "#]],
792     );
793 }
794
795 #[test]
796 fn replace_type() {
797     assert_ssr_transform(
798         "Result<(), $a> ==>> Option<$a>",
799         "struct Result<T, E> {} struct Option<T> {} fn f1() -> Result<(), Vec<Error>> {foo()}",
800         expect![[
801             "struct Result<T, E> {} struct Option<T> {} fn f1() -> Option<Vec<Error>> {foo()}"
802         ]],
803     );
804     assert_ssr_transform(
805         "dyn Trait<$a> ==>> DynTrait<$a>",
806         r#"
807 trait Trait<T> {}
808 struct DynTrait<T> {}
809 fn f1() -> dyn Trait<Vec<Error>> {foo()}
810 "#,
811         expect![[r#"
812 trait Trait<T> {}
813 struct DynTrait<T> {}
814 fn f1() -> DynTrait<Vec<Error>> {foo()}
815 "#]],
816     );
817 }
818
819 #[test]
820 fn replace_macro_invocations() {
821     assert_ssr_transform(
822         "try!($a) ==>> $a?",
823         "macro_rules! try {() => {}} fn f1() -> Result<(), E> {bar(try!(foo()));}",
824         expect![["macro_rules! try {() => {}} fn f1() -> Result<(), E> {bar(foo()?);}"]],
825     );
826     // FIXME: Figure out why this doesn't work anymore
827     // assert_ssr_transform(
828     //     "foo!($a($b)) ==>> foo($b, $a)",
829     //     "macro_rules! foo {() => {}} fn f1() {foo!(abc(def() + 2));}",
830     //     expect![["macro_rules! foo {() => {}} fn f1() {foo(def() + 2, abc);}"]],
831     // );
832 }
833
834 #[test]
835 fn replace_binary_op() {
836     assert_ssr_transform(
837         "$a + $b ==>> $b + $a",
838         "fn f() {2 * 3 + 4 * 5}",
839         expect![["fn f() {4 * 5 + 2 * 3}"]],
840     );
841     assert_ssr_transform(
842         "$a + $b ==>> $b + $a",
843         "fn f() {1 + 2 + 3 + 4}",
844         expect![[r#"fn f() {4 + (3 + (2 + 1))}"#]],
845     );
846 }
847
848 #[test]
849 fn match_binary_op() {
850     assert_matches("$a + $b", "fn f() {1 + 2 + 3 + 4}", &["1 + 2", "1 + 2 + 3", "1 + 2 + 3 + 4"]);
851 }
852
853 #[test]
854 fn multiple_rules() {
855     assert_ssr_transforms(
856         &["$a + 1 ==>> add_one($a)", "$a + $b ==>> add($a, $b)"],
857         "fn add() {} fn add_one() {} fn f() -> i32 {3 + 2 + 1}",
858         expect![["fn add() {} fn add_one() {} fn f() -> i32 {add_one(add(3, 2))}"]],
859     )
860 }
861
862 #[test]
863 fn multiple_rules_with_nested_matches() {
864     assert_ssr_transforms(
865         &["foo1($a) ==>> bar1($a)", "foo2($a) ==>> bar2($a)"],
866         r#"
867             fn foo1() {} fn foo2() {} fn bar1() {} fn bar2() {}
868             fn f() {foo1(foo2(foo1(foo2(foo1(42)))))}
869             "#,
870         expect![[r#"
871             fn foo1() {} fn foo2() {} fn bar1() {} fn bar2() {}
872             fn f() {bar1(bar2(bar1(bar2(bar1(42)))))}
873         "#]],
874     )
875 }
876
877 #[test]
878 fn match_within_macro_invocation() {
879     let code = r#"
880             macro_rules! foo {
881                 ($a:stmt; $b:expr) => {
882                     $b
883                 };
884             }
885             struct A {}
886             impl A {
887                 fn bar() {}
888             }
889             fn f1() {
890                 let aaa = A {};
891                 foo!(macro_ignores_this(); aaa.bar());
892             }
893         "#;
894     assert_matches("$a.bar()", code, &["aaa.bar()"]);
895 }
896
897 #[test]
898 fn replace_within_macro_expansion() {
899     assert_ssr_transform(
900         "$a.foo() ==>> bar($a)",
901         r#"
902             macro_rules! macro1 {
903                 ($a:expr) => {$a}
904             }
905             fn bar() {}
906             fn f() {macro1!(5.x().foo().o2())}
907             "#,
908         expect![[r#"
909             macro_rules! macro1 {
910                 ($a:expr) => {$a}
911             }
912             fn bar() {}
913             fn f() {macro1!(bar(5.x()).o2())}
914             "#]],
915     )
916 }
917
918 #[test]
919 fn replace_outside_and_within_macro_expansion() {
920     assert_ssr_transform(
921         "foo($a) ==>> bar($a)",
922         r#"
923             fn foo() {} fn bar() {}
924             macro_rules! macro1 {
925                 ($a:expr) => {$a}
926             }
927             fn f() {foo(foo(macro1!(foo(foo(42)))))}
928             "#,
929         expect![[r#"
930             fn foo() {} fn bar() {}
931             macro_rules! macro1 {
932                 ($a:expr) => {$a}
933             }
934             fn f() {bar(bar(macro1!(bar(bar(42)))))}
935         "#]],
936     )
937 }
938
939 #[test]
940 fn preserves_whitespace_within_macro_expansion() {
941     assert_ssr_transform(
942         "$a + $b ==>> $b - $a",
943         r#"
944             macro_rules! macro1 {
945                 ($a:expr) => {$a}
946             }
947             fn f() {macro1!(1   *   2 + 3 + 4)}
948             "#,
949         expect![[r#"
950             macro_rules! macro1 {
951                 ($a:expr) => {$a}
952             }
953             fn f() {macro1!(4 - (3 - 1   *   2))}
954             "#]],
955     )
956 }
957
958 #[test]
959 fn add_parenthesis_when_necessary() {
960     assert_ssr_transform(
961         "foo($a) ==>> $a.to_string()",
962         r#"
963         fn foo(_: i32) {}
964         fn bar3(v: i32) {
965             foo(1 + 2);
966             foo(-v);
967         }
968         "#,
969         expect![[r#"
970             fn foo(_: i32) {}
971             fn bar3(v: i32) {
972                 (1 + 2).to_string();
973                 (-v).to_string();
974             }
975         "#]],
976     )
977 }
978
979 #[test]
980 fn match_failure_reasons() {
981     let code = r#"
982         fn bar() {}
983         macro_rules! foo {
984             ($a:expr) => {
985                 1 + $a + 2
986             };
987         }
988         fn f1() {
989             bar(1, 2);
990             foo!(5 + 43.to_string() + 5);
991         }
992         "#;
993     assert_match_failure_reason(
994         "bar($a, 3)",
995         code,
996         "bar(1, 2)",
997         r#"Pattern wanted token '3' (INT_NUMBER), but code had token '2' (INT_NUMBER)"#,
998     );
999     assert_match_failure_reason(
1000         "42.to_string()",
1001         code,
1002         "43.to_string()",
1003         r#"Pattern wanted token '42' (INT_NUMBER), but code had token '43' (INT_NUMBER)"#,
1004     );
1005 }
1006
1007 #[test]
1008 fn overlapping_possible_matches() {
1009     // There are three possible matches here, however the middle one, `foo(foo(foo(42)))` shouldn't
1010     // match because it overlaps with the outer match. The inner match is permitted since it's is
1011     // contained entirely within the placeholder of the outer match.
1012     assert_matches(
1013         "foo(foo($a))",
1014         "fn foo() {} fn main() {foo(foo(foo(foo(42))))}",
1015         &["foo(foo(42))", "foo(foo(foo(foo(42))))"],
1016     );
1017 }
1018
1019 #[test]
1020 fn use_declaration_with_braces() {
1021     // It would be OK for a path rule to match and alter a use declaration. We shouldn't mess it up
1022     // though. In particular, we must not change `use foo::{baz, bar}` to `use foo::{baz,
1023     // foo2::bar2}`.
1024     cov_mark::check!(use_declaration_with_braces);
1025     assert_ssr_transform(
1026         "foo::bar ==>> foo2::bar2",
1027         r#"
1028         mod foo { pub fn bar() {} pub fn baz() {} }
1029         mod foo2 { pub fn bar2() {} }
1030         use foo::{baz, bar};
1031         fn main() { bar() }
1032         "#,
1033         expect![["
1034         mod foo { pub fn bar() {} pub fn baz() {} }
1035         mod foo2 { pub fn bar2() {} }
1036         use foo::{baz, bar};
1037         fn main() { foo2::bar2() }
1038         "]],
1039     )
1040 }
1041
1042 #[test]
1043 fn ufcs_matches_method_call() {
1044     let code = r#"
1045     struct Foo {}
1046     impl Foo {
1047         fn new(_: i32) -> Foo { Foo {} }
1048         fn do_stuff(&self, _: i32) {}
1049     }
1050     struct Bar {}
1051     impl Bar {
1052         fn new(_: i32) -> Bar { Bar {} }
1053         fn do_stuff(&self, v: i32) {}
1054     }
1055     fn main() {
1056         let b = Bar {};
1057         let f = Foo {};
1058         b.do_stuff(1);
1059         f.do_stuff(2);
1060         Foo::new(4).do_stuff(3);
1061         // Too many / too few args - should never match
1062         f.do_stuff(2, 10);
1063         f.do_stuff();
1064     }
1065     "#;
1066     assert_matches("Foo::do_stuff($a, $b)", code, &["f.do_stuff(2)", "Foo::new(4).do_stuff(3)"]);
1067     // The arguments needs special handling in the case of a function call matching a method call
1068     // and the first argument is different.
1069     assert_matches("Foo::do_stuff($a, 2)", code, &["f.do_stuff(2)"]);
1070     assert_matches("Foo::do_stuff(Foo::new(4), $b)", code, &["Foo::new(4).do_stuff(3)"]);
1071
1072     assert_ssr_transform(
1073         "Foo::do_stuff(Foo::new($a), $b) ==>> Bar::new($b).do_stuff($a)",
1074         code,
1075         expect![[r#"
1076             struct Foo {}
1077             impl Foo {
1078                 fn new(_: i32) -> Foo { Foo {} }
1079                 fn do_stuff(&self, _: i32) {}
1080             }
1081             struct Bar {}
1082             impl Bar {
1083                 fn new(_: i32) -> Bar { Bar {} }
1084                 fn do_stuff(&self, v: i32) {}
1085             }
1086             fn main() {
1087                 let b = Bar {};
1088                 let f = Foo {};
1089                 b.do_stuff(1);
1090                 f.do_stuff(2);
1091                 Bar::new(3).do_stuff(4);
1092                 // Too many / too few args - should never match
1093                 f.do_stuff(2, 10);
1094                 f.do_stuff();
1095             }
1096         "#]],
1097     );
1098 }
1099
1100 #[test]
1101 fn pattern_is_a_single_segment_path() {
1102     cov_mark::check!(pattern_is_a_single_segment_path);
1103     // The first function should not be altered because the `foo` in scope at the cursor position is
1104     // a different `foo`. This case is special because "foo" can be parsed as a pattern (IDENT_PAT ->
1105     // NAME -> IDENT), which contains no path. If we're not careful we'll end up matching the `foo`
1106     // in `let foo` from the first function. Whether we should match the `let foo` in the second
1107     // function is less clear. At the moment, we don't. Doing so sounds like a rename operation,
1108     // which isn't really what SSR is for, especially since the replacement `bar` must be able to be
1109     // resolved, which means if we rename `foo` we'll get a name collision.
1110     assert_ssr_transform(
1111         "foo ==>> bar",
1112         r#"
1113         fn f1() -> i32 {
1114             let foo = 1;
1115             let bar = 2;
1116             foo
1117         }
1118         fn f1() -> i32 {
1119             let foo = 1;
1120             let bar = 2;
1121             foo$0
1122         }
1123         "#,
1124         expect![[r#"
1125             fn f1() -> i32 {
1126                 let foo = 1;
1127                 let bar = 2;
1128                 foo
1129             }
1130             fn f1() -> i32 {
1131                 let foo = 1;
1132                 let bar = 2;
1133                 bar
1134             }
1135         "#]],
1136     );
1137 }
1138
1139 #[test]
1140 fn replace_local_variable_reference() {
1141     // The pattern references a local variable `foo` in the block containing the cursor. We should
1142     // only replace references to this variable `foo`, not other variables that just happen to have
1143     // the same name.
1144     cov_mark::check!(cursor_after_semicolon);
1145     assert_ssr_transform(
1146         "foo + $a ==>> $a - foo",
1147         r#"
1148             fn bar1() -> i32 {
1149                 let mut res = 0;
1150                 let foo = 5;
1151                 res += foo + 1;
1152                 let foo = 10;
1153                 res += foo + 2;$0
1154                 res += foo + 3;
1155                 let foo = 15;
1156                 res += foo + 4;
1157                 res
1158             }
1159             "#,
1160         expect![[r#"
1161             fn bar1() -> i32 {
1162                 let mut res = 0;
1163                 let foo = 5;
1164                 res += foo + 1;
1165                 let foo = 10;
1166                 res += 2 - foo;
1167                 res += 3 - foo;
1168                 let foo = 15;
1169                 res += foo + 4;
1170                 res
1171             }
1172         "#]],
1173     )
1174 }
1175
1176 #[test]
1177 fn replace_path_within_selection() {
1178     assert_ssr_transform(
1179         "foo ==>> bar",
1180         r#"
1181         fn main() {
1182             let foo = 41;
1183             let bar = 42;
1184             do_stuff(foo);
1185             do_stuff(foo);$0
1186             do_stuff(foo);
1187             do_stuff(foo);$0
1188             do_stuff(foo);
1189         }"#,
1190         expect![[r#"
1191             fn main() {
1192                 let foo = 41;
1193                 let bar = 42;
1194                 do_stuff(foo);
1195                 do_stuff(foo);
1196                 do_stuff(bar);
1197                 do_stuff(bar);
1198                 do_stuff(foo);
1199             }"#]],
1200     );
1201 }
1202
1203 #[test]
1204 fn replace_nonpath_within_selection() {
1205     cov_mark::check!(replace_nonpath_within_selection);
1206     assert_ssr_transform(
1207         "$a + $b ==>> $b * $a",
1208         r#"
1209         fn main() {
1210             let v = 1 + 2;$0
1211             let v2 = 3 + 3;
1212             let v3 = 4 + 5;$0
1213             let v4 = 6 + 7;
1214         }"#,
1215         expect![[r#"
1216             fn main() {
1217                 let v = 1 + 2;
1218                 let v2 = 3 * 3;
1219                 let v3 = 5 * 4;
1220                 let v4 = 6 + 7;
1221             }"#]],
1222     );
1223 }
1224
1225 #[test]
1226 fn replace_self() {
1227     // `foo(self)` occurs twice in the code, however only the first occurrence is the `self` that's
1228     // in scope where the rule is invoked.
1229     assert_ssr_transform(
1230         "foo(self) ==>> bar(self)",
1231         r#"
1232         struct S1 {}
1233         fn foo(_: &S1) {}
1234         fn bar(_: &S1) {}
1235         impl S1 {
1236             fn f1(&self) {
1237                 foo(self)$0
1238             }
1239             fn f2(&self) {
1240                 foo(self)
1241             }
1242         }
1243         "#,
1244         expect![[r#"
1245             struct S1 {}
1246             fn foo(_: &S1) {}
1247             fn bar(_: &S1) {}
1248             impl S1 {
1249                 fn f1(&self) {
1250                     bar(self)
1251                 }
1252                 fn f2(&self) {
1253                     foo(self)
1254                 }
1255             }
1256         "#]],
1257     );
1258 }
1259
1260 #[test]
1261 fn match_trait_method_call() {
1262     // `Bar::foo` and `Bar2::foo` resolve to the same function. Make sure we only match if the type
1263     // matches what's in the pattern. Also checks that we handle autoderef.
1264     let code = r#"
1265         pub struct Bar {}
1266         pub struct Bar2 {}
1267         pub trait Foo {
1268             fn foo(&self, _: i32) {}
1269         }
1270         impl Foo for Bar {}
1271         impl Foo for Bar2 {}
1272         fn main() {
1273             let v1 = Bar {};
1274             let v2 = Bar2 {};
1275             let v1_ref = &v1;
1276             let v2_ref = &v2;
1277             v1.foo(1);
1278             v2.foo(2);
1279             Bar::foo(&v1, 3);
1280             Bar2::foo(&v2, 4);
1281             v1_ref.foo(5);
1282             v2_ref.foo(6);
1283         }
1284         "#;
1285     assert_matches("Bar::foo($a, $b)", code, &["v1.foo(1)", "Bar::foo(&v1, 3)", "v1_ref.foo(5)"]);
1286     assert_matches("Bar2::foo($a, $b)", code, &["v2.foo(2)", "Bar2::foo(&v2, 4)", "v2_ref.foo(6)"]);
1287 }
1288
1289 #[test]
1290 fn replace_autoref_autoderef_capture() {
1291     // Here we have several calls to `$a.foo()`. In the first case autoref is applied, in the
1292     // second, we already have a reference, so it isn't. When $a is used in a context where autoref
1293     // doesn't apply, we need to prefix it with `&`. Finally, we have some cases where autoderef
1294     // needs to be applied.
1295     cov_mark::check!(replace_autoref_autoderef_capture);
1296     let code = r#"
1297         struct Foo {}
1298         impl Foo {
1299             fn foo(&self) {}
1300             fn foo2(&self) {}
1301         }
1302         fn bar(_: &Foo) {}
1303         fn main() {
1304             let f = Foo {};
1305             let fr = &f;
1306             let fr2 = &fr;
1307             let fr3 = &fr2;
1308             f.foo();
1309             fr.foo();
1310             fr2.foo();
1311             fr3.foo();
1312         }
1313         "#;
1314     assert_ssr_transform(
1315         "Foo::foo($a) ==>> bar($a)",
1316         code,
1317         expect![[r#"
1318             struct Foo {}
1319             impl Foo {
1320                 fn foo(&self) {}
1321                 fn foo2(&self) {}
1322             }
1323             fn bar(_: &Foo) {}
1324             fn main() {
1325                 let f = Foo {};
1326                 let fr = &f;
1327                 let fr2 = &fr;
1328                 let fr3 = &fr2;
1329                 bar(&f);
1330                 bar(&*fr);
1331                 bar(&**fr2);
1332                 bar(&***fr3);
1333             }
1334         "#]],
1335     );
1336     // If the placeholder is used as the receiver of another method call, then we don't need to
1337     // explicitly autoderef or autoref.
1338     assert_ssr_transform(
1339         "Foo::foo($a) ==>> $a.foo2()",
1340         code,
1341         expect![[r#"
1342             struct Foo {}
1343             impl Foo {
1344                 fn foo(&self) {}
1345                 fn foo2(&self) {}
1346             }
1347             fn bar(_: &Foo) {}
1348             fn main() {
1349                 let f = Foo {};
1350                 let fr = &f;
1351                 let fr2 = &fr;
1352                 let fr3 = &fr2;
1353                 f.foo2();
1354                 fr.foo2();
1355                 fr2.foo2();
1356                 fr3.foo2();
1357             }
1358         "#]],
1359     );
1360 }
1361
1362 #[test]
1363 fn replace_autoref_mut() {
1364     let code = r#"
1365         struct Foo {}
1366         impl Foo {
1367             fn foo(&mut self) {}
1368         }
1369         fn bar(_: &mut Foo) {}
1370         fn main() {
1371             let mut f = Foo {};
1372             f.foo();
1373             let fr = &mut f;
1374             fr.foo();
1375         }
1376         "#;
1377     assert_ssr_transform(
1378         "Foo::foo($a) ==>> bar($a)",
1379         code,
1380         expect![[r#"
1381             struct Foo {}
1382             impl Foo {
1383                 fn foo(&mut self) {}
1384             }
1385             fn bar(_: &mut Foo) {}
1386             fn main() {
1387                 let mut f = Foo {};
1388                 bar(&mut f);
1389                 let fr = &mut f;
1390                 bar(&mut *fr);
1391             }
1392         "#]],
1393     );
1394 }