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