]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/references/rename.rs
Merge #6246
[rust.git] / crates / ide / src / references / rename.rs
1 //! FIXME: write short doc here
2
3 use base_db::SourceDatabaseExt;
4 use hir::{Module, ModuleDef, ModuleSource, Semantics};
5 use ide_db::{
6     defs::{Definition, NameClass, NameRefClass},
7     RootDatabase,
8 };
9
10 use std::{
11     convert::TryInto,
12     error::Error,
13     fmt::{self, Display},
14 };
15 use syntax::{
16     algo::find_node_at_offset,
17     ast::{self, NameOwner},
18     lex_single_syntax_kind, match_ast, AstNode, SyntaxKind, SyntaxNode, SyntaxToken,
19 };
20 use test_utils::mark;
21 use text_edit::TextEdit;
22
23 use crate::{
24     references::find_all_refs, FilePosition, FileSystemEdit, RangeInfo, Reference, ReferenceKind,
25     SourceChange, SourceFileEdit, TextRange, TextSize,
26 };
27
28 #[derive(Debug)]
29 pub struct RenameError(pub(crate) String);
30
31 impl fmt::Display for RenameError {
32     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33         Display::fmt(&self.0, f)
34     }
35 }
36
37 impl Error for RenameError {}
38
39 pub(crate) fn rename(
40     db: &RootDatabase,
41     position: FilePosition,
42     new_name: &str,
43 ) -> Result<RangeInfo<SourceChange>, RenameError> {
44     let sema = Semantics::new(db);
45     rename_with_semantics(&sema, position, new_name)
46 }
47
48 pub(crate) fn rename_with_semantics(
49     sema: &Semantics<RootDatabase>,
50     position: FilePosition,
51     new_name: &str,
52 ) -> Result<RangeInfo<SourceChange>, RenameError> {
53     match lex_single_syntax_kind(new_name) {
54         Some(res) => match res {
55             (SyntaxKind::IDENT, _) => (),
56             (SyntaxKind::UNDERSCORE, _) => (),
57             (SyntaxKind::SELF_KW, _) => return rename_to_self(&sema, position),
58             (_, Some(syntax_error)) => {
59                 return Err(RenameError(format!("Invalid name `{}`: {}", new_name, syntax_error)))
60             }
61             (_, None) => {
62                 return Err(RenameError(format!("Invalid name `{}`: not an identifier", new_name)))
63             }
64         },
65         None => return Err(RenameError(format!("Invalid name `{}`: not an identifier", new_name))),
66     }
67
68     let source_file = sema.parse(position.file_id);
69     let syntax = source_file.syntax();
70     if let Some(module) = find_module_at_offset(&sema, position, syntax) {
71         rename_mod(&sema, position, module, new_name)
72     } else if let Some(self_token) =
73         syntax.token_at_offset(position.offset).find(|t| t.kind() == SyntaxKind::SELF_KW)
74     {
75         rename_self_to_param(&sema, position, self_token, new_name)
76     } else {
77         rename_reference(&sema, position, new_name)
78     }
79 }
80
81 fn find_module_at_offset(
82     sema: &Semantics<RootDatabase>,
83     position: FilePosition,
84     syntax: &SyntaxNode,
85 ) -> Option<Module> {
86     let ident = syntax.token_at_offset(position.offset).find(|t| t.kind() == SyntaxKind::IDENT)?;
87
88     let module = match_ast! {
89         match (ident.parent()) {
90             ast::NameRef(name_ref) => {
91                 match NameRefClass::classify(sema, &name_ref)? {
92                     NameRefClass::Definition(Definition::ModuleDef(ModuleDef::Module(module))) => module,
93                     _ => return None,
94                 }
95             },
96             ast::Name(name) => {
97                 match NameClass::classify(&sema, &name)? {
98                     NameClass::Definition(Definition::ModuleDef(ModuleDef::Module(module))) => module,
99                     _ => return None,
100                 }
101             },
102             _ => return None,
103         }
104     };
105
106     Some(module)
107 }
108
109 fn source_edit_from_reference(reference: Reference, new_name: &str) -> SourceFileEdit {
110     let mut replacement_text = String::new();
111     let file_id = reference.file_range.file_id;
112     let range = match reference.kind {
113         ReferenceKind::FieldShorthandForField => {
114             mark::hit!(test_rename_struct_field_for_shorthand);
115             replacement_text.push_str(new_name);
116             replacement_text.push_str(": ");
117             TextRange::new(reference.file_range.range.start(), reference.file_range.range.start())
118         }
119         ReferenceKind::FieldShorthandForLocal => {
120             mark::hit!(test_rename_local_for_field_shorthand);
121             replacement_text.push_str(": ");
122             replacement_text.push_str(new_name);
123             TextRange::new(reference.file_range.range.end(), reference.file_range.range.end())
124         }
125         _ => {
126             replacement_text.push_str(new_name);
127             reference.file_range.range
128         }
129     };
130     SourceFileEdit { file_id, edit: TextEdit::replace(range, replacement_text) }
131 }
132
133 fn rename_mod(
134     sema: &Semantics<RootDatabase>,
135     position: FilePosition,
136     module: Module,
137     new_name: &str,
138 ) -> Result<RangeInfo<SourceChange>, RenameError> {
139     let mut source_file_edits = Vec::new();
140     let mut file_system_edits = Vec::new();
141
142     let src = module.definition_source(sema.db);
143     let file_id = src.file_id.original_file(sema.db);
144     match src.value {
145         ModuleSource::SourceFile(..) => {
146             // mod is defined in path/to/dir/mod.rs
147             let dst = if module.is_mod_rs(sema.db) {
148                 format!("../{}/mod.rs", new_name)
149             } else {
150                 format!("{}.rs", new_name)
151             };
152             let move_file = FileSystemEdit::MoveFile { src: file_id, anchor: file_id, dst };
153             file_system_edits.push(move_file);
154         }
155         ModuleSource::Module(..) => {}
156     }
157
158     if let Some(src) = module.declaration_source(sema.db) {
159         let file_id = src.file_id.original_file(sema.db);
160         let name = src.value.name().unwrap();
161         let edit = SourceFileEdit {
162             file_id,
163             edit: TextEdit::replace(name.syntax().text_range(), new_name.into()),
164         };
165         source_file_edits.push(edit);
166     }
167
168     let RangeInfo { range, info: refs } = find_all_refs(sema, position, None)
169         .ok_or_else(|| RenameError("No references found at position".to_string()))?;
170     let ref_edits = refs
171         .references
172         .into_iter()
173         .map(|reference| source_edit_from_reference(reference, new_name));
174     source_file_edits.extend(ref_edits);
175
176     Ok(RangeInfo::new(range, SourceChange::from_edits(source_file_edits, file_system_edits)))
177 }
178
179 fn rename_to_self(
180     sema: &Semantics<RootDatabase>,
181     position: FilePosition,
182 ) -> Result<RangeInfo<SourceChange>, RenameError> {
183     let source_file = sema.parse(position.file_id);
184     let syn = source_file.syntax();
185
186     let fn_def = find_node_at_offset::<ast::Fn>(syn, position.offset)
187         .ok_or_else(|| RenameError("No surrounding method declaration found".to_string()))?;
188     let params =
189         fn_def.param_list().ok_or_else(|| RenameError("Method has no parameters".to_string()))?;
190     if params.self_param().is_some() {
191         return Err(RenameError("Method already has a self parameter".to_string()));
192     }
193     let first_param =
194         params.params().next().ok_or_else(|| RenameError("Method has no parameters".into()))?;
195     let mutable = match first_param.ty() {
196         Some(ast::Type::RefType(rt)) => rt.mut_token().is_some(),
197         _ => return Err(RenameError("Not renaming other types".to_string())),
198     };
199
200     let RangeInfo { range, info: refs } = find_all_refs(sema, position, None)
201         .ok_or_else(|| RenameError("No reference found at position".to_string()))?;
202
203     let param_range = first_param.syntax().text_range();
204     let (param_ref, usages): (Vec<Reference>, Vec<Reference>) = refs
205         .into_iter()
206         .partition(|reference| param_range.intersect(reference.file_range.range).is_some());
207
208     if param_ref.is_empty() {
209         return Err(RenameError("Parameter to rename not found".to_string()));
210     }
211
212     let mut edits = usages
213         .into_iter()
214         .map(|reference| source_edit_from_reference(reference, "self"))
215         .collect::<Vec<_>>();
216
217     edits.push(SourceFileEdit {
218         file_id: position.file_id,
219         edit: TextEdit::replace(
220             param_range,
221             String::from(if mutable { "&mut self" } else { "&self" }),
222         ),
223     });
224
225     Ok(RangeInfo::new(range, SourceChange::from(edits)))
226 }
227
228 fn text_edit_from_self_param(
229     syn: &SyntaxNode,
230     self_param: &ast::SelfParam,
231     new_name: &str,
232 ) -> Option<TextEdit> {
233     fn target_type_name(impl_def: &ast::Impl) -> Option<String> {
234         if let Some(ast::Type::PathType(p)) = impl_def.self_ty() {
235             return Some(p.path()?.segment()?.name_ref()?.text().to_string());
236         }
237         None
238     }
239
240     let impl_def = find_node_at_offset::<ast::Impl>(syn, self_param.syntax().text_range().start())?;
241     let type_name = target_type_name(&impl_def)?;
242
243     let mut replacement_text = String::from(new_name);
244     replacement_text.push_str(": ");
245     replacement_text.push_str(self_param.mut_token().map_or("&", |_| "&mut "));
246     replacement_text.push_str(type_name.as_str());
247
248     Some(TextEdit::replace(self_param.syntax().text_range(), replacement_text))
249 }
250
251 fn rename_self_to_param(
252     sema: &Semantics<RootDatabase>,
253     position: FilePosition,
254     self_token: SyntaxToken,
255     new_name: &str,
256 ) -> Result<RangeInfo<SourceChange>, RenameError> {
257     let source_file = sema.parse(position.file_id);
258     let syn = source_file.syntax();
259
260     let text = sema.db.file_text(position.file_id);
261     let fn_def = find_node_at_offset::<ast::Fn>(syn, position.offset)
262         .ok_or_else(|| RenameError("No surrounding method declaration found".to_string()))?;
263     let search_range = fn_def.syntax().text_range();
264
265     let mut edits: Vec<SourceFileEdit> = vec![];
266
267     for (idx, _) in text.match_indices("self") {
268         let offset: TextSize = idx.try_into().unwrap();
269         if !search_range.contains_inclusive(offset) {
270             continue;
271         }
272         if let Some(ref usage) =
273             syn.token_at_offset(offset).find(|t| t.kind() == SyntaxKind::SELF_KW)
274         {
275             let edit = if let Some(ref self_param) = ast::SelfParam::cast(usage.parent()) {
276                 text_edit_from_self_param(syn, self_param, new_name)
277                     .ok_or_else(|| RenameError("No target type found".to_string()))?
278             } else {
279                 TextEdit::replace(usage.text_range(), String::from(new_name))
280             };
281             edits.push(SourceFileEdit { file_id: position.file_id, edit });
282         }
283     }
284
285     let range = ast::SelfParam::cast(self_token.parent())
286         .map_or(self_token.text_range(), |p| p.syntax().text_range());
287
288     Ok(RangeInfo::new(range, SourceChange::from(edits)))
289 }
290
291 fn rename_reference(
292     sema: &Semantics<RootDatabase>,
293     position: FilePosition,
294     new_name: &str,
295 ) -> Result<RangeInfo<SourceChange>, RenameError> {
296     let RangeInfo { range, info: refs } = match find_all_refs(sema, position, None) {
297         Some(range_info) => range_info,
298         None => return Err(RenameError("No references found at position".to_string())),
299     };
300
301     let edit = refs
302         .into_iter()
303         .map(|reference| source_edit_from_reference(reference, new_name))
304         .collect::<Vec<_>>();
305
306     if edit.is_empty() {
307         return Err(RenameError("No references found at position".to_string()));
308     }
309
310     Ok(RangeInfo::new(range, SourceChange::from(edit)))
311 }
312
313 #[cfg(test)]
314 mod tests {
315     use expect_test::{expect, Expect};
316     use stdx::trim_indent;
317     use test_utils::{assert_eq_text, mark};
318     use text_edit::TextEdit;
319
320     use crate::{fixture, FileId};
321
322     fn check(new_name: &str, ra_fixture_before: &str, ra_fixture_after: &str) {
323         let ra_fixture_after = &trim_indent(ra_fixture_after);
324         let (analysis, position) = fixture::position(ra_fixture_before);
325         let rename_result = analysis
326             .rename(position, new_name)
327             .unwrap_or_else(|err| panic!("Rename to '{}' was cancelled: {}", new_name, err));
328         match rename_result {
329             Ok(source_change) => {
330                 let mut text_edit_builder = TextEdit::builder();
331                 let mut file_id: Option<FileId> = None;
332                 for edit in source_change.info.source_file_edits {
333                     file_id = Some(edit.file_id);
334                     for indel in edit.edit.into_iter() {
335                         text_edit_builder.replace(indel.delete, indel.insert);
336                     }
337                 }
338                 let mut result = analysis.file_text(file_id.unwrap()).unwrap().to_string();
339                 text_edit_builder.finish().apply(&mut result);
340                 assert_eq_text!(ra_fixture_after, &*result);
341             }
342             Err(err) => {
343                 if ra_fixture_after.starts_with("error:") {
344                     let error_message = ra_fixture_after
345                         .chars()
346                         .into_iter()
347                         .skip("error:".len())
348                         .collect::<String>();
349                     assert_eq!(error_message.trim(), err.to_string());
350                     return;
351                 } else {
352                     panic!("Rename to '{}' failed unexpectedly: {}", new_name, err)
353                 }
354             }
355         };
356     }
357
358     fn check_expect(new_name: &str, ra_fixture: &str, expect: Expect) {
359         let (analysis, position) = fixture::position(ra_fixture);
360         let source_change = analysis
361             .rename(position, new_name)
362             .unwrap()
363             .expect("Expect returned RangeInfo to be Some, but was None");
364         expect.assert_debug_eq(&source_change)
365     }
366
367     #[test]
368     fn test_rename_to_underscore() {
369         check("_", r#"fn main() { let i<|> = 1; }"#, r#"fn main() { let _ = 1; }"#);
370     }
371
372     #[test]
373     fn test_rename_to_raw_identifier() {
374         check("r#fn", r#"fn main() { let i<|> = 1; }"#, r#"fn main() { let r#fn = 1; }"#);
375     }
376
377     #[test]
378     fn test_rename_to_invalid_identifier1() {
379         check(
380             "invalid!",
381             r#"fn main() { let i<|> = 1; }"#,
382             "error: Invalid name `invalid!`: not an identifier",
383         );
384     }
385
386     #[test]
387     fn test_rename_to_invalid_identifier2() {
388         check(
389             "multiple tokens",
390             r#"fn main() { let i<|> = 1; }"#,
391             "error: Invalid name `multiple tokens`: not an identifier",
392         );
393     }
394
395     #[test]
396     fn test_rename_to_invalid_identifier3() {
397         check(
398             "let",
399             r#"fn main() { let i<|> = 1; }"#,
400             "error: Invalid name `let`: not an identifier",
401         );
402     }
403
404     #[test]
405     fn test_rename_for_local() {
406         check(
407             "k",
408             r#"
409 fn main() {
410     let mut i = 1;
411     let j = 1;
412     i = i<|> + j;
413
414     { i = 0; }
415
416     i = 5;
417 }
418 "#,
419             r#"
420 fn main() {
421     let mut k = 1;
422     let j = 1;
423     k = k + j;
424
425     { k = 0; }
426
427     k = 5;
428 }
429 "#,
430         );
431     }
432
433     #[test]
434     fn test_rename_unresolved_reference() {
435         check(
436             "new_name",
437             r#"fn main() { let _ = unresolved_ref<|>; }"#,
438             "error: No references found at position",
439         );
440     }
441
442     #[test]
443     fn test_rename_for_macro_args() {
444         check(
445             "b",
446             r#"
447 macro_rules! foo {($i:ident) => {$i} }
448 fn main() {
449     let a<|> = "test";
450     foo!(a);
451 }
452 "#,
453             r#"
454 macro_rules! foo {($i:ident) => {$i} }
455 fn main() {
456     let b = "test";
457     foo!(b);
458 }
459 "#,
460         );
461     }
462
463     #[test]
464     fn test_rename_for_macro_args_rev() {
465         check(
466             "b",
467             r#"
468 macro_rules! foo {($i:ident) => {$i} }
469 fn main() {
470     let a = "test";
471     foo!(a<|>);
472 }
473 "#,
474             r#"
475 macro_rules! foo {($i:ident) => {$i} }
476 fn main() {
477     let b = "test";
478     foo!(b);
479 }
480 "#,
481         );
482     }
483
484     #[test]
485     fn test_rename_for_macro_define_fn() {
486         check(
487             "bar",
488             r#"
489 macro_rules! define_fn {($id:ident) => { fn $id{} }}
490 define_fn!(foo);
491 fn main() {
492     fo<|>o();
493 }
494 "#,
495             r#"
496 macro_rules! define_fn {($id:ident) => { fn $id{} }}
497 define_fn!(bar);
498 fn main() {
499     bar();
500 }
501 "#,
502         );
503     }
504
505     #[test]
506     fn test_rename_for_macro_define_fn_rev() {
507         check(
508             "bar",
509             r#"
510 macro_rules! define_fn {($id:ident) => { fn $id{} }}
511 define_fn!(fo<|>o);
512 fn main() {
513     foo();
514 }
515 "#,
516             r#"
517 macro_rules! define_fn {($id:ident) => { fn $id{} }}
518 define_fn!(bar);
519 fn main() {
520     bar();
521 }
522 "#,
523         );
524     }
525
526     #[test]
527     fn test_rename_for_param_inside() {
528         check("j", r#"fn foo(i : u32) -> u32 { i<|> }"#, r#"fn foo(j : u32) -> u32 { j }"#);
529     }
530
531     #[test]
532     fn test_rename_refs_for_fn_param() {
533         check("j", r#"fn foo(i<|> : u32) -> u32 { i }"#, r#"fn foo(j : u32) -> u32 { j }"#);
534     }
535
536     #[test]
537     fn test_rename_for_mut_param() {
538         check("j", r#"fn foo(mut i<|> : u32) -> u32 { i }"#, r#"fn foo(mut j : u32) -> u32 { j }"#);
539     }
540
541     #[test]
542     fn test_rename_struct_field() {
543         check(
544             "j",
545             r#"
546 struct Foo { i<|>: i32 }
547
548 impl Foo {
549     fn new(i: i32) -> Self {
550         Self { i: i }
551     }
552 }
553 "#,
554             r#"
555 struct Foo { j: i32 }
556
557 impl Foo {
558     fn new(i: i32) -> Self {
559         Self { j: i }
560     }
561 }
562 "#,
563         );
564     }
565
566     #[test]
567     fn test_rename_struct_field_for_shorthand() {
568         mark::check!(test_rename_struct_field_for_shorthand);
569         check(
570             "j",
571             r#"
572 struct Foo { i<|>: i32 }
573
574 impl Foo {
575     fn new(i: i32) -> Self {
576         Self { i }
577     }
578 }
579 "#,
580             r#"
581 struct Foo { j: i32 }
582
583 impl Foo {
584     fn new(i: i32) -> Self {
585         Self { j: i }
586     }
587 }
588 "#,
589         );
590     }
591
592     #[test]
593     fn test_rename_local_for_field_shorthand() {
594         mark::check!(test_rename_local_for_field_shorthand);
595         check(
596             "j",
597             r#"
598 struct Foo { i: i32 }
599
600 impl Foo {
601     fn new(i<|>: i32) -> Self {
602         Self { i }
603     }
604 }
605 "#,
606             r#"
607 struct Foo { i: i32 }
608
609 impl Foo {
610     fn new(j: i32) -> Self {
611         Self { i: j }
612     }
613 }
614 "#,
615         );
616     }
617
618     #[test]
619     fn test_field_shorthand_correct_struct() {
620         check(
621             "j",
622             r#"
623 struct Foo { i<|>: i32 }
624 struct Bar { i: i32 }
625
626 impl Bar {
627     fn new(i: i32) -> Self {
628         Self { i }
629     }
630 }
631 "#,
632             r#"
633 struct Foo { j: i32 }
634 struct Bar { i: i32 }
635
636 impl Bar {
637     fn new(i: i32) -> Self {
638         Self { i }
639     }
640 }
641 "#,
642         );
643     }
644
645     #[test]
646     fn test_shadow_local_for_struct_shorthand() {
647         check(
648             "j",
649             r#"
650 struct Foo { i: i32 }
651
652 fn baz(i<|>: i32) -> Self {
653      let x = Foo { i };
654      {
655          let i = 0;
656          Foo { i }
657      }
658 }
659 "#,
660             r#"
661 struct Foo { i: i32 }
662
663 fn baz(j: i32) -> Self {
664      let x = Foo { i: j };
665      {
666          let i = 0;
667          Foo { i }
668      }
669 }
670 "#,
671         );
672     }
673
674     #[test]
675     fn test_rename_mod() {
676         check_expect(
677             "foo2",
678             r#"
679 //- /lib.rs
680 mod bar;
681
682 //- /bar.rs
683 mod foo<|>;
684
685 //- /bar/foo.rs
686 // empty
687 "#,
688             expect![[r#"
689                 RangeInfo {
690                     range: 4..7,
691                     info: SourceChange {
692                         source_file_edits: [
693                             SourceFileEdit {
694                                 file_id: FileId(
695                                     1,
696                                 ),
697                                 edit: TextEdit {
698                                     indels: [
699                                         Indel {
700                                             insert: "foo2",
701                                             delete: 4..7,
702                                         },
703                                     ],
704                                 },
705                             },
706                         ],
707                         file_system_edits: [
708                             MoveFile {
709                                 src: FileId(
710                                     2,
711                                 ),
712                                 anchor: FileId(
713                                     2,
714                                 ),
715                                 dst: "foo2.rs",
716                             },
717                         ],
718                         is_snippet: false,
719                     },
720                 }
721             "#]],
722         );
723     }
724
725     #[test]
726     fn test_rename_mod_in_use_tree() {
727         check_expect(
728             "quux",
729             r#"
730 //- /main.rs
731 pub mod foo;
732 pub mod bar;
733 fn main() {}
734
735 //- /foo.rs
736 pub struct FooContent;
737
738 //- /bar.rs
739 use crate::foo<|>::FooContent;
740 "#,
741             expect![[r#"
742                 RangeInfo {
743                     range: 11..14,
744                     info: SourceChange {
745                         source_file_edits: [
746                             SourceFileEdit {
747                                 file_id: FileId(
748                                     0,
749                                 ),
750                                 edit: TextEdit {
751                                     indels: [
752                                         Indel {
753                                             insert: "quux",
754                                             delete: 8..11,
755                                         },
756                                     ],
757                                 },
758                             },
759                             SourceFileEdit {
760                                 file_id: FileId(
761                                     2,
762                                 ),
763                                 edit: TextEdit {
764                                     indels: [
765                                         Indel {
766                                             insert: "quux",
767                                             delete: 11..14,
768                                         },
769                                     ],
770                                 },
771                             },
772                         ],
773                         file_system_edits: [
774                             MoveFile {
775                                 src: FileId(
776                                     1,
777                                 ),
778                                 anchor: FileId(
779                                     1,
780                                 ),
781                                 dst: "quux.rs",
782                             },
783                         ],
784                         is_snippet: false,
785                     },
786                 }
787             "#]],
788         );
789     }
790
791     #[test]
792     fn test_rename_mod_in_dir() {
793         check_expect(
794             "foo2",
795             r#"
796 //- /lib.rs
797 mod fo<|>o;
798 //- /foo/mod.rs
799 // emtpy
800 "#,
801             expect![[r#"
802                 RangeInfo {
803                     range: 4..7,
804                     info: SourceChange {
805                         source_file_edits: [
806                             SourceFileEdit {
807                                 file_id: FileId(
808                                     0,
809                                 ),
810                                 edit: TextEdit {
811                                     indels: [
812                                         Indel {
813                                             insert: "foo2",
814                                             delete: 4..7,
815                                         },
816                                     ],
817                                 },
818                             },
819                         ],
820                         file_system_edits: [
821                             MoveFile {
822                                 src: FileId(
823                                     1,
824                                 ),
825                                 anchor: FileId(
826                                     1,
827                                 ),
828                                 dst: "../foo2/mod.rs",
829                             },
830                         ],
831                         is_snippet: false,
832                     },
833                 }
834             "#]],
835         );
836     }
837
838     #[test]
839     fn test_rename_unusually_nested_mod() {
840         check_expect(
841             "bar",
842             r#"
843 //- /lib.rs
844 mod outer { mod fo<|>o; }
845
846 //- /outer/foo.rs
847 // emtpy
848 "#,
849             expect![[r#"
850                 RangeInfo {
851                     range: 16..19,
852                     info: SourceChange {
853                         source_file_edits: [
854                             SourceFileEdit {
855                                 file_id: FileId(
856                                     0,
857                                 ),
858                                 edit: TextEdit {
859                                     indels: [
860                                         Indel {
861                                             insert: "bar",
862                                             delete: 16..19,
863                                         },
864                                     ],
865                                 },
866                             },
867                         ],
868                         file_system_edits: [
869                             MoveFile {
870                                 src: FileId(
871                                     1,
872                                 ),
873                                 anchor: FileId(
874                                     1,
875                                 ),
876                                 dst: "bar.rs",
877                             },
878                         ],
879                         is_snippet: false,
880                     },
881                 }
882             "#]],
883         );
884     }
885
886     #[test]
887     fn test_module_rename_in_path() {
888         check(
889             "baz",
890             r#"
891 mod <|>foo { pub fn bar() {} }
892
893 fn main() { foo::bar(); }
894 "#,
895             r#"
896 mod baz { pub fn bar() {} }
897
898 fn main() { baz::bar(); }
899 "#,
900         );
901     }
902
903     #[test]
904     fn test_rename_mod_filename_and_path() {
905         check_expect(
906             "foo2",
907             r#"
908 //- /lib.rs
909 mod bar;
910 fn f() {
911     bar::foo::fun()
912 }
913
914 //- /bar.rs
915 pub mod foo<|>;
916
917 //- /bar/foo.rs
918 // pub fn fun() {}
919 "#,
920             expect![[r#"
921                 RangeInfo {
922                     range: 8..11,
923                     info: SourceChange {
924                         source_file_edits: [
925                             SourceFileEdit {
926                                 file_id: FileId(
927                                     1,
928                                 ),
929                                 edit: TextEdit {
930                                     indels: [
931                                         Indel {
932                                             insert: "foo2",
933                                             delete: 8..11,
934                                         },
935                                     ],
936                                 },
937                             },
938                             SourceFileEdit {
939                                 file_id: FileId(
940                                     0,
941                                 ),
942                                 edit: TextEdit {
943                                     indels: [
944                                         Indel {
945                                             insert: "foo2",
946                                             delete: 27..30,
947                                         },
948                                     ],
949                                 },
950                             },
951                         ],
952                         file_system_edits: [
953                             MoveFile {
954                                 src: FileId(
955                                     2,
956                                 ),
957                                 anchor: FileId(
958                                     2,
959                                 ),
960                                 dst: "foo2.rs",
961                             },
962                         ],
963                         is_snippet: false,
964                     },
965                 }
966             "#]],
967         );
968     }
969
970     #[test]
971     fn test_enum_variant_from_module_1() {
972         check(
973             "Baz",
974             r#"
975 mod foo {
976     pub enum Foo { Bar<|> }
977 }
978
979 fn func(f: foo::Foo) {
980     match f {
981         foo::Foo::Bar => {}
982     }
983 }
984 "#,
985             r#"
986 mod foo {
987     pub enum Foo { Baz }
988 }
989
990 fn func(f: foo::Foo) {
991     match f {
992         foo::Foo::Baz => {}
993     }
994 }
995 "#,
996         );
997     }
998
999     #[test]
1000     fn test_enum_variant_from_module_2() {
1001         check(
1002             "baz",
1003             r#"
1004 mod foo {
1005     pub struct Foo { pub bar<|>: uint }
1006 }
1007
1008 fn foo(f: foo::Foo) {
1009     let _ = f.bar;
1010 }
1011 "#,
1012             r#"
1013 mod foo {
1014     pub struct Foo { pub baz: uint }
1015 }
1016
1017 fn foo(f: foo::Foo) {
1018     let _ = f.baz;
1019 }
1020 "#,
1021         );
1022     }
1023
1024     #[test]
1025     fn test_parameter_to_self() {
1026         check(
1027             "self",
1028             r#"
1029 struct Foo { i: i32 }
1030
1031 impl Foo {
1032     fn f(foo<|>: &mut Foo) -> i32 {
1033         foo.i
1034     }
1035 }
1036 "#,
1037             r#"
1038 struct Foo { i: i32 }
1039
1040 impl Foo {
1041     fn f(&mut self) -> i32 {
1042         self.i
1043     }
1044 }
1045 "#,
1046         );
1047     }
1048
1049     #[test]
1050     fn test_self_to_parameter() {
1051         check(
1052             "foo",
1053             r#"
1054 struct Foo { i: i32 }
1055
1056 impl Foo {
1057     fn f(&mut <|>self) -> i32 {
1058         self.i
1059     }
1060 }
1061 "#,
1062             r#"
1063 struct Foo { i: i32 }
1064
1065 impl Foo {
1066     fn f(foo: &mut Foo) -> i32 {
1067         foo.i
1068     }
1069 }
1070 "#,
1071         );
1072     }
1073
1074     #[test]
1075     fn test_self_in_path_to_parameter() {
1076         check(
1077             "foo",
1078             r#"
1079 struct Foo { i: i32 }
1080
1081 impl Foo {
1082     fn f(&self) -> i32 {
1083         let self_var = 1;
1084         self<|>.i
1085     }
1086 }
1087 "#,
1088             r#"
1089 struct Foo { i: i32 }
1090
1091 impl Foo {
1092     fn f(foo: &Foo) -> i32 {
1093         let self_var = 1;
1094         foo.i
1095     }
1096 }
1097 "#,
1098         );
1099     }
1100 }