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.rs1081
1 files changed, 0 insertions, 1081 deletions
diff --git a/crates/ra_ssr/src/tests.rs b/crates/ra_ssr/src/tests.rs
deleted file mode 100644
index d483640df..000000000
--- a/crates/ra_ssr/src/tests.rs
+++ /dev/null
@@ -1,1081 +0,0 @@
1use crate::{MatchFinder, SsrRule};
2use expect::{expect, Expect};
3use ra_db::{salsa::Durability, FileId, FilePosition, FileRange, SourceDatabaseExt};
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) -> (ra_ide_db::RootDatabase, FilePosition, Vec<FileRange>) {
65 use ra_db::fixture::WithFixture;
66 use ra_ide_db::symbol_index::SymbolsDatabase;
67 let (mut db, file_id, range_or_offset) = if code.contains(test_utils::CURSOR_MARKER) {
68 ra_ide_db::RootDatabase::with_range_or_offset(code)
69 } else {
70 let (db, file_id) = ra_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(ra_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_path_in_different_contexts() {
554 // Note the <|> inside module a::b which marks the point where the rule is interpreted. We
555 // replace foo with bar, but both need different path qualifiers in different contexts. In f4,
556 // foo is unqualified because of a use statement, however the replacement needs to be fully
557 // qualified.
558 assert_ssr_transform(
559 "c::foo() ==>> c::bar()",
560 r#"
561 mod a {
562 pub mod b {<|>
563 pub mod c {
564 pub fn foo() {}
565 pub fn bar() {}
566 fn f1() { foo() }
567 }
568 fn f2() { c::foo() }
569 }
570 fn f3() { b::c::foo() }
571 }
572 use a::b::c::foo;
573 fn f4() { foo() }
574 "#,
575 expect![[r#"
576 mod a {
577 pub mod b {
578 pub mod c {
579 pub fn foo() {}
580 pub fn bar() {}
581 fn f1() { bar() }
582 }
583 fn f2() { c::bar() }
584 }
585 fn f3() { b::c::bar() }
586 }
587 use a::b::c::foo;
588 fn f4() { a::b::c::bar() }
589 "#]],
590 );
591}
592
593#[test]
594fn replace_associated_function_with_generics() {
595 assert_ssr_transform(
596 "c::Foo::<$a>::new() ==>> d::Bar::<$a>::default()",
597 r#"
598 mod c {
599 pub struct Foo<T> {v: T}
600 impl<T> Foo<T> { pub fn new() {} }
601 fn f1() {
602 Foo::<i32>::new();
603 }
604 }
605 mod d {
606 pub struct Bar<T> {v: T}
607 impl<T> Bar<T> { pub fn default() {} }
608 fn f1() {
609 super::c::Foo::<i32>::new();
610 }
611 }
612 "#,
613 expect![[r#"
614 mod c {
615 pub struct Foo<T> {v: T}
616 impl<T> Foo<T> { pub fn new() {} }
617 fn f1() {
618 crate::d::Bar::<i32>::default();
619 }
620 }
621 mod d {
622 pub struct Bar<T> {v: T}
623 impl<T> Bar<T> { pub fn default() {} }
624 fn f1() {
625 Bar::<i32>::default();
626 }
627 }
628 "#]],
629 );
630}
631
632#[test]
633fn replace_type() {
634 assert_ssr_transform(
635 "Result<(), $a> ==>> Option<$a>",
636 "struct Result<T, E> {} struct Option<T> {} fn f1() -> Result<(), Vec<Error>> {foo()}",
637 expect![[
638 "struct Result<T, E> {} struct Option<T> {} fn f1() -> Option<Vec<Error>> {foo()}"
639 ]],
640 );
641}
642
643#[test]
644fn replace_macro_invocations() {
645 assert_ssr_transform(
646 "try!($a) ==>> $a?",
647 "macro_rules! try {() => {}} fn f1() -> Result<(), E> {bar(try!(foo()));}",
648 expect![["macro_rules! try {() => {}} fn f1() -> Result<(), E> {bar(foo()?);}"]],
649 );
650 assert_ssr_transform(
651 "foo!($a($b)) ==>> foo($b, $a)",
652 "macro_rules! foo {() => {}} fn f1() {foo!(abc(def() + 2));}",
653 expect![["macro_rules! foo {() => {}} fn f1() {foo(def() + 2, abc);}"]],
654 );
655}
656
657#[test]
658fn replace_binary_op() {
659 assert_ssr_transform(
660 "$a + $b ==>> $b + $a",
661 "fn f() {2 * 3 + 4 * 5}",
662 expect![["fn f() {4 * 5 + 2 * 3}"]],
663 );
664 assert_ssr_transform(
665 "$a + $b ==>> $b + $a",
666 "fn f() {1 + 2 + 3 + 4}",
667 expect![[r#"fn f() {4 + (3 + (2 + 1))}"#]],
668 );
669}
670
671#[test]
672fn match_binary_op() {
673 assert_matches("$a + $b", "fn f() {1 + 2 + 3 + 4}", &["1 + 2", "1 + 2 + 3", "1 + 2 + 3 + 4"]);
674}
675
676#[test]
677fn multiple_rules() {
678 assert_ssr_transforms(
679 &["$a + 1 ==>> add_one($a)", "$a + $b ==>> add($a, $b)"],
680 "fn add() {} fn add_one() {} fn f() -> i32 {3 + 2 + 1}",
681 expect![["fn add() {} fn add_one() {} fn f() -> i32 {add_one(add(3, 2))}"]],
682 )
683}
684
685#[test]
686fn multiple_rules_with_nested_matches() {
687 assert_ssr_transforms(
688 &["foo1($a) ==>> bar1($a)", "foo2($a) ==>> bar2($a)"],
689 r#"
690 fn foo1() {} fn foo2() {} fn bar1() {} fn bar2() {}
691 fn f() {foo1(foo2(foo1(foo2(foo1(42)))))}
692 "#,
693 expect![[r#"
694 fn foo1() {} fn foo2() {} fn bar1() {} fn bar2() {}
695 fn f() {bar1(bar2(bar1(bar2(bar1(42)))))}
696 "#]],
697 )
698}
699
700#[test]
701fn match_within_macro_invocation() {
702 let code = r#"
703 macro_rules! foo {
704 ($a:stmt; $b:expr) => {
705 $b
706 };
707 }
708 struct A {}
709 impl A {
710 fn bar() {}
711 }
712 fn f1() {
713 let aaa = A {};
714 foo!(macro_ignores_this(); aaa.bar());
715 }
716 "#;
717 assert_matches("$a.bar()", code, &["aaa.bar()"]);
718}
719
720#[test]
721fn replace_within_macro_expansion() {
722 assert_ssr_transform(
723 "$a.foo() ==>> bar($a)",
724 r#"
725 macro_rules! macro1 {
726 ($a:expr) => {$a}
727 }
728 fn bar() {}
729 fn f() {macro1!(5.x().foo().o2())}
730 "#,
731 expect![[r#"
732 macro_rules! macro1 {
733 ($a:expr) => {$a}
734 }
735 fn bar() {}
736 fn f() {macro1!(bar(5.x()).o2())}
737 "#]],
738 )
739}
740
741#[test]
742fn replace_outside_and_within_macro_expansion() {
743 assert_ssr_transform(
744 "foo($a) ==>> bar($a)",
745 r#"
746 fn foo() {} fn bar() {}
747 macro_rules! macro1 {
748 ($a:expr) => {$a}
749 }
750 fn f() {foo(foo(macro1!(foo(foo(42)))))}
751 "#,
752 expect![[r#"
753 fn foo() {} fn bar() {}
754 macro_rules! macro1 {
755 ($a:expr) => {$a}
756 }
757 fn f() {bar(bar(macro1!(bar(bar(42)))))}
758 "#]],
759 )
760}
761
762#[test]
763fn preserves_whitespace_within_macro_expansion() {
764 assert_ssr_transform(
765 "$a + $b ==>> $b - $a",
766 r#"
767 macro_rules! macro1 {
768 ($a:expr) => {$a}
769 }
770 fn f() {macro1!(1 * 2 + 3 + 4}
771 "#,
772 expect![[r#"
773 macro_rules! macro1 {
774 ($a:expr) => {$a}
775 }
776 fn f() {macro1!(4 - (3 - 1 * 2)}
777 "#]],
778 )
779}
780
781#[test]
782fn add_parenthesis_when_necessary() {
783 assert_ssr_transform(
784 "foo($a) ==>> $a.to_string()",
785 r#"
786 fn foo(_: i32) {}
787 fn bar3(v: i32) {
788 foo(1 + 2);
789 foo(-v);
790 }
791 "#,
792 expect![[r#"
793 fn foo(_: i32) {}
794 fn bar3(v: i32) {
795 (1 + 2).to_string();
796 (-v).to_string();
797 }
798 "#]],
799 )
800}
801
802#[test]
803fn match_failure_reasons() {
804 let code = r#"
805 fn bar() {}
806 macro_rules! foo {
807 ($a:expr) => {
808 1 + $a + 2
809 };
810 }
811 fn f1() {
812 bar(1, 2);
813 foo!(5 + 43.to_string() + 5);
814 }
815 "#;
816 assert_match_failure_reason(
817 "bar($a, 3)",
818 code,
819 "bar(1, 2)",
820 r#"Pattern wanted token '3' (INT_NUMBER), but code had token '2' (INT_NUMBER)"#,
821 );
822 assert_match_failure_reason(
823 "42.to_string()",
824 code,
825 "43.to_string()",
826 r#"Pattern wanted token '42' (INT_NUMBER), but code had token '43' (INT_NUMBER)"#,
827 );
828}
829
830#[test]
831fn overlapping_possible_matches() {
832 // There are three possible matches here, however the middle one, `foo(foo(foo(42)))` shouldn't
833 // match because it overlaps with the outer match. The inner match is permitted since it's is
834 // contained entirely within the placeholder of the outer match.
835 assert_matches(
836 "foo(foo($a))",
837 "fn foo() {} fn main() {foo(foo(foo(foo(42))))}",
838 &["foo(foo(42))", "foo(foo(foo(foo(42))))"],
839 );
840}
841
842#[test]
843fn use_declaration_with_braces() {
844 // It would be OK for a path rule to match and alter a use declaration. We shouldn't mess it up
845 // though. In particular, we must not change `use foo::{baz, bar}` to `use foo::{baz,
846 // foo2::bar2}`.
847 mark::check!(use_declaration_with_braces);
848 assert_ssr_transform(
849 "foo::bar ==>> foo2::bar2",
850 r#"
851 mod foo { pub fn bar() {} pub fn baz() {} }
852 mod foo2 { pub fn bar2() {} }
853 use foo::{baz, bar};
854 fn main() { bar() }
855 "#,
856 expect![["
857 mod foo { pub fn bar() {} pub fn baz() {} }
858 mod foo2 { pub fn bar2() {} }
859 use foo::{baz, bar};
860 fn main() { foo2::bar2() }
861 "]],
862 )
863}
864
865#[test]
866fn ufcs_matches_method_call() {
867 let code = r#"
868 struct Foo {}
869 impl Foo {
870 fn new(_: i32) -> Foo { Foo {} }
871 fn do_stuff(&self, _: i32) {}
872 }
873 struct Bar {}
874 impl Bar {
875 fn new(_: i32) -> Bar { Bar {} }
876 fn do_stuff(&self, v: i32) {}
877 }
878 fn main() {
879 let b = Bar {};
880 let f = Foo {};
881 b.do_stuff(1);
882 f.do_stuff(2);
883 Foo::new(4).do_stuff(3);
884 // Too many / too few args - should never match
885 f.do_stuff(2, 10);
886 f.do_stuff();
887 }
888 "#;
889 assert_matches("Foo::do_stuff($a, $b)", code, &["f.do_stuff(2)", "Foo::new(4).do_stuff(3)"]);
890 // The arguments needs special handling in the case of a function call matching a method call
891 // and the first argument is different.
892 assert_matches("Foo::do_stuff($a, 2)", code, &["f.do_stuff(2)"]);
893 assert_matches("Foo::do_stuff(Foo::new(4), $b)", code, &["Foo::new(4).do_stuff(3)"]);
894
895 assert_ssr_transform(
896 "Foo::do_stuff(Foo::new($a), $b) ==>> Bar::new($b).do_stuff($a)",
897 code,
898 expect![[r#"
899 struct Foo {}
900 impl Foo {
901 fn new(_: i32) -> Foo { Foo {} }
902 fn do_stuff(&self, _: i32) {}
903 }
904 struct Bar {}
905 impl Bar {
906 fn new(_: i32) -> Bar { Bar {} }
907 fn do_stuff(&self, v: i32) {}
908 }
909 fn main() {
910 let b = Bar {};
911 let f = Foo {};
912 b.do_stuff(1);
913 f.do_stuff(2);
914 Bar::new(3).do_stuff(4);
915 // Too many / too few args - should never match
916 f.do_stuff(2, 10);
917 f.do_stuff();
918 }
919 "#]],
920 );
921}
922
923#[test]
924fn pattern_is_a_single_segment_path() {
925 mark::check!(pattern_is_a_single_segment_path);
926 // The first function should not be altered because the `foo` in scope at the cursor position is
927 // a different `foo`. This case is special because "foo" can be parsed as a pattern (IDENT_PAT ->
928 // NAME -> IDENT), which contains no path. If we're not careful we'll end up matching the `foo`
929 // in `let foo` from the first function. Whether we should match the `let foo` in the second
930 // function is less clear. At the moment, we don't. Doing so sounds like a rename operation,
931 // which isn't really what SSR is for, especially since the replacement `bar` must be able to be
932 // resolved, which means if we rename `foo` we'll get a name collision.
933 assert_ssr_transform(
934 "foo ==>> bar",
935 r#"
936 fn f1() -> i32 {
937 let foo = 1;
938 let bar = 2;
939 foo
940 }
941 fn f1() -> i32 {
942 let foo = 1;
943 let bar = 2;
944 foo<|>
945 }
946 "#,
947 expect![[r#"
948 fn f1() -> i32 {
949 let foo = 1;
950 let bar = 2;
951 foo
952 }
953 fn f1() -> i32 {
954 let foo = 1;
955 let bar = 2;
956 bar
957 }
958 "#]],
959 );
960}
961
962#[test]
963fn replace_local_variable_reference() {
964 // The pattern references a local variable `foo` in the block containing the cursor. We should
965 // only replace references to this variable `foo`, not other variables that just happen to have
966 // the same name.
967 mark::check!(cursor_after_semicolon);
968 assert_ssr_transform(
969 "foo + $a ==>> $a - foo",
970 r#"
971 fn bar1() -> i32 {
972 let mut res = 0;
973 let foo = 5;
974 res += foo + 1;
975 let foo = 10;
976 res += foo + 2;<|>
977 res += foo + 3;
978 let foo = 15;
979 res += foo + 4;
980 res
981 }
982 "#,
983 expect![[r#"
984 fn bar1() -> i32 {
985 let mut res = 0;
986 let foo = 5;
987 res += foo + 1;
988 let foo = 10;
989 res += 2 - foo;
990 res += 3 - foo;
991 let foo = 15;
992 res += foo + 4;
993 res
994 }
995 "#]],
996 )
997}
998
999#[test]
1000fn replace_path_within_selection() {
1001 assert_ssr_transform(
1002 "foo ==>> bar",
1003 r#"
1004 fn main() {
1005 let foo = 41;
1006 let bar = 42;
1007 do_stuff(foo);
1008 do_stuff(foo);<|>
1009 do_stuff(foo);
1010 do_stuff(foo);<|>
1011 do_stuff(foo);
1012 }"#,
1013 expect![[r#"
1014 fn main() {
1015 let foo = 41;
1016 let bar = 42;
1017 do_stuff(foo);
1018 do_stuff(foo);
1019 do_stuff(bar);
1020 do_stuff(bar);
1021 do_stuff(foo);
1022 }"#]],
1023 );
1024}
1025
1026#[test]
1027fn replace_nonpath_within_selection() {
1028 mark::check!(replace_nonpath_within_selection);
1029 assert_ssr_transform(
1030 "$a + $b ==>> $b * $a",
1031 r#"
1032 fn main() {
1033 let v = 1 + 2;<|>
1034 let v2 = 3 + 3;
1035 let v3 = 4 + 5;<|>
1036 let v4 = 6 + 7;
1037 }"#,
1038 expect![[r#"
1039 fn main() {
1040 let v = 1 + 2;
1041 let v2 = 3 * 3;
1042 let v3 = 5 * 4;
1043 let v4 = 6 + 7;
1044 }"#]],
1045 );
1046}
1047
1048#[test]
1049fn replace_self() {
1050 // `foo(self)` occurs twice in the code, however only the first occurrence is the `self` that's
1051 // in scope where the rule is invoked.
1052 assert_ssr_transform(
1053 "foo(self) ==>> bar(self)",
1054 r#"
1055 struct S1 {}
1056 fn foo(_: &S1) {}
1057 fn bar(_: &S1) {}
1058 impl S1 {
1059 fn f1(&self) {
1060 foo(self)<|>
1061 }
1062 fn f2(&self) {
1063 foo(self)
1064 }
1065 }
1066 "#,
1067 expect![[r#"
1068 struct S1 {}
1069 fn foo(_: &S1) {}
1070 fn bar(_: &S1) {}
1071 impl S1 {
1072 fn f1(&self) {
1073 bar(self)
1074 }
1075 fn f2(&self) {
1076 foo(self)
1077 }
1078 }
1079 "#]],
1080 );
1081}