]> git.lizzy.rs Git - rust.git/blob - crates/ide_ssr/src/tests.rs
remove Item::parse
[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);
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);
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);
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);
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 ignores_whitespace() {
336     assert_matches("1+2", "fn f() -> i32 {1  +  2}", &["1  +  2"]);
337     assert_matches("1 + 2", "fn f() -> i32 {1+2}", &["1+2"]);
338 }
339
340 #[test]
341 fn no_match() {
342     assert_no_match("1 + 3", "fn f() -> i32 {1  +  2}");
343 }
344
345 #[test]
346 fn match_fn_definition() {
347     assert_matches("fn $a($b: $t) {$c}", "fn f(a: i32) {bar()}", &["fn f(a: i32) {bar()}"]);
348 }
349
350 #[test]
351 fn match_struct_definition() {
352     let code = r#"
353         struct Option<T> {}
354         struct Bar {}
355         struct Foo {name: Option<String>}"#;
356     assert_matches("struct $n {$f: Option<String>}", code, &["struct Foo {name: Option<String>}"]);
357 }
358
359 #[test]
360 fn match_expr() {
361     let code = r#"
362         fn foo() {}
363         fn f() -> i32 {foo(40 + 2, 42)}"#;
364     assert_matches("foo($a, $b)", code, &["foo(40 + 2, 42)"]);
365     assert_no_match("foo($a, $b, $c)", code);
366     assert_no_match("foo($a)", code);
367 }
368
369 #[test]
370 fn match_nested_method_calls() {
371     assert_matches(
372         "$a.z().z().z()",
373         "fn f() {h().i().j().z().z().z().d().e()}",
374         &["h().i().j().z().z().z()"],
375     );
376 }
377
378 // Make sure that our node matching semantics don't differ within macro calls.
379 #[test]
380 fn match_nested_method_calls_with_macro_call() {
381     assert_matches(
382         "$a.z().z().z()",
383         r#"
384             macro_rules! m1 { ($a:expr) => {$a}; }
385             fn f() {m1!(h().i().j().z().z().z().d().e())}"#,
386         &["h().i().j().z().z().z()"],
387     );
388 }
389
390 #[test]
391 fn match_complex_expr() {
392     let code = r#"
393         fn foo() {} fn bar() {}
394         fn f() -> i32 {foo(bar(40, 2), 42)}"#;
395     assert_matches("foo($a, $b)", code, &["foo(bar(40, 2), 42)"]);
396     assert_no_match("foo($a, $b, $c)", code);
397     assert_no_match("foo($a)", code);
398     assert_matches("bar($a, $b)", code, &["bar(40, 2)"]);
399 }
400
401 // Trailing commas in the code should be ignored.
402 #[test]
403 fn match_with_trailing_commas() {
404     // Code has comma, pattern doesn't.
405     assert_matches("foo($a, $b)", "fn foo() {} fn f() {foo(1, 2,);}", &["foo(1, 2,)"]);
406     assert_matches("Foo{$a, $b}", "struct Foo {} fn f() {Foo{1, 2,};}", &["Foo{1, 2,}"]);
407
408     // Pattern has comma, code doesn't.
409     assert_matches("foo($a, $b,)", "fn foo() {} fn f() {foo(1, 2);}", &["foo(1, 2)"]);
410     assert_matches("Foo{$a, $b,}", "struct Foo {} fn f() {Foo{1, 2};}", &["Foo{1, 2}"]);
411 }
412
413 #[test]
414 fn match_type() {
415     assert_matches("i32", "fn f() -> i32 {1  +  2}", &["i32"]);
416     assert_matches(
417         "Option<$a>",
418         "struct Option<T> {} fn f() -> Option<i32> {42}",
419         &["Option<i32>"],
420     );
421     assert_no_match(
422         "Option<$a>",
423         "struct Option<T> {} struct Result<T, E> {} fn f() -> Result<i32, ()> {42}",
424     );
425 }
426
427 #[test]
428 fn match_struct_instantiation() {
429     let code = r#"
430         struct Foo {bar: i32, baz: i32}
431         fn f() {Foo {bar: 1, baz: 2}}"#;
432     assert_matches("Foo {bar: 1, baz: 2}", code, &["Foo {bar: 1, baz: 2}"]);
433     // Now with placeholders for all parts of the struct.
434     assert_matches("Foo {$a: $b, $c: $d}", code, &["Foo {bar: 1, baz: 2}"]);
435     assert_matches("Foo {}", "struct Foo {} fn f() {Foo {}}", &["Foo {}"]);
436 }
437
438 #[test]
439 fn match_path() {
440     let code = r#"
441         mod foo {
442             pub fn bar() {}
443         }
444         fn f() {foo::bar(42)}"#;
445     assert_matches("foo::bar", code, &["foo::bar"]);
446     assert_matches("$a::bar", code, &["foo::bar"]);
447     assert_matches("foo::$b", code, &["foo::bar"]);
448 }
449
450 #[test]
451 fn match_pattern() {
452     assert_matches("Some($a)", "struct Some(); fn f() {if let Some(x) = foo() {}}", &["Some(x)"]);
453 }
454
455 // If our pattern has a full path, e.g. a::b::c() and the code has c(), but c resolves to
456 // a::b::c, then we should match.
457 #[test]
458 fn match_fully_qualified_fn_path() {
459     let code = r#"
460         mod a {
461             pub mod b {
462                 pub fn c(_: i32) {}
463             }
464         }
465         use a::b::c;
466         fn f1() {
467             c(42);
468         }
469         "#;
470     assert_matches("a::b::c($a)", code, &["c(42)"]);
471 }
472
473 #[test]
474 fn match_resolved_type_name() {
475     let code = r#"
476         mod m1 {
477             pub mod m2 {
478                 pub trait Foo<T> {}
479             }
480         }
481         mod m3 {
482             trait Foo<T> {}
483             fn f1(f: Option<&dyn Foo<bool>>) {}
484         }
485         mod m4 {
486             use crate::m1::m2::Foo;
487             fn f1(f: Option<&dyn Foo<i32>>) {}
488         }
489         "#;
490     assert_matches("m1::m2::Foo<$t>", code, &["Foo<i32>"]);
491 }
492
493 #[test]
494 fn type_arguments_within_path() {
495     cov_mark::check!(type_arguments_within_path);
496     let code = r#"
497         mod foo {
498             pub struct Bar<T> {t: T}
499             impl<T> Bar<T> {
500                 pub fn baz() {}
501             }
502         }
503         fn f1() {foo::Bar::<i32>::baz();}
504         "#;
505     assert_no_match("foo::Bar::<i64>::baz()", code);
506     assert_matches("foo::Bar::<i32>::baz()", code, &["foo::Bar::<i32>::baz()"]);
507 }
508
509 #[test]
510 fn literal_constraint() {
511     cov_mark::check!(literal_constraint);
512     let code = r#"
513         enum Option<T> { Some(T), None }
514         use Option::Some;
515         fn f1() {
516             let x1 = Some(42);
517             let x2 = Some("foo");
518             let x3 = Some(x1);
519             let x4 = Some(40 + 2);
520             let x5 = Some(true);
521         }
522         "#;
523     assert_matches("Some(${a:kind(literal)})", code, &["Some(42)", "Some(\"foo\")", "Some(true)"]);
524     assert_matches("Some(${a:not(kind(literal))})", code, &["Some(x1)", "Some(40 + 2)"]);
525 }
526
527 #[test]
528 fn match_reordered_struct_instantiation() {
529     assert_matches(
530         "Foo {aa: 1, b: 2, ccc: 3}",
531         "struct Foo {} fn f() {Foo {b: 2, ccc: 3, aa: 1}}",
532         &["Foo {b: 2, ccc: 3, aa: 1}"],
533     );
534     assert_no_match("Foo {a: 1}", "struct Foo {} fn f() {Foo {b: 1}}");
535     assert_no_match("Foo {a: 1}", "struct Foo {} fn f() {Foo {a: 2}}");
536     assert_no_match("Foo {a: 1, b: 2}", "struct Foo {} fn f() {Foo {a: 1}}");
537     assert_no_match("Foo {a: 1, b: 2}", "struct Foo {} fn f() {Foo {b: 2}}");
538     assert_no_match("Foo {a: 1, }", "struct Foo {} fn f() {Foo {a: 1, b: 2}}");
539     assert_no_match("Foo {a: 1, z: 9}", "struct Foo {} fn f() {Foo {a: 1}}");
540 }
541
542 #[test]
543 fn match_macro_invocation() {
544     assert_matches(
545         "foo!($a)",
546         "macro_rules! foo {() => {}} fn() {foo(foo!(foo()))}",
547         &["foo!(foo())"],
548     );
549     assert_matches(
550         "foo!(41, $a, 43)",
551         "macro_rules! foo {() => {}} fn() {foo!(41, 42, 43)}",
552         &["foo!(41, 42, 43)"],
553     );
554     assert_no_match("foo!(50, $a, 43)", "macro_rules! foo {() => {}} fn() {foo!(41, 42, 43}");
555     assert_no_match("foo!(41, $a, 50)", "macro_rules! foo {() => {}} fn() {foo!(41, 42, 43}");
556     assert_matches(
557         "foo!($a())",
558         "macro_rules! foo {() => {}} fn() {foo!(bar())}",
559         &["foo!(bar())"],
560     );
561 }
562
563 // When matching within a macro expansion, we only allow matches of nodes that originated from
564 // the macro call, not from the macro definition.
565 #[test]
566 fn no_match_expression_from_macro() {
567     assert_no_match(
568         "$a.clone()",
569         r#"
570             macro_rules! m1 {
571                 () => {42.clone()}
572             }
573             fn f1() {m1!()}
574             "#,
575     );
576 }
577
578 // We definitely don't want to allow matching of an expression that part originates from the
579 // macro call `42` and part from the macro definition `.clone()`.
580 #[test]
581 fn no_match_split_expression() {
582     assert_no_match(
583         "$a.clone()",
584         r#"
585             macro_rules! m1 {
586                 ($x:expr) => {$x.clone()}
587             }
588             fn f1() {m1!(42)}
589             "#,
590     );
591 }
592
593 #[test]
594 fn replace_function_call() {
595     // This test also makes sure that we ignore empty-ranges.
596     assert_ssr_transform(
597         "foo() ==>> bar()",
598         "fn foo() {$0$0} fn bar() {} fn f1() {foo(); foo();}",
599         expect![["fn foo() {} fn bar() {} fn f1() {bar(); bar();}"]],
600     );
601 }
602
603 #[test]
604 fn replace_function_call_with_placeholders() {
605     assert_ssr_transform(
606         "foo($a, $b) ==>> bar($b, $a)",
607         "fn foo() {} fn bar() {} fn f1() {foo(5, 42)}",
608         expect![["fn foo() {} fn bar() {} fn f1() {bar(42, 5)}"]],
609     );
610 }
611
612 #[test]
613 fn replace_nested_function_calls() {
614     assert_ssr_transform(
615         "foo($a) ==>> bar($a)",
616         "fn foo() {} fn bar() {} fn f1() {foo(foo(42))}",
617         expect![["fn foo() {} fn bar() {} fn f1() {bar(bar(42))}"]],
618     );
619 }
620
621 #[test]
622 fn replace_associated_function_call() {
623     assert_ssr_transform(
624         "Foo::new() ==>> Bar::new()",
625         r#"
626             struct Foo {}
627             impl Foo { fn new() {} }
628             struct Bar {}
629             impl Bar { fn new() {} }
630             fn f1() {Foo::new();}
631             "#,
632         expect![[r#"
633             struct Foo {}
634             impl Foo { fn new() {} }
635             struct Bar {}
636             impl Bar { fn new() {} }
637             fn f1() {Bar::new();}
638         "#]],
639     );
640 }
641
642 #[test]
643 fn replace_associated_trait_default_function_call() {
644     cov_mark::check!(replace_associated_trait_default_function_call);
645     assert_ssr_transform(
646         "Bar2::foo() ==>> Bar2::foo2()",
647         r#"
648             trait Foo { fn foo() {} }
649             pub struct Bar {}
650             impl Foo for Bar {}
651             pub struct Bar2 {}
652             impl Foo for Bar2 {}
653             impl Bar2 { fn foo2() {} }
654             fn main() {
655                 Bar::foo();
656                 Bar2::foo();
657             }
658         "#,
659         expect![[r#"
660             trait Foo { fn foo() {} }
661             pub struct Bar {}
662             impl Foo for Bar {}
663             pub struct Bar2 {}
664             impl Foo for Bar2 {}
665             impl Bar2 { fn foo2() {} }
666             fn main() {
667                 Bar::foo();
668                 Bar2::foo2();
669             }
670         "#]],
671     );
672 }
673
674 #[test]
675 fn replace_associated_trait_constant() {
676     cov_mark::check!(replace_associated_trait_constant);
677     assert_ssr_transform(
678         "Bar2::VALUE ==>> Bar2::VALUE_2222",
679         r#"
680             trait Foo { const VALUE: i32; const VALUE_2222: i32; }
681             pub struct Bar {}
682             impl Foo for Bar { const VALUE: i32 = 1;  const VALUE_2222: i32 = 2; }
683             pub struct Bar2 {}
684             impl Foo for Bar2 { const VALUE: i32 = 1;  const VALUE_2222: i32 = 2; }
685             impl Bar2 { fn foo2() {} }
686             fn main() {
687                 Bar::VALUE;
688                 Bar2::VALUE;
689             }
690             "#,
691         expect![[r#"
692             trait Foo { const VALUE: i32; const VALUE_2222: i32; }
693             pub struct Bar {}
694             impl Foo for Bar { const VALUE: i32 = 1;  const VALUE_2222: i32 = 2; }
695             pub struct Bar2 {}
696             impl Foo for Bar2 { const VALUE: i32 = 1;  const VALUE_2222: i32 = 2; }
697             impl Bar2 { fn foo2() {} }
698             fn main() {
699                 Bar::VALUE;
700                 Bar2::VALUE_2222;
701             }
702         "#]],
703     );
704 }
705
706 #[test]
707 fn replace_path_in_different_contexts() {
708     // Note the $0 inside module a::b which marks the point where the rule is interpreted. We
709     // replace foo with bar, but both need different path qualifiers in different contexts. In f4,
710     // foo is unqualified because of a use statement, however the replacement needs to be fully
711     // qualified.
712     assert_ssr_transform(
713         "c::foo() ==>> c::bar()",
714         r#"
715             mod a {
716                 pub mod b {$0
717                     pub mod c {
718                         pub fn foo() {}
719                         pub fn bar() {}
720                         fn f1() { foo() }
721                     }
722                     fn f2() { c::foo() }
723                 }
724                 fn f3() { b::c::foo() }
725             }
726             use a::b::c::foo;
727             fn f4() { foo() }
728             "#,
729         expect![[r#"
730             mod a {
731                 pub mod b {
732                     pub mod c {
733                         pub fn foo() {}
734                         pub fn bar() {}
735                         fn f1() { bar() }
736                     }
737                     fn f2() { c::bar() }
738                 }
739                 fn f3() { b::c::bar() }
740             }
741             use a::b::c::foo;
742             fn f4() { a::b::c::bar() }
743             "#]],
744     );
745 }
746
747 #[test]
748 fn replace_associated_function_with_generics() {
749     assert_ssr_transform(
750         "c::Foo::<$a>::new() ==>> d::Bar::<$a>::default()",
751         r#"
752             mod c {
753                 pub struct Foo<T> {v: T}
754                 impl<T> Foo<T> { pub fn new() {} }
755                 fn f1() {
756                     Foo::<i32>::new();
757                 }
758             }
759             mod d {
760                 pub struct Bar<T> {v: T}
761                 impl<T> Bar<T> { pub fn default() {} }
762                 fn f1() {
763                     super::c::Foo::<i32>::new();
764                 }
765             }
766             "#,
767         expect![[r#"
768             mod c {
769                 pub struct Foo<T> {v: T}
770                 impl<T> Foo<T> { pub fn new() {} }
771                 fn f1() {
772                     crate::d::Bar::<i32>::default();
773                 }
774             }
775             mod d {
776                 pub struct Bar<T> {v: T}
777                 impl<T> Bar<T> { pub fn default() {} }
778                 fn f1() {
779                     Bar::<i32>::default();
780                 }
781             }
782             "#]],
783     );
784 }
785
786 #[test]
787 fn replace_type() {
788     assert_ssr_transform(
789         "Result<(), $a> ==>> Option<$a>",
790         "struct Result<T, E> {} struct Option<T> {} fn f1() -> Result<(), Vec<Error>> {foo()}",
791         expect![[
792             "struct Result<T, E> {} struct Option<T> {} fn f1() -> Option<Vec<Error>> {foo()}"
793         ]],
794     );
795     assert_ssr_transform(
796         "dyn Trait<$a> ==>> DynTrait<$a>",
797         r#"
798 trait Trait<T> {}
799 struct DynTrait<T> {}
800 fn f1() -> dyn Trait<Vec<Error>> {foo()}
801 "#,
802         expect![[r#"
803 trait Trait<T> {}
804 struct DynTrait<T> {}
805 fn f1() -> DynTrait<Vec<Error>> {foo()}
806 "#]],
807     );
808 }
809
810 #[test]
811 fn replace_macro_invocations() {
812     assert_ssr_transform(
813         "try!($a) ==>> $a?",
814         "macro_rules! try {() => {}} fn f1() -> Result<(), E> {bar(try!(foo()));}",
815         expect![["macro_rules! try {() => {}} fn f1() -> Result<(), E> {bar(foo()?);}"]],
816     );
817     assert_ssr_transform(
818         "foo!($a($b)) ==>> foo($b, $a)",
819         "macro_rules! foo {() => {}} fn f1() {foo!(abc(def() + 2));}",
820         expect![["macro_rules! foo {() => {}} fn f1() {foo(def() + 2, abc);}"]],
821     );
822 }
823
824 #[test]
825 fn replace_binary_op() {
826     assert_ssr_transform(
827         "$a + $b ==>> $b + $a",
828         "fn f() {2 * 3 + 4 * 5}",
829         expect![["fn f() {4 * 5 + 2 * 3}"]],
830     );
831     assert_ssr_transform(
832         "$a + $b ==>> $b + $a",
833         "fn f() {1 + 2 + 3 + 4}",
834         expect![[r#"fn f() {4 + (3 + (2 + 1))}"#]],
835     );
836 }
837
838 #[test]
839 fn match_binary_op() {
840     assert_matches("$a + $b", "fn f() {1 + 2 + 3 + 4}", &["1 + 2", "1 + 2 + 3", "1 + 2 + 3 + 4"]);
841 }
842
843 #[test]
844 fn multiple_rules() {
845     assert_ssr_transforms(
846         &["$a + 1 ==>> add_one($a)", "$a + $b ==>> add($a, $b)"],
847         "fn add() {} fn add_one() {} fn f() -> i32 {3 + 2 + 1}",
848         expect![["fn add() {} fn add_one() {} fn f() -> i32 {add_one(add(3, 2))}"]],
849     )
850 }
851
852 #[test]
853 fn multiple_rules_with_nested_matches() {
854     assert_ssr_transforms(
855         &["foo1($a) ==>> bar1($a)", "foo2($a) ==>> bar2($a)"],
856         r#"
857             fn foo1() {} fn foo2() {} fn bar1() {} fn bar2() {}
858             fn f() {foo1(foo2(foo1(foo2(foo1(42)))))}
859             "#,
860         expect![[r#"
861             fn foo1() {} fn foo2() {} fn bar1() {} fn bar2() {}
862             fn f() {bar1(bar2(bar1(bar2(bar1(42)))))}
863         "#]],
864     )
865 }
866
867 #[test]
868 fn match_within_macro_invocation() {
869     let code = r#"
870             macro_rules! foo {
871                 ($a:stmt; $b:expr) => {
872                     $b
873                 };
874             }
875             struct A {}
876             impl A {
877                 fn bar() {}
878             }
879             fn f1() {
880                 let aaa = A {};
881                 foo!(macro_ignores_this(); aaa.bar());
882             }
883         "#;
884     assert_matches("$a.bar()", code, &["aaa.bar()"]);
885 }
886
887 #[test]
888 fn replace_within_macro_expansion() {
889     assert_ssr_transform(
890         "$a.foo() ==>> bar($a)",
891         r#"
892             macro_rules! macro1 {
893                 ($a:expr) => {$a}
894             }
895             fn bar() {}
896             fn f() {macro1!(5.x().foo().o2())}
897             "#,
898         expect![[r#"
899             macro_rules! macro1 {
900                 ($a:expr) => {$a}
901             }
902             fn bar() {}
903             fn f() {macro1!(bar(5.x()).o2())}
904             "#]],
905     )
906 }
907
908 #[test]
909 fn replace_outside_and_within_macro_expansion() {
910     assert_ssr_transform(
911         "foo($a) ==>> bar($a)",
912         r#"
913             fn foo() {} fn bar() {}
914             macro_rules! macro1 {
915                 ($a:expr) => {$a}
916             }
917             fn f() {foo(foo(macro1!(foo(foo(42)))))}
918             "#,
919         expect![[r#"
920             fn foo() {} fn bar() {}
921             macro_rules! macro1 {
922                 ($a:expr) => {$a}
923             }
924             fn f() {bar(bar(macro1!(bar(bar(42)))))}
925         "#]],
926     )
927 }
928
929 #[test]
930 fn preserves_whitespace_within_macro_expansion() {
931     assert_ssr_transform(
932         "$a + $b ==>> $b - $a",
933         r#"
934             macro_rules! macro1 {
935                 ($a:expr) => {$a}
936             }
937             fn f() {macro1!(1   *   2 + 3 + 4)}
938             "#,
939         expect![[r#"
940             macro_rules! macro1 {
941                 ($a:expr) => {$a}
942             }
943             fn f() {macro1!(4 - (3 - 1   *   2))}
944             "#]],
945     )
946 }
947
948 #[test]
949 fn add_parenthesis_when_necessary() {
950     assert_ssr_transform(
951         "foo($a) ==>> $a.to_string()",
952         r#"
953         fn foo(_: i32) {}
954         fn bar3(v: i32) {
955             foo(1 + 2);
956             foo(-v);
957         }
958         "#,
959         expect![[r#"
960             fn foo(_: i32) {}
961             fn bar3(v: i32) {
962                 (1 + 2).to_string();
963                 (-v).to_string();
964             }
965         "#]],
966     )
967 }
968
969 #[test]
970 fn match_failure_reasons() {
971     let code = r#"
972         fn bar() {}
973         macro_rules! foo {
974             ($a:expr) => {
975                 1 + $a + 2
976             };
977         }
978         fn f1() {
979             bar(1, 2);
980             foo!(5 + 43.to_string() + 5);
981         }
982         "#;
983     assert_match_failure_reason(
984         "bar($a, 3)",
985         code,
986         "bar(1, 2)",
987         r#"Pattern wanted token '3' (INT_NUMBER), but code had token '2' (INT_NUMBER)"#,
988     );
989     assert_match_failure_reason(
990         "42.to_string()",
991         code,
992         "43.to_string()",
993         r#"Pattern wanted token '42' (INT_NUMBER), but code had token '43' (INT_NUMBER)"#,
994     );
995 }
996
997 #[test]
998 fn overlapping_possible_matches() {
999     // There are three possible matches here, however the middle one, `foo(foo(foo(42)))` shouldn't
1000     // match because it overlaps with the outer match. The inner match is permitted since it's is
1001     // contained entirely within the placeholder of the outer match.
1002     assert_matches(
1003         "foo(foo($a))",
1004         "fn foo() {} fn main() {foo(foo(foo(foo(42))))}",
1005         &["foo(foo(42))", "foo(foo(foo(foo(42))))"],
1006     );
1007 }
1008
1009 #[test]
1010 fn use_declaration_with_braces() {
1011     // It would be OK for a path rule to match and alter a use declaration. We shouldn't mess it up
1012     // though. In particular, we must not change `use foo::{baz, bar}` to `use foo::{baz,
1013     // foo2::bar2}`.
1014     cov_mark::check!(use_declaration_with_braces);
1015     assert_ssr_transform(
1016         "foo::bar ==>> foo2::bar2",
1017         r#"
1018         mod foo { pub fn bar() {} pub fn baz() {} }
1019         mod foo2 { pub fn bar2() {} }
1020         use foo::{baz, bar};
1021         fn main() { bar() }
1022         "#,
1023         expect![["
1024         mod foo { pub fn bar() {} pub fn baz() {} }
1025         mod foo2 { pub fn bar2() {} }
1026         use foo::{baz, bar};
1027         fn main() { foo2::bar2() }
1028         "]],
1029     )
1030 }
1031
1032 #[test]
1033 fn ufcs_matches_method_call() {
1034     let code = r#"
1035     struct Foo {}
1036     impl Foo {
1037         fn new(_: i32) -> Foo { Foo {} }
1038         fn do_stuff(&self, _: i32) {}
1039     }
1040     struct Bar {}
1041     impl Bar {
1042         fn new(_: i32) -> Bar { Bar {} }
1043         fn do_stuff(&self, v: i32) {}
1044     }
1045     fn main() {
1046         let b = Bar {};
1047         let f = Foo {};
1048         b.do_stuff(1);
1049         f.do_stuff(2);
1050         Foo::new(4).do_stuff(3);
1051         // Too many / too few args - should never match
1052         f.do_stuff(2, 10);
1053         f.do_stuff();
1054     }
1055     "#;
1056     assert_matches("Foo::do_stuff($a, $b)", code, &["f.do_stuff(2)", "Foo::new(4).do_stuff(3)"]);
1057     // The arguments needs special handling in the case of a function call matching a method call
1058     // and the first argument is different.
1059     assert_matches("Foo::do_stuff($a, 2)", code, &["f.do_stuff(2)"]);
1060     assert_matches("Foo::do_stuff(Foo::new(4), $b)", code, &["Foo::new(4).do_stuff(3)"]);
1061
1062     assert_ssr_transform(
1063         "Foo::do_stuff(Foo::new($a), $b) ==>> Bar::new($b).do_stuff($a)",
1064         code,
1065         expect![[r#"
1066             struct Foo {}
1067             impl Foo {
1068                 fn new(_: i32) -> Foo { Foo {} }
1069                 fn do_stuff(&self, _: i32) {}
1070             }
1071             struct Bar {}
1072             impl Bar {
1073                 fn new(_: i32) -> Bar { Bar {} }
1074                 fn do_stuff(&self, v: i32) {}
1075             }
1076             fn main() {
1077                 let b = Bar {};
1078                 let f = Foo {};
1079                 b.do_stuff(1);
1080                 f.do_stuff(2);
1081                 Bar::new(3).do_stuff(4);
1082                 // Too many / too few args - should never match
1083                 f.do_stuff(2, 10);
1084                 f.do_stuff();
1085             }
1086         "#]],
1087     );
1088 }
1089
1090 #[test]
1091 fn pattern_is_a_single_segment_path() {
1092     cov_mark::check!(pattern_is_a_single_segment_path);
1093     // The first function should not be altered because the `foo` in scope at the cursor position is
1094     // a different `foo`. This case is special because "foo" can be parsed as a pattern (IDENT_PAT ->
1095     // NAME -> IDENT), which contains no path. If we're not careful we'll end up matching the `foo`
1096     // in `let foo` from the first function. Whether we should match the `let foo` in the second
1097     // function is less clear. At the moment, we don't. Doing so sounds like a rename operation,
1098     // which isn't really what SSR is for, especially since the replacement `bar` must be able to be
1099     // resolved, which means if we rename `foo` we'll get a name collision.
1100     assert_ssr_transform(
1101         "foo ==>> bar",
1102         r#"
1103         fn f1() -> i32 {
1104             let foo = 1;
1105             let bar = 2;
1106             foo
1107         }
1108         fn f1() -> i32 {
1109             let foo = 1;
1110             let bar = 2;
1111             foo$0
1112         }
1113         "#,
1114         expect![[r#"
1115             fn f1() -> i32 {
1116                 let foo = 1;
1117                 let bar = 2;
1118                 foo
1119             }
1120             fn f1() -> i32 {
1121                 let foo = 1;
1122                 let bar = 2;
1123                 bar
1124             }
1125         "#]],
1126     );
1127 }
1128
1129 #[test]
1130 fn replace_local_variable_reference() {
1131     // The pattern references a local variable `foo` in the block containing the cursor. We should
1132     // only replace references to this variable `foo`, not other variables that just happen to have
1133     // the same name.
1134     cov_mark::check!(cursor_after_semicolon);
1135     assert_ssr_transform(
1136         "foo + $a ==>> $a - foo",
1137         r#"
1138             fn bar1() -> i32 {
1139                 let mut res = 0;
1140                 let foo = 5;
1141                 res += foo + 1;
1142                 let foo = 10;
1143                 res += foo + 2;$0
1144                 res += foo + 3;
1145                 let foo = 15;
1146                 res += foo + 4;
1147                 res
1148             }
1149             "#,
1150         expect![[r#"
1151             fn bar1() -> i32 {
1152                 let mut res = 0;
1153                 let foo = 5;
1154                 res += foo + 1;
1155                 let foo = 10;
1156                 res += 2 - foo;
1157                 res += 3 - foo;
1158                 let foo = 15;
1159                 res += foo + 4;
1160                 res
1161             }
1162         "#]],
1163     )
1164 }
1165
1166 #[test]
1167 fn replace_path_within_selection() {
1168     assert_ssr_transform(
1169         "foo ==>> bar",
1170         r#"
1171         fn main() {
1172             let foo = 41;
1173             let bar = 42;
1174             do_stuff(foo);
1175             do_stuff(foo);$0
1176             do_stuff(foo);
1177             do_stuff(foo);$0
1178             do_stuff(foo);
1179         }"#,
1180         expect![[r#"
1181             fn main() {
1182                 let foo = 41;
1183                 let bar = 42;
1184                 do_stuff(foo);
1185                 do_stuff(foo);
1186                 do_stuff(bar);
1187                 do_stuff(bar);
1188                 do_stuff(foo);
1189             }"#]],
1190     );
1191 }
1192
1193 #[test]
1194 fn replace_nonpath_within_selection() {
1195     cov_mark::check!(replace_nonpath_within_selection);
1196     assert_ssr_transform(
1197         "$a + $b ==>> $b * $a",
1198         r#"
1199         fn main() {
1200             let v = 1 + 2;$0
1201             let v2 = 3 + 3;
1202             let v3 = 4 + 5;$0
1203             let v4 = 6 + 7;
1204         }"#,
1205         expect![[r#"
1206             fn main() {
1207                 let v = 1 + 2;
1208                 let v2 = 3 * 3;
1209                 let v3 = 5 * 4;
1210                 let v4 = 6 + 7;
1211             }"#]],
1212     );
1213 }
1214
1215 #[test]
1216 fn replace_self() {
1217     // `foo(self)` occurs twice in the code, however only the first occurrence is the `self` that's
1218     // in scope where the rule is invoked.
1219     assert_ssr_transform(
1220         "foo(self) ==>> bar(self)",
1221         r#"
1222         struct S1 {}
1223         fn foo(_: &S1) {}
1224         fn bar(_: &S1) {}
1225         impl S1 {
1226             fn f1(&self) {
1227                 foo(self)$0
1228             }
1229             fn f2(&self) {
1230                 foo(self)
1231             }
1232         }
1233         "#,
1234         expect![[r#"
1235             struct S1 {}
1236             fn foo(_: &S1) {}
1237             fn bar(_: &S1) {}
1238             impl S1 {
1239                 fn f1(&self) {
1240                     bar(self)
1241                 }
1242                 fn f2(&self) {
1243                     foo(self)
1244                 }
1245             }
1246         "#]],
1247     );
1248 }
1249
1250 #[test]
1251 fn match_trait_method_call() {
1252     // `Bar::foo` and `Bar2::foo` resolve to the same function. Make sure we only match if the type
1253     // matches what's in the pattern. Also checks that we handle autoderef.
1254     let code = r#"
1255         pub struct Bar {}
1256         pub struct Bar2 {}
1257         pub trait Foo {
1258             fn foo(&self, _: i32) {}
1259         }
1260         impl Foo for Bar {}
1261         impl Foo for Bar2 {}
1262         fn main() {
1263             let v1 = Bar {};
1264             let v2 = Bar2 {};
1265             let v1_ref = &v1;
1266             let v2_ref = &v2;
1267             v1.foo(1);
1268             v2.foo(2);
1269             Bar::foo(&v1, 3);
1270             Bar2::foo(&v2, 4);
1271             v1_ref.foo(5);
1272             v2_ref.foo(6);
1273         }
1274         "#;
1275     assert_matches("Bar::foo($a, $b)", code, &["v1.foo(1)", "Bar::foo(&v1, 3)", "v1_ref.foo(5)"]);
1276     assert_matches("Bar2::foo($a, $b)", code, &["v2.foo(2)", "Bar2::foo(&v2, 4)", "v2_ref.foo(6)"]);
1277 }
1278
1279 #[test]
1280 fn replace_autoref_autoderef_capture() {
1281     // Here we have several calls to `$a.foo()`. In the first case autoref is applied, in the
1282     // second, we already have a reference, so it isn't. When $a is used in a context where autoref
1283     // doesn't apply, we need to prefix it with `&`. Finally, we have some cases where autoderef
1284     // needs to be applied.
1285     cov_mark::check!(replace_autoref_autoderef_capture);
1286     let code = r#"
1287         struct Foo {}
1288         impl Foo {
1289             fn foo(&self) {}
1290             fn foo2(&self) {}
1291         }
1292         fn bar(_: &Foo) {}
1293         fn main() {
1294             let f = Foo {};
1295             let fr = &f;
1296             let fr2 = &fr;
1297             let fr3 = &fr2;
1298             f.foo();
1299             fr.foo();
1300             fr2.foo();
1301             fr3.foo();
1302         }
1303         "#;
1304     assert_ssr_transform(
1305         "Foo::foo($a) ==>> bar($a)",
1306         code,
1307         expect![[r#"
1308             struct Foo {}
1309             impl Foo {
1310                 fn foo(&self) {}
1311                 fn foo2(&self) {}
1312             }
1313             fn bar(_: &Foo) {}
1314             fn main() {
1315                 let f = Foo {};
1316                 let fr = &f;
1317                 let fr2 = &fr;
1318                 let fr3 = &fr2;
1319                 bar(&f);
1320                 bar(&*fr);
1321                 bar(&**fr2);
1322                 bar(&***fr3);
1323             }
1324         "#]],
1325     );
1326     // If the placeholder is used as the receiver of another method call, then we don't need to
1327     // explicitly autoderef or autoref.
1328     assert_ssr_transform(
1329         "Foo::foo($a) ==>> $a.foo2()",
1330         code,
1331         expect![[r#"
1332             struct Foo {}
1333             impl Foo {
1334                 fn foo(&self) {}
1335                 fn foo2(&self) {}
1336             }
1337             fn bar(_: &Foo) {}
1338             fn main() {
1339                 let f = Foo {};
1340                 let fr = &f;
1341                 let fr2 = &fr;
1342                 let fr3 = &fr2;
1343                 f.foo2();
1344                 fr.foo2();
1345                 fr2.foo2();
1346                 fr3.foo2();
1347             }
1348         "#]],
1349     );
1350 }
1351
1352 #[test]
1353 fn replace_autoref_mut() {
1354     let code = r#"
1355         struct Foo {}
1356         impl Foo {
1357             fn foo(&mut self) {}
1358         }
1359         fn bar(_: &mut Foo) {}
1360         fn main() {
1361             let mut f = Foo {};
1362             f.foo();
1363             let fr = &mut f;
1364             fr.foo();
1365         }
1366         "#;
1367     assert_ssr_transform(
1368         "Foo::foo($a) ==>> bar($a)",
1369         code,
1370         expect![[r#"
1371             struct Foo {}
1372             impl Foo {
1373                 fn foo(&mut self) {}
1374             }
1375             fn bar(_: &mut Foo) {}
1376             fn main() {
1377                 let mut f = Foo {};
1378                 bar(&mut f);
1379                 let fr = &mut f;
1380                 bar(&mut *fr);
1381             }
1382         "#]],
1383     );
1384 }