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;
6 use test_utils::RangeOrOffset;
8 fn parse_error_text(query: &str) -> String {
9 format!("{}", query.parse::<SsrRule>().unwrap_err())
13 fn parser_empty_query() {
14 assert_eq!(parse_error_text(""), "Parse error: Cannot find delimiter `==>>`");
18 fn parser_no_delimiter() {
19 assert_eq!(parse_error_text("foo()"), "Parse error: Cannot find delimiter `==>>`");
23 fn parser_two_delimiters() {
25 parse_error_text("foo() ==>> a ==>> b "),
26 "Parse error: More than one delimiter found"
31 fn parser_repeated_name() {
33 parse_error_text("foo($a, $a) ==>>"),
34 "Parse error: Placeholder `$a` repeats more than once"
39 fn parser_invalid_pattern() {
41 parse_error_text(" ==>> ()"),
42 "Parse error: Not a valid Rust expression, type, item, path or pattern"
47 fn parser_invalid_template() {
49 parse_error_text("() ==>> )"),
50 "Parse error: Not a valid Rust expression, type, item, path or pattern"
55 fn parser_undefined_placeholder_in_replacement() {
57 parse_error_text("42 ==>> $a"),
58 "Parse error: Replacement contains undefined placeholders: $a"
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)
70 let (db, file_id) = ide_db::RootDatabase::with_single_file(code);
71 (db, file_id, RangeOrOffset::Offset(0.into()))
75 match range_or_offset {
76 RangeOrOffset::Range(range) => {
77 position = FilePosition { file_id, offset: range.start() };
78 selections = vec![FileRange { file_id, range }];
80 RangeOrOffset::Offset(offset) => {
81 position = FilePosition { file_id, offset };
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)
91 fn assert_ssr_transform(rule: &str, input: &str, expected: Expect) {
92 assert_ssr_transforms(&[rule], input, expected);
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);
99 let rule: SsrRule = rule.parse().unwrap();
100 match_finder.add_rule(rule).unwrap();
102 let edits = match_finder.edits();
103 if edits.is_empty() {
104 panic!("No edits were made");
106 // Note, db.file_text is not necessarily the same as `input`, since fixture parsing alters
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);
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);
116 "Match debug info: {} nodes had text exactly equal to '{}'",
120 for (index, d) in debug_info.iter().enumerate() {
121 println!("Node #{}\n{:#?}\n", index, d);
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]);
134 assert_eq!(matched_strings, expected);
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);
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());
158 assert_eq!(reasons, vec![expected_reason]);
162 fn ssr_let_stmt_in_macro_match() {
166 macro_rules! m1 { ($a:stmt) => {$a}; }
167 fn f() {m1!{ let a = 0 };}"#,
168 // FIXME: Whitespace is not part of the matched block
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;"]);
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 }"]);
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 }"]],
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 }"]],
206 fn ssr_blockexpr_replace_stmt_with_stmt() {
207 assert_ssr_transform(
208 "if $a() {$b;} ==>> $b;",
223 fn ssr_blockexpr_match_trailing_expr() {
238 fn ssr_blockexpr_replace_trailing_expr_with_stmt() {
239 assert_ssr_transform(
240 "if $a() {$b;} ==>> $b;",
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) } }"]],
262 fn ssr_nested_function() {
263 assert_ssr_transform(
264 "foo($a, $b, $c) ==>> bar($c, baz($a, $b))",
266 //- /lib.rs crate:foo
270 fn main { foo (x + value.method(b), x+y-z, true && false) }
276 fn main { bar(true && false, baz(x + value.method(b), x+y-z)) }
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) }"]],
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) }"]],
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 */)) }"]],
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 */ }"]],
318 fn ssr_struct_lit() {
319 assert_ssr_transform(
320 "Foo{a: $a, b: $b} ==>> Foo::new($a, $b)",
323 impl Foo { fn new() {} }
324 fn main() { Foo{b:2, a:1} }
328 impl Foo { fn new() {} }
329 fn main() { Foo::new(1, 2) }
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);"#]],
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"]);
351 assert_no_match("1 + 3", "fn f() -> i32 {1 + 2}");
355 fn match_fn_definition() {
356 assert_matches("fn $a($b: $t) {$c}", "fn f(a: i32) {bar()}", &["fn f(a: i32) {bar()}"]);
360 fn match_struct_definition() {
364 struct Foo {name: Option<String>}"#;
365 assert_matches("struct $n {$f: Option<String>}", code, &["struct Foo {name: Option<String>}"]);
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);
379 fn match_nested_method_calls() {
382 "fn f() {h().i().j().z().z().z().d().e()}",
383 &["h().i().j().z().z().z()"],
387 // Make sure that our node matching semantics don't differ within macro calls.
389 fn match_nested_method_calls_with_macro_call() {
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()"],
400 fn match_complex_expr() {
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)"]);
410 // Trailing commas in the code should be ignored.
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,}"]);
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}"]);
424 assert_matches("i32", "fn f() -> i32 {1 + 2}", &["i32"]);
427 "struct Option<T> {} fn f() -> Option<i32> {42}",
432 "struct Option<T> {} struct Result<T, E> {} fn f() -> Result<i32, ()> {42}",
437 fn match_struct_instantiation() {
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 {}"]);
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"]);
461 assert_matches("Some($a)", "struct Some(); fn f() {if let Some(x) = foo() {}}", &["Some(x)"]);
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.
467 fn match_fully_qualified_fn_path() {
479 assert_matches("a::b::c($a)", code, &["c(42)"]);
483 fn match_resolved_type_name() {
492 fn f1(f: Option<&dyn Foo<bool>>) {}
495 use crate::m1::m2::Foo;
496 fn f1(f: Option<&dyn Foo<i32>>) {}
499 assert_matches("m1::m2::Foo<$t>", code, &["Foo<i32>"]);
503 fn type_arguments_within_path() {
504 cov_mark::check!(type_arguments_within_path);
507 pub struct Bar<T> {t: T}
512 fn f1() {foo::Bar::<i32>::baz();}
514 assert_no_match("foo::Bar::<i64>::baz()", code);
515 assert_matches("foo::Bar::<i32>::baz()", code, &["foo::Bar::<i32>::baz()"]);
519 fn literal_constraint() {
520 cov_mark::check!(literal_constraint);
522 enum Option<T> { Some(T), None }
526 let x2 = Some("foo");
528 let x4 = Some(40 + 2);
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)"]);
537 fn match_reordered_struct_instantiation() {
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}"],
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}}");
552 fn match_macro_invocation() {
555 "macro_rules! foo {() => {}} fn() {foo(foo!(foo()))}",
560 "macro_rules! foo {() => {}} fn() {foo!(41, 42, 43)}",
561 &["foo!(41, 42, 43)"],
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}");
567 "macro_rules! foo {() => {}} fn() {foo!(bar())}",
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.
575 fn no_match_expression_from_macro() {
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()`.
590 fn no_match_split_expression() {
595 ($x:expr) => {$x.clone()}
603 fn replace_function_call() {
604 // This test also makes sure that we ignore empty-ranges.
605 assert_ssr_transform(
607 "fn foo() {$0$0} fn bar() {} fn f1() {foo(); foo();}",
608 expect![["fn foo() {} fn bar() {} fn f1() {bar(); bar();}"]],
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)}"]],
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))}"]],
631 fn replace_associated_function_call() {
632 assert_ssr_transform(
633 "Foo::new() ==>> Bar::new()",
636 impl Foo { fn new() {} }
638 impl Bar { fn new() {} }
639 fn f1() {Foo::new();}
643 impl Foo { fn new() {} }
645 impl Bar { fn new() {} }
646 fn f1() {Bar::new();}
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()",
657 trait Foo { fn foo() {} }
662 impl Bar2 { fn foo2() {} }
669 trait Foo { fn foo() {} }
674 impl Bar2 { fn foo2() {} }
684 fn replace_associated_trait_constant() {
685 cov_mark::check!(replace_associated_trait_constant);
686 assert_ssr_transform(
687 "Bar2::VALUE ==>> Bar2::VALUE_2222",
689 trait Foo { const VALUE: i32; const VALUE_2222: i32; }
691 impl Foo for Bar { const VALUE: i32 = 1; const VALUE_2222: i32 = 2; }
693 impl Foo for Bar2 { const VALUE: i32 = 1; const VALUE_2222: i32 = 2; }
694 impl Bar2 { fn foo2() {} }
701 trait Foo { const VALUE: i32; const VALUE_2222: i32; }
703 impl Foo for Bar { const VALUE: i32 = 1; const VALUE_2222: i32 = 2; }
705 impl Foo for Bar2 { const VALUE: i32 = 1; const VALUE_2222: i32 = 2; }
706 impl Bar2 { fn foo2() {} }
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
721 assert_ssr_transform(
722 "c::foo() ==>> c::bar()",
733 fn f3() { b::c::foo() }
748 fn f3() { b::c::bar() }
751 fn f4() { a::b::c::bar() }
757 fn replace_associated_function_with_generics() {
758 assert_ssr_transform(
759 "c::Foo::<$a>::new() ==>> d::Bar::<$a>::default()",
762 pub struct Foo<T> {v: T}
763 impl<T> Foo<T> { pub fn new() {} }
769 pub struct Bar<T> {v: T}
770 impl<T> Bar<T> { pub fn default() {} }
772 super::c::Foo::<i32>::new();
778 pub struct Foo<T> {v: T}
779 impl<T> Foo<T> { pub fn new() {} }
781 crate::d::Bar::<i32>::default();
785 pub struct Bar<T> {v: T}
786 impl<T> Bar<T> { pub fn default() {} }
788 Bar::<i32>::default();
797 assert_ssr_transform(
798 "Result<(), $a> ==>> Option<$a>",
799 "struct Result<T, E> {} struct Option<T> {} fn f1() -> Result<(), Vec<Error>> {foo()}",
801 "struct Result<T, E> {} struct Option<T> {} fn f1() -> Option<Vec<Error>> {foo()}"
804 assert_ssr_transform(
805 "dyn Trait<$a> ==>> DynTrait<$a>",
808 struct DynTrait<T> {}
809 fn f1() -> dyn Trait<Vec<Error>> {foo()}
813 struct DynTrait<T> {}
814 fn f1() -> DynTrait<Vec<Error>> {foo()}
820 fn replace_macro_invocations() {
821 assert_ssr_transform(
823 "macro_rules! try {() => {}} fn f1() -> Result<(), E> {bar(try!(foo()));}",
824 expect![["macro_rules! try {() => {}} fn f1() -> Result<(), E> {bar(foo()?);}"]],
826 assert_ssr_transform(
827 "foo!($a($b)) ==>> foo($b, $a)",
828 "macro_rules! foo {() => {}} fn f1() {foo!(abc(def() + 2));}",
829 expect![["macro_rules! foo {() => {}} fn f1() {foo(def() + 2, abc);}"]],
834 fn replace_binary_op() {
835 assert_ssr_transform(
836 "$a + $b ==>> $b + $a",
837 "fn f() {2 * 3 + 4 * 5}",
838 expect![["fn f() {4 * 5 + 2 * 3}"]],
840 assert_ssr_transform(
841 "$a + $b ==>> $b + $a",
842 "fn f() {1 + 2 + 3 + 4}",
843 expect![[r#"fn f() {4 + (3 + (2 + 1))}"#]],
848 fn match_binary_op() {
849 assert_matches("$a + $b", "fn f() {1 + 2 + 3 + 4}", &["1 + 2", "1 + 2 + 3", "1 + 2 + 3 + 4"]);
853 fn multiple_rules() {
854 assert_ssr_transforms(
855 &["$a + 1 ==>> add_one($a)", "$a + $b ==>> add($a, $b)"],
856 "fn add() {} fn add_one() {} fn f() -> i32 {3 + 2 + 1}",
857 expect![["fn add() {} fn add_one() {} fn f() -> i32 {add_one(add(3, 2))}"]],
862 fn multiple_rules_with_nested_matches() {
863 assert_ssr_transforms(
864 &["foo1($a) ==>> bar1($a)", "foo2($a) ==>> bar2($a)"],
866 fn foo1() {} fn foo2() {} fn bar1() {} fn bar2() {}
867 fn f() {foo1(foo2(foo1(foo2(foo1(42)))))}
870 fn foo1() {} fn foo2() {} fn bar1() {} fn bar2() {}
871 fn f() {bar1(bar2(bar1(bar2(bar1(42)))))}
877 fn match_within_macro_invocation() {
880 ($a:stmt; $b:expr) => {
890 foo!(macro_ignores_this(); aaa.bar());
893 assert_matches("$a.bar()", code, &["aaa.bar()"]);
897 fn replace_within_macro_expansion() {
898 assert_ssr_transform(
899 "$a.foo() ==>> bar($a)",
901 macro_rules! macro1 {
905 fn f() {macro1!(5.x().foo().o2())}
908 macro_rules! macro1 {
912 fn f() {macro1!(bar(5.x()).o2())}
918 fn replace_outside_and_within_macro_expansion() {
919 assert_ssr_transform(
920 "foo($a) ==>> bar($a)",
922 fn foo() {} fn bar() {}
923 macro_rules! macro1 {
926 fn f() {foo(foo(macro1!(foo(foo(42)))))}
929 fn foo() {} fn bar() {}
930 macro_rules! macro1 {
933 fn f() {bar(bar(macro1!(bar(bar(42)))))}
939 fn preserves_whitespace_within_macro_expansion() {
940 assert_ssr_transform(
941 "$a + $b ==>> $b - $a",
943 macro_rules! macro1 {
946 fn f() {macro1!(1 * 2 + 3 + 4)}
949 macro_rules! macro1 {
952 fn f() {macro1!(4 - (3 - 1 * 2))}
958 fn add_parenthesis_when_necessary() {
959 assert_ssr_transform(
960 "foo($a) ==>> $a.to_string()",
979 fn match_failure_reasons() {
989 foo!(5 + 43.to_string() + 5);
992 assert_match_failure_reason(
996 r#"Pattern wanted token '3' (INT_NUMBER), but code had token '2' (INT_NUMBER)"#,
998 assert_match_failure_reason(
1002 r#"Pattern wanted token '42' (INT_NUMBER), but code had token '43' (INT_NUMBER)"#,
1007 fn overlapping_possible_matches() {
1008 // There are three possible matches here, however the middle one, `foo(foo(foo(42)))` shouldn't
1009 // match because it overlaps with the outer match. The inner match is permitted since it's is
1010 // contained entirely within the placeholder of the outer match.
1013 "fn foo() {} fn main() {foo(foo(foo(foo(42))))}",
1014 &["foo(foo(42))", "foo(foo(foo(foo(42))))"],
1019 fn use_declaration_with_braces() {
1020 // It would be OK for a path rule to match and alter a use declaration. We shouldn't mess it up
1021 // though. In particular, we must not change `use foo::{baz, bar}` to `use foo::{baz,
1023 cov_mark::check!(use_declaration_with_braces);
1024 assert_ssr_transform(
1025 "foo::bar ==>> foo2::bar2",
1027 mod foo { pub fn bar() {} pub fn baz() {} }
1028 mod foo2 { pub fn bar2() {} }
1029 use foo::{baz, bar};
1033 mod foo { pub fn bar() {} pub fn baz() {} }
1034 mod foo2 { pub fn bar2() {} }
1035 use foo::{baz, bar};
1036 fn main() { foo2::bar2() }
1042 fn ufcs_matches_method_call() {
1046 fn new(_: i32) -> Foo { Foo {} }
1047 fn do_stuff(&self, _: i32) {}
1051 fn new(_: i32) -> Bar { Bar {} }
1052 fn do_stuff(&self, v: i32) {}
1059 Foo::new(4).do_stuff(3);
1060 // Too many / too few args - should never match
1065 assert_matches("Foo::do_stuff($a, $b)", code, &["f.do_stuff(2)", "Foo::new(4).do_stuff(3)"]);
1066 // The arguments needs special handling in the case of a function call matching a method call
1067 // and the first argument is different.
1068 assert_matches("Foo::do_stuff($a, 2)", code, &["f.do_stuff(2)"]);
1069 assert_matches("Foo::do_stuff(Foo::new(4), $b)", code, &["Foo::new(4).do_stuff(3)"]);
1071 assert_ssr_transform(
1072 "Foo::do_stuff(Foo::new($a), $b) ==>> Bar::new($b).do_stuff($a)",
1077 fn new(_: i32) -> Foo { Foo {} }
1078 fn do_stuff(&self, _: i32) {}
1082 fn new(_: i32) -> Bar { Bar {} }
1083 fn do_stuff(&self, v: i32) {}
1090 Bar::new(3).do_stuff(4);
1091 // Too many / too few args - should never match
1100 fn pattern_is_a_single_segment_path() {
1101 cov_mark::check!(pattern_is_a_single_segment_path);
1102 // The first function should not be altered because the `foo` in scope at the cursor position is
1103 // a different `foo`. This case is special because "foo" can be parsed as a pattern (IDENT_PAT ->
1104 // NAME -> IDENT), which contains no path. If we're not careful we'll end up matching the `foo`
1105 // in `let foo` from the first function. Whether we should match the `let foo` in the second
1106 // function is less clear. At the moment, we don't. Doing so sounds like a rename operation,
1107 // which isn't really what SSR is for, especially since the replacement `bar` must be able to be
1108 // resolved, which means if we rename `foo` we'll get a name collision.
1109 assert_ssr_transform(
1139 fn replace_local_variable_reference() {
1140 // The pattern references a local variable `foo` in the block containing the cursor. We should
1141 // only replace references to this variable `foo`, not other variables that just happen to have
1143 cov_mark::check!(cursor_after_semicolon);
1144 assert_ssr_transform(
1145 "foo + $a ==>> $a - foo",
1176 fn replace_path_within_selection() {
1177 assert_ssr_transform(
1203 fn replace_nonpath_within_selection() {
1204 cov_mark::check!(replace_nonpath_within_selection);
1205 assert_ssr_transform(
1206 "$a + $b ==>> $b * $a",
1226 // `foo(self)` occurs twice in the code, however only the first occurrence is the `self` that's
1227 // in scope where the rule is invoked.
1228 assert_ssr_transform(
1229 "foo(self) ==>> bar(self)",
1260 fn match_trait_method_call() {
1261 // `Bar::foo` and `Bar2::foo` resolve to the same function. Make sure we only match if the type
1262 // matches what's in the pattern. Also checks that we handle autoderef.
1267 fn foo(&self, _: i32) {}
1270 impl Foo for Bar2 {}
1284 assert_matches("Bar::foo($a, $b)", code, &["v1.foo(1)", "Bar::foo(&v1, 3)", "v1_ref.foo(5)"]);
1285 assert_matches("Bar2::foo($a, $b)", code, &["v2.foo(2)", "Bar2::foo(&v2, 4)", "v2_ref.foo(6)"]);
1289 fn replace_autoref_autoderef_capture() {
1290 // Here we have several calls to `$a.foo()`. In the first case autoref is applied, in the
1291 // second, we already have a reference, so it isn't. When $a is used in a context where autoref
1292 // doesn't apply, we need to prefix it with `&`. Finally, we have some cases where autoderef
1293 // needs to be applied.
1294 cov_mark::check!(replace_autoref_autoderef_capture);
1313 assert_ssr_transform(
1314 "Foo::foo($a) ==>> bar($a)",
1335 // If the placeholder is used as the receiver of another method call, then we don't need to
1336 // explicitly autoderef or autoref.
1337 assert_ssr_transform(
1338 "Foo::foo($a) ==>> $a.foo2()",
1362 fn replace_autoref_mut() {
1366 fn foo(&mut self) {}
1368 fn bar(_: &mut Foo) {}
1376 assert_ssr_transform(
1377 "Foo::foo($a) ==>> bar($a)",
1382 fn foo(&mut self) {}
1384 fn bar(_: &mut Foo) {}