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