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