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},
13 use stdx::{always, never};
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 (name_like, def) = find_definition(&sema, syntax, position)?;
35 if def.range_for_rename(&sema).is_none() {
36 bail!("No references found at position")
39 let frange = sema.original_range(name_like.syntax());
40 always!(frange.range.contains_inclusive(position.offset) && frange.file_id == position.file_id);
41 Ok(RangeInfo::new(frange.range, ()))
46 // Renames the item below the cursor and all of its references
49 // | Editor | Shortcut
51 // | VS Code | kbd:[F2]
54 // image::https://user-images.githubusercontent.com/48062697/113065582-055aae80-91b1-11eb-8ade-2b58e6d81883.gif[]
57 position: FilePosition,
59 ) -> RenameResult<SourceChange> {
60 let sema = Semantics::new(db);
61 let source_file = sema.parse(position.file_id);
62 let syntax = source_file.syntax();
64 let (_name_like, def) = find_definition(&sema, syntax, position)?;
66 if let Definition::Local(local) = def {
67 if let Some(self_param) = local.as_self_param(sema.db) {
68 cov_mark::hit!(rename_self_to_param);
69 return rename_self_to_param(&sema, local, self_param, new_name);
71 if new_name == "self" {
72 cov_mark::hit!(rename_to_self);
73 return rename_to_self(&sema, local);
77 def.rename(&sema, new_name)
80 /// Called by the client when it is about to rename a file.
81 pub(crate) fn will_rename_file(
85 ) -> Option<SourceChange> {
86 let sema = Semantics::new(db);
87 let module = sema.to_module_def(file_id)?;
88 let def = Definition::ModuleDef(module.into());
89 let mut change = def.rename(&sema, new_name_stem).ok()?;
90 change.file_system_edits.clear();
95 sema: &Semantics<RootDatabase>,
97 position: FilePosition,
98 ) -> RenameResult<(ast::NameLike, Definition)> {
100 .find_node_at_offset_with_descend::<ast::NameLike>(syntax, position.offset)
101 .ok_or_else(|| format_err!("No references found at position"))?;
103 let def = match &name_like {
104 // renaming aliases would rename the item being aliased as the HIR doesn't track aliases yet
105 ast::NameLike::Name(name)
106 if name.syntax().parent().map_or(false, |it| ast::Rename::can_cast(it.kind())) =>
108 bail!("Renaming aliases is currently unsupported")
110 ast::NameLike::Name(name) => NameClass::classify(sema, name).map(|class| match class {
111 NameClass::Definition(it) | NameClass::ConstReference(it) => it,
112 NameClass::PatFieldShorthand { local_def, field_ref: _ } => {
113 Definition::Local(local_def)
116 ast::NameLike::NameRef(name_ref) => {
117 if let Some(def) = NameRefClass::classify(sema, name_ref).map(|class| match class {
118 NameRefClass::Definition(def) => def,
119 NameRefClass::FieldShorthand { local_ref, field_ref: _ } => {
120 Definition::Local(local_ref)
123 // if the name differs from the definitions name it has to be an alias
124 if def.name(sema.db).map_or(false, |it| it.to_string() != name_ref.text()) {
125 bail!("Renaming aliases is currently unsupported");
132 ast::NameLike::Lifetime(lifetime) => NameRefClass::classify_lifetime(sema, lifetime)
133 .and_then(|class| match class {
134 NameRefClass::Definition(def) => Some(def),
138 NameClass::classify_lifetime(sema, lifetime).and_then(|it| match it {
139 NameClass::Definition(it) => Some(it),
144 .ok_or_else(|| format_err!("No references found at position"))?;
149 fn rename_to_self(sema: &Semantics<RootDatabase>, local: hir::Local) -> RenameResult<SourceChange> {
150 if never!(local.is_self(sema.db)) {
151 bail!("rename_to_self invoked on self");
154 let fn_def = match local.parent(sema.db) {
155 hir::DefWithBody::Function(func) => func,
156 _ => bail!("Cannot rename local to self outside of function"),
159 if fn_def.self_param(sema.db).is_some() {
160 bail!("Method already has a self parameter");
163 let params = fn_def.assoc_fn_params(sema.db);
164 let first_param = params
166 .ok_or_else(|| format_err!("Cannot rename local to self unless it is a parameter"))?;
167 if first_param.as_local(sema.db) != local {
168 bail!("Only the first parameter may be renamed to self");
171 let assoc_item = fn_def
172 .as_assoc_item(sema.db)
173 .ok_or_else(|| format_err!("Cannot rename parameter to self for free function"))?;
174 let impl_ = match assoc_item.container(sema.db) {
175 hir::AssocItemContainer::Trait(_) => {
176 bail!("Cannot rename parameter to self for trait functions");
178 hir::AssocItemContainer::Impl(impl_) => impl_,
180 let first_param_ty = first_param.ty();
181 let impl_ty = impl_.self_ty(sema.db);
182 let (ty, self_param) = if impl_ty.remove_ref().is_some() {
183 // if the impl is a ref to the type we can just match the `&T` with self directly
184 (first_param_ty.clone(), "self")
186 first_param_ty.remove_ref().map_or((first_param_ty.clone(), "self"), |ty| {
187 (ty, if first_param_ty.is_mutable_reference() { "&mut self" } else { "&self" })
192 bail!("Parameter type differs from impl block type");
195 let InFile { file_id, value: param_source } =
196 first_param.source(sema.db).ok_or_else(|| format_err!("No source for parameter found"))?;
198 let def = Definition::Local(local);
199 let usages = def.usages(sema).all();
200 let mut source_change = SourceChange::default();
201 source_change.extend(usages.iter().map(|(&file_id, references)| {
202 (file_id, source_edit_from_references(references, def, "self"))
204 source_change.insert_source_edit(
205 file_id.original_file(sema.db),
206 TextEdit::replace(param_source.syntax().text_range(), String::from(self_param)),
211 fn rename_self_to_param(
212 sema: &Semantics<RootDatabase>,
214 self_param: hir::SelfParam,
216 ) -> RenameResult<SourceChange> {
217 if new_name == "self" {
218 // Let's do nothing rather than complain.
219 cov_mark::hit!(rename_self_to_self);
220 return Ok(SourceChange::default());
223 let identifier_kind = IdentifierKind::classify(new_name)?;
225 let InFile { file_id, value: self_param } =
226 self_param.source(sema.db).ok_or_else(|| format_err!("cannot find function source"))?;
228 let def = Definition::Local(local);
229 let usages = def.usages(sema).all();
230 let edit = text_edit_from_self_param(&self_param, new_name)
231 .ok_or_else(|| format_err!("No target type found"))?;
232 if usages.len() > 1 && identifier_kind == IdentifierKind::Underscore {
233 bail!("Cannot rename reference to `_` as it is being referenced multiple times");
235 let mut source_change = SourceChange::default();
236 source_change.insert_source_edit(file_id.original_file(sema.db), edit);
237 source_change.extend(usages.iter().map(|(&file_id, references)| {
238 (file_id, source_edit_from_references(references, def, new_name))
243 fn text_edit_from_self_param(self_param: &ast::SelfParam, new_name: &str) -> Option<TextEdit> {
244 fn target_type_name(impl_def: &ast::Impl) -> Option<String> {
245 if let Some(ast::Type::PathType(p)) = impl_def.self_ty() {
246 return Some(p.path()?.segment()?.name_ref()?.text().to_string());
251 let impl_def = self_param.syntax().ancestors().find_map(ast::Impl::cast)?;
252 let type_name = target_type_name(&impl_def)?;
254 let mut replacement_text = String::from(new_name);
255 replacement_text.push_str(": ");
256 match (self_param.amp_token(), self_param.mut_token()) {
257 (Some(_), None) => replacement_text.push('&'),
258 (Some(_), Some(_)) => replacement_text.push_str("&mut "),
261 replacement_text.push_str(type_name.as_str());
263 Some(TextEdit::replace(self_param.syntax().text_range(), replacement_text))
268 use expect_test::{expect, Expect};
269 use stdx::trim_indent;
270 use test_utils::assert_eq_text;
271 use text_edit::TextEdit;
273 use crate::{fixture, FileId};
275 use super::{RangeInfo, RenameError};
278 fn check(new_name: &str, ra_fixture_before: &str, ra_fixture_after: &str) {
279 let ra_fixture_after = &trim_indent(ra_fixture_after);
280 let (analysis, position) = fixture::position(ra_fixture_before);
281 let rename_result = analysis
282 .rename(position, new_name)
283 .unwrap_or_else(|err| panic!("Rename to '{}' was cancelled: {}", new_name, err));
284 match rename_result {
285 Ok(source_change) => {
286 let mut text_edit_builder = TextEdit::builder();
287 let mut file_id: Option<FileId> = None;
288 for edit in source_change.source_file_edits {
289 file_id = Some(edit.0);
290 for indel in edit.1.into_iter() {
291 text_edit_builder.replace(indel.delete, indel.insert);
294 if let Some(file_id) = file_id {
295 let mut result = analysis.file_text(file_id).unwrap().to_string();
296 text_edit_builder.finish().apply(&mut result);
297 assert_eq_text!(ra_fixture_after, &*result);
301 if ra_fixture_after.starts_with("error:") {
302 let error_message = ra_fixture_after
305 .skip("error:".len())
306 .collect::<String>();
307 assert_eq!(error_message.trim(), err.to_string());
309 panic!("Rename to '{}' failed unexpectedly: {}", new_name, err)
315 fn check_expect(new_name: &str, ra_fixture: &str, expect: Expect) {
316 let (analysis, position) = fixture::position(ra_fixture);
318 analysis.rename(position, new_name).unwrap().expect("Expect returned a RenameError");
319 expect.assert_debug_eq(&source_change)
322 fn check_prepare(ra_fixture: &str, expect: Expect) {
323 let (analysis, position) = fixture::position(ra_fixture);
324 let result = analysis
325 .prepare_rename(position)
326 .unwrap_or_else(|err| panic!("PrepareRename was cancelled: {}", err));
328 Ok(RangeInfo { range, info: () }) => {
329 let source = analysis.file_text(position.file_id).unwrap();
330 expect.assert_eq(&format!("{:?}: {}", range, &source[range]))
332 Err(RenameError(err)) => expect.assert_eq(&err),
337 fn test_prepare_rename_namelikes() {
338 check_prepare(r"fn name$0<'lifetime>() {}", expect![[r#"3..7: name"#]]);
339 check_prepare(r"fn name<'lifetime$0>() {}", expect![[r#"8..17: 'lifetime"#]]);
340 check_prepare(r"fn name<'lifetime>() { name$0(); }", expect![[r#"23..27: name"#]]);
344 fn test_prepare_rename_in_macro() {
352 expect![[r#"83..86: Foo"#]],
357 fn test_prepare_rename_keyword() {
358 check_prepare(r"struct$0 Foo;", expect![[r#"No references found at position"#]]);
362 fn test_prepare_rename_tuple_field() {
372 expect![[r#"No references found at position"#]],
377 fn test_prepare_rename_builtin() {
384 expect![[r#"No references found at position"#]],
389 fn test_prepare_rename_self() {
395 fn foo(self) -> Self$0 {
400 expect![[r#"No references found at position"#]],
405 fn test_rename_to_underscore() {
406 check("_", r#"fn main() { let i$0 = 1; }"#, r#"fn main() { let _ = 1; }"#);
410 fn test_rename_to_raw_identifier() {
411 check("r#fn", r#"fn main() { let i$0 = 1; }"#, r#"fn main() { let r#fn = 1; }"#);
415 fn test_rename_to_invalid_identifier1() {
418 r#"fn main() { let i$0 = 1; }"#,
419 "error: Invalid name `invalid!`: not an identifier",
424 fn test_rename_to_invalid_identifier2() {
427 r#"fn main() { let i$0 = 1; }"#,
428 "error: Invalid name `multiple tokens`: not an identifier",
433 fn test_rename_to_invalid_identifier3() {
436 r#"fn main() { let i$0 = 1; }"#,
437 "error: Invalid name `let`: not an identifier",
442 fn test_rename_to_invalid_identifier_lifetime() {
443 cov_mark::check!(rename_not_an_ident_ref);
446 r#"fn main() { let i$0 = 1; }"#,
447 "error: Invalid name `'foo`: not an identifier",
452 fn test_rename_to_invalid_identifier_lifetime2() {
453 cov_mark::check!(rename_not_a_lifetime_ident_ref);
456 r#"fn main<'a>(_: &'a$0 ()) {}"#,
457 "error: Invalid name `foo`: not a lifetime identifier",
462 fn test_rename_to_underscore_invalid() {
463 cov_mark::check!(rename_underscore_multiple);
466 r#"fn main(foo$0: ()) {foo;}"#,
467 "error: Cannot rename reference to `_` as it is being referenced multiple times",
472 fn test_rename_mod_invalid() {
476 "error: Invalid name `'foo`: cannot rename module to 'foo",
481 fn test_rename_for_local() {
510 fn test_rename_unresolved_reference() {
513 r#"fn main() { let _ = unresolved_ref$0; }"#,
514 "error: No references found at position",
519 fn test_rename_for_macro_args() {
523 macro_rules! foo {($i:ident) => {$i} }
530 macro_rules! foo {($i:ident) => {$i} }
540 fn test_rename_for_macro_args_rev() {
544 macro_rules! foo {($i:ident) => {$i} }
551 macro_rules! foo {($i:ident) => {$i} }
561 fn test_rename_for_macro_define_fn() {
565 macro_rules! define_fn {($id:ident) => { fn $id{} }}
572 macro_rules! define_fn {($id:ident) => { fn $id{} }}
582 fn test_rename_for_macro_define_fn_rev() {
586 macro_rules! define_fn {($id:ident) => { fn $id{} }}
593 macro_rules! define_fn {($id:ident) => { fn $id{} }}
603 fn test_rename_for_param_inside() {
604 check("j", r#"fn foo(i : u32) -> u32 { i$0 }"#, r#"fn foo(j : u32) -> u32 { j }"#);
608 fn test_rename_refs_for_fn_param() {
609 check("j", r#"fn foo(i$0 : u32) -> u32 { i }"#, r#"fn foo(j : u32) -> u32 { j }"#);
613 fn test_rename_for_mut_param() {
614 check("j", r#"fn foo(mut i$0 : u32) -> u32 { i }"#, r#"fn foo(mut j : u32) -> u32 { j }"#);
618 fn test_rename_struct_field() {
622 struct Foo { field$0: i32 }
625 fn new(i: i32) -> Self {
631 struct Foo { foo: i32 }
634 fn new(i: i32) -> Self {
643 fn test_rename_field_in_field_shorthand() {
644 cov_mark::check!(test_rename_field_in_field_shorthand);
648 struct Foo { foo$0: i32 }
651 fn new(foo: i32) -> Self {
657 struct Foo { field: i32 }
660 fn new(foo: i32) -> Self {
669 fn test_rename_local_in_field_shorthand() {
670 cov_mark::check!(test_rename_local_in_field_shorthand);
674 struct Foo { i: i32 }
677 fn new(i$0: i32) -> Self {
683 struct Foo { i: i32 }
686 fn new(j: i32) -> Self {
695 fn test_field_shorthand_correct_struct() {
699 struct Foo { i$0: i32 }
700 struct Bar { i: i32 }
703 fn new(i: i32) -> Self {
709 struct Foo { j: i32 }
710 struct Bar { i: i32 }
713 fn new(i: i32) -> Self {
722 fn test_shadow_local_for_struct_shorthand() {
726 struct Foo { i: i32 }
728 fn baz(i$0: i32) -> Self {
737 struct Foo { i: i32 }
739 fn baz(j: i32) -> Self {
740 let x = Foo { i: j };
751 fn test_rename_mod() {
783 dst: AnchoredPathBuf {
798 fn test_rename_mod_in_use_tree() {
808 pub struct FooContent;
811 use crate::foo$0::FooContent;
842 dst: AnchoredPathBuf {
857 fn test_rename_mod_in_dir() {
885 dst: AnchoredPathBuf {
889 path: "../foo2/mod.rs",
900 fn test_rename_unusually_nested_mod() {
905 mod outer { mod fo$0o; }
929 dst: AnchoredPathBuf {
944 fn test_module_rename_in_path() {
949 pub use self::bar as qux;
953 fn main() { foo::bar(); }
957 pub use self::bar as qux;
961 fn main() { baz::bar(); }
967 fn test_rename_mod_filename_and_path() {
1007 file_system_edits: [
1012 dst: AnchoredPathBuf {
1027 fn test_enum_variant_from_module_1() {
1028 cov_mark::check!(rename_non_local);
1033 pub enum Foo { Bar$0 }
1036 fn func(f: foo::Foo) {
1044 pub enum Foo { Baz }
1047 fn func(f: foo::Foo) {
1057 fn test_enum_variant_from_module_2() {
1062 pub struct Foo { pub bar$0: uint }
1065 fn foo(f: foo::Foo) {
1071 pub struct Foo { pub baz: uint }
1074 fn foo(f: foo::Foo) {
1082 fn test_parameter_to_self() {
1083 cov_mark::check!(rename_to_self);
1087 struct Foo { i: i32 }
1090 fn f(foo$0: &mut Foo) -> i32 {
1096 struct Foo { i: i32 }
1099 fn f(&mut self) -> i32 {
1108 struct Foo { i: i32 }
1111 fn f(foo$0: Foo) -> i32 {
1117 struct Foo { i: i32 }
1129 fn test_parameter_to_self_error_no_impl() {
1133 struct Foo { i: i32 }
1135 fn f(foo$0: &mut Foo) -> i32 {
1139 "error: Cannot rename parameter to self for free function",
1144 struct Foo { i: i32 }
1148 fn f(foo$0: &mut Foo) -> i32 {
1153 "error: Parameter type differs from impl block type",
1158 fn test_parameter_to_self_error_not_first() {
1162 struct Foo { i: i32 }
1164 fn f(x: (), foo$0: &mut Foo) -> i32 {
1169 "error: Only the first parameter may be renamed to self",
1174 fn test_parameter_to_self_impl_ref() {
1178 struct Foo { i: i32 }
1180 fn f(foo$0: &Foo) -> i32 {
1186 struct Foo { i: i32 }
1197 fn test_self_to_parameter() {
1201 struct Foo { i: i32 }
1204 fn f(&mut $0self) -> i32 {
1210 struct Foo { i: i32 }
1213 fn f(foo: &mut Foo) -> i32 {
1222 fn test_owned_self_to_parameter() {
1223 cov_mark::check!(rename_self_to_param);
1227 struct Foo { i: i32 }
1230 fn f($0self) -> i32 {
1236 struct Foo { i: i32 }
1239 fn f(foo: Foo) -> i32 {
1248 fn test_self_in_path_to_parameter() {
1252 struct Foo { i: i32 }
1255 fn f(&self) -> i32 {
1262 struct Foo { i: i32 }
1265 fn f(foo: &Foo) -> i32 {
1275 fn test_rename_field_put_init_shorthand() {
1276 cov_mark::check!(test_rename_field_put_init_shorthand);
1280 struct Foo { i$0: i32 }
1282 fn foo(bar: i32) -> Foo {
1287 struct Foo { bar: i32 }
1289 fn foo(bar: i32) -> Foo {
1297 fn test_rename_local_put_init_shorthand() {
1298 cov_mark::check!(test_rename_local_put_init_shorthand);
1302 struct Foo { i: i32 }
1304 fn foo(bar$0: i32) -> Foo {
1309 struct Foo { i: i32 }
1311 fn foo(i: i32) -> Foo {
1319 fn test_struct_field_pat_into_shorthand() {
1320 cov_mark::check!(test_rename_field_put_init_shorthand_pat);
1324 struct Foo { i$0: i32 }
1327 let Foo { i: ref baz @ qux } = foo;
1332 struct Foo { baz: i32 }
1335 let Foo { baz: ref baz @ qux } = foo;
1343 struct Foo { i$0: i32 }
1346 let Foo { i: ref baz } = foo;
1351 struct Foo { baz: i32 }
1354 let Foo { ref baz } = foo;
1362 fn test_struct_local_pat_into_shorthand() {
1363 cov_mark::check!(test_rename_local_put_init_shorthand_pat);
1367 struct Foo { field: i32 }
1370 let Foo { field: qux$0 } = foo;
1375 struct Foo { field: i32 }
1378 let Foo { field } = foo;
1386 struct Foo { field: i32 }
1389 let Foo { field: x @ qux$0 } = foo;
1394 struct Foo { field: i32 }
1397 let Foo { field: x @ field } = foo;
1405 fn test_rename_binding_in_destructure_pat() {
1406 let expected_fixture = r#"
1412 let Foo { i: bar } = foo;
1424 let Foo { i: b } = foo;
1438 let Foo { i } = foo;
1447 fn test_rename_binding_in_destructure_param_pat() {
1455 fn foo(Foo { i }: Foo) -> i32 {
1464 fn foo(Foo { i: bar }: Foo) -> i32 {
1472 fn test_struct_field_complex_ident_pat() {
1473 cov_mark::check!(rename_record_pat_field_name_split);
1477 struct Foo { i$0: i32 }
1480 let Foo { ref i } = foo;
1484 struct Foo { baz: i32 }
1487 let Foo { baz: ref i } = foo;
1494 fn test_rename_lifetimes() {
1495 cov_mark::check!(rename_lifetime);
1502 impl<'a> Foo<'a> for &'a () {
1503 fn foo() -> &'a$0 () {
1512 impl<'yeeee> Foo<'yeeee> for &'yeeee () {
1513 fn foo() -> &'yeeee () {
1522 fn test_rename_bind_pat() {
1527 enum CustomOption<T> {
1532 let test_variable = CustomOption::Some(22);
1534 match test_variable {
1535 CustomOption::Some(foo$0) if foo == 11 => {}
1541 enum CustomOption<T> {
1546 let test_variable = CustomOption::Some(22);
1548 match test_variable {
1549 CustomOption::Some(new_name) if new_name == 11 => {}
1557 fn test_rename_label() {
1561 fn foo<'a>() -> &'a () {
1570 fn foo<'a>() -> &'a () {
1582 fn test_self_to_self() {
1583 cov_mark::check!(rename_self_to_self);
1602 fn test_rename_field_in_pat_in_macro_doesnt_shorthand() {
1603 // ideally we would be able to make this emit a short hand, but I doubt this is easily possible
1609 let $pattern = loop {};
1616 foo!(Foo { bar: baz });
1622 let $pattern = loop {};
1629 foo!(Foo { baz: baz });
1636 fn test_rename_tuple_field() {
1647 "error: No identifier available to rename",
1652 fn test_rename_builtin() {
1660 "error: Cannot rename builtin type",
1665 fn test_rename_self() {
1672 fn foo(self) -> Self$0 {
1677 "error: Cannot rename `Self`",
1682 fn test_rename_ignores_self_ty() {
1688 impl Foo where Self: {}
1693 impl Fo0 where Self: {}
1699 fn test_rename_fails_on_aliases() {
1706 "error: Renaming aliases is currently unsupported",
1715 "error: Renaming aliases is currently unsupported",
1720 fn test_rename_trait_method() {
1800 fn test_rename_trait_method_prefix_of_second() {
1819 fn test_rename_trait_const() {
1828 fn f() { <()>::FOO; }";
1839 fn f() { <()>::BAR; }"#,
1852 fn f() { <()>::BAR; }"#,
1865 fn f() { <()>::BAR$0; }"#,
1871 fn defs_from_macros_arent_renamed() {
1875 macro_rules! m { () => { fn f() {} } }
1879 "error: No identifier available to rename",
1884 fn attributed_item() {
1888 //- proc_macros: identity
1890 #[proc_macros::identity]
1897 #[proc_macros::identity]
1906 fn in_macro_multi_mapping() {
1911 macro_rules! match_ast2 {
1915 $( if $node { $res } else )*
1930 macro_rules! match_ast2 {
1934 $( if $node { $res } else )*