]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/references/rename.rs
Refactor rename name checking
[rust.git] / crates / ide / src / references / rename.rs
1 //! FIXME: write short doc here
2 use std::{
3     convert::TryInto,
4     error::Error,
5     fmt::{self, Display},
6 };
7
8 use hir::{Module, ModuleDef, ModuleSource, Semantics};
9 use ide_db::base_db::{AnchoredPathBuf, FileId, FileRange, SourceDatabaseExt};
10 use ide_db::{
11     defs::{Definition, NameClass, NameRefClass},
12     RootDatabase,
13 };
14 use syntax::{
15     algo::find_node_at_offset,
16     ast::{self, NameOwner},
17     lex_single_syntax_kind, match_ast, AstNode, SyntaxKind, SyntaxNode, SyntaxToken,
18 };
19 use test_utils::mark;
20 use text_edit::TextEdit;
21
22 use crate::{
23     FilePosition, FileSystemEdit, RangeInfo, Reference, ReferenceKind, ReferenceSearchResult,
24     SourceChange, SourceFileEdit, TextRange, TextSize,
25 };
26
27 type RenameResult<T> = Result<T, RenameError>;
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 prepare_rename(
40     db: &RootDatabase,
41     position: FilePosition,
42 ) -> RenameResult<RangeInfo<()>> {
43     let sema = Semantics::new(db);
44     let source_file = sema.parse(position.file_id);
45     let syntax = source_file.syntax();
46     if let Some(module) = find_module_at_offset(&sema, position, syntax) {
47         rename_mod(&sema, position, module, "dummy")
48     } else if let Some(self_token) =
49         syntax.token_at_offset(position.offset).find(|t| t.kind() == SyntaxKind::SELF_KW)
50     {
51         rename_self_to_param(&sema, position, self_token, "dummy")
52     } else {
53         let RangeInfo { range, .. } = find_all_refs(&sema, position)?;
54         Ok(RangeInfo::new(range, SourceChange::from(vec![])))
55     }
56     .map(|info| RangeInfo::new(info.range, ()))
57 }
58
59 pub(crate) fn rename(
60     db: &RootDatabase,
61     position: FilePosition,
62     new_name: &str,
63 ) -> RenameResult<RangeInfo<SourceChange>> {
64     let sema = Semantics::new(db);
65     rename_with_semantics(&sema, position, new_name)
66 }
67
68 pub(crate) fn rename_with_semantics(
69     sema: &Semantics<RootDatabase>,
70     position: FilePosition,
71     new_name: &str,
72 ) -> RenameResult<RangeInfo<SourceChange>> {
73     let source_file = sema.parse(position.file_id);
74     let syntax = source_file.syntax();
75
76     if let Some(module) = find_module_at_offset(&sema, position, syntax) {
77         rename_mod(&sema, position, module, new_name)
78     } else if let Some(self_token) =
79         syntax.token_at_offset(position.offset).find(|t| t.kind() == SyntaxKind::SELF_KW)
80     {
81         rename_self_to_param(&sema, position, self_token, new_name)
82     } else {
83         rename_reference(&sema, position, new_name)
84     }
85 }
86
87 pub(crate) fn will_rename_file(
88     db: &RootDatabase,
89     file_id: FileId,
90     new_name_stem: &str,
91 ) -> Option<SourceChange> {
92     let sema = Semantics::new(db);
93     let module = sema.to_module_def(file_id)?;
94
95     let decl = module.declaration_source(db)?;
96     let range = decl.value.name()?.syntax().text_range();
97
98     let position = FilePosition { file_id: decl.file_id.original_file(db), offset: range.start() };
99     let mut change = rename_mod(&sema, position, module, new_name_stem).ok()?.info;
100     change.file_system_edits.clear();
101     Some(change)
102 }
103
104 #[derive(PartialEq)]
105 enum IdentifierKind {
106     Ident,
107     Lifetime,
108     ToSelf,
109     Underscore,
110 }
111
112 fn check_identifier(new_name: &str) -> RenameResult<IdentifierKind> {
113     match lex_single_syntax_kind(new_name) {
114         Some(res) => match res {
115             (SyntaxKind::IDENT, _) => Ok(IdentifierKind::Ident),
116             (SyntaxKind::UNDERSCORE, _) => Ok(IdentifierKind::Underscore),
117             (SyntaxKind::SELF_KW, _) => Ok(IdentifierKind::ToSelf),
118             (SyntaxKind::LIFETIME_IDENT, _) if new_name != "'static" && new_name != "'_" => {
119                 Ok(IdentifierKind::Lifetime)
120             }
121             (SyntaxKind::LIFETIME_IDENT, _) => {
122                 Err(format!("Invalid name `{0}`: Cannot rename lifetime to {0}", new_name))
123             }
124             (_, Some(syntax_error)) => {
125                 Err(format!("Invalid name `{}`: {}", new_name, syntax_error))
126             }
127             (_, None) => Err(format!("Invalid name `{}`: not an identifier", new_name)),
128         },
129         None => Err(format!("Invalid name `{}`: not an identifier", new_name)),
130     }
131     .map_err(RenameError)
132 }
133
134 fn find_module_at_offset(
135     sema: &Semantics<RootDatabase>,
136     position: FilePosition,
137     syntax: &SyntaxNode,
138 ) -> Option<Module> {
139     let ident = syntax.token_at_offset(position.offset).find(|t| t.kind() == SyntaxKind::IDENT)?;
140
141     let module = match_ast! {
142         match (ident.parent()) {
143             ast::NameRef(name_ref) => {
144                 match NameRefClass::classify(sema, &name_ref)? {
145                     NameRefClass::Definition(Definition::ModuleDef(ModuleDef::Module(module))) => module,
146                     _ => return None,
147                 }
148             },
149             ast::Name(name) => {
150                 match NameClass::classify(&sema, &name)? {
151                     NameClass::Definition(Definition::ModuleDef(ModuleDef::Module(module))) => module,
152                     _ => return None,
153                 }
154             },
155             _ => return None,
156         }
157     };
158
159     Some(module)
160 }
161
162 fn find_all_refs(
163     sema: &Semantics<RootDatabase>,
164     position: FilePosition,
165 ) -> RenameResult<RangeInfo<ReferenceSearchResult>> {
166     crate::references::find_all_refs(sema, position, None)
167         .ok_or_else(|| RenameError("No references found at position".to_string()))
168 }
169
170 fn source_edit_from_reference(
171     sema: &Semantics<RootDatabase>,
172     reference: Reference,
173     new_name: &str,
174 ) -> SourceFileEdit {
175     let mut replacement_text = String::new();
176     let range = match reference.kind {
177         ReferenceKind::FieldShorthandForField => {
178             mark::hit!(test_rename_struct_field_for_shorthand);
179             replacement_text.push_str(new_name);
180             replacement_text.push_str(": ");
181             TextRange::new(reference.file_range.range.start(), reference.file_range.range.start())
182         }
183         ReferenceKind::FieldShorthandForLocal => {
184             mark::hit!(test_rename_local_for_field_shorthand);
185             replacement_text.push_str(": ");
186             replacement_text.push_str(new_name);
187             TextRange::new(reference.file_range.range.end(), reference.file_range.range.end())
188         }
189         ReferenceKind::RecordFieldExprOrPat => {
190             mark::hit!(test_rename_field_expr_pat);
191             replacement_text.push_str(new_name);
192             edit_text_range_for_record_field_expr_or_pat(sema, reference.file_range, new_name)
193         }
194         _ => {
195             replacement_text.push_str(new_name);
196             reference.file_range.range
197         }
198     };
199     SourceFileEdit {
200         file_id: reference.file_range.file_id,
201         edit: TextEdit::replace(range, replacement_text),
202     }
203 }
204
205 fn edit_text_range_for_record_field_expr_or_pat(
206     sema: &Semantics<RootDatabase>,
207     file_range: FileRange,
208     new_name: &str,
209 ) -> TextRange {
210     let source_file = sema.parse(file_range.file_id);
211     let file_syntax = source_file.syntax();
212     let original_range = file_range.range;
213
214     syntax::algo::find_node_at_range::<ast::RecordExprField>(file_syntax, original_range)
215         .and_then(|field_expr| match field_expr.expr().and_then(|e| e.name_ref()) {
216             Some(name) if &name.to_string() == new_name => Some(field_expr.syntax().text_range()),
217             _ => None,
218         })
219         .or_else(|| {
220             syntax::algo::find_node_at_range::<ast::RecordPatField>(file_syntax, original_range)
221                 .and_then(|field_pat| match field_pat.pat() {
222                     Some(ast::Pat::IdentPat(pat))
223                         if pat.name().map(|n| n.to_string()).as_deref() == Some(new_name) =>
224                     {
225                         Some(field_pat.syntax().text_range())
226                     }
227                     _ => None,
228                 })
229         })
230         .unwrap_or(original_range)
231 }
232
233 fn rename_mod(
234     sema: &Semantics<RootDatabase>,
235     position: FilePosition,
236     module: Module,
237     new_name: &str,
238 ) -> RenameResult<RangeInfo<SourceChange>> {
239     if IdentifierKind::Ident != check_identifier(new_name)? {
240         return Err(RenameError(format!(
241             "Invalid name `{0}`: cannot rename module to {0}",
242             new_name
243         )));
244     }
245     let mut source_file_edits = Vec::new();
246     let mut file_system_edits = Vec::new();
247
248     let src = module.definition_source(sema.db);
249     let file_id = src.file_id.original_file(sema.db);
250     match src.value {
251         ModuleSource::SourceFile(..) => {
252             // mod is defined in path/to/dir/mod.rs
253             let path = if module.is_mod_rs(sema.db) {
254                 format!("../{}/mod.rs", new_name)
255             } else {
256                 format!("{}.rs", new_name)
257             };
258             let dst = AnchoredPathBuf { anchor: file_id, path };
259             let move_file = FileSystemEdit::MoveFile { src: file_id, dst };
260             file_system_edits.push(move_file);
261         }
262         ModuleSource::Module(..) => {}
263     }
264
265     if let Some(src) = module.declaration_source(sema.db) {
266         let file_id = src.file_id.original_file(sema.db);
267         let name = src.value.name().unwrap();
268         let edit = SourceFileEdit {
269             file_id,
270             edit: TextEdit::replace(name.syntax().text_range(), new_name.into()),
271         };
272         source_file_edits.push(edit);
273     }
274
275     let RangeInfo { range, info: refs } = find_all_refs(sema, position)?;
276     let ref_edits = refs
277         .references
278         .into_iter()
279         .map(|reference| source_edit_from_reference(sema, reference, new_name));
280     source_file_edits.extend(ref_edits);
281
282     Ok(RangeInfo::new(range, SourceChange::from_edits(source_file_edits, file_system_edits)))
283 }
284
285 fn rename_to_self(
286     sema: &Semantics<RootDatabase>,
287     position: FilePosition,
288 ) -> Result<RangeInfo<SourceChange>, RenameError> {
289     let source_file = sema.parse(position.file_id);
290     let syn = source_file.syntax();
291
292     let (fn_def, fn_ast) = find_node_at_offset::<ast::Fn>(syn, position.offset)
293         .and_then(|fn_ast| sema.to_def(&fn_ast).zip(Some(fn_ast)))
294         .ok_or_else(|| RenameError("No surrounding method declaration found".to_string()))?;
295     let param_range = fn_ast
296         .param_list()
297         .and_then(|p| p.params().next())
298         .ok_or_else(|| RenameError("Method has no parameters".to_string()))?
299         .syntax()
300         .text_range();
301     if !param_range.contains(position.offset) {
302         return Err(RenameError("Only the first parameter can be self".to_string()));
303     }
304
305     let impl_block = find_node_at_offset::<ast::Impl>(syn, position.offset)
306         .and_then(|def| sema.to_def(&def))
307         .ok_or_else(|| RenameError("No impl block found for function".to_string()))?;
308     if fn_def.self_param(sema.db).is_some() {
309         return Err(RenameError("Method already has a self parameter".to_string()));
310     }
311
312     let params = fn_def.assoc_fn_params(sema.db);
313     let first_param =
314         params.first().ok_or_else(|| RenameError("Method has no parameters".into()))?;
315     let first_param_ty = first_param.ty();
316     let impl_ty = impl_block.target_ty(sema.db);
317     let (ty, self_param) = if impl_ty.remove_ref().is_some() {
318         // if the impl is a ref to the type we can just match the `&T` with self directly
319         (first_param_ty.clone(), "self")
320     } else {
321         first_param_ty.remove_ref().map_or((first_param_ty.clone(), "self"), |ty| {
322             (ty, if first_param_ty.is_mutable_reference() { "&mut self" } else { "&self" })
323         })
324     };
325
326     if ty != impl_ty {
327         return Err(RenameError("Parameter type differs from impl block type".to_string()));
328     }
329
330     let RangeInfo { range, info: refs } = find_all_refs(sema, position)?;
331
332     let (param_ref, usages): (Vec<Reference>, Vec<Reference>) = refs
333         .into_iter()
334         .partition(|reference| param_range.intersect(reference.file_range.range).is_some());
335
336     if param_ref.is_empty() {
337         return Err(RenameError("Parameter to rename not found".to_string()));
338     }
339
340     let mut edits = usages
341         .into_iter()
342         .map(|reference| source_edit_from_reference(sema, reference, "self"))
343         .collect::<Vec<_>>();
344
345     edits.push(SourceFileEdit {
346         file_id: position.file_id,
347         edit: TextEdit::replace(param_range, String::from(self_param)),
348     });
349
350     Ok(RangeInfo::new(range, SourceChange::from(edits)))
351 }
352
353 fn text_edit_from_self_param(
354     syn: &SyntaxNode,
355     self_param: &ast::SelfParam,
356     new_name: &str,
357 ) -> Option<TextEdit> {
358     fn target_type_name(impl_def: &ast::Impl) -> Option<String> {
359         if let Some(ast::Type::PathType(p)) = impl_def.self_ty() {
360             return Some(p.path()?.segment()?.name_ref()?.text().to_string());
361         }
362         None
363     }
364
365     let impl_def = find_node_at_offset::<ast::Impl>(syn, self_param.syntax().text_range().start())?;
366     let type_name = target_type_name(&impl_def)?;
367
368     let mut replacement_text = String::from(new_name);
369     replacement_text.push_str(": ");
370     match (self_param.amp_token(), self_param.mut_token()) {
371         (None, None) => (),
372         (Some(_), None) => replacement_text.push('&'),
373         (_, Some(_)) => replacement_text.push_str("&mut "),
374     };
375     replacement_text.push_str(type_name.as_str());
376
377     Some(TextEdit::replace(self_param.syntax().text_range(), replacement_text))
378 }
379
380 fn rename_self_to_param(
381     sema: &Semantics<RootDatabase>,
382     position: FilePosition,
383     self_token: SyntaxToken,
384     new_name: &str,
385 ) -> Result<RangeInfo<SourceChange>, RenameError> {
386     let ident_kind = check_identifier(new_name)?;
387     match ident_kind {
388         IdentifierKind::Lifetime => {
389             return Err(RenameError(format!("Invalid name `{}`: not an identifier", new_name)))
390         }
391         IdentifierKind::ToSelf => {
392             // no-op
393             return Ok(RangeInfo::new(self_token.text_range(), SourceChange::default()));
394         }
395         _ => (),
396     }
397     let source_file = sema.parse(position.file_id);
398     let syn = source_file.syntax();
399
400     let text = sema.db.file_text(position.file_id);
401     let fn_def = find_node_at_offset::<ast::Fn>(syn, position.offset)
402         .ok_or_else(|| RenameError("No surrounding method declaration found".to_string()))?;
403     let search_range = fn_def.syntax().text_range();
404
405     let mut edits: Vec<SourceFileEdit> = vec![];
406
407     for (idx, _) in text.match_indices("self") {
408         let offset: TextSize = idx.try_into().unwrap();
409         if !search_range.contains_inclusive(offset) {
410             continue;
411         }
412         if let Some(ref usage) =
413             syn.token_at_offset(offset).find(|t| t.kind() == SyntaxKind::SELF_KW)
414         {
415             let edit = if let Some(ref self_param) = ast::SelfParam::cast(usage.parent()) {
416                 text_edit_from_self_param(syn, self_param, new_name)
417                     .ok_or_else(|| RenameError("No target type found".to_string()))?
418             } else {
419                 TextEdit::replace(usage.text_range(), String::from(new_name))
420             };
421             edits.push(SourceFileEdit { file_id: position.file_id, edit });
422         }
423     }
424
425     if edits.len() > 1 && ident_kind == IdentifierKind::Underscore {
426         return Err(RenameError(format!(
427             "Cannot rename reference to `_` as it is being referenced multiple times",
428         )));
429     }
430
431     let range = ast::SelfParam::cast(self_token.parent())
432         .map_or(self_token.text_range(), |p| p.syntax().text_range());
433
434     Ok(RangeInfo::new(range, SourceChange::from(edits)))
435 }
436
437 fn rename_reference(
438     sema: &Semantics<RootDatabase>,
439     position: FilePosition,
440     new_name: &str,
441 ) -> Result<RangeInfo<SourceChange>, RenameError> {
442     let ident_kind = check_identifier(new_name)?;
443     let RangeInfo { range, info: refs } = find_all_refs(sema, position)?;
444
445     match (ident_kind, &refs.declaration.kind) {
446         (IdentifierKind::ToSelf, ReferenceKind::Lifetime)
447         | (IdentifierKind::Underscore, ReferenceKind::Lifetime)
448         | (IdentifierKind::Ident, ReferenceKind::Lifetime) => {
449             return Err(RenameError(format!(
450                 "Invalid name `{}`: not a lifetime identifier",
451                 new_name
452             )))
453         }
454         (IdentifierKind::Lifetime, ReferenceKind::Lifetime) => (),
455         (IdentifierKind::Lifetime, _) => {
456             return Err(RenameError(format!("Invalid name `{}`: not an identifier", new_name)))
457         }
458         (IdentifierKind::ToSelf, ReferenceKind::SelfKw) => {
459             //no-op
460             return Ok(RangeInfo::new(range, SourceChange::default()));
461         }
462         (IdentifierKind::ToSelf, _) => {
463             return rename_to_self(sema, position);
464         }
465         (IdentifierKind::Underscore, _) if !refs.references.is_empty() => {
466             return Err(RenameError(format!(
467                 "Cannot rename reference to `_` as it is being referenced multiple times",
468             )))
469         }
470         (IdentifierKind::Ident, _) | (IdentifierKind::Underscore, _) => (),
471     }
472
473     let edit = refs
474         .into_iter()
475         .map(|reference| source_edit_from_reference(sema, reference, new_name))
476         .collect::<Vec<_>>();
477
478     Ok(RangeInfo::new(range, SourceChange::from(edit)))
479 }
480
481 #[cfg(test)]
482 mod tests {
483     use expect_test::{expect, Expect};
484     use stdx::trim_indent;
485     use test_utils::{assert_eq_text, mark};
486     use text_edit::TextEdit;
487
488     use crate::{fixture, FileId};
489
490     fn check(new_name: &str, ra_fixture_before: &str, ra_fixture_after: &str) {
491         let ra_fixture_after = &trim_indent(ra_fixture_after);
492         let (analysis, position) = fixture::position(ra_fixture_before);
493         let rename_result = analysis
494             .rename(position, new_name)
495             .unwrap_or_else(|err| panic!("Rename to '{}' was cancelled: {}", new_name, err));
496         match rename_result {
497             Ok(source_change) => {
498                 let mut text_edit_builder = TextEdit::builder();
499                 let mut file_id: Option<FileId> = None;
500                 for edit in source_change.info.source_file_edits {
501                     file_id = Some(edit.file_id);
502                     for indel in edit.edit.into_iter() {
503                         text_edit_builder.replace(indel.delete, indel.insert);
504                     }
505                 }
506                 let mut result = analysis.file_text(file_id.unwrap()).unwrap().to_string();
507                 text_edit_builder.finish().apply(&mut result);
508                 assert_eq_text!(ra_fixture_after, &*result);
509             }
510             Err(err) => {
511                 if ra_fixture_after.starts_with("error:") {
512                     let error_message = ra_fixture_after
513                         .chars()
514                         .into_iter()
515                         .skip("error:".len())
516                         .collect::<String>();
517                     assert_eq!(error_message.trim(), err.to_string());
518                     return;
519                 } else {
520                     panic!("Rename to '{}' failed unexpectedly: {}", new_name, err)
521                 }
522             }
523         };
524     }
525
526     fn check_expect(new_name: &str, ra_fixture: &str, expect: Expect) {
527         let (analysis, position) = fixture::position(ra_fixture);
528         let source_change = analysis
529             .rename(position, new_name)
530             .unwrap()
531             .expect("Expect returned RangeInfo to be Some, but was None");
532         expect.assert_debug_eq(&source_change)
533     }
534
535     #[test]
536     fn test_rename_to_underscore() {
537         check("_", r#"fn main() { let i$0 = 1; }"#, r#"fn main() { let _ = 1; }"#);
538     }
539
540     #[test]
541     fn test_rename_to_raw_identifier() {
542         check("r#fn", r#"fn main() { let i$0 = 1; }"#, r#"fn main() { let r#fn = 1; }"#);
543     }
544
545     #[test]
546     fn test_rename_to_invalid_identifier1() {
547         check(
548             "invalid!",
549             r#"fn main() { let i$0 = 1; }"#,
550             "error: Invalid name `invalid!`: not an identifier",
551         );
552     }
553
554     #[test]
555     fn test_rename_to_invalid_identifier2() {
556         check(
557             "multiple tokens",
558             r#"fn main() { let i$0 = 1; }"#,
559             "error: Invalid name `multiple tokens`: not an identifier",
560         );
561     }
562
563     #[test]
564     fn test_rename_to_invalid_identifier3() {
565         check(
566             "let",
567             r#"fn main() { let i$0 = 1; }"#,
568             "error: Invalid name `let`: not an identifier",
569         );
570     }
571
572     #[test]
573     fn test_rename_to_invalid_identifier_lifetime() {
574         check(
575             "'foo",
576             r#"fn main() { let i$0 = 1; }"#,
577             "error: Invalid name `'foo`: not an identifier",
578         );
579     }
580
581     #[test]
582     fn test_rename_to_invalid_identifier_lifetime2() {
583         check(
584             "foo",
585             r#"fn main<'a>(_: &'a$0 ()) {}"#,
586             "error: Invalid name `foo`: not a lifetime identifier",
587         );
588     }
589
590     #[test]
591     fn test_rename_to_underscore_invalid() {
592         check(
593             "_",
594             r#"fn main(foo$0: ()) {foo;}"#,
595             "error: Cannot rename reference to `_` as it is being referenced multiple times",
596         );
597     }
598
599     #[test]
600     fn test_rename_for_local() {
601         check(
602             "k",
603             r#"
604 fn main() {
605     let mut i = 1;
606     let j = 1;
607     i = i$0 + j;
608
609     { i = 0; }
610
611     i = 5;
612 }
613 "#,
614             r#"
615 fn main() {
616     let mut k = 1;
617     let j = 1;
618     k = k + j;
619
620     { k = 0; }
621
622     k = 5;
623 }
624 "#,
625         );
626     }
627
628     #[test]
629     fn test_rename_unresolved_reference() {
630         check(
631             "new_name",
632             r#"fn main() { let _ = unresolved_ref$0; }"#,
633             "error: No references found at position",
634         );
635     }
636
637     #[test]
638     fn test_rename_for_macro_args() {
639         check(
640             "b",
641             r#"
642 macro_rules! foo {($i:ident) => {$i} }
643 fn main() {
644     let a$0 = "test";
645     foo!(a);
646 }
647 "#,
648             r#"
649 macro_rules! foo {($i:ident) => {$i} }
650 fn main() {
651     let b = "test";
652     foo!(b);
653 }
654 "#,
655         );
656     }
657
658     #[test]
659     fn test_rename_for_macro_args_rev() {
660         check(
661             "b",
662             r#"
663 macro_rules! foo {($i:ident) => {$i} }
664 fn main() {
665     let a = "test";
666     foo!(a$0);
667 }
668 "#,
669             r#"
670 macro_rules! foo {($i:ident) => {$i} }
671 fn main() {
672     let b = "test";
673     foo!(b);
674 }
675 "#,
676         );
677     }
678
679     #[test]
680     fn test_rename_for_macro_define_fn() {
681         check(
682             "bar",
683             r#"
684 macro_rules! define_fn {($id:ident) => { fn $id{} }}
685 define_fn!(foo);
686 fn main() {
687     fo$0o();
688 }
689 "#,
690             r#"
691 macro_rules! define_fn {($id:ident) => { fn $id{} }}
692 define_fn!(bar);
693 fn main() {
694     bar();
695 }
696 "#,
697         );
698     }
699
700     #[test]
701     fn test_rename_for_macro_define_fn_rev() {
702         check(
703             "bar",
704             r#"
705 macro_rules! define_fn {($id:ident) => { fn $id{} }}
706 define_fn!(fo$0o);
707 fn main() {
708     foo();
709 }
710 "#,
711             r#"
712 macro_rules! define_fn {($id:ident) => { fn $id{} }}
713 define_fn!(bar);
714 fn main() {
715     bar();
716 }
717 "#,
718         );
719     }
720
721     #[test]
722     fn test_rename_for_param_inside() {
723         check("j", r#"fn foo(i : u32) -> u32 { i$0 }"#, r#"fn foo(j : u32) -> u32 { j }"#);
724     }
725
726     #[test]
727     fn test_rename_refs_for_fn_param() {
728         check("j", r#"fn foo(i$0 : u32) -> u32 { i }"#, r#"fn foo(j : u32) -> u32 { j }"#);
729     }
730
731     #[test]
732     fn test_rename_for_mut_param() {
733         check("j", r#"fn foo(mut i$0 : u32) -> u32 { i }"#, r#"fn foo(mut j : u32) -> u32 { j }"#);
734     }
735
736     #[test]
737     fn test_rename_struct_field() {
738         check(
739             "j",
740             r#"
741 struct Foo { i$0: i32 }
742
743 impl Foo {
744     fn new(i: i32) -> Self {
745         Self { i: i }
746     }
747 }
748 "#,
749             r#"
750 struct Foo { j: i32 }
751
752 impl Foo {
753     fn new(i: i32) -> Self {
754         Self { j: i }
755     }
756 }
757 "#,
758         );
759     }
760
761     #[test]
762     fn test_rename_struct_field_for_shorthand() {
763         mark::check!(test_rename_struct_field_for_shorthand);
764         check(
765             "j",
766             r#"
767 struct Foo { i$0: i32 }
768
769 impl Foo {
770     fn new(i: i32) -> Self {
771         Self { i }
772     }
773 }
774 "#,
775             r#"
776 struct Foo { j: i32 }
777
778 impl Foo {
779     fn new(i: i32) -> Self {
780         Self { j: i }
781     }
782 }
783 "#,
784         );
785     }
786
787     #[test]
788     fn test_rename_local_for_field_shorthand() {
789         mark::check!(test_rename_local_for_field_shorthand);
790         check(
791             "j",
792             r#"
793 struct Foo { i: i32 }
794
795 impl Foo {
796     fn new(i$0: i32) -> Self {
797         Self { i }
798     }
799 }
800 "#,
801             r#"
802 struct Foo { i: i32 }
803
804 impl Foo {
805     fn new(j: i32) -> Self {
806         Self { i: j }
807     }
808 }
809 "#,
810         );
811     }
812
813     #[test]
814     fn test_field_shorthand_correct_struct() {
815         check(
816             "j",
817             r#"
818 struct Foo { i$0: i32 }
819 struct Bar { i: i32 }
820
821 impl Bar {
822     fn new(i: i32) -> Self {
823         Self { i }
824     }
825 }
826 "#,
827             r#"
828 struct Foo { j: i32 }
829 struct Bar { i: i32 }
830
831 impl Bar {
832     fn new(i: i32) -> Self {
833         Self { i }
834     }
835 }
836 "#,
837         );
838     }
839
840     #[test]
841     fn test_shadow_local_for_struct_shorthand() {
842         check(
843             "j",
844             r#"
845 struct Foo { i: i32 }
846
847 fn baz(i$0: i32) -> Self {
848      let x = Foo { i };
849      {
850          let i = 0;
851          Foo { i }
852      }
853 }
854 "#,
855             r#"
856 struct Foo { i: i32 }
857
858 fn baz(j: i32) -> Self {
859      let x = Foo { i: j };
860      {
861          let i = 0;
862          Foo { i }
863      }
864 }
865 "#,
866         );
867     }
868
869     #[test]
870     fn test_rename_mod() {
871         check_expect(
872             "foo2",
873             r#"
874 //- /lib.rs
875 mod bar;
876
877 //- /bar.rs
878 mod foo$0;
879
880 //- /bar/foo.rs
881 // empty
882 "#,
883             expect![[r#"
884                 RangeInfo {
885                     range: 4..7,
886                     info: SourceChange {
887                         source_file_edits: [
888                             SourceFileEdit {
889                                 file_id: FileId(
890                                     1,
891                                 ),
892                                 edit: TextEdit {
893                                     indels: [
894                                         Indel {
895                                             insert: "foo2",
896                                             delete: 4..7,
897                                         },
898                                     ],
899                                 },
900                             },
901                         ],
902                         file_system_edits: [
903                             MoveFile {
904                                 src: FileId(
905                                     2,
906                                 ),
907                                 dst: AnchoredPathBuf {
908                                     anchor: FileId(
909                                         2,
910                                     ),
911                                     path: "foo2.rs",
912                                 },
913                             },
914                         ],
915                         is_snippet: false,
916                     },
917                 }
918             "#]],
919         );
920     }
921
922     #[test]
923     fn test_rename_mod_in_use_tree() {
924         check_expect(
925             "quux",
926             r#"
927 //- /main.rs
928 pub mod foo;
929 pub mod bar;
930 fn main() {}
931
932 //- /foo.rs
933 pub struct FooContent;
934
935 //- /bar.rs
936 use crate::foo$0::FooContent;
937 "#,
938             expect![[r#"
939                 RangeInfo {
940                     range: 11..14,
941                     info: SourceChange {
942                         source_file_edits: [
943                             SourceFileEdit {
944                                 file_id: FileId(
945                                     0,
946                                 ),
947                                 edit: TextEdit {
948                                     indels: [
949                                         Indel {
950                                             insert: "quux",
951                                             delete: 8..11,
952                                         },
953                                     ],
954                                 },
955                             },
956                             SourceFileEdit {
957                                 file_id: FileId(
958                                     2,
959                                 ),
960                                 edit: TextEdit {
961                                     indels: [
962                                         Indel {
963                                             insert: "quux",
964                                             delete: 11..14,
965                                         },
966                                     ],
967                                 },
968                             },
969                         ],
970                         file_system_edits: [
971                             MoveFile {
972                                 src: FileId(
973                                     1,
974                                 ),
975                                 dst: AnchoredPathBuf {
976                                     anchor: FileId(
977                                         1,
978                                     ),
979                                     path: "quux.rs",
980                                 },
981                             },
982                         ],
983                         is_snippet: false,
984                     },
985                 }
986             "#]],
987         );
988     }
989
990     #[test]
991     fn test_rename_mod_in_dir() {
992         check_expect(
993             "foo2",
994             r#"
995 //- /lib.rs
996 mod fo$0o;
997 //- /foo/mod.rs
998 // emtpy
999 "#,
1000             expect![[r#"
1001                 RangeInfo {
1002                     range: 4..7,
1003                     info: SourceChange {
1004                         source_file_edits: [
1005                             SourceFileEdit {
1006                                 file_id: FileId(
1007                                     0,
1008                                 ),
1009                                 edit: TextEdit {
1010                                     indels: [
1011                                         Indel {
1012                                             insert: "foo2",
1013                                             delete: 4..7,
1014                                         },
1015                                     ],
1016                                 },
1017                             },
1018                         ],
1019                         file_system_edits: [
1020                             MoveFile {
1021                                 src: FileId(
1022                                     1,
1023                                 ),
1024                                 dst: AnchoredPathBuf {
1025                                     anchor: FileId(
1026                                         1,
1027                                     ),
1028                                     path: "../foo2/mod.rs",
1029                                 },
1030                             },
1031                         ],
1032                         is_snippet: false,
1033                     },
1034                 }
1035             "#]],
1036         );
1037     }
1038
1039     #[test]
1040     fn test_rename_unusually_nested_mod() {
1041         check_expect(
1042             "bar",
1043             r#"
1044 //- /lib.rs
1045 mod outer { mod fo$0o; }
1046
1047 //- /outer/foo.rs
1048 // emtpy
1049 "#,
1050             expect![[r#"
1051                 RangeInfo {
1052                     range: 16..19,
1053                     info: SourceChange {
1054                         source_file_edits: [
1055                             SourceFileEdit {
1056                                 file_id: FileId(
1057                                     0,
1058                                 ),
1059                                 edit: TextEdit {
1060                                     indels: [
1061                                         Indel {
1062                                             insert: "bar",
1063                                             delete: 16..19,
1064                                         },
1065                                     ],
1066                                 },
1067                             },
1068                         ],
1069                         file_system_edits: [
1070                             MoveFile {
1071                                 src: FileId(
1072                                     1,
1073                                 ),
1074                                 dst: AnchoredPathBuf {
1075                                     anchor: FileId(
1076                                         1,
1077                                     ),
1078                                     path: "bar.rs",
1079                                 },
1080                             },
1081                         ],
1082                         is_snippet: false,
1083                     },
1084                 }
1085             "#]],
1086         );
1087     }
1088
1089     #[test]
1090     fn test_module_rename_in_path() {
1091         check(
1092             "baz",
1093             r#"
1094 mod $0foo { pub fn bar() {} }
1095
1096 fn main() { foo::bar(); }
1097 "#,
1098             r#"
1099 mod baz { pub fn bar() {} }
1100
1101 fn main() { baz::bar(); }
1102 "#,
1103         );
1104     }
1105
1106     #[test]
1107     fn test_rename_mod_filename_and_path() {
1108         check_expect(
1109             "foo2",
1110             r#"
1111 //- /lib.rs
1112 mod bar;
1113 fn f() {
1114     bar::foo::fun()
1115 }
1116
1117 //- /bar.rs
1118 pub mod foo$0;
1119
1120 //- /bar/foo.rs
1121 // pub fn fun() {}
1122 "#,
1123             expect![[r#"
1124                 RangeInfo {
1125                     range: 8..11,
1126                     info: SourceChange {
1127                         source_file_edits: [
1128                             SourceFileEdit {
1129                                 file_id: FileId(
1130                                     1,
1131                                 ),
1132                                 edit: TextEdit {
1133                                     indels: [
1134                                         Indel {
1135                                             insert: "foo2",
1136                                             delete: 8..11,
1137                                         },
1138                                     ],
1139                                 },
1140                             },
1141                             SourceFileEdit {
1142                                 file_id: FileId(
1143                                     0,
1144                                 ),
1145                                 edit: TextEdit {
1146                                     indels: [
1147                                         Indel {
1148                                             insert: "foo2",
1149                                             delete: 27..30,
1150                                         },
1151                                     ],
1152                                 },
1153                             },
1154                         ],
1155                         file_system_edits: [
1156                             MoveFile {
1157                                 src: FileId(
1158                                     2,
1159                                 ),
1160                                 dst: AnchoredPathBuf {
1161                                     anchor: FileId(
1162                                         2,
1163                                     ),
1164                                     path: "foo2.rs",
1165                                 },
1166                             },
1167                         ],
1168                         is_snippet: false,
1169                     },
1170                 }
1171             "#]],
1172         );
1173     }
1174
1175     #[test]
1176     fn test_enum_variant_from_module_1() {
1177         check(
1178             "Baz",
1179             r#"
1180 mod foo {
1181     pub enum Foo { Bar$0 }
1182 }
1183
1184 fn func(f: foo::Foo) {
1185     match f {
1186         foo::Foo::Bar => {}
1187     }
1188 }
1189 "#,
1190             r#"
1191 mod foo {
1192     pub enum Foo { Baz }
1193 }
1194
1195 fn func(f: foo::Foo) {
1196     match f {
1197         foo::Foo::Baz => {}
1198     }
1199 }
1200 "#,
1201         );
1202     }
1203
1204     #[test]
1205     fn test_enum_variant_from_module_2() {
1206         check(
1207             "baz",
1208             r#"
1209 mod foo {
1210     pub struct Foo { pub bar$0: uint }
1211 }
1212
1213 fn foo(f: foo::Foo) {
1214     let _ = f.bar;
1215 }
1216 "#,
1217             r#"
1218 mod foo {
1219     pub struct Foo { pub baz: uint }
1220 }
1221
1222 fn foo(f: foo::Foo) {
1223     let _ = f.baz;
1224 }
1225 "#,
1226         );
1227     }
1228
1229     #[test]
1230     fn test_parameter_to_self() {
1231         check(
1232             "self",
1233             r#"
1234 struct Foo { i: i32 }
1235
1236 impl Foo {
1237     fn f(foo$0: &mut Foo) -> i32 {
1238         foo.i
1239     }
1240 }
1241 "#,
1242             r#"
1243 struct Foo { i: i32 }
1244
1245 impl Foo {
1246     fn f(&mut self) -> i32 {
1247         self.i
1248     }
1249 }
1250 "#,
1251         );
1252         check(
1253             "self",
1254             r#"
1255 struct Foo { i: i32 }
1256
1257 impl Foo {
1258     fn f(foo$0: Foo) -> i32 {
1259         foo.i
1260     }
1261 }
1262 "#,
1263             r#"
1264 struct Foo { i: i32 }
1265
1266 impl Foo {
1267     fn f(self) -> i32 {
1268         self.i
1269     }
1270 }
1271 "#,
1272         );
1273     }
1274
1275     #[test]
1276     fn test_parameter_to_self_error_no_impl() {
1277         check(
1278             "self",
1279             r#"
1280 struct Foo { i: i32 }
1281
1282 fn f(foo$0: &mut Foo) -> i32 {
1283     foo.i
1284 }
1285 "#,
1286             "error: No impl block found for function",
1287         );
1288         check(
1289             "self",
1290             r#"
1291 struct Foo { i: i32 }
1292 struct Bar;
1293
1294 impl Bar {
1295     fn f(foo$0: &mut Foo) -> i32 {
1296         foo.i
1297     }
1298 }
1299 "#,
1300             "error: Parameter type differs from impl block type",
1301         );
1302     }
1303
1304     #[test]
1305     fn test_parameter_to_self_error_not_first() {
1306         check(
1307             "self",
1308             r#"
1309 struct Foo { i: i32 }
1310 impl Foo {
1311     fn f(x: (), foo$0: &mut Foo) -> i32 {
1312         foo.i
1313     }
1314 }
1315 "#,
1316             "error: Only the first parameter can be self",
1317         );
1318     }
1319
1320     #[test]
1321     fn test_parameter_to_self_impl_ref() {
1322         check(
1323             "self",
1324             r#"
1325 struct Foo { i: i32 }
1326 impl &Foo {
1327     fn f(foo$0: &Foo) -> i32 {
1328         foo.i
1329     }
1330 }
1331 "#,
1332             r#"
1333 struct Foo { i: i32 }
1334 impl &Foo {
1335     fn f(self) -> i32 {
1336         self.i
1337     }
1338 }
1339 "#,
1340         );
1341     }
1342
1343     #[test]
1344     fn test_self_to_parameter() {
1345         check(
1346             "foo",
1347             r#"
1348 struct Foo { i: i32 }
1349
1350 impl Foo {
1351     fn f(&mut $0self) -> i32 {
1352         self.i
1353     }
1354 }
1355 "#,
1356             r#"
1357 struct Foo { i: i32 }
1358
1359 impl Foo {
1360     fn f(foo: &mut Foo) -> i32 {
1361         foo.i
1362     }
1363 }
1364 "#,
1365         );
1366     }
1367
1368     #[test]
1369     fn test_owned_self_to_parameter() {
1370         check(
1371             "foo",
1372             r#"
1373 struct Foo { i: i32 }
1374
1375 impl Foo {
1376     fn f($0self) -> i32 {
1377         self.i
1378     }
1379 }
1380 "#,
1381             r#"
1382 struct Foo { i: i32 }
1383
1384 impl Foo {
1385     fn f(foo: Foo) -> i32 {
1386         foo.i
1387     }
1388 }
1389 "#,
1390         );
1391     }
1392
1393     #[test]
1394     fn test_self_in_path_to_parameter() {
1395         check(
1396             "foo",
1397             r#"
1398 struct Foo { i: i32 }
1399
1400 impl Foo {
1401     fn f(&self) -> i32 {
1402         let self_var = 1;
1403         self$0.i
1404     }
1405 }
1406 "#,
1407             r#"
1408 struct Foo { i: i32 }
1409
1410 impl Foo {
1411     fn f(foo: &Foo) -> i32 {
1412         let self_var = 1;
1413         foo.i
1414     }
1415 }
1416 "#,
1417         );
1418     }
1419
1420     #[test]
1421     fn test_initializer_use_field_init_shorthand() {
1422         mark::check!(test_rename_field_expr_pat);
1423         check(
1424             "bar",
1425             r#"
1426 struct Foo { i$0: i32 }
1427
1428 fn foo(bar: i32) -> Foo {
1429     Foo { i: bar }
1430 }
1431 "#,
1432             r#"
1433 struct Foo { bar: i32 }
1434
1435 fn foo(bar: i32) -> Foo {
1436     Foo { bar }
1437 }
1438 "#,
1439         );
1440     }
1441
1442     #[test]
1443     fn test_struct_field_destructure_into_shorthand() {
1444         check(
1445             "baz",
1446             r#"
1447 struct Foo { i$0: i32 }
1448
1449 fn foo(foo: Foo) {
1450     let Foo { i: baz } = foo;
1451     let _ = baz;
1452 }
1453 "#,
1454             r#"
1455 struct Foo { baz: i32 }
1456
1457 fn foo(foo: Foo) {
1458     let Foo { baz } = foo;
1459     let _ = baz;
1460 }
1461 "#,
1462         );
1463     }
1464
1465     #[test]
1466     fn test_rename_binding_in_destructure_pat() {
1467         let expected_fixture = r#"
1468 struct Foo {
1469     i: i32,
1470 }
1471
1472 fn foo(foo: Foo) {
1473     let Foo { i: bar } = foo;
1474     let _ = bar;
1475 }
1476 "#;
1477         check(
1478             "bar",
1479             r#"
1480 struct Foo {
1481     i: i32,
1482 }
1483
1484 fn foo(foo: Foo) {
1485     let Foo { i: b } = foo;
1486     let _ = b$0;
1487 }
1488 "#,
1489             expected_fixture,
1490         );
1491         check(
1492             "bar",
1493             r#"
1494 struct Foo {
1495     i: i32,
1496 }
1497
1498 fn foo(foo: Foo) {
1499     let Foo { i } = foo;
1500     let _ = i$0;
1501 }
1502 "#,
1503             expected_fixture,
1504         );
1505     }
1506
1507     #[test]
1508     fn test_rename_binding_in_destructure_param_pat() {
1509         check(
1510             "bar",
1511             r#"
1512 struct Foo {
1513     i: i32
1514 }
1515
1516 fn foo(Foo { i }: foo) -> i32 {
1517     i$0
1518 }
1519 "#,
1520             r#"
1521 struct Foo {
1522     i: i32
1523 }
1524
1525 fn foo(Foo { i: bar }: foo) -> i32 {
1526     bar
1527 }
1528 "#,
1529         )
1530     }
1531
1532     #[test]
1533     fn test_rename_lifetimes() {
1534         check(
1535             "'yeeee",
1536             r#"
1537 trait Foo<'a> {
1538     fn foo() -> &'a ();
1539 }
1540 impl<'a> Foo<'a> for &'a () {
1541     fn foo() -> &'a$0 () {
1542         unimplemented!()
1543     }
1544 }
1545 "#,
1546             r#"
1547 trait Foo<'a> {
1548     fn foo() -> &'a ();
1549 }
1550 impl<'yeeee> Foo<'yeeee> for &'yeeee () {
1551     fn foo() -> &'yeeee () {
1552         unimplemented!()
1553     }
1554 }
1555 "#,
1556         )
1557     }
1558
1559     #[test]
1560     fn test_rename_bind_pat() {
1561         check(
1562             "new_name",
1563             r#"
1564 fn main() {
1565     enum CustomOption<T> {
1566         None,
1567         Some(T),
1568     }
1569
1570     let test_variable = CustomOption::Some(22);
1571
1572     match test_variable {
1573         CustomOption::Some(foo$0) if foo == 11 => {}
1574         _ => (),
1575     }
1576 }"#,
1577             r#"
1578 fn main() {
1579     enum CustomOption<T> {
1580         None,
1581         Some(T),
1582     }
1583
1584     let test_variable = CustomOption::Some(22);
1585
1586     match test_variable {
1587         CustomOption::Some(new_name) if new_name == 11 => {}
1588         _ => (),
1589     }
1590 }"#,
1591         );
1592     }
1593
1594     #[test]
1595     fn test_rename_label() {
1596         check(
1597             "'foo",
1598             r#"
1599 fn foo<'a>() -> &'a () {
1600     'a: {
1601         'b: loop {
1602             break 'a$0;
1603         }
1604     }
1605 }
1606 "#,
1607             r#"
1608 fn foo<'a>() -> &'a () {
1609     'foo: {
1610         'b: loop {
1611             break 'foo;
1612         }
1613     }
1614 }
1615 "#,
1616         )
1617     }
1618 }