1 //! Renaming functionality.
3 //! This is mostly front-end for [`ide_db::rename`], but it also includes the
4 //! tests. This module also implements a couple of magic tricks, like renaming
5 //! `self` and to `self` (to switch between associated function and method).
6 use hir::{AsAssocItem, InFile, Semantics};
9 defs::{Definition, NameClass, NameRefClass},
10 rename::{bail, format_err, source_edit_from_references, IdentifierKind},
14 use syntax::{ast, AstNode, SyntaxNode};
16 use text_edit::TextEdit;
18 use crate::{FilePosition, RangeInfo, SourceChange};
20 pub use ide_db::rename::RenameError;
22 type RenameResult<T> = Result<T, RenameError>;
24 /// Prepares a rename. The sole job of this function is to return the TextRange of the thing that is
25 /// being targeted for a rename.
26 pub(crate) fn prepare_rename(
28 position: FilePosition,
29 ) -> RenameResult<RangeInfo<()>> {
30 let sema = Semantics::new(db);
31 let source_file = sema.parse(position.file_id);
32 let syntax = source_file.syntax();
34 let def = find_definition(&sema, syntax, position)?;
36 .range_for_rename(&sema)
37 .ok_or_else(|| format_err!("No references found at position"))?;
38 Ok(RangeInfo::new(frange.range, ()))
43 // Renames the item below the cursor and all of its references
46 // | Editor | Shortcut
48 // | VS Code | kbd:[F2]
51 // image::https://user-images.githubusercontent.com/48062697/113065582-055aae80-91b1-11eb-8ade-2b58e6d81883.gif[]
54 position: FilePosition,
56 ) -> RenameResult<SourceChange> {
57 let sema = Semantics::new(db);
58 rename_with_semantics(&sema, position, new_name)
61 pub(crate) fn rename_with_semantics(
62 sema: &Semantics<RootDatabase>,
63 position: FilePosition,
65 ) -> RenameResult<SourceChange> {
66 let source_file = sema.parse(position.file_id);
67 let syntax = source_file.syntax();
69 let def = find_definition(sema, syntax, position)?;
71 if let Definition::Local(local) = def {
72 if let Some(self_param) = local.as_self_param(sema.db) {
73 cov_mark::hit!(rename_self_to_param);
74 return rename_self_to_param(sema, local, self_param, new_name);
76 if new_name == "self" {
77 cov_mark::hit!(rename_to_self);
78 return rename_to_self(sema, local);
82 def.rename(sema, new_name)
85 /// Called by the client when it is about to rename a file.
86 pub(crate) fn will_rename_file(
90 ) -> Option<SourceChange> {
91 let sema = Semantics::new(db);
92 let module = sema.to_module_def(file_id)?;
93 let def = Definition::ModuleDef(module.into());
94 let mut change = def.rename(&sema, new_name_stem).ok()?;
95 change.file_system_edits.clear();
100 sema: &Semantics<RootDatabase>,
102 position: FilePosition,
103 ) -> RenameResult<Definition> {
105 .find_node_at_offset_with_descend(syntax, position.offset)
106 .ok_or_else(|| format_err!("No references found at position"))?
108 // renaming aliases would rename the item being aliased as the HIR doesn't track aliases yet
109 ast::NameLike::Name(name)
110 if name.syntax().parent().map_or(false, |it| ast::Rename::can_cast(it.kind())) =>
112 bail!("Renaming aliases is currently unsupported")
114 ast::NameLike::Name(name) => {
115 NameClass::classify(sema, &name).map(|class| class.referenced_or_defined(sema.db))
117 ast::NameLike::NameRef(name_ref) => {
119 NameRefClass::classify(sema, &name_ref).map(|class| class.referenced(sema.db))
121 // if the name differs from the definitions name it has to be an alias
122 if def.name(sema.db).map_or(false, |it| it.to_string() != name_ref.text()) {
123 bail!("Renaming aliases is currently unsupported");
130 ast::NameLike::Lifetime(lifetime) => NameRefClass::classify_lifetime(sema, &lifetime)
131 .map(|class| NameRefClass::referenced(class, sema.db))
133 NameClass::classify_lifetime(sema, &lifetime)
134 .map(|it| it.referenced_or_defined(sema.db))
137 .ok_or_else(|| format_err!("No references found at position"))
140 fn rename_to_self(sema: &Semantics<RootDatabase>, local: hir::Local) -> RenameResult<SourceChange> {
141 if never!(local.is_self(sema.db)) {
142 bail!("rename_to_self invoked on self");
145 let fn_def = match local.parent(sema.db) {
146 hir::DefWithBody::Function(func) => func,
147 _ => bail!("Cannot rename local to self outside of function"),
150 if let Some(_) = fn_def.self_param(sema.db) {
151 bail!("Method already has a self parameter");
154 let params = fn_def.assoc_fn_params(sema.db);
155 let first_param = params
157 .ok_or_else(|| format_err!("Cannot rename local to self unless it is a parameter"))?;
158 if first_param.as_local(sema.db) != local {
159 bail!("Only the first parameter may be renamed to self");
162 let assoc_item = fn_def
163 .as_assoc_item(sema.db)
164 .ok_or_else(|| format_err!("Cannot rename parameter to self for free function"))?;
165 let impl_ = match assoc_item.container(sema.db) {
166 hir::AssocItemContainer::Trait(_) => {
167 bail!("Cannot rename parameter to self for trait functions");
169 hir::AssocItemContainer::Impl(impl_) => impl_,
171 let first_param_ty = first_param.ty();
172 let impl_ty = impl_.self_ty(sema.db);
173 let (ty, self_param) = if impl_ty.remove_ref().is_some() {
174 // if the impl is a ref to the type we can just match the `&T` with self directly
175 (first_param_ty.clone(), "self")
177 first_param_ty.remove_ref().map_or((first_param_ty.clone(), "self"), |ty| {
178 (ty, if first_param_ty.is_mutable_reference() { "&mut self" } else { "&self" })
183 bail!("Parameter type differs from impl block type");
186 let InFile { file_id, value: param_source } =
187 first_param.source(sema.db).ok_or_else(|| format_err!("No source for parameter found"))?;
189 let def = Definition::Local(local);
190 let usages = def.usages(sema).all();
191 let mut source_change = SourceChange::default();
192 source_change.extend(usages.iter().map(|(&file_id, references)| {
193 (file_id, source_edit_from_references(references, def, "self"))
195 source_change.insert_source_edit(
196 file_id.original_file(sema.db),
197 TextEdit::replace(param_source.syntax().text_range(), String::from(self_param)),
202 fn rename_self_to_param(
203 sema: &Semantics<RootDatabase>,
205 self_param: hir::SelfParam,
207 ) -> RenameResult<SourceChange> {
208 if new_name == "self" {
209 // Let's do nothing rather than complain.
210 cov_mark::hit!(rename_self_to_self);
211 return Ok(SourceChange::default());
214 let identifier_kind = IdentifierKind::classify(new_name)?;
216 let InFile { file_id, value: self_param } =
217 self_param.source(sema.db).ok_or_else(|| format_err!("cannot find function source"))?;
219 let def = Definition::Local(local);
220 let usages = def.usages(sema).all();
221 let edit = text_edit_from_self_param(&self_param, new_name)
222 .ok_or_else(|| format_err!("No target type found"))?;
223 if usages.len() > 1 && identifier_kind == IdentifierKind::Underscore {
224 bail!("Cannot rename reference to `_` as it is being referenced multiple times");
226 let mut source_change = SourceChange::default();
227 source_change.insert_source_edit(file_id.original_file(sema.db), edit);
228 source_change.extend(usages.iter().map(|(&file_id, references)| {
229 (file_id, source_edit_from_references(references, def, new_name))
234 fn text_edit_from_self_param(self_param: &ast::SelfParam, new_name: &str) -> Option<TextEdit> {
235 fn target_type_name(impl_def: &ast::Impl) -> Option<String> {
236 if let Some(ast::Type::PathType(p)) = impl_def.self_ty() {
237 return Some(p.path()?.segment()?.name_ref()?.text().to_string());
242 let impl_def = self_param.syntax().ancestors().find_map(ast::Impl::cast)?;
243 let type_name = target_type_name(&impl_def)?;
245 let mut replacement_text = String::from(new_name);
246 replacement_text.push_str(": ");
247 match (self_param.amp_token(), self_param.mut_token()) {
248 (Some(_), None) => replacement_text.push('&'),
249 (Some(_), Some(_)) => replacement_text.push_str("&mut "),
252 replacement_text.push_str(type_name.as_str());
254 Some(TextEdit::replace(self_param.syntax().text_range(), replacement_text))
259 use expect_test::{expect, Expect};
260 use stdx::trim_indent;
261 use test_utils::assert_eq_text;
262 use text_edit::TextEdit;
264 use crate::{fixture, FileId};
266 use super::{RangeInfo, RenameError};
268 fn check(new_name: &str, ra_fixture_before: &str, ra_fixture_after: &str) {
269 let ra_fixture_after = &trim_indent(ra_fixture_after);
270 let (analysis, position) = fixture::position(ra_fixture_before);
271 let rename_result = analysis
272 .rename(position, new_name)
273 .unwrap_or_else(|err| panic!("Rename to '{}' was cancelled: {}", new_name, err));
274 match rename_result {
275 Ok(source_change) => {
276 let mut text_edit_builder = TextEdit::builder();
277 let mut file_id: Option<FileId> = None;
278 for edit in source_change.source_file_edits {
279 file_id = Some(edit.0);
280 for indel in edit.1.into_iter() {
281 text_edit_builder.replace(indel.delete, indel.insert);
284 if let Some(file_id) = file_id {
285 let mut result = analysis.file_text(file_id).unwrap().to_string();
286 text_edit_builder.finish().apply(&mut result);
287 assert_eq_text!(ra_fixture_after, &*result);
291 if ra_fixture_after.starts_with("error:") {
292 let error_message = ra_fixture_after
295 .skip("error:".len())
296 .collect::<String>();
297 assert_eq!(error_message.trim(), err.to_string());
300 panic!("Rename to '{}' failed unexpectedly: {}", new_name, err)
306 fn check_expect(new_name: &str, ra_fixture: &str, expect: Expect) {
307 let (analysis, position) = fixture::position(ra_fixture);
309 analysis.rename(position, new_name).unwrap().expect("Expect returned a RenameError");
310 expect.assert_debug_eq(&source_change)
313 fn check_prepare(ra_fixture: &str, expect: Expect) {
314 let (analysis, position) = fixture::position(ra_fixture);
315 let result = analysis
316 .prepare_rename(position)
317 .unwrap_or_else(|err| panic!("PrepareRename was cancelled: {}", err));
319 Ok(RangeInfo { range, info: () }) => {
320 let source = analysis.file_text(position.file_id).unwrap();
321 expect.assert_eq(&format!("{:?}: {}", range, &source[range]))
323 Err(RenameError(err)) => expect.assert_eq(&err),
328 fn test_prepare_rename_namelikes() {
329 check_prepare(r"fn name$0<'lifetime>() {}", expect![[r#"3..7: name"#]]);
330 check_prepare(r"fn name<'lifetime$0>() {}", expect![[r#"8..17: 'lifetime"#]]);
331 check_prepare(r"fn name<'lifetime>() { name$0(); }", expect![[r#"3..7: name"#]]);
335 fn test_prepare_rename_in_macro() {
343 expect![[r#"83..86: Foo"#]],
348 fn test_prepare_rename_keyword() {
349 check_prepare(r"struct$0 Foo;", expect![[r#"No references found at position"#]]);
353 fn test_prepare_rename_tuple_field() {
363 expect![[r#"No references found at position"#]],
368 fn test_prepare_rename_builtin() {
375 expect![[r#"No references found at position"#]],
380 fn test_prepare_rename_self() {
386 fn foo(self) -> Self$0 {
391 expect![[r#"No references found at position"#]],
396 fn test_rename_to_underscore() {
397 check("_", r#"fn main() { let i$0 = 1; }"#, r#"fn main() { let _ = 1; }"#);
401 fn test_rename_to_raw_identifier() {
402 check("r#fn", r#"fn main() { let i$0 = 1; }"#, r#"fn main() { let r#fn = 1; }"#);
406 fn test_rename_to_invalid_identifier1() {
409 r#"fn main() { let i$0 = 1; }"#,
410 "error: Invalid name `invalid!`: not an identifier",
415 fn test_rename_to_invalid_identifier2() {
418 r#"fn main() { let i$0 = 1; }"#,
419 "error: Invalid name `multiple tokens`: not an identifier",
424 fn test_rename_to_invalid_identifier3() {
427 r#"fn main() { let i$0 = 1; }"#,
428 "error: Invalid name `let`: not an identifier",
433 fn test_rename_to_invalid_identifier_lifetime() {
434 cov_mark::check!(rename_not_an_ident_ref);
437 r#"fn main() { let i$0 = 1; }"#,
438 "error: Invalid name `'foo`: not an identifier",
443 fn test_rename_to_invalid_identifier_lifetime2() {
444 cov_mark::check!(rename_not_a_lifetime_ident_ref);
447 r#"fn main<'a>(_: &'a$0 ()) {}"#,
448 "error: Invalid name `foo`: not a lifetime identifier",
453 fn test_rename_to_underscore_invalid() {
454 cov_mark::check!(rename_underscore_multiple);
457 r#"fn main(foo$0: ()) {foo;}"#,
458 "error: Cannot rename reference to `_` as it is being referenced multiple times",
463 fn test_rename_mod_invalid() {
467 "error: Invalid name `'foo`: cannot rename module to 'foo",
472 fn test_rename_for_local() {
501 fn test_rename_unresolved_reference() {
504 r#"fn main() { let _ = unresolved_ref$0; }"#,
505 "error: No references found at position",
510 fn test_rename_for_macro_args() {
514 macro_rules! foo {($i:ident) => {$i} }
521 macro_rules! foo {($i:ident) => {$i} }
531 fn test_rename_for_macro_args_rev() {
535 macro_rules! foo {($i:ident) => {$i} }
542 macro_rules! foo {($i:ident) => {$i} }
552 fn test_rename_for_macro_define_fn() {
556 macro_rules! define_fn {($id:ident) => { fn $id{} }}
563 macro_rules! define_fn {($id:ident) => { fn $id{} }}
573 fn test_rename_for_macro_define_fn_rev() {
577 macro_rules! define_fn {($id:ident) => { fn $id{} }}
584 macro_rules! define_fn {($id:ident) => { fn $id{} }}
594 fn test_rename_for_param_inside() {
595 check("j", r#"fn foo(i : u32) -> u32 { i$0 }"#, r#"fn foo(j : u32) -> u32 { j }"#);
599 fn test_rename_refs_for_fn_param() {
600 check("j", r#"fn foo(i$0 : u32) -> u32 { i }"#, r#"fn foo(j : u32) -> u32 { j }"#);
604 fn test_rename_for_mut_param() {
605 check("j", r#"fn foo(mut i$0 : u32) -> u32 { i }"#, r#"fn foo(mut j : u32) -> u32 { j }"#);
609 fn test_rename_struct_field() {
613 struct Foo { i$0: i32 }
616 fn new(i: i32) -> Self {
622 struct Foo { j: i32 }
625 fn new(i: i32) -> Self {
634 fn test_rename_field_in_field_shorthand() {
635 cov_mark::check!(test_rename_field_in_field_shorthand);
639 struct Foo { i$0: i32 }
642 fn new(i: i32) -> Self {
648 struct Foo { j: i32 }
651 fn new(i: i32) -> Self {
660 fn test_rename_local_in_field_shorthand() {
661 cov_mark::check!(test_rename_local_in_field_shorthand);
665 struct Foo { i: i32 }
668 fn new(i$0: i32) -> Self {
674 struct Foo { i: i32 }
677 fn new(j: i32) -> Self {
686 fn test_field_shorthand_correct_struct() {
690 struct Foo { i$0: i32 }
691 struct Bar { i: i32 }
694 fn new(i: i32) -> Self {
700 struct Foo { j: i32 }
701 struct Bar { i: i32 }
704 fn new(i: i32) -> Self {
713 fn test_shadow_local_for_struct_shorthand() {
717 struct Foo { i: i32 }
719 fn baz(i$0: i32) -> Self {
728 struct Foo { i: i32 }
730 fn baz(j: i32) -> Self {
731 let x = Foo { i: j };
742 fn test_rename_mod() {
774 dst: AnchoredPathBuf {
789 fn test_rename_mod_in_use_tree() {
799 pub struct FooContent;
802 use crate::foo$0::FooContent;
833 dst: AnchoredPathBuf {
848 fn test_rename_mod_in_dir() {
876 dst: AnchoredPathBuf {
880 path: "../foo2/mod.rs",
891 fn test_rename_unusually_nested_mod() {
896 mod outer { mod fo$0o; }
920 dst: AnchoredPathBuf {
935 fn test_module_rename_in_path() {
939 mod $0foo { pub fn bar() {} }
941 fn main() { foo::bar(); }
944 mod baz { pub fn bar() {} }
946 fn main() { baz::bar(); }
952 fn test_rename_mod_filename_and_path() {
997 dst: AnchoredPathBuf {
1012 fn test_enum_variant_from_module_1() {
1013 cov_mark::check!(rename_non_local);
1018 pub enum Foo { Bar$0 }
1021 fn func(f: foo::Foo) {
1029 pub enum Foo { Baz }
1032 fn func(f: foo::Foo) {
1042 fn test_enum_variant_from_module_2() {
1047 pub struct Foo { pub bar$0: uint }
1050 fn foo(f: foo::Foo) {
1056 pub struct Foo { pub baz: uint }
1059 fn foo(f: foo::Foo) {
1067 fn test_parameter_to_self() {
1068 cov_mark::check!(rename_to_self);
1072 struct Foo { i: i32 }
1075 fn f(foo$0: &mut Foo) -> i32 {
1081 struct Foo { i: i32 }
1084 fn f(&mut self) -> i32 {
1093 struct Foo { i: i32 }
1096 fn f(foo$0: Foo) -> i32 {
1102 struct Foo { i: i32 }
1114 fn test_parameter_to_self_error_no_impl() {
1118 struct Foo { i: i32 }
1120 fn f(foo$0: &mut Foo) -> i32 {
1124 "error: Cannot rename parameter to self for free function",
1129 struct Foo { i: i32 }
1133 fn f(foo$0: &mut Foo) -> i32 {
1138 "error: Parameter type differs from impl block type",
1143 fn test_parameter_to_self_error_not_first() {
1147 struct Foo { i: i32 }
1149 fn f(x: (), foo$0: &mut Foo) -> i32 {
1154 "error: Only the first parameter may be renamed to self",
1159 fn test_parameter_to_self_impl_ref() {
1163 struct Foo { i: i32 }
1165 fn f(foo$0: &Foo) -> i32 {
1171 struct Foo { i: i32 }
1182 fn test_self_to_parameter() {
1186 struct Foo { i: i32 }
1189 fn f(&mut $0self) -> i32 {
1195 struct Foo { i: i32 }
1198 fn f(foo: &mut Foo) -> i32 {
1207 fn test_owned_self_to_parameter() {
1208 cov_mark::check!(rename_self_to_param);
1212 struct Foo { i: i32 }
1215 fn f($0self) -> i32 {
1221 struct Foo { i: i32 }
1224 fn f(foo: Foo) -> i32 {
1233 fn test_self_in_path_to_parameter() {
1237 struct Foo { i: i32 }
1240 fn f(&self) -> i32 {
1247 struct Foo { i: i32 }
1250 fn f(foo: &Foo) -> i32 {
1260 fn test_rename_field_put_init_shorthand() {
1261 cov_mark::check!(test_rename_field_put_init_shorthand);
1265 struct Foo { i$0: i32 }
1267 fn foo(bar: i32) -> Foo {
1272 struct Foo { bar: i32 }
1274 fn foo(bar: i32) -> Foo {
1282 fn test_rename_local_put_init_shorthand() {
1283 cov_mark::check!(test_rename_local_put_init_shorthand);
1287 struct Foo { i: i32 }
1289 fn foo(bar$0: i32) -> Foo {
1294 struct Foo { i: i32 }
1296 fn foo(i: i32) -> Foo {
1304 fn test_struct_field_pat_into_shorthand() {
1305 cov_mark::check!(test_rename_field_put_init_shorthand_pat);
1309 struct Foo { i$0: i32 }
1312 let Foo { i: ref baz @ qux } = foo;
1317 struct Foo { baz: i32 }
1320 let Foo { ref baz @ qux } = foo;
1328 fn test_rename_binding_in_destructure_pat() {
1329 let expected_fixture = r#"
1335 let Foo { i: bar } = foo;
1347 let Foo { i: b } = foo;
1361 let Foo { i } = foo;
1370 fn test_rename_binding_in_destructure_param_pat() {
1378 fn foo(Foo { i }: foo) -> i32 {
1387 fn foo(Foo { i: bar }: foo) -> i32 {
1395 fn test_struct_field_complex_ident_pat() {
1399 struct Foo { i$0: i32 }
1402 let Foo { ref i } = foo;
1406 struct Foo { baz: i32 }
1409 let Foo { baz: ref i } = foo;
1416 fn test_rename_lifetimes() {
1417 cov_mark::check!(rename_lifetime);
1424 impl<'a> Foo<'a> for &'a () {
1425 fn foo() -> &'a$0 () {
1434 impl<'yeeee> Foo<'yeeee> for &'yeeee () {
1435 fn foo() -> &'yeeee () {
1444 fn test_rename_bind_pat() {
1449 enum CustomOption<T> {
1454 let test_variable = CustomOption::Some(22);
1456 match test_variable {
1457 CustomOption::Some(foo$0) if foo == 11 => {}
1463 enum CustomOption<T> {
1468 let test_variable = CustomOption::Some(22);
1470 match test_variable {
1471 CustomOption::Some(new_name) if new_name == 11 => {}
1479 fn test_rename_label() {
1483 fn foo<'a>() -> &'a () {
1492 fn foo<'a>() -> &'a () {
1504 fn test_self_to_self() {
1505 cov_mark::check!(rename_self_to_self);
1524 fn test_rename_field_in_pat_in_macro_doesnt_shorthand() {
1525 // ideally we would be able to make this emit a short hand, but I doubt this is easily possible
1531 let $pattern = loop {};
1538 foo!(Foo { bar: baz });
1544 let $pattern = loop {};
1551 foo!(Foo { baz: baz });
1558 fn test_rename_tuple_field() {
1569 "error: No identifier available to rename",
1574 fn test_rename_builtin() {
1582 "error: Cannot rename builtin type",
1587 fn test_rename_self() {
1594 fn foo(self) -> Self$0 {
1599 "error: Cannot rename `Self`",
1604 fn test_rename_ignores_self_ty() {
1610 impl Foo where Self: {}
1615 impl Fo0 where Self: {}
1621 fn test_rename_fails_on_aliases() {
1628 "error: Renaming aliases is currently unsupported",
1637 "error: Renaming aliases is currently unsupported",
1642 fn test_rename_trait_method() {
1722 fn test_rename_trait_const() {
1731 fn f() { <()>::FOO; }";
1742 fn f() { <()>::BAR; }"#,
1755 fn f() { <()>::BAR; }"#,
1768 fn f() { <()>::BAR$0; }"#,
1774 fn macros_are_broken_lol() {
1775 cov_mark::check!(macros_are_broken_lol);
1779 macro_rules! m { () => { fn f() {} } }
1784 macro_rules! m { () => { fn f() {} } }